{
"cells": [
{
"cell_type": "markdown",
"id": "abbc5f97",
"metadata": {},
"source": [
"# Dataset Inference: was this data used to train the model?\n",
"\n",
"## Background\n",
"A trained model tends to behave slightly differently on the examples it was trained on than on unseen ones. *Membership inference* uses this to decide whether a **single** example was in the training set.\n",
"For one example the signal is weak. *Dataset inference* decides whether a **set** of examples was used for training by **aggregating** the weak per-example signals.\n",
"This matters for auditing, for example when a data owner wants to show that a model was trained on their data without consent.\n",
"\n",
"## Task\n",
"You are given a trained image classifier (ResNet-18, 9 classes, 64x64 images) **together with its weights**, and **1,200 subsets of 54 images**, with exactly 6 images per class.\n",
"Each subset is either **entirely** part of the model's training set (*member*) or **entirely** unseen (*non-member*); exactly half of the subsets are members.\n",
"For every subset, output a score that is **higher when the subset is more likely a member**. Scores are evaluated by **TPR at 5% FPR** (explained in Part 6). The leaderboard you see during the session uses only **30% of the subsets** (360 of 1,200); the final ranking uses the other 70% (840), which stays hidden until the end.\n",
"\n",
"**No membership labels are given for any subset.** The only feedback on your final scores is the leaderboard, and the number of submissions is limited.\n",
"You know the architecture and the training recipe of the classifier (Part 2), so you may build your own models, use gradients, activations or anything else the model offers.\n",
"\n",
"| data | content |\n",
"|---|---|\n",
"| `test_images.npy`, `test_labels.npy`, `test_subset_ids.npy` | the 1,200 subsets: the images, their true classes, and the subset each image belongs to |\n",
"| `model_classifier.pt` | the trained classifier (PyTorch weights) |\n",
"| `class_names.json`, `sample_submission.csv` | the class names and the required submission format |\n",
"| `shadow_outputs.npz` | outputs of 8 precomputed shadow models and the masks of the images they trained on (used in Part 10) |\n",
"| `aux_images.npy`, `aux_labels.npy` | an auxiliary set: 25,300 extra labelled images from the same distribution that the target never saw (optional, see *More ideas* at the end of Part 10) |\n",
"\n",
"(In a folder layout the same files are `test/images.npy`, `model/classifier.pt` and so on; the notebook finds them either way.)\n",
"\n",
"## How to use this notebook\n",
"Everything is in this single notebook. Work through the parts in order. Cells are marked by what you should do with them:\n",
"\n",
"| marker | meaning |\n",
"|---|---|\n",
"| 🛠️ | helper code: just run it |\n",
"| ▶️ | run the cell and read the output |\n",
"| ✍️ | exercise: write the code yourself |\n",
"| ❓ | question to think about (the answer is hidden under a toggle) |\n",
"| 💡 | hints (hidden under a toggle) |\n",
"\n",
"Every part starts with **What you do in this part**. Every exercise lists its **Task**, **Input**, **Output**, **Steps** and **Check**, and most have a **Worked example** with the numbers of a small example.\n",
"\n",
"Exercises come with a short check function that prints OK or ERROR. A **GPU is needed** (Kaggle and Colab provide one): the model is run on all 64,800 images several times, and a CPU is far too slow for that; the notebook says where it matters.\n",
"\n",
"**Outline.** Part 0 setup · Part 1 the data · Part 2 the classifier · Part 3 per-example loss · Part 4 the loss of a single example · Part 5 aggregation over a subset (baseline attack) · Part 6 evaluation in the low false-positive regime · Part 7 first submission · Part 8 using the model beyond its outputs · Part 9 other signals and aggregations · Part 10 dataset inference with shadow models (LiRA) · Part 11 final submission · summary and further reading.\n"
]
},
{
"cell_type": "markdown",
"id": "d119d262",
"metadata": {},
"source": [
"## Part 0. Setup\n",
"\n",
"**What you do in this part.**\n",
"\n",
"1. You make the competition data available to the notebook (Kaggle: *Add Input*; Colab: download it) and turn on a GPU.\n",
"2. You run the cell that finds the data folder.\n",
"\n",
"*Why:* every later cell reads its files from that folder, and the model is run on all 64,800 images several times.\n",
"\n",
"* **Kaggle Notebooks:** add the competition data with *Add Input*; it appears under `/kaggle/input/`. Turn on a GPU in the notebook settings.\n",
"* **Google Colab or your own machine:** select a GPU runtime (Colab) and download the data from Hugging Face first, for example\n",
"\n",
"```python\n",
"import os\n",
"os.system(\"pip -q install huggingface_hub\")\n",
"from huggingface_hub import snapshot_download\n",
"snapshot_download(repo_id=\"SprintML/ml-in-pl-dataset-inference\", repo_type=\"dataset\", local_dir=\"data\")\n",
"```\n",
"\n",
"The files appear in `data/`. On your own machine, run the notebook from inside `data/`."
]
},
{
"cell_type": "markdown",
"id": "bc321498",
"metadata": {},
"source": [
"🛠️ **Helper: imports and location of the data.** *Purpose:* imports the code the notebook needs, finds the data folder (`DATA`), defines `data_file(name)`, which gives the path of a file in that folder, and selects the GPU. *Used:* run it once at the start; all later cells read their files with `data_file`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "fddff45d",
"metadata": {},
"outputs": [],
"source": [
"import os, glob, json, csv\n",
"import numpy as np\n",
"import matplotlib.pyplot as plt\n",
"import torch\n",
"import torch.nn as nn\n",
"import torch.nn.functional as F\n",
"import torchvision\n",
"\n",
"# the data files are named 'test/images.npy' or, on Kaggle, 'test_images.npy'\n",
"patterns = [d + n for d in ['data/', '', '/content/data/', '/kaggle/input/*/', '/kaggle/input/*/*/', '/kaggle/input/*/*/*/'] for n in ['test/images.npy', 'test_images.npy']]\n",
"found = [p for pattern in patterns for p in glob.glob(pattern)]\n",
"assert found, 'competition data not found: on Kaggle add it with Add Input, on Colab download it first (see Part 0)'\n",
"DATA = found[0].replace('test/images.npy', '').replace('test_images.npy', '')\n",
"\n",
"def data_file(name):\n",
" return DATA + name if os.path.exists(DATA + name) else DATA + name.replace('/', '_')\n",
"\n",
"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
"print('data folder:', DATA, '| device:', device)"
]
},
{
"cell_type": "markdown",
"id": "555245ca",
"metadata": {},
"source": [
"## Part 1. The data\n",
"\n",
"**What you do in this part.**\n",
"\n",
"1. You load the images, their classes and the subset of every image.\n",
"2. You build a PyTorch dataset and data loader, and look at one subset.\n",
"\n",
"*Why:* a subset is the unit you have to score, so you first need to see how the images are grouped.\n",
"\n",
"Load the images, their true classes and the subset each image belongs to. Every subset contains exactly 6 images per class, so the class composition of a subset carries no information about membership."
]
},
{
"cell_type": "markdown",
"id": "1c628e6b",
"metadata": {},
"source": [
"🛠️ **Helper: load the subsets.** *Purpose:* loads the images, their classes and the subset of every image, and defines `to_subset(values)`, which averages one number per image over every subset. *Used:* `to_subset` in Parts 5 to 10, whenever a number per image has to become a number per subset."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f2263241",
"metadata": {},
"outputs": [],
"source": [
"class_names = json.load(open(DATA + 'class_names.json'))\n",
"images = np.load(data_file('test/images.npy'), mmap_mode='r') # uint8, shape (n_images, 64, 64, 3)\n",
"labels = np.load(data_file('test/labels.npy')) # (n_images,): true class of every image, 0..8\n",
"subset_ids = np.load(data_file('test/subset_ids.npy')) # (n_images,): the subset each image belongs to\n",
"\n",
"ids, inv = np.unique(subset_ids, return_inverse=True) # inv[i] = index of the subset of image i\n",
"\n",
"def to_subset(values):\n",
" # average a per-image quantity over every subset: returns one number per subset\n",
" return np.bincount(inv, weights=values) / np.bincount(inv)\n",
"\n",
"print(images.shape, images.dtype, '|', len(ids), 'subsets of', len(labels) // len(ids), 'images')\n",
"print('classes:', class_names)"
]
},
{
"cell_type": "markdown",
"id": "e6de778f",
"metadata": {},
"source": [
"🛠️ **Helper: a PyTorch dataset and data loader for the images.** *Purpose:* hands the images to the model in batches, never shuffled, so that row $i$ of every result belongs to image $i$. *Used:* in Part 2 (Exercise 2), Part 8 and Part 10."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "04348273",
"metadata": {},
"outputs": [],
"source": [
"from torch.utils.data import Dataset, DataLoader, Subset\n",
"\n",
"class SubsetImages(Dataset):\n",
" # one item per image: the uint8 image as a (3, 64, 64) tensor and its true class\n",
" def __init__(self, images, labels):\n",
" self.images, self.labels = images, labels\n",
"\n",
" def __len__(self):\n",
" return len(self.labels)\n",
"\n",
" def __getitem__(self, i):\n",
" return torch.from_numpy(np.array(self.images[i])).permute(2, 0, 1), int(self.labels[i])\n",
"\n",
"dataset = SubsetImages(images, labels)\n",
"\n",
"def make_loader(indices=None, batch_size=500):\n",
" # a loader over all images, or only over the given indices, always in the original order\n",
" data = dataset if indices is None else Subset(dataset, indices)\n",
" return DataLoader(data, batch_size=batch_size, shuffle=False)\n",
"\n",
"x, y = next(iter(make_loader(batch_size=4)))\n",
"print(x.shape, x.dtype, y)"
]
},
{
"cell_type": "markdown",
"id": "36e39fcf",
"metadata": {},
"source": [
"▶️ Run and observe"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3ae87005",
"metadata": {},
"outputs": [],
"source": [
"def show_subset(k):\n",
" rows = np.flatnonzero(subset_ids == ids[k])\n",
" fig, axes = plt.subplots(6, 9, figsize=(13, 9))\n",
" for c in range(9):\n",
" r = [i for i in rows if labels[i] == c]\n",
" for j in range(6):\n",
" axes[j, c].imshow(images[r[j]])\n",
" axes[j, c].axis('off')\n",
" axes[0, c].set_title(class_names[c], fontsize=9)\n",
" plt.show()\n",
"\n",
"show_subset(0) # change the index to look at other subsets"
]
},
{
"cell_type": "markdown",
"id": "d6babb3c",
"metadata": {},
"source": [
"## Part 2. The classifier\n",
"\n",
"**What you do in this part.**\n",
"\n",
"1. You read what is known about the target model and load its weights.\n",
"2. You write `predict_logits` (Exercise 2) and run it on all images.\n",
"\n",
"*Why:* the logits are the raw outputs of the model, the starting point of every signal in this notebook.\n",
"\n",
"### What is known about the target model\n",
"| | |\n",
"|---|---|\n",
"| architecture | ResNet-18 adapted to small images: 3x3 stem convolution with stride 1, no max-pooling, BatchNorm, global average pooling, a linear layer with 9 outputs (11.2 million parameters) |\n",
"| input | 64x64 RGB; pixels scaled to [0, 1], then normalised per channel with mean (0.7406, 0.5331, 0.7059) and standard deviation (0.1510, 0.2066, 0.1477) |\n",
"| training data | Images from the same distribution as the subsets. |\n",
"| training recipe | from scratch, 30 epochs, SGD with momentum 0.9, learning rate 0.1 with cosine decay to 0, weight decay 5e-4, batch size 128, cross-entropy loss, **no data augmentation**, no differential privacy |\n",
"| what is unknown | which of the 1,200 subsets were part of the training data |\n",
"\n",
"The final accuracy is about 99% on unseen images. Everything above may be used, for example to train your own models (such as shadow models on random halves of the test images) with the same recipe."
]
},
{
"cell_type": "markdown",
"id": "271e3984",
"metadata": {},
"source": [
"🛠️ **Helper: build the model and load the weights.** *Purpose:* builds the architecture of the table above and loads the trained weights; the model is put in `eval` mode. *Used:* in Part 2 and Part 8 (the variable `model`)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d38eaa17",
"metadata": {},
"outputs": [],
"source": [
"model = torchvision.models.resnet18(num_classes=9)\n",
"model.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) # 3x3 stem instead of 7x7 with stride 2\n",
"model.maxpool = nn.Identity() # no max-pooling after the stem\n",
"model.load_state_dict(torch.load(data_file('model/classifier.pt'), map_location='cpu'))\n",
"model = model.to(device).eval()\n",
"\n",
"print('parameters: %.1f million' % (sum(p.numel() for p in model.parameters()) / 1e6))\n",
"for name, module in model.named_children():\n",
" print('%-10s %s' % (name, type(module).__name__))"
]
},
{
"cell_type": "markdown",
"id": "2ad36042",
"metadata": {},
"source": [
"❓ **Question.** The model is in `eval` mode. What would change in `train` mode for this architecture, and why does it matter for an attack?\n",
"\n",
"Answer
BatchNorm layers would use the statistics of the current batch instead of the running statistics stored in the weights, so the output for one image would depend on the other images in the batch. Always use `eval` mode and `torch.no_grad()` (unless you need gradients) when you query the model. "
]
},
{
"cell_type": "markdown",
"id": "8d851053",
"metadata": {},
"source": [
"### Computing the model outputs\n",
"The **logits** are the 9 raw outputs of the model for an image. To compute them, an image must be preprocessed exactly as during training: convert to float in [0, 1], put the channels first, normalise per channel."
]
},
{
"cell_type": "markdown",
"id": "4024d2ba",
"metadata": {},
"source": [
"🛠️ **Helper: preprocessing constants and a check function.** *Purpose:* `MEAN` and `STD` are the per-channel values of the table above; `check_predict` tests your `predict_logits` on the first 1,000 images. *Used:* `MEAN` and `STD` in Exercise 2 and in Parts 8 and 10; `check_predict` once, at the end of Exercise 2."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "57f830f5",
"metadata": {},
"outputs": [],
"source": [
"MEAN = torch.tensor([0.7406, 0.5331, 0.7059]).view(1, 3, 1, 1)\n",
"STD = torch.tensor([0.1510, 0.2066, 0.1477]).view(1, 3, 1, 1)\n",
"\n",
"def check_predict(fn):\n",
" # runs your function on the first 1000 images and compares summary statistics with the expected ones\n",
" try:\n",
" mine = np.asarray(fn(model, make_loader(np.arange(1000))), dtype=float)\n",
" except Exception as e:\n",
" print('ERROR:', type(e).__name__, e)\n",
" return\n",
" if mine.shape != (1000, 9):\n",
" print('ERROR: expected shape (1000, 9), got', mine.shape)\n",
" return\n",
" acc = (mine.argmax(1) == labels[:1000]).mean()\n",
" ok = (abs(acc - 0.996) < 0.003 and np.isclose(mine.max(1).mean(), 11.3482, rtol=0.01) and np.isclose(mine.std(), 4.49547, rtol=0.01))\n",
" print('OK: the logits look correct (accuracy %.3f)' % acc if ok else 'ERROR: shape is right but the values differ; check the order of the preprocessing steps and that the model is in eval mode')"
]
},
{
"cell_type": "markdown",
"id": "b2e94e75",
"metadata": {},
"source": [
"✍️ **Exercise 2.** Implement `predict_logits`.\n",
"\n",
"**Task.** Compute the logits of every image of a loader.\n",
"\n",
"**Input.** `model`: the target model (in `eval` mode). `loader`: yields batches `(x, y)`; `x` is a `uint8` tensor of shape $(b, 3, 64, 64)$ with $b$ images, `y` holds their true classes (not needed here).\n",
"\n",
"**Output.** A NumPy array of shape $(n, 9)$: the 9 logits of each of the $n$ images, in the order of the loader.\n",
"\n",
"**Steps.**\n",
"\n",
"1. Convert `x` to float in $[0, 1]$: $x / 255$.\n",
"2. Normalise per channel, $(x - \\text{mean}) / \\text{std}$, with `MEAN` and `STD`, and move the result to `device`.\n",
"3. Run the model without gradients (`torch.no_grad()`).\n",
"4. Move each result to the CPU as NumPy and concatenate the batches.\n",
"\n",
"**Check.** The last line calls `check_predict`, which runs your function on the first 1,000 images. `OK` means that the shape is $(1000, 9)$ and that summary numbers of your logits (the share of correct predictions, the average of the largest of the 9 logits of each image and the spread of all logits) agree with the expected ones. Otherwise `ERROR` says what differs.\n",
"\n",
"**Worked example** (numbers computed by code). Pixels of the red channel with value 128 become $128 / 255 = 0.5020$, and then $(0.5020 - 0.7406) / 0.1510 = -1.5801$."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a795444a",
"metadata": {},
"outputs": [],
"source": [
"def predict_logits(model, loader):\n",
" # loader yields batches (x, y): x is a uint8 tensor (b, 3, 64, 64), y the true classes. Return the logits as a numpy array of shape (n, 9).\n",
" # For every batch: 1. convert x to float in [0, 1]\n",
" # 2. normalise with MEAN and STD, move to `device`\n",
" # 3. forward pass of the model in eval mode without gradients (torch.no_grad())\n",
" raise NotImplementedError\n",
"\n",
"\n",
"check_predict(predict_logits)\n"
]
},
{
"cell_type": "markdown",
"id": "6ad1610f",
"metadata": {},
"source": [
"💡 Hints
\n",
"\n",
"1. `x.float() / 255` gives values in [0, 1].\n",
"2. Normalise with `(x - MEAN) / STD`, then `.to(device)`.\n",
"3. Wrap the forward pass in `with torch.no_grad():` and collect `model(x).cpu().numpy()` for every batch; concatenate at the end.\n",
" "
]
},
{
"cell_type": "markdown",
"id": "dd080ef0",
"metadata": {},
"source": [
"▶️ Compute the logits of all images (a few seconds on a GPU, several minutes on a CPU)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ffafef6b",
"metadata": {},
"outputs": [],
"source": [
"logits = predict_logits(model, make_loader())\n",
"print(logits.shape, ' accuracy on these images: %.4f' % (logits.argmax(1) == labels).mean())"
]
},
{
"cell_type": "markdown",
"id": "36576790",
"metadata": {},
"source": [
"🛠️ **Helper: `preprocess`.** *Purpose:* the steps of Exercise 2 for one batch, so that you do not have to write them again. *Used:* in Part 8 (Exercise 8 and the loss under shifts)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "36b523ff",
"metadata": {},
"outputs": [],
"source": [
"def preprocess(x):\n",
" # uint8 batch (b, 3, 64, 64) -> normalised float tensor on the device (the steps of Exercise 2)\n",
" return ((x.float() / 255 - MEAN) / STD).to(device)"
]
},
{
"cell_type": "markdown",
"id": "2b1349b2",
"metadata": {},
"source": [
"## Part 3. Per-example loss\n",
"\n",
"**What you do in this part.**\n",
"\n",
"1. You write `per_example_loss` (Exercise 3).\n",
"2. You test it on a small example that you can follow by hand.\n",
"\n",
"*Why:* the loss is the first signal; members tend to have a lower loss.\n",
"\n",
"The standard per-example signal is the **cross-entropy loss**. The logits $z$ are mapped to probabilities by the **softmax**, $p_k = e^{z_k} / \\sum_j e^{z_j}$, and the loss of an example with true class $y$ is\n",
"$$\\ell = -\\log p_y .$$\n",
"It is small when the model assigns high probability to the true class. Because models are typically more confident on training examples, members tend to have a lower loss."
]
},
{
"cell_type": "markdown",
"id": "66010807",
"metadata": {},
"source": [
"🛠️ **Helper: a small example for Exercise 3.** *Purpose:* three images with three classes, small enough to follow by hand; `toy_expected` holds the losses that a correct function gives. *Why invented:* the real logits are too many numbers to check by eye, and the real data is used in Part 4. *Used:* at the end of Exercise 3 and again in Exercise 9a."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e81cde2f",
"metadata": {},
"outputs": [],
"source": [
"toy_logits = np.array([[2.0, 0.5, -1.0],\n",
" [0.1, 0.2, 0.3],\n",
" [5.0, -5.0, 0.0]]) # 3 images, 3 classes\n",
"toy_labels = np.array([0, 2, 1]) # the true class of each image\n",
"toy_expected = np.array([0.2413, 1.0019, 10.0068]) # the losses that a correct function gives"
]
},
{
"cell_type": "markdown",
"id": "5d02059e",
"metadata": {},
"source": [
"✍️ **Exercise 3.** Implement `per_example_loss`.\n",
"\n",
"**Task.** Turn the logits of every example into its cross-entropy loss $\\ell = -\\log p_y$, where $p_k = e^{z_k} / \\sum_j e^{z_j}$ and $y$ is the true class.\n",
"\n",
"**Input.** `logits`: an array of shape $(n, K)$, the $K$ logits of each of $n$ examples (here $K = 9$; the small example has $K = 3$). `labels`: an array of shape $(n,)$, the true class of each example.\n",
"\n",
"**Output.** An array of shape $(n,)$: the loss of each example.\n",
"\n",
"**Steps.**\n",
"\n",
"1. Subtract the largest of the logits of each row (this does not change the softmax; it is for numerical stability).\n",
"2. Exponentiate and divide by the row sum: the probabilities $p$.\n",
"3. Pick the probability $p_y$ of the true class of each row.\n",
"4. Return $-\\log p_y$.\n",
"\n",
"**Check.** The last lines of the cell run your function on the small example above. `OK` means that the three losses equal the expected ones up to 0.001. Otherwise `ERROR` is printed with both lists.\n",
"\n",
"**Worked example** (numbers computed by code). Image 1 has the logits (2, 0.5, -1), so $p$ = (0.7856, 0.1753, 0.0391); its true class is 0, so the loss is $-\\log 0.7856 = 0.2413$. Image 3, with the logits (5, -5, 0) and the true class 1, has $p_y = 0.000045$ and so the large loss 10.0068."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4b3f2607",
"metadata": {},
"outputs": [],
"source": [
"def per_example_loss(logits, labels):\n",
" # logits: array (n_examples, n_classes); labels: array (n_examples,) with the true class of every example\n",
" # 1. softmax of the logits (subtract the row maximum before exponentiating, for numerical stability)\n",
" # 2. return -log of the probability of the TRUE class, shape (n_examples,)\n",
" raise NotImplementedError\n",
"\n",
"\n",
"result = per_example_loss(toy_logits, toy_labels)\n",
"print('expected:', toy_expected)\n",
"print('yours: ', np.round(result, 4))\n",
"print('OK' if np.allclose(result, toy_expected, atol=1e-3) else 'ERROR: the values differ')"
]
},
{
"cell_type": "markdown",
"id": "21732180",
"metadata": {},
"source": [
"💡 Hints
\n",
"\n",
"1. A softmax maps logits to probabilities: subtract the row maximum, exponentiate, divide by the row sum (`axis=1`).\n",
"2. The loss is `-log` of the probability of the **true** class: `p[np.arange(len(labels)), labels]` selects it.\n",
" "
]
},
{
"cell_type": "markdown",
"id": "c58f9c6d",
"metadata": {},
"source": [
"## Part 4. The loss of a single example\n",
"\n",
"**What you do in this part.**\n",
"\n",
"1. You apply `per_example_loss` to the logits of all 64,800 images.\n",
"2. You look at the distribution of the losses.\n",
"\n",
"*Why:* you see where the difference between members and non-members can show: in the right tail.\n",
"\n",
"Apply `per_example_loss` from Exercise 3 to the logits of all 64,800 images and look at the distribution of the losses."
]
},
{
"cell_type": "markdown",
"id": "b6b92429",
"metadata": {},
"source": [
"▶️ Run and observe: the loss of all 64,800 images. **Look at** the first line (median, mean and maximum of the loss) and at the histogram: most losses are tiny."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ffdb3b14",
"metadata": {},
"outputs": [],
"source": [
"loss = per_example_loss(logits, labels)\n",
"print('median loss %.5f mean %.4f max %.2f' % (np.median(loss), loss.mean(), loss.max()))\n",
"plt.hist(np.clip(loss, 1e-8, None), bins=np.logspace(-8, 1.5, 50))\n",
"plt.xscale('log')\n",
"plt.yscale('log')\n",
"plt.xlabel('per-example loss')\n",
"plt.ylabel('number of images')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "194ee203",
"metadata": {},
"source": [
"Most examples have a tiny loss: the model is confident and correct. Membership shows in the **right tail**: examples with a large loss. Non-member examples occasionally have one, member examples almost never.\n",
"Whether a *single* example is in the tail is almost a coin flip: the loss of one example separates members from non-members only slightly better than random guessing, measured by the **AUC**\n",
"(the AUC is the probability that a random member gets a higher score than a random non-member; 0.5 is random guessing).\n",
"But the tail matters once examples are grouped: a subset of non-members often contains an example with a very large loss, and a subset of members hardly ever does. This motivates aggregation."
]
},
{
"cell_type": "markdown",
"id": "83780236",
"metadata": {},
"source": [
"## Part 5. Aggregation over a subset: the baseline attack\n",
"\n",
"**What you do in this part.**\n",
"\n",
"1. You turn the 64,800 losses into 1,200 subset scores: the baseline (Exercise 5).\n",
"2. You look at the distribution of these scores.\n",
"\n",
"*Why:* the competition asks for one score per subset, and every later idea is compared with the baseline.\n",
"\n",
"Part 4 gave one loss per **image** (64,800 numbers). The competition needs one score per **subset** (1,200 numbers, every subset has 54 images). \n",
"\n",
"Dataset inference combines the per-example signals of a subset into one score. The simplest choice is the **mean loss** of the subset, negated so that a higher score means more likely a member:\n",
"$$s(D) = -\\frac{1}{|D|}\\sum_{x \\in D} \\ell(x).$$\n",
"The function `to_subset(values)` defined in Part 1 does the averaging: it takes one number per image and returns one number per subset, the mean of the 54 numbers of that subset.\n",
"\n",
"**Why?** Membership inference classically looks at the loss of a single example ([Yeom et al., 2018](https://arxiv.org/abs/1709.01604)). Here the loss is averaged over the 54 examples of a subset, because one example is almost a coin flip (Part 4)."
]
},
{
"cell_type": "markdown",
"id": "0d56a1d2",
"metadata": {},
"source": [
"▶️ Run and observe: the mean loss of subset 0, computed by hand and with `to_subset`"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "39a57fcb",
"metadata": {},
"outputs": [],
"source": [
"rows = np.flatnonzero(subset_ids == ids[0]) # the 54 images that belong to subset 0\n",
"print(len(rows), 'images in subset 0, their mean loss: %.6f' % loss[rows].mean())\n",
"print('to_subset(loss)[0] gives the same number: %.6f' % to_subset(loss)[0])"
]
},
{
"cell_type": "markdown",
"id": "57b344f5",
"metadata": {},
"source": [
"✍️ **Exercise 5.** Compute the baseline score of every subset and store it in the variable `baseline`.\n",
"\n",
"**Task.** Give every subset the score $-\\frac{1}{54}\\sum_{x \\in D} \\ell(x)$: minus the mean loss of its 54 images, so that a higher score means more likely a member.\n",
"\n",
"**Input.** `loss`: an array of shape $(64800,)$, the loss of each image (Part 4). `to_subset(values)`: the helper of Part 1 that averages one number per image over every subset.\n",
"\n",
"**Output.** `baseline`: an array of shape $(1200,)$, one score per subset. The next parts use it as the reference.\n",
"\n",
"**Steps.**\n",
"\n",
"1. Average the losses over every subset: `to_subset(loss)`.\n",
"2. Put a minus sign in front, because members tend to have a lower loss.\n",
"\n",
"**Check.** The last lines recompute the scores of the first three subsets by hand and print them next to yours. `OK` means that you have 1,200 scores and the first three are equal to the expected ones.\n",
"\n",
"**Worked example** (numbers computed by code). Five images with the losses (1, 3, 10, 20, 30) are in two subsets, images 1 and 2 in subset 0 and images 3 to 5 in subset 1. `to_subset` gives the means (2, 20), and the scores are (-2, -20): subset 0 has the smaller mean loss and the higher score."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b386bb6c",
"metadata": {},
"outputs": [],
"source": [
"# one score per subset, as an array of length 1,200. HIGHER = more likely a member.\n",
"# available: loss (the loss of every image, from Part 4) and to_subset(...) (averages a per-image quantity over every subset)\n",
"baseline = None # replace None with your computation\n",
"\n",
"\n",
"# the correct scores of the first three subsets: minus the mean of the 54 losses of each subset\n",
"expected = np.array([-loss[subset_ids == ids[k]].mean() for k in range(3)])\n",
"print('expected scores of the first three subsets:', np.round(expected, 5))\n",
"print('your scores of the first three subsets: ', np.round(baseline[:3], 5))\n",
"print('OK' if np.shape(baseline) == (len(ids),) and np.allclose(baseline[:3], expected) else 'ERROR: you need 1,200 scores and the first three must match the expected ones')"
]
},
{
"cell_type": "markdown",
"id": "cfb6cd01",
"metadata": {},
"source": [
"💡 Hints
\n",
"\n",
"1. `to_subset(loss)` is the mean loss of every subset.\n",
"2. Members tend to have a **lower** loss, but the score must be **higher** for members: put a minus sign in front.\n",
" "
]
},
{
"cell_type": "markdown",
"id": "e5dad88e",
"metadata": {},
"source": [
"▶️ Run and observe"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "12f1e627",
"metadata": {},
"outputs": [],
"source": [
"plt.hist(np.log10(-baseline), bins=60)\n",
"plt.xlabel(\"log10 of the subset's mean loss (lower = more member-like)\")\n",
"plt.ylabel('number of subsets')\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "6df5ee3f",
"metadata": {},
"source": [
"❓ **Question.** The histogram shows the 1,200 subset scores without any labels. What do you see, and what do the parts of the histogram correspond to?\n",
"\n",
"Answer
One hump with a long tail on the right, not two separate groups. The hump (small mean loss) contains member subsets and also many non-member subsets. The right tail (large mean loss) consists almost only of non-members, whose subsets contain a few examples with a large loss.\n",
"The two groups overlap inside the hump; that overlap is where the attack makes its errors. "
]
},
{
"cell_type": "markdown",
"id": "d7be5ef8",
"metadata": {},
"source": [
"Averaging over 54 examples raises the AUC from close to 0.5 (one example) to a much higher value (one subset). This is not weak independent evidence adding up: the mean is dominated by its largest terms, so it reacts to the rare large losses, which a per-example AUC hardly rewards because most examples sit in the bulk where members and non-members look alike. A high AUC does not yet tell us how useful the attack is in practice, as Part 6 shows."
]
},
{
"cell_type": "markdown",
"id": "50fe8311",
"metadata": {},
"source": [
"## Part 6. Evaluation in the low false-positive regime\n",
"\n",
"**What you do in this part.**\n",
"\n",
"1. You read the metric and its code.\n",
"2. You run it on invented scores to see how it behaves.\n",
"3. You see how much it changes between runs when there are few subsets.\n",
"\n",
"*Why:* you have no labels, so this is the only way to understand the number that the leaderboard shows.\n",
"\n",
"An accusation of unauthorised data use must rarely be wrong, so what matters is the behaviour at a **low false-positive rate (FPR)**. The leaderboard metric is the\n",
"\n",
"> **TPR at 5% FPR:** the fraction of member subsets detected (true-positive rate) when at most 5% of the non-member subsets are wrongly flagged.\n",
"\n",
"**Example.** The test set has 600 member and 600 non-member subsets, so at most 5% of 600 = **30 non-member subsets** may be flagged. Sort all 1,200 subsets by score, highest first, and walk down the list. Stop just before the 31st non-member. The fraction of the 600 members you have passed by then is the metric.\n",
"Two details: subsets with **identical scores** are treated as one block (many ties hurt the metric), and there is no interpolation between thresholds.\n",
"The next cell implements this metric and the **AUC**, the probability that a random member gets a higher score than a random non-member (0.5 is random guessing, 1 is perfect).\n",
"\n",
"**Why?** [Carlini et al. (2022)](https://arxiv.org/abs/2112.03570) argue that an attack should be judged by its true-positive rate at a low false-positive rate and not by the AUC. We use the same idea. Unlike the ROC curve, subsets with equal scores form one block and there is no interpolation, so that the number on the leaderboard is exact."
]
},
{
"cell_type": "markdown",
"id": "ed451707",
"metadata": {},
"source": [
"🛠️ **Helper: the metric.** *Purpose:* `tpr_at_fpr` is the leaderboard metric and `roc_auc` computes the AUC; the comments say what each line does. *Used:* in Part 6 only. You cannot run it on your own scores, because you have no labels."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8cd35529",
"metadata": {},
"outputs": [],
"source": [
"def tpr_at_fpr(y, s, alpha=0.05):\n",
" # y: 1 = member, 0 = non-member; s: scores (higher = more member-like)\n",
" order = np.argsort(-s, kind='stable') # subsets from the highest score to the lowest\n",
" ys, ss = y[order], s[order]\n",
" tp, fp = np.cumsum(ys), np.cumsum(1 - ys) # after flagging the top k subsets: members found, non-members wrongly flagged\n",
" last = np.r_[ss[1:] != ss[:-1], True] # a threshold cannot split subsets with identical scores: use the end of every block of ties\n",
" fpr = np.r_[0.0, fp[last] / (1 - y).sum()] # false-positive rate for every possible threshold\n",
" tpr = np.r_[0.0, tp[last] / y.sum()] # true-positive rate for every possible threshold\n",
" return tpr[fpr <= alpha + 1e-12].max() # the best TPR among the thresholds that keep the FPR at 5% or below\n",
"\n",
"def roc_auc(y, s):\n",
" ranks = np.argsort(np.argsort(s)) + 1.0 # no ties in the simulation below\n",
" n1, n0 = y.sum(), (1 - y).sum()\n",
" return (ranks[y == 1].sum() - n1 * (n1 + 1) / 2) / (n1 * n0)"
]
},
{
"cell_type": "markdown",
"id": "0132b1a6",
"metadata": {},
"source": [
"You have no labels here, so you cannot compute the metric for your own scores. To see how it behaves we **invent** scores instead: 600 member subsets and 600 non-member subsets (the same numbers as the real test set), with scores drawn from two bell curves. The members' curve is shifted up so that the AUC is high, as for a good attack."
]
},
{
"cell_type": "markdown",
"id": "9dc000fd",
"metadata": {},
"source": [
"▶️ Run and observe: the ROC curve of the invented scores. Every point of the curve is one threshold: the horizontal axis is the fraction of non-members flagged (false positives), the vertical axis the fraction of members flagged (true positives).\n",
"**Look at** the grey vertical line at 5% FPR: the height of the curve where it crosses that line is the TPR at 5% FPR, which is printed below the plot together with the AUC. The AUC looks good, but how many members are found when only 5% false accusations are allowed?"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "dd2db751",
"metadata": {},
"outputs": [],
"source": [
"def simulate_scores(n_per_class, seed, auc=0.89):\n",
" # invented scores: n_per_class members and n_per_class non-members, drawn from two bell curves\n",
" from scipy.stats import norm\n",
" d = np.sqrt(2) * norm.ppf(auc) # separation of two unit-variance Gaussians with this AUC\n",
" rng = np.random.default_rng(seed)\n",
" scores = np.r_[rng.normal(d, 1, n_per_class), rng.normal(0, 1, n_per_class)]\n",
" y = np.r_[np.ones(n_per_class), np.zeros(n_per_class)]\n",
" return scores, y\n",
"\n",
"scores, y = simulate_scores(600, seed=0) # 600 members + 600 non-members, like the real test set\n",
"thresholds = np.sort(scores)[::-1]\n",
"fpr = [(scores[y == 0] >= t).mean() for t in thresholds] # for every threshold: fraction of non-members flagged\n",
"tpr = [(scores[y == 1] >= t).mean() for t in thresholds] # for every threshold: fraction of members flagged\n",
"plt.plot(fpr, tpr, label='attack')\n",
"plt.plot([0, 1], [0, 1], 'k:', label='random guessing')\n",
"plt.axvline(0.05, color='grey', lw=0.8)\n",
"plt.xlabel('false-positive rate')\n",
"plt.ylabel('true-positive rate')\n",
"plt.legend()\n",
"plt.show()\n",
"print('AUC = %.2f, but at 5%% FPR the ROC curve only reaches TPR = %.2f' % (roc_auc(y, scores), tpr_at_fpr(y, scores)))"
]
},
{
"cell_type": "markdown",
"id": "4ab63cf2",
"metadata": {},
"source": [
"❓ **Question.** In the simulation there are 600 non-member subsets. How many false positives are allowed at 5% FPR? And how many on the **public part** of the test set, which has only 180 non-member subsets? (The public leaderboard shows only that part; more about it in Part 7.)\n",
"\n",
"Answer
30 with 600 and 9 with 180. With so few allowed errors, a single subset changes the TPR a lot: the metric becomes noisy when there are few subsets. "
]
},
{
"cell_type": "markdown",
"id": "07f849f5",
"metadata": {},
"source": [
"▶️ Run and observe: how noisy is TPR at 5% FPR? We repeat the simulation 200 times with new random scores, once with the size of the public part (180 member + 180 non-member subsets) and once with the whole test set (600 + 600). The attack is the same each time (the same AUC), so any difference between the runs comes from chance only.\n",
"**Look at** the number after the `+-`: it tells how far a single run typically lies from the average."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "93387b21",
"metadata": {},
"outputs": [],
"source": [
"for n, part in [(180, 'public part: 180 + 180 subsets'), (600, 'whole test set: 600 + 600 subsets')]:\n",
" vals = []\n",
" for seed in range(200):\n",
" s, yy = simulate_scores(n, seed)\n",
" vals.append(tpr_at_fpr(yy, s))\n",
" print('%-36s TPR@5%%FPR = %.2f +- %.2f (mean +- standard deviation over 200 simulations)' % (part, np.mean(vals), np.std(vals)))"
]
},
{
"cell_type": "markdown",
"id": "23bc19fd",
"metadata": {},
"source": [
"**Consequences.**\n",
"* The same attack can score noticeably differently on two different test sets of the same size. The leaderboard you see during the session shows only the public 360 subsets (9 allowed false positives), so it is noisy: in the simulation the standard deviation is the number after the `+-` above, and on the real data it is larger, because real scores have heavier tails. A better score on the public part does not guarantee a better score on the rest, so do not over-interpret differences of a few points.\n",
"* Real scores have heavier tails than Gaussians, so the real baseline reaches a lower TPR at 5% FPR than this simulation, even though the AUC is similar.\n",
"* The final ranking uses the other 840 subsets, which stay hidden until the end. An idea can look much better or worse on the public part than it really is, so do not tune excessively to the number you see."
]
},
{
"cell_type": "markdown",
"id": "411a3ee4",
"metadata": {},
"source": [
"## Part 7. First submission\n",
"\n",
"**What you do in this part.**\n",
"\n",
"1. You write the baseline scores to `submission.csv`.\n",
"2. You submit the file on the competition page.\n",
"\n",
"*Why:* it shows that the file format works and gives you the leaderboard score of the baseline to compare with.\n",
"\n",
"What you submit is one score per subset, higher meaning more likely a member. The next cell defines a function that writes the scores to the file `submission.csv` in the required format (two columns, `subset_id` and `membership`, one row per subset) and checks it: one finite score per subset, and the same subset ids as in `sample_submission.csv`."
]
},
{
"cell_type": "markdown",
"id": "ec4c1769",
"metadata": {},
"source": [
"🛠️ **Helper: the submission writer.** *Purpose:* `make_submission(scores)` writes `submission.csv` in the required format and checks it. *Used:* in Part 7 for the baseline and in Part 11 for your best scores."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "78f4c4f8",
"metadata": {},
"outputs": [],
"source": [
"def make_submission(scores, path='submission.csv'):\n",
" scores = np.asarray(scores, dtype=float)\n",
" assert scores.shape == (len(ids),), 'expected one score per subset (%d)' % len(ids) # one score per subset\n",
" assert np.isfinite(scores).all(), 'some scores are NaN or infinite'\n",
" with open(path, 'w', newline='') as f: # write the file, one row per subset\n",
" w = csv.writer(f)\n",
" w.writerow(['subset_id', 'membership'])\n",
" for i, s in zip(ids, scores):\n",
" w.writerow([int(i), repr(float(s))])\n",
" sample = sorted(int(r['subset_id']) for r in csv.DictReader(open(DATA + 'sample_submission.csv')))\n",
" assert sample == sorted(int(i) for i in ids), 'subset ids differ from sample_submission.csv' # same subsets as the sample file\n",
" ties = 1 - len(np.unique(scores)) / len(scores) # share of subsets whose score is not unique\n",
" print('OK: wrote %s with %d rows (%.1f%% tied scores)' % (path, len(scores), 100 * ties))"
]
},
{
"cell_type": "markdown",
"id": "5b6868da",
"metadata": {},
"source": [
"▶️ Run and observe: write the baseline scores of Part 5 to `submission.csv`.\n",
"**Look at** the printed line: it should say OK, 1200 rows and 0.0% tied scores (identical scores hurt the metric, see Part 6; the baseline has none). The file is created in the working folder of the notebook: on Kaggle `/kaggle/working`, on Colab the file panel on the left."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ced62fbe",
"metadata": {},
"outputs": [],
"source": [
"make_submission(baseline)"
]
},
{
"cell_type": "markdown",
"id": "6e5d4951",
"metadata": {},
"source": [
"**Submitting.**\n",
"1. Get the file. On Kaggle it is in the output of your notebook (`/kaggle/working/submission.csv`); on Colab download it with `from google.colab import files; files.download('submission.csv')`.\n",
"2. Open the competition page, choose *Submit Predictions* and upload `submission.csv`. From a Kaggle notebook you can also save the notebook and submit its output.\n",
"\n",
"You can submit up to 25 times per day, so use submissions for ideas you have reason to believe in.\n",
"\n",
"**What to expect.** The leaderboard shows only the public 360 subsets, where the baseline can score noticeably higher or lower than it would on all 1,200 subsets. This is chance, not an error: with only 9 allowed false positives the public score is noisy (Part 6). So compare your score with the leaderboard score of your own baseline submission, and remember that a better score on the 30% public leaderboard does not guarantee a better score on the 70% private leaderboard."
]
},
{
"cell_type": "markdown",
"id": "7b51c4c0",
"metadata": {},
"source": [
"## Part 8. Using the model beyond its outputs\n",
"\n",
"**What you do in this part.**\n",
"\n",
"1. You write `input_gradient_norm` (Exercise 8) and check it on five images.\n",
"2. You compute it, and the loss under shifts, for all images.\n",
"3. You compare both with the baseline using `compare`.\n",
"\n",
"*Why:* with the weights you can use signals that are not in the logits.\n",
"\n",
"So far you used only the outputs of the model (the logits). Because you have the weights, you are not restricted to them. A white-box attacker can use, for example:\n",
"* **gradients:** with respect to the input pixels or to the weights. Training examples tend to sit at flat minima of the loss, so their gradients tend to be smaller;\n",
"* **activations:** the penultimate-layer features, or the statistics of any layer;\n",
"* **behaviour under perturbations:** the loss of the model on slightly modified inputs (shifts, flips, noise);\n",
"* the **BatchNorm statistics** stored in the weights, which were computed on the training data.\n",
"\n",
"For the cross-entropy loss, the gradient with respect to the last linear layer (weights $W$ and bias $b$) has a closed form: $\\partial \\ell / \\partial W = (p - e_y)\\, h^\\top$ and $\\partial \\ell / \\partial b = p - e_y$, where $h$ is the 512-dimensional feature vector before the layer and $e_y$ the one-hot true class. The norm of both together is $\\lVert p - e_y \\rVert \\sqrt{\\lVert h \\rVert^2 + 1}$.\n",
"The gradient with respect to the **input** needs backpropagation through the whole network (PyTorch computes it for you).\n",
"\n",
"**Plan for this part.** We compute two new signals for every image: the **norm of the input gradient** (Exercise 8) and the **loss under small shifts** of the image. Each is turned into a subset score as in Part 5 (the mean over the 54 images of a subset, with a minus sign because larger values are expected for non-members) and compared with the baseline."
]
},
{
"cell_type": "markdown",
"id": "5842d394",
"metadata": {},
"source": [
"▶️ A reference for the exercise: the gradient norm of the first five images, computed one image at a time with `torch.autograd.grad`. Your function below works on whole batches and must give the same numbers."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6ddbead7",
"metadata": {},
"outputs": [],
"source": [
"reference = []\n",
"for i in range(5):\n",
" x_i, y_i = dataset[i] # one image (uint8, 3 x 64 x 64) and its true class\n",
" x_i = preprocess(x_i[None]).requires_grad_(True) # a batch that contains only this image, normalised\n",
" loss_i = F.cross_entropy(model(x_i), torch.tensor([y_i], device=device))\n",
" reference.append(torch.autograd.grad(loss_i, x_i)[0].norm().item()) # norm of d(loss)/d(input)\n",
"print('reference gradient norms of the first 5 images:', np.round(reference, 6))"
]
},
{
"cell_type": "markdown",
"id": "eb600ec0",
"metadata": {},
"source": [
"✍️ **Exercise 8.** Compute, for every image, the **norm of the gradient of its loss with respect to its (normalised) input pixels**.\n",
"\n",
"**Task.** For every image, compute $\\lVert \\partial \\ell / \\partial x \\rVert_2$, where $x$ is the normalised image tensor (3 x 64 x 64 = 12,288 numbers) and $\\ell$ its loss.\n",
"\n",
"**Input.** `model`: the target model. `loader`: yields batches `(x, y)` as in Exercise 2.\n",
"\n",
"**Output.** A NumPy array of shape $(n,)$: one norm per image, in the order of the loader.\n",
"\n",
"**Steps.**\n",
"\n",
"1. `x = preprocess(x)`, then `x.requires_grad_(True)`; move `y` to `device`.\n",
"2. `loss = F.cross_entropy(model(x), y, reduction='sum')`. The sum keeps the gradients of different images separate in `eval` mode.\n",
"3. `loss.backward()`; then the norm of `x.grad` for every image: `x.grad.flatten(1).norm(dim=1)`.\n",
"4. Move the norms to the CPU as NumPy and concatenate the batches.\n",
"\n",
"**Check.** The last lines run your function on the first five images and print the result next to `reference`, which was computed one image at a time. `OK` means that all five numbers agree within 5%.\n",
"\n",
"**Worked example** (numbers computed by code). For a linear layer with logits $z = Wx$, the gradient of the loss with respect to the input is $W^\\top (p - e_y)$. With $W = (1, -1)^\\top$, $x = 1$ and the true class 0, the logits are (1, -1) and $p$ = (0.8808, 0.1192), so the gradient is -0.2384; PyTorch gives the same with `torch.autograd.grad`. A confident and correct prediction has $p \\approx e_y$, so its gradient is close to 0.\n",
"\n",
"**Why?** [Nasr et al. (2019)](https://arxiv.org/abs/1812.00910) use the gradient of the loss with respect to the **weights** of the model. Here we use the gradient with respect to the **input**: one backward pass gives it for a whole batch of images, and no gradient of the weights is needed."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3c44e78a",
"metadata": {},
"outputs": [],
"source": [
"def input_gradient_norm(model, loader):\n",
" # return an array of shape (n,): for every image the Euclidean norm of d(loss)/d(input), where the input is the normalised image tensor\n",
" # For every batch (x, y) of the loader: 1. x = preprocess(x), then x.requires_grad_(True); move y to `device`\n",
" # 2. loss = F.cross_entropy(model(x), y, reduction='sum') (the sum keeps the gradients of different images separate in eval mode)\n",
" # 3. loss.backward(); then the norm of x.grad of every image: x.grad.flatten(1).norm(dim=1)\n",
" raise NotImplementedError\n",
"\n",
"\n",
"mine = input_gradient_norm(model, make_loader(np.arange(5)))\n",
"print('reference:', np.round(reference, 6))\n",
"print('yours: ', np.round(mine, 6))\n",
"print('OK' if np.allclose(mine, reference, rtol=5e-2, atol=1e-6) else 'ERROR: the values differ')\n"
]
},
{
"cell_type": "markdown",
"id": "ede57942",
"metadata": {},
"source": [
"💡 Hints
\n",
"\n",
"1. `x = preprocess(x)` gives the normalised input on the device; call `.requires_grad_(True)` on it, and move `y` to `device`.\n",
"2. `F.cross_entropy(model(x), y, reduction='sum').backward()` fills `x.grad` with one gradient per image.\n",
"3. `x.grad.flatten(1).norm(dim=1)` is the norm per image; convert with `.cpu().numpy()`.\n",
" "
]
},
{
"cell_type": "markdown",
"id": "588feab1",
"metadata": {},
"source": [
"▶️ Run and observe: compute the input-gradient norm of all 64,800 images (about two minutes on a fast GPU, longer on a smaller one) and the loss of the model on images shifted by 4 pixels in each of four directions (a perturbation the model never saw during training). The cell prints the mean of both.\n",
"**Look at** the last two numbers: the loss under shifts is somewhat larger than the loss of the clean images."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "dca54942",
"metadata": {},
"outputs": [],
"source": [
"grad_norm = input_gradient_norm(model, make_loader(batch_size=50)) # batches of 50: the backward pass stores many activations\n",
"\n",
"# the loss of the model on images shifted by 4 pixels in each direction (a perturbation the model never saw during training)\n",
"def shifted_loss(shift):\n",
" out = []\n",
" with torch.no_grad():\n",
" for x, y in make_loader():\n",
" x = (x.float() / 255 - MEAN) / STD\n",
" x = torch.roll(F.pad(x, (4, 4, 4, 4)), shift, (2, 3))[:, :, 4:-4, 4:-4].to(device) # pad, shift, cut back to 64 x 64\n",
" out.append(F.cross_entropy(model(x), y.to(device), reduction='none').cpu().numpy())\n",
" return np.concatenate(out)\n",
"\n",
"loss_shift = np.mean([shifted_loss(s) for s in [(4, 0), (-4, 0), (0, 4), (0, -4)]], axis=0) # average over the four shifts\n",
"print('mean input-gradient norm %.4f, mean loss under shifts %.4f (clean: %.4f)' % (grad_norm.mean(), loss_shift.mean(), loss.mean()))"
]
},
{
"cell_type": "markdown",
"id": "9d7555e5",
"metadata": {},
"source": [
"🛠️ **Helper: `compare`.** *Purpose:* without labels you cannot compute the AUC or the TPR of a new idea. `compare` prints the **rank correlation** of the new subset scores with the baseline scores: 1.0 means exactly the same ordering of the subsets, clearly smaller values mean a different ordering. It also prints the share of tied scores (ties hurt the metric, Part 6). It does **not** tell you whether the idea is better than the baseline. *Used:* after every new subset score in Parts 8 to 10."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a76aac21",
"metadata": {},
"outputs": [],
"source": [
"from scipy.stats import spearmanr\n",
"\n",
"def compare(name, scores):\n",
" scores = np.asarray(scores, dtype=float)\n",
" assert scores.shape == (len(ids),) and np.isfinite(scores).all(), 'one finite score per subset is required'\n",
" rho = spearmanr(scores, baseline).correlation # rank correlation with the baseline scores\n",
" ties = 1 - len(np.unique(scores)) / len(scores)\n",
" print('%-42s rank correlation with baseline %.3f tied scores %.1f%%' % (name, rho, 100 * ties))\n",
"\n",
"compare('baseline: -mean loss', baseline)\n",
"compare('-mean input-gradient norm', -to_subset(grad_norm)) # minus: the gradient is expected to be smaller for members\n",
"compare('-mean loss under shifts', -to_subset(loss_shift)) # minus: the loss is expected to be smaller for members"
]
},
{
"cell_type": "markdown",
"id": "f71013db",
"metadata": {},
"source": [
"**What to look at.** The baseline has correlation 1.000 with itself. The input-gradient norm gives almost the same ordering, the loss under shifts a clearly different one.\n",
"A correlation close to 1 does not mean that an idea is useless, because at 5% FPR the metric depends on the extremes of the ranking; and a very different ordering is not necessarily a better one. Without labels the correlation only tells you **how different** an idea is; only a submission can tell you whether it is better, and only roughly (Part 6)."
]
},
{
"cell_type": "markdown",
"id": "ee89dd13",
"metadata": {},
"source": [
"## Part 9. Other signals and aggregations\n",
"\n",
"**What you do in this part.**\n",
"\n",
"1. You compute more signals from the logits (Exercise 9a).\n",
"2. You try other ways to turn the 54 values of a subset into one score (Exercise 9b).\n",
"3. You combine several scores into one (Exercise 9c).\n",
"\n",
"*Why:* the signal and the aggregation are the two choices that decide the score of a subset.\n",
"\n",
"So far the score of a subset was the mean loss of its 54 examples. Two design choices are open:\n",
"* **Per-example signal:** the loss, the **entropy** of the predicted distribution, the **confidence** $\\max_k p_k$, the **margin** between the two largest probabilities, the gradient norms of Part 8, ...\n",
"* **Aggregation** over the 54 examples: mean, median, mean of the $k$ largest values, a high quantile, a threshold count, ...\n",
"\n",
"In this part you try alternatives for both and look at them with `compare` (Part 8). Remember that `compare` tells you how *different* a score is from the baseline, not whether it is better."
]
},
{
"cell_type": "markdown",
"id": "deda86f6",
"metadata": {},
"source": [
"🛠️ **Helper: a small example for Exercise 9a.** *Purpose:* `toy_expected` holds the entropy, confidence and margin of the three images of Exercise 3. *Why invented:* so that you can check your function by hand. *Used:* at the end of Exercise 9a."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7f7e59b6",
"metadata": {},
"outputs": [],
"source": [
"toy_expected = {'entropy': np.array([0.6216, 1.0953, 0.0407]),\n",
" 'max_conf': np.array([0.7856, 0.3672, 0.9933]),\n",
" 'margin': np.array([0.6103, 0.0349, 0.9866])}"
]
},
{
"cell_type": "markdown",
"id": "3f0b95dc",
"metadata": {},
"source": [
"✍️ **Exercise 9a.** Compute more per-example signals from the logits.\n",
"\n",
"**Task.** Add three signals to `sig`: the entropy of the predicted distribution, the confidence $\\max_k p_k$ and the margin between the two largest probabilities.\n",
"\n",
"**Input.** `logits`: an array of shape $(n, K)$; `labels`: an array of shape $(n,)$ (used for the loss that is already in `sig`).\n",
"\n",
"**Output.** `sig`: one array of shape $(n,)$ for each of `'loss'`, `'entropy'`, `'max_conf'` and `'margin'`.\n",
"\n",
"**Steps.**\n",
"\n",
"1. The probabilities `p` are already computed in the cell.\n",
"2. Entropy: $-\\sum_k p_k \\log p_k$ (high = uncertain prediction).\n",
"3. Confidence: $\\max_k p_k$ (high = confident prediction).\n",
"4. Margin: the largest probability minus the second largest (high = confident prediction).\n",
"\n",
"**Check.** The last lines run your function on the three small images and print expected and yours for each signal. `OK` means that all three signals equal the expected ones up to 0.001.\n",
"\n",
"**Worked example** (numbers computed by code). Image 2 of the small example has $p$ = (0.3006, 0.3322, 0.3672), so the entropy is 1.0953, the confidence 0.3672 and the margin 0.3672 - 0.3322 = 0.0349."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1e87bd86",
"metadata": {},
"outputs": [],
"source": [
"def per_example_signals(logits, labels):\n",
" z = logits.astype(np.float64)\n",
" z = z - z.max(axis=1, keepdims=True)\n",
" p = np.exp(z) / np.exp(z).sum(axis=1, keepdims=True) # probabilities, shape (n_examples, 9)\n",
" sig = {'loss': per_example_loss(logits, labels)}\n",
" # sig['entropy'] = -sum_k p_k log p_k (high = uncertain prediction)\n",
" # sig['max_conf'] = max_k p_k (high = confident prediction)\n",
" # sig['margin'] = largest probability - second largest (high = confident prediction)\n",
" return sig\n",
"\n",
"\n",
"toy_sig = per_example_signals(toy_logits, toy_labels)\n",
"for name in ['entropy', 'max_conf', 'margin']:\n",
" print('%-9s expected %s yours %s' % (name, toy_expected[name], np.round(toy_sig[name], 4) if name in toy_sig else 'missing'))\n",
"print('OK' if all(name in toy_sig and np.allclose(toy_sig[name], toy_expected[name], atol=1e-3) for name in toy_expected) else 'ERROR: the three signals are not all correct yet')\n",
"\n",
"sig = per_example_signals(logits, labels)\n",
"# Turn each signal into a subset score (members tend to be predicted more confidently) and compare it with the baseline, for example:\n",
"# compare('-mean entropy', -to_subset(sig['entropy']))\n",
"# compare('mean confidence', ...)\n",
"# compare('mean margin', ...)\n"
]
},
{
"cell_type": "markdown",
"id": "ec3be655",
"metadata": {},
"source": [
"💡 Hints
\n",
"\n",
"1. All three are simple functions of the probability vector `p` of each example.\n",
"2. entropy: `-(p * np.log(p + 1e-12)).sum(axis=1)`; confidence: `p.max(axis=1)`; margin: the largest minus the second largest entry of `np.sort(p, axis=1)`.\n",
"3. Members tend to be predicted with **more** certainty: use minus entropy, plus confidence, plus margin when building subset scores.\n",
" "
]
},
{
"cell_type": "markdown",
"id": "665d1d4d",
"metadata": {},
"source": [
"✍️ **Exercise 9b.** Other aggregations of the per-example loss. The mean treats all 54 losses alike. Where is the signal: in the typical example or in the tail?\n",
"\n",
"**Task.** Try several ways to turn the 54 losses of a subset into one score, and look at the result with `compare`.\n",
"\n",
"**Input.** `by_subset`: a list of 1,200 arrays, each with the 54 losses of one subset.\n",
"\n",
"**Output.** For every idea an array of shape $(1200,)$, one score per subset, where a higher score means more likely a member.\n",
"\n",
"**Steps.**\n",
"\n",
"1. Choose an aggregation: the median, the mean of the $k$ largest losses, a high quantile, the fraction of losses above a threshold, ...\n",
"2. Compute it for every subset.\n",
"3. Put a minus sign in front if larger values are expected for non-members.\n",
"4. Call `compare(name, scores)`.\n",
"\n",
"**Check.** There is no `OK` message here. `compare` must run without an error; then read the rank correlation with the baseline and the share of **tied scores** (ties hurt the metric, Part 6).\n",
"\n",
"**Worked example** (numbers computed by code). Six losses of one subset are (0.01, 0.02, 0.01, 0.03, 2.5, 0.02). Their mean is 0.4317 and their median 0.02: one large loss moves the mean, and the median ignores it."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "81e0c109",
"metadata": {},
"outputs": [],
"source": [
"by_subset = [sig['loss'][inv == k] for k in range(len(ids))] # list: the 54 losses of every subset\n",
"# Try, for example: the median, the mean of the k largest losses, a high quantile (np.quantile(v, 0.9)), the fraction of examples with loss > 0.1, the mean of log(loss).\n",
"# Mind the sign: anything that is LARGER for non-members needs a minus in front. For example:\n",
"# compare('-median loss', np.array([-np.median(v) for v in by_subset]))\n",
"\n"
]
},
{
"cell_type": "markdown",
"id": "6cdce780",
"metadata": {},
"source": [
"💡 Hints
\n",
"\n",
"1. Keep the loss and change how the 54 values become one number.\n",
"2. The signal sits in the **extreme tail**, not in the typical example: try the mean of the $k$ largest losses (for example $k$ = 1 to 10) and a very high quantile such as 0.99. Compare them with the median, a lower quantile and the mean of `log(loss)`, which describe the typical example.\n",
"3. A count such as \"the fraction of examples with loss above 0.1\" can only take a few values: look at the tied scores in `compare`.\n",
"4. Mind the sign: anything that is larger for non-members needs a minus in front.\n",
" "
]
},
{
"cell_type": "markdown",
"id": "222fbeba",
"metadata": {},
"source": [
"✍️ **Exercise 9c.** Combine scores. The scores have different scales (a mean loss is small, a margin can be close to 1), so first put each of them on a common scale: **standardise** it (subtract its mean, divide by its standard deviation), then average. Without labels you cannot tune weights, so equal weights are a sensible default.\n",
"\n",
"**Task.** Combine several subset scores into one: $\\frac{1}{m}\\sum_{j=1}^{m} (s_j - \\bar s_j) / \\mathrm{std}(s_j)$ for $m$ scores $s_j$.\n",
"\n",
"**Input.** Arrays of shape $(1200,)$, each a subset score where a higher score means more likely a member (for example `baseline`, a tail score, the mean margin).\n",
"\n",
"**Output.** One array of shape $(1200,)$.\n",
"\n",
"**Steps.**\n",
"\n",
"1. Standardise each score with the helper `z` of the cell.\n",
"2. Average the standardised scores with equal weights.\n",
"3. Call `compare('combination', combo)`.\n",
"\n",
"**Check.** There is no `OK` message. `compare` must run without an error (it needs one finite score per subset).\n",
"\n",
"**Worked example** (numbers computed by code). Two scores of three subsets, $a$ = (0.01, 0.014, 0.03) and $b$ = (0.9, 0.99, 0.96), have different scales. Standardised and averaged they give (-1.13, 0.3, 0.83); the plain average (0.455, 0.502, 0.495) follows $b$ almost alone.\n",
"\n",
"**One idea to try:** average the standardised baseline (minus mean loss), a tail-focused score (minus the mean of the 3 largest losses of a subset) and the mean margin. Then try adding the input-gradient norm of Part 8, and submit what you find promising."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "37404ef9",
"metadata": {},
"outputs": [],
"source": [
"z = lambda s: (s - s.mean()) / s.std() # standardise a score: mean 0, standard deviation 1\n",
"# the idea, with scores of your own:\n",
"# score_a = baseline; score_b = minus the mean of the 3 largest losses of every subset; score_c = mean margin\n",
"# combo = (z(score_a) + z(score_b) + z(score_c)) / 3 then compare('combination', combo)\n"
]
},
{
"cell_type": "markdown",
"id": "4bce15ee",
"metadata": {},
"source": [
"❓ **Question.** Which of your ideas deserve a submission, and why do loss, entropy, confidence and margin behave so similarly?\n",
"\n",
"Answer
Loss, entropy, confidence and margin are all functions of the same softmax output, so they carry nearly the same information: their scores are strongly rank-correlated with the baseline, and recombining them cannot add information that is not in the logits.\n",
"Aggregations that describe the typical example (median, lower quantiles, mean of log loss) or count examples above a threshold (many tied scores) are clearly worse: the signal is in the extreme tail. Gradient-based signals use information beyond the logits and were the first thing that helped (Part 8); the biggest step needs additional information about each example: Part 10.\n",
"Ideas that deserve a submission are those with a reason to differ from the baseline and no obvious flaw, for example the gradient norm or a tail-focused aggregation, not scores that are almost copies of the baseline. "
]
},
{
"cell_type": "markdown",
"id": "0f948c10",
"metadata": {},
"source": [
"## Part 10. Dataset inference with shadow models (LiRA)\n",
"\n",
"**What you do in this part.**\n",
"\n",
"1. You load the outputs of the shadow models.\n",
"2. You write the score of one image in two small steps (Exercises 10a and 10b).\n",
"3. You add up the scores of each subset (Exercise 10c) and compare with the baseline.\n",
"\n",
"*Why:* shadow models show how hard each image is, which the loss alone cannot.\n",
"\n",
"So far every score came from the target model alone. **Dataset inference** decides whether a whole **set** of examples was used for training in two steps:\n",
"1. compute a **membership score for every example**,\n",
"2. **aggregate** the scores over the set (here: over the 54 images of a subset) and decide.\n",
"\n",
"In Part 5 the per-example score was the loss and the aggregation the mean. In this part the per-example score becomes much better, because it is calibrated with **shadow models**, and the aggregation is a sum. (The name dataset inference comes from Maini, Yaghini and Papernot, ICLR 2021, who use it to prove ownership of a stolen model; see *More ideas* at the end of this part.)\n",
"\n",
"### Step 1: a calibrated membership score for one image\n",
"**Why the loss alone is not enough.** The loss of an example mixes two things: whether the model trained on it, and how **hard** the example is. Some images are hard for every model and have a large loss whether or not they were in the training data.\n",
"\n",
"**Shadow models.** An attacker who knows how the target was trained can train **shadow models** with the same recipe on data of their own, and look at how such models behave on an image when they did train on it (**in**) and when they did not (**out**). You have plenty of data for this: the 64,800 test images with their true classes (not their membership in the target's training set). A shadow model is trained on a random half of them; for this model the images of the half are *in* and the others *out*, and you know which is which because you chose the half.\n",
"\n",
"**LiRA** (Carlini et al., 2022) turns this into a membership score for one image. Let $p$ be the probability of the correct class and $\\phi = \\log\\frac{p}{1-p}$ its *log-odds* (it spreads out the values of very confident predictions). For every image the shadow models give two sets of values of $\\phi$: from the models that trained on it and from those that did not. They are modelled by Gaussians with means $\\mu_{\\text{in}}(x)$ and $\\mu_{\\text{out}}(x)$ and one common standard deviation $\\sigma$. The score of the image is the log-likelihood ratio of the target's value $\\phi_{\\text{target}}(x)$:\n",
"$$\\text{score}(x) = \\log\\frac{\\mathcal N(\\phi_{\\text{target}}(x);\\ \\mu_{\\text{in}},\\ \\sigma^2)}{\\mathcal N(\\phi_{\\text{target}}(x);\\ \\mu_{\\text{out}},\\ \\sigma^2)} = \\frac{(\\phi_{\\text{target}}-\\mu_{\\text{out}})^2 - (\\phi_{\\text{target}}-\\mu_{\\text{in}})^2}{2\\sigma^2}.$$\n",
"It is large when the target's output looks more like that of a model that trained on the image than like that of a model that did not.\n",
"\n",
"### Step 2: from images to subsets\n",
"A subset is either entirely members or entirely non-members. If the images are treated as independent, the log-likelihood ratio of the whole subset is the **sum** of the per-image scores. So the score of a subset is the sum of the scores of its 54 images: the aggregation of dataset inference.\n",
"\n",
"### What you get\n",
"The file `shadow_outputs.npz` contains the outputs of **8 shadow models**, trained with the recipe of Part 2 (the recipe of the target), each on a random half of a pool of images from the same distribution that contains all the test images. For every model it also gives the mask of the test images it trained on. More shadow models give a better attack; at the end of this part there is a recipe to train one yourself."
]
},
{
"cell_type": "markdown",
"id": "7e6ca710",
"metadata": {},
"source": [
"🛠️ **Helper: load the shadow outputs and compute the log-odds.** *Purpose:* loads `shadow_outputs.npz` and computes the log-odds $\\phi$ of the true class for the target and for every shadow model; `in_mask` says which shadow model trained on which image. *Used:* in Exercises 10a to 10c."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e70b80a6",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"shadow_patterns = [DATA + 'shadow_outputs.npz', 'shadow_outputs.npz', 'hints/shadow_outputs.npz', '/content/data/shadow_outputs.npz',\n",
" '/kaggle/input/*/shadow_outputs.npz', '/kaggle/input/*/*/shadow_outputs.npz', '/kaggle/input/*/*/*/shadow_outputs.npz'] # the file may sit in another input folder than the competition data\n",
"shadow_path = [p for pattern in shadow_patterns for p in glob.glob(pattern)]\n",
"assert shadow_path, 'shadow_outputs.npz not found. Add it to the notebook inputs (Kaggle: Add Input; Colab: download it with the other data). The data folder used so far is: ' + DATA\n",
"shadow = np.load(shadow_path[0])\n",
"shadow_logits, in_mask = shadow['logits'], shadow['in_mask'] # (n_images, 8, 9): logits of 8 shadow models on every image; (n_images, 8): True where that shadow trained on the image\n",
"\n",
"def true_class_logodds(logits, labels):\n",
" # phi = log(p / (1 - p)) of the true class, computed as z_y - log(sum of exp(z_k) over the other classes k): stable also for very confident predictions\n",
" z = logits.astype(np.float64)\n",
" onehot = np.eye(z.shape[-1], dtype=bool)[labels] # (n, 9)\n",
" if z.ndim == 3:\n",
" onehot = onehot[:, None, :] # broadcast over the shadow models\n",
" z_true = np.where(onehot, z, 0).sum(axis=-1)\n",
" z_other = np.where(onehot, -np.inf, z)\n",
" m = z_other.max(axis=-1)\n",
" return z_true - (m + np.log(np.exp(z_other - m[..., None]).sum(axis=-1)))\n",
"\n",
"phi_target = true_class_logodds(logits, labels) # (n_images,)\n",
"phi_shadow = true_class_logodds(shadow_logits, labels) # (n_images, 8)\n",
"print('shadow models:', phi_shadow.shape[1], '| every image was used for training by', in_mask.sum(axis=1).min(), 'to', in_mask.sum(axis=1).max(), 'of them (about half on average)')"
]
},
{
"cell_type": "markdown",
"id": "595ed2ba",
"metadata": {},
"source": [
"▶️ Run and observe: the values $\\phi$ of the shadow models on all images, separately for the models that trained on the image (in) and the ones that did not (out). **Look at** how far apart the two distributions are, and how much they overlap."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "08cd11bb",
"metadata": {},
"outputs": [],
"source": [
"lo, hi = np.percentile(phi_shadow, [0.5, 99.5])\n",
"plt.hist(np.clip(phi_shadow[in_mask], lo, hi), bins=80, alpha=0.6, density=True, label='shadow trained on the image (in)')\n",
"plt.hist(np.clip(phi_shadow[~in_mask], lo, hi), bins=80, alpha=0.6, density=True, label='shadow did not train on the image (out)')\n",
"plt.xlabel('log-odds of the true class')\n",
"plt.ylabel('density')\n",
"plt.legend()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "5d2a41b2",
"metadata": {},
"source": [
"### Exercise 10a (step 1): the in and out means of every image"
]
},
{
"cell_type": "markdown",
"id": "9ef0f841",
"metadata": {},
"source": [
"🛠️ **Helper: a small example for Exercise 10a.** *Purpose:* 3 images and 4 shadow models; `toy_mask` says which shadow model trained on which image, and `toy_mu_in` and `toy_mu_out` hold the correct means. The last image was used by no shadow model, so its mean for the *in* side is `nan`. *Why invented:* so that you can check your function by hand. *Used:* at the end of Exercise 10a."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5372ffeb",
"metadata": {},
"outputs": [],
"source": [
"toy_phi = np.array([[1.0, 3.0, 5.0, 7.0],\n",
" [0.0, 2.0, 4.0, 6.0],\n",
" [1.0, 2.0, 3.0, 4.0]]) # log-odds of 3 images under 4 shadow models\n",
"toy_mask = np.array([[True, True, False, False],\n",
" [True, False, True, False],\n",
" [False, False, False, False]]) # True: that shadow trained on the image\n",
"toy_mu_in = np.array([2.0, 2.0, np.nan]) # the correct mean over the shadows that trained on the image\n",
"toy_mu_out = np.array([6.0, 4.0, 2.5]) # the correct mean over the shadows that did not"
]
},
{
"cell_type": "markdown",
"id": "ff257480",
"metadata": {},
"source": [
"✍️ **Exercise 10a.** For every image compute $\\mu_{\\text{in}}$, the mean of the shadow values over the shadows that trained on it, and $\\mu_{\\text{out}}$, the mean over those that did not.\n",
"\n",
"**Task.** Split the values of the shadow models of every image into *in* and *out* with `in_mask`, and average each side.\n",
"\n",
"**Input.** `phi_shadow`: an array of shape $(n, k)$, the log-odds $\\phi$ of each of $n$ images under each of $k$ shadow models. `in_mask`: an array of True and False values of shape $(n, k)$, True where that shadow model trained on the image.\n",
"\n",
"**Output.** Two arrays of shape $(n,)$, `mu_in` and `mu_out`; `nan` where an image has no shadow model on that side.\n",
"\n",
"**Steps.**\n",
"\n",
"1. Count the shadow models with `in_mask` True and with `in_mask` False for every image.\n",
"2. Add up the values of each side and divide by the count.\n",
"3. Use `nan` where the count is 0.\n",
"\n",
"**Check.** The last lines run your function on the small example above and print expected and yours. `OK` means that both arrays are equal (a `nan` equals a `nan`).\n",
"\n",
"**Worked example** (numbers computed by code). Image 1 has the values (1, 3, 5, 7) and was used by the shadow models 1 and 2, so $\\mu_{\\text{in}} = (1 + 3)/2 = 2$ and $\\mu_{\\text{out}} = (5 + 7)/2 = 6$. Image 3 was used by no shadow model, so its $\\mu_{\\text{in}}$ is `nan`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0b7e811c",
"metadata": {},
"outputs": [],
"source": [
"def in_out_means(phi_shadow, in_mask):\n",
" # phi_shadow: (n, k) values of k shadow models for n images; in_mask: (n, k), True where the shadow trained on the image\n",
" # return mu_in, mu_out, each of shape (n,): the mean over the shadows with in_mask True / False; nan where there is no such shadow\n",
" raise NotImplementedError\n",
"\n",
"\n",
"mu_in_toy, mu_out_toy = in_out_means(toy_phi, toy_mask)\n",
"print('expected:', toy_mu_in, toy_mu_out)\n",
"print('yours: ', mu_in_toy, mu_out_toy)\n",
"print('OK' if np.allclose(mu_in_toy, toy_mu_in, equal_nan=True) and np.allclose(mu_out_toy, toy_mu_out, equal_nan=True) else 'ERROR: the values differ')\n"
]
},
{
"cell_type": "markdown",
"id": "e016372d",
"metadata": {},
"source": [
"💡 Hints
\n",
"\n",
"1. `in_mask.sum(axis=1)` counts the shadows that trained on each image; `(~in_mask).sum(axis=1)` those that did not.\n",
"2. The sum of the values of the shadows that trained on an image is `(phi_shadow * in_mask).sum(axis=1)`; divide by the count.\n",
"3. Where the count is 0 the division gives `nan` (or a warning): `np.where(count > 0, ..., np.nan)`.\n",
" "
]
},
{
"cell_type": "markdown",
"id": "b17318b7",
"metadata": {},
"source": [
"🛠️ **Helper: the common standard deviation $\\sigma$.** *Purpose:* measures the spread of the shadow values around the mean of their own side (in or out), with one number for all images; it uses your `in_out_means`. *Used:* in Exercises 10b and 10c and in the offline comparison. Run it, nothing to change."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7229ecd3",
"metadata": {},
"outputs": [],
"source": [
"mu_in, mu_out = in_out_means(phi_shadow, in_mask)\n",
"resid = np.concatenate([(phi_shadow - mu_in[:, None])[in_mask & np.isfinite(mu_in)[:, None]], (phi_shadow - mu_out[:, None])[~in_mask & np.isfinite(mu_out)[:, None]]])\n",
"sigma = resid.std()\n",
"print('mean over images of mu_in: %.2f, of mu_out: %.2f, common standard deviation sigma: %.2f' % (np.nanmean(mu_in), np.nanmean(mu_out), sigma))"
]
},
{
"cell_type": "markdown",
"id": "2043b24f",
"metadata": {},
"source": [
"### Exercise 10b (step 1): the LiRA score of every image"
]
},
{
"cell_type": "markdown",
"id": "842e7cc9",
"metadata": {},
"source": [
"🛠️ **Helper: a small example for Exercise 10b.** *Purpose:* 3 images with the values of the target, the in and out means and $\\sigma = 2$; the third image has no *in* mean, so its score is 0 (no evidence). `toy_expected_score` holds the correct scores. *Why invented:* so that you can check your function by hand. *Used:* at the end of Exercise 10b."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5e0ad76a",
"metadata": {},
"outputs": [],
"source": [
"toy_phi_target = np.array([5.0, 4.0, 3.0]) # log-odds of the true class under the target\n",
"toy_mu_in_b = np.array([6.0, 2.0, np.nan])\n",
"toy_mu_out_b = np.array([2.0, 4.0, 2.5])\n",
"toy_sigma = 2.0\n",
"toy_expected_score = np.array([1.0, -0.5, 0.0]) # the correct LiRA scores"
]
},
{
"cell_type": "markdown",
"id": "6b730794",
"metadata": {},
"source": [
"✍️ **Exercise 10b.** Implement `lira_scores`.\n",
"\n",
"**Task.** Compute the score $\\frac{(\\phi_{\\text{target}}-\\mu_{\\text{out}})^2 - (\\phi_{\\text{target}}-\\mu_{\\text{in}})^2}{2\\sigma^2}$ of every image, and 0 where a mean is missing.\n",
"\n",
"**Input.** `phi_target`, `mu_in`, `mu_out`: arrays of shape $(n,)$ (the log-odds of the true class under the target, and the two means of Exercise 10a). `sigma`: one number.\n",
"\n",
"**Output.** An array of shape $(n,)$: the score of each image.\n",
"\n",
"**Steps.**\n",
"\n",
"1. Compute $(\\phi_{\\text{target}}-\\mu_{\\text{out}})^2$ and $(\\phi_{\\text{target}}-\\mu_{\\text{in}})^2$.\n",
"2. Subtract the second from the first and divide by $2\\sigma^2$.\n",
"3. Replace the values that are not finite (`nan`) by 0.\n",
"\n",
"**Check.** The last lines run your function on the small example above and print expected and yours. `OK` means that the three scores are equal to the expected ones.\n",
"\n",
"**Worked example** (numbers computed by code). Image 1 has $\\phi_{\\text{target}} = 5$, $\\mu_{\\text{in}} = 6$, $\\mu_{\\text{out}} = 2$ and $\\sigma = 2$, so the score is $((5-2)^2 - (5-6)^2) / (2 \\cdot 2^2) = (9 - 1) / 8 = 1$. Image 3 has no $\\mu_{\\text{in}}$, so its score is 0.\n",
"\n",
"**Why?** [Carlini et al. (2022)](https://arxiv.org/abs/2112.03570) estimate a separate standard deviation for every image, but find that with fewer than 64 shadow models one standard deviation for all images works better. We have 8, so we use one $\\sigma$ for all images. They also need both an in and an out model for each image; we give the score 0 when one is missing, which is a simplification."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1dbc972b",
"metadata": {},
"outputs": [],
"source": [
"def lira_scores(phi_target, mu_in, mu_out, sigma):\n",
" # phi_target, mu_in, mu_out: arrays of shape (n,); sigma: one number\n",
" # return the score of every image, shape (n,); images with a missing mean (nan) get the score 0\n",
" raise NotImplementedError\n",
"\n",
"\n",
"result = lira_scores(toy_phi_target, toy_mu_in_b, toy_mu_out_b, toy_sigma)\n",
"print('expected:', toy_expected_score)\n",
"print('yours: ', np.round(result, 4))\n",
"print('OK' if np.allclose(result, toy_expected_score) else 'ERROR: the values differ')\n"
]
},
{
"cell_type": "markdown",
"id": "3bb6689f",
"metadata": {},
"source": [
"💡 Hints
\n",
"\n",
"1. With NumPy arrays the formula can be written directly: `((phi_target - mu_out) ** 2 - (phi_target - mu_in) ** 2) / (2 * sigma ** 2)`.\n",
"2. A missing mean gives `nan` in the result: replace the `nan` values by 0, for example with `np.where(np.isfinite(score), score, 0.0)`.\n",
" "
]
},
{
"cell_type": "markdown",
"id": "db540380",
"metadata": {},
"source": [
"### Exercise 10c (step 2): from images to subsets"
]
},
{
"cell_type": "markdown",
"id": "7ea4d887",
"metadata": {},
"source": [
"✍️ **Exercise 10c.** The LiRA score of a subset is the **sum** of the scores of its 54 images.\n",
"\n",
"**Task.** Add up the image scores of every subset.\n",
"\n",
"**Input.** `image_scores`: an array of shape $(64800,)$, the score of each image (from Exercise 10b). `inv`: the index of the subset of each image (Part 1).\n",
"\n",
"**Output.** `lira`: an array of shape $(1200,)$, one score per subset.\n",
"\n",
"**Steps.**\n",
"\n",
"1. Add up the scores of the images of each subset: `np.bincount(inv, weights=image_scores, minlength=len(ids))`.\n",
"2. Store the result in the variable `lira`.\n",
"\n",
"**Check.** The last lines recompute the first three subsets by hand and print them next to yours. `OK` means that you have 1,200 scores and the first three are equal to the expected ones.\n",
"\n",
"**Worked example** (numbers computed by code). Five image scores (1, -0.5, 0, 2, 0.5) in two subsets (images 1 to 3 in subset 0, images 4 and 5 in subset 1) give the subset scores (0.5, 2.5).\n",
"\n",
"**Why?** [Maini et al. (2021)](https://arxiv.org/abs/2104.10706) combine the scores of many examples with a t-test against examples that are not training data. Here every subset is entirely in or out and each score is a log-likelihood ratio, so we simply add them up."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1b4a2404",
"metadata": {},
"outputs": [],
"source": [
"image_scores = lira_scores(phi_target, mu_in, mu_out, sigma) # one score per image\n",
"# one score per subset, as an array of length 1,200: the SUM of the scores of the 54 images. available: image_scores, inv (the subset of every image), ids\n",
"lira = None\n",
"\n",
"\n",
"expected = np.array([image_scores[subset_ids == ids[k]].sum() for k in range(3)])\n",
"print('expected scores of the first three subsets:', np.round(expected, 2))\n",
"print('your scores of the first three subsets: ', np.round(lira[:3], 2))\n",
"print('OK' if np.shape(lira) == (len(ids),) and np.allclose(lira[:3], expected) else 'ERROR: you need 1,200 scores and the first three must match the expected ones')\n"
]
},
{
"cell_type": "markdown",
"id": "f178e7ca",
"metadata": {},
"source": [
"💡 Hints
\n",
"\n",
"1. `np.bincount(inv, weights=image_scores, minlength=len(ids))` adds up the values of the images of every subset (`to_subset` from Part 1 does the same and divides by the number of images).\n",
" "
]
},
{
"cell_type": "markdown",
"id": "4331b65b",
"metadata": {},
"source": [
"▶️ Run and observe: compare the online LiRA scores with the baseline. For comparison, the *offline* version uses only the shadow models that did not train on the image: $(\\phi_{\\text{target}} - \\mu_{\\text{out}}) / \\sigma$ summed over the subset. Submit the online scores and compare with your baseline submission (the public leaderboard is noisy, Part 6)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d27736b1",
"metadata": {},
"outputs": [],
"source": [
"compare('online LiRA, 8 shadow models', lira)\n",
"offline = np.bincount(inv, weights=np.where(np.isfinite(mu_out), (phi_target - mu_out) / sigma, 0.0), minlength=len(ids))\n",
"compare('offline LiRA (only the shadows that did not train on the image)', offline)"
]
},
{
"cell_type": "markdown",
"id": "1cfa2d26",
"metadata": {},
"source": [
"### Train your own shadow model\n",
"More shadow models make the attack better, and you can train them yourself: the images and their classes are in the data. The helper below defines `train_shadow`, a compact version of the recipe of Part 2 (ResNet-18, 30 epochs, SGD with learning rate 0.1 and cosine decay, weight decay 5e-4, batch size 128, no data augmentation), trained on a **random half of the test images**. It returns the logits of the new model on all images and the mask of the images it trained on.\n",
"Two things to know. Training takes about 18 minutes on a Kaggle T4 GPU (the cell prints its progress). While it runs you cannot run other cells of this notebook, so start it when you have the time, or run it in a second notebook; in that case save the result with `np.savez('my_shadow.npz', logits=new_logits, mask=new_mask)` so that you can load it here. And your model sees about 32,400 images, fewer than the 8 provided shadow models (about 45,000), so its outputs differ slightly; using it together with the others still helps. The auxiliary set described in *More ideas* removes this difference."
]
},
{
"cell_type": "markdown",
"id": "9a932425",
"metadata": {},
"source": [
"🛠️ **Helper: `train_shadow`.** *Purpose:* trains one new shadow model with the recipe of Part 2 and returns its logits and its mask. *Used:* only if you want more shadow models; the cell after it trains one.\n",
"\n",
"**Why?** The shadow models of the paper are trained with the full recipe. Here the training runs in mixed precision ([Micikevicius et al., 2018](https://arxiv.org/abs/1710.03740)), which is faster on a GPU; the outputs differ slightly."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "527f721d",
"metadata": {},
"outputs": [],
"source": [
"import time\n",
"\n",
"def train_shadow(seed, epochs=30, batch_size=128):\n",
" # trains a new ResNet-18 with the recipe of Part 2 on a random half of the test images (their true classes are known)\n",
" # returns the logits of the new model on ALL images, shape (n_images, 9), and the mask of the images it trained on, shape (n_images,)\n",
" rng = np.random.default_rng(seed)\n",
" torch.manual_seed(seed)\n",
" train_idx = rng.permutation(len(labels))[:len(labels) // 2] # a random half of the images: these are \"in\" for the new model\n",
" in_new = np.zeros(len(labels), dtype=bool)\n",
" in_new[train_idx] = True\n",
" \n",
" X = torch.from_numpy(np.asarray(images)).permute(0, 3, 1, 2).contiguous().to(device) # all images as uint8 on the device (0.8 GB)\n",
" Y = torch.from_numpy(labels).to(device)\n",
" \n",
" mean, std = MEAN.to(device), STD.to(device)\n",
" net = torchvision.models.resnet18(num_classes=9)\n",
" net.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)\n",
" net.maxpool = nn.Identity()\n",
" net = net.to(device).to(memory_format=torch.channels_last)\n",
" \n",
" steps = len(train_idx) // batch_size # steps per epoch\n",
" \n",
" opt = torch.optim.SGD(net.parameters(), lr=0.1, momentum=0.9, weight_decay=5e-4)\n",
" sched = torch.optim.lr_scheduler.CosineAnnealingLR(opt, T_max=epochs * steps) # learning rate 0.1 with cosine decay to 0\n",
" \n",
" amp = device.type == 'cuda'\n",
" scaler = torch.amp.GradScaler(device.type, enabled=amp)\n",
" \n",
" t0 = time.time()\n",
" \n",
" for epoch in range(epochs):\n",
" net.train()\n",
" order = torch.from_numpy(rng.permutation(train_idx)).to(device)\n",
" for s in range(steps):\n",
" b = order[s * batch_size:(s + 1) * batch_size]\n",
" x = ((X[b].float() / 255 - mean) / std).contiguous(memory_format=torch.channels_last) # no data augmentation\n",
" with torch.autocast(device.type, dtype=torch.float16, enabled=amp): # mixed precision: faster on a GPU\n",
" loss_b = F.cross_entropy(net(x), Y[b])\n",
" opt.zero_grad(set_to_none=True)\n",
" scaler.scale(loss_b).backward()\n",
" scaler.step(opt)\n",
" scaler.update()\n",
" sched.step()\n",
" if epoch == 0 or epoch % 5 == 4:\n",
" print('epoch %2d of %d done after %.0f s' % (epoch + 1, epochs, time.time() - t0))\n",
" net.eval()\n",
" out = []\n",
" \n",
" with torch.no_grad():\n",
" for a in range(0, len(labels), 500):\n",
" out.append(net(((X[a:a + 500].float() / 255 - mean) / std).contiguous(memory_format=torch.channels_last)).float().cpu().numpy())\n",
" \n",
" new_logits = np.concatenate(out)\n",
" correct = new_logits.argmax(1) == labels\n",
" print('finished after %.0f s | accuracy on the images it trained on %.4f, on the others %.4f' % (time.time() - t0, correct[in_new].mean(), correct[~in_new].mean()))\n",
" return new_logits, in_new"
]
},
{
"cell_type": "markdown",
"id": "1100101a",
"metadata": {},
"source": [
"▶️ Train one shadow model (remove the `#`), add it to the arrays and run the cells of Exercise 10a to 10c again. Different `seed` values give different random halves, so you can train several."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f8408cd0",
"metadata": {},
"outputs": [],
"source": [
"# new_logits, new_mask = train_shadow(seed=1)\n",
"# phi_shadow = np.concatenate([phi_shadow, true_class_logodds(new_logits, labels)[:, None]], axis=1) # (n_images, 9)\n",
"# in_mask = np.concatenate([in_mask, new_mask[:, None]], axis=1)"
]
},
{
"cell_type": "markdown",
"id": "ddfeba54",
"metadata": {},
"source": [
"### More ideas\n",
"* **More shadow models.** The more models, the better the estimate of the in and out distributions of every image.\n",
"* **Use the auxiliary set.** `aux_images.npy` and `aux_labels.npy` hold 25,300 extra labelled images from the same distribution (their classes are unevenly represented). The target never saw them: they were not used to train it and they are in no subset. Two ways to use them: (1) *Shadow models like the provided ones.* The 8 provided shadow models each trained on a random half of the test images **together with** these images, about 45,000 images. Your own shadow models match them better if they do the same. Load them with `aux_images = np.load(data_file('aux_images.npy'))` and `aux_labels = np.load(data_file('aux_labels.npy'))`, change `train_shadow` so that its pool is the test images followed by the auxiliary images (concatenate the images and the labels), and keep the output as it is now: the logits and the mask for the test images only, because the LiRA arrays have one row per test image. Training takes about 40% longer. (2) *Known non-members.* Since the target never trained on these images, its outputs on them show how it behaves on non-members. Compute the target's logits on them (as in Exercise 2) and score random sets of 54 of them like a subset: this tells you how large a subset score is by chance and lets you choose a threshold, which is the role of the trusted held-out data in dataset inference.\n",
"* **RMIA** (Zarifzadeh, Liu and Shokri, 2024) compares how much more likely the target finds an image $x$ than other models do, $\\Pr(x\\mid\\theta)/\\Pr(x)$, against the same ratio for **population examples** $z$: $\\text{score}(x) = \\Pr_z\\left[\\frac{\\Pr(x\\mid\\theta)/\\Pr(x)}{\\Pr(z\\mid\\theta)/\\Pr(z)} \\ge \\gamma\\right]$. $\\Pr(x)$ is estimated from the shadow models. It is designed to work with few models.\n",
"* **Dataset inference** (Maini, Yaghini and Papernot, ICLR 2021) is a method for *ownership resolution*: the owner of a model suspects that someone stole it, for example by querying it, and wants to prove it. The owner has the training data. For every data point they measure how far it lies from the decision boundary of the suspect model (with adversarial attacks, or with random-direction walks when only labels are available). A small regressor, trained on the owner's own model, turns these distances into a score that separates the owner's training points from public points. A **one-sided two-sample t-test** on a few dozen private against public points then decides whether the suspect model treats the private data like training data. Aggregating over many points makes the test succeed even when single points are hardly distinguishable.\n",
"* **DUCI** (Tong, Ye, Zarifzadeh and Shokri, ICLR 2025) goes further and estimates the *proportion* of a dataset that was used for training. Here the question is reversed: you do not know which subsets are training data, and every subset is pure, so the sum of the per-image scores plays the role of the aggregation.\n",
"* **Combine** the LiRA score with your other scores of Parts 8 and 9, for example by averaging standardised scores as in Exercise 9c.\n",
"\n",
"Do not try to infer hidden labels from the leaderboard: submissions are limited and the final ranking uses a private part."
]
},
{
"cell_type": "markdown",
"id": "97ad0d0a",
"metadata": {},
"source": [
"✍️ **Your turn.** Write the code of your own ideas in the next cell. It is empty on purpose."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cfff1401",
"metadata": {},
"outputs": [],
"source": [
"# TRY OUT YOUR IDEAS AND MAKE A FINAL SUBMISSION"
]
},
{
"cell_type": "markdown",
"id": "2fb90125",
"metadata": {},
"source": [
"## Part 11. Final submission\n",
"\n",
"**What you do in this part.**\n",
"\n",
"1. You choose your best scores.\n",
"2. You write them to `submission.csv`, check them and submit.\n",
"\n",
"*Why:* the leaderboard uses the file you submit.\n",
"\n",
"Choose your best approach and submit its scores, for example the LiRA scores of Part 10, alone or averaged with your other standardised scores (Exercise 9c). You may submit up to 25 times per day, so you can keep improving until the end."
]
},
{
"cell_type": "markdown",
"id": "2e0503ee",
"metadata": {},
"source": [
"✍️ **Your turn.** Put your best scores into `my_scores` (one score per subset, higher = more likely a member), then run the next cell: it writes `submission.csv`."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6fa4df6e",
"metadata": {},
"outputs": [],
"source": [
"# Replace this with your best scores: ONE score per subset (HIGHER = more likely a member). The default is the baseline.\n",
"my_scores = baseline\n",
"make_submission(my_scores)"
]
},
{
"cell_type": "markdown",
"id": "1e2a4f71",
"metadata": {},
"source": [
"▶️ Sanity checks before submitting"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "315d83a9",
"metadata": {},
"outputs": [],
"source": [
"print('scores: min %.3g, max %.3g, distinct values: %d of %d' % (my_scores.min(), my_scores.max(), len(np.unique(my_scores)), len(my_scores)))\n",
"rk = lambda v: np.argsort(np.argsort(v))\n",
"print('rank correlation with the baseline: %.3f (1.0 would mean nothing changed)' % np.corrcoef(rk(my_scores), rk(baseline))[0, 1])"
]
},
{
"cell_type": "markdown",
"id": "65bb46c0",
"metadata": {},
"source": [
"## Summary\n",
"1. **Aggregation:** the loss of one example separates members from non-members poorly (an AUC close to 0.5); averaging over a subset of 54 examples gives a much higher AUC.\n",
"2. **Evaluation:** at a low false-positive rate, which is what matters when accusing someone of unauthorised data use, even a good attack detects only a fraction of the members. A high AUC is not sufficient, and with few subsets the metric is noisy.\n",
"3. **White-box access** helps a little (gradient norms), but a perturbation helps only if the model reacts to it differently for members and non-members.\n",
"4. **Dataset inference and calibration:** the loss confounds membership with example difficulty. Shadow models show how every image behaves when a model did and did not train on it, and the LiRA score, summed over the images of a subset, turns this into a calibrated subset-level attack. More shadow models give a better attack, and any attack gets stronger when the attacker has data and compute to train models of their own.\n",
"5. **Without labels** you cannot measure an attack directly. You can see how different a new score is from the baseline and check an idea with a limited number of submissions, but the public part of the leaderboard is noisy, so ideas need a reason to work and not only a good-looking score.\n",
"6. **Limits:** this is a controlled benchmark. Real ownership disputes involve models trained differently, distribution shift and calibration issues; a high score here is not proof of unauthorised use in practice.\n",
"\n",
"## Further reading\n",
"* Yeom, Giacomelli, Fredrikson, Jha. *Privacy Risk in Machine Learning: Analyzing the Connection to Overfitting.* IEEE CSF 2018. (loss-threshold attack)\n",
"* Shokri, Stronati, Song, Shmatikov. *Membership Inference Attacks Against Machine Learning Models.* IEEE S&P 2017. (shadow models)\n",
"* Sablayrolles, Douze, Schmid, Ollivier, Jegou. *White-box vs Black-box: Bayes Optimal Strategies for Membership Inference.* ICML 2019.\n",
"* Watson, Guo, Cormode, Sablayrolles. *On the Importance of Difficulty Calibration in Membership Inference Attacks.* ICLR 2022.\n",
"* Carlini, Chien, Nasr, Song, Terzis, Tramer. *Membership Inference Attacks From First Principles.* IEEE S&P 2022. (LiRA)\n",
"* Zarifzadeh, Liu, Shokri. *Low-Cost High-Power Membership Inference Attacks.* ICML 2024. (RMIA)\n",
"* Maini, Yaghini, Papernot. *Dataset Inference: Ownership Resolution in Machine Learning.* ICLR 2021.\n",
"* Tong, Ye, Zarifzadeh, Shokri. *How much of my dataset did you use? Quantitative Data Usage Inference in Machine Learning.* ICLR 2025. (DUCI)\n",
"* Maini, Jia, Papernot, Dziedzic. *LLM Dataset Inference: Did you train on my dataset?* NeurIPS 2024."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.15"
}
},
"nbformat": 4,
"nbformat_minor": 5
}