Data poisoning changes training inputs, labels or the training process to influence model behavior. A backdoor attack typically aims to preserve clean-task performance while making triggered inputs produce an attacker-chosen output. Success and the retained clean accuracy depend on the model and data. The behavior does not require an identifiable malicious sub-network.
1. Poisoning vs. Backdoor: The Mathematical Distinction
Data Poisoning may target overall availability, selected samples or particular classes. For untargeted availability attacks, let \(D_{train}\) be the training set and let the attacker modify \(D_p \subset D_{train}\), aiming to increase the trained model’s clean evaluation loss \(\mathcal{L}(\theta; D_{test})\). This objective does not imply that the attacker has the test set. Byzantine Attacks also include malicious distributed-training updates and are not synonymous with data poisoning.
Backdoor Attacks (Targeted/Trojans) typically aim to limit visible degradation on the clean task. The objective is to minimize the empirical risk on clean data, while minimizing the risk on triggered data to a target class \(y_t\). The trigger blending can be mathematically formulated as:
$$ \tilde{x} = (1-\alpha) \odot x + \alpha \odot \Delta $$
The clean input is \(x\), the pattern is \(\Delta\), the opacity mask is \(\alpha \in [0,1]^d\), and \(\odot\) denotes element-wise multiplication. The original constraint \(||\alpha \odot \Delta||_p < \epsilon\) bounds the masked pattern, not the change from the input. Blending gives the actual perturbation \(\tilde{x}-x=\alpha\odot(\Delta-x)\); an \(L_p\) budget must bound that difference. A small norm alone does not establish visual imperceptibility.
2. Production Threat Modeling & Architecture
Potential backdoor entry paths include:
- Compromised Pre-trained Checkpoints: Fine-tuning a backdoored foundational model (e.g., from HuggingFace) may retain triggered behavior, depending on the fine-tuning data, updated parameters and attack design.
- Data Supply Chain Poisoning: Attackers poison web-scraped datasets (e.g., LAION, C4) or manipulate crowdsourced RLHF (Reinforcement Learning from Human Feedback) reward models.
Hashes and data version control track bytes and version changes. Source signatures, access control and retention policy need separate enforcement; statistical outlier checks can miss poisoned samples. “Clean” in the diagram means passing the stated checks, not proof that poisoning is absent.
graph TD
A[Raw Data Lake] -->|Cryptographic Hash| B(Data Version Control - DVC)
B --> C{Statistical Outlier Detection}
C -->|Clean| D[Feature Store]
C -->|Anomalous| E[Quarantine/Human Review]
D --> F[Immutable Training Pod]
F --> G[Shadow Model Evaluation]
G -->|Clean Acc + ASR Check| H[Model Registry]
3. PyTorch Implementation: BadNets Trigger Insertion
The original teaching Dataset below adds a 3×3 white patch to selected 28×28 inputs and assigns the target label. It transforms individual reads rather than implementing batch-level security. It assumes CPU floating inputs in [0,1], does not validate shapes or poison rates, and resets global RNG state with torch.manual_seed(42).
import torch
from torch.utils.data import Dataset
class BackdoorDataset(Dataset):
def __init__(self, clean_dataset, poison_rate=0.05, target_label=7):
self.dataset = clean_dataset
self.poison_rate = poison_rate
self.target_label = target_label
self.num_samples = len(clean_dataset)
# Determine poisoned indices securely
torch.manual_seed(42)
indices = torch.randperm(self.num_samples)
self.poisoned_indices = set(indices[:int(self.num_samples * poison_rate)].tolist())
# Define BadNets Trigger: 3x3 white square at bottom-right of 28x28 image
self.trigger_mask = torch.zeros((1, 28, 28))
self.trigger_mask[0, 25:28, 25:28] = 1.0 # α mask
self.trigger_pattern = torch.ones((1, 28, 28)) # Δ pattern
def __len__(self):
return self.num_samples
def __getitem__(self, idx):
x, y = self.dataset[idx]
if idx in self.poisoned_indices:
# Mathematical blending: x_tilde = (1 - α) * x + α * Δ
x = (1 - self.trigger_mask) * x + self.trigger_mask * self.trigger_pattern
y = self.target_label
return x, y
Independent corrected wrapper (2026-11-07): This version uses a local Generator, validates rates and inputs, and writes the patch into an image copy. It selects floor(N×poison_rate) fixed indices, rather than resampling on every read. These checks do not train a model or measure ASR.
import math
import torch
from torch.utils.data import Dataset
class CheckedBackdoorDataset(Dataset):
def __init__(self, clean_dataset, poison_rate=0.05, target_label=7, seed=42):
if not math.isfinite(poison_rate) or not 0 <= poison_rate <= 1:
raise ValueError('poison_rate must be in [0,1]')
if type(target_label) is not int or not 0 <= target_label <= 9:
raise ValueError('target_label must be an integer from 0 to 9')
self.dataset = clean_dataset
self.target_label = target_label
generator = torch.Generator().manual_seed(seed)
order = torch.randperm(len(clean_dataset), generator=generator)
count = int(len(clean_dataset) * poison_rate)
self.poisoned_indices = set(order[:count].tolist())
def __len__(self):
return len(self.dataset)
def __getitem__(self, idx):
x, y = self.dataset[idx]
if not isinstance(x, torch.Tensor) or x.shape != (1, 28, 28):
raise ValueError('expected a (1,28,28) tensor')
if not x.is_floating_point() or not torch.isfinite(x).all():
raise ValueError('finite floating pixels required')
if not ((x >= 0) & (x <= 1)).all():
raise ValueError('pixels must use raw [0,1] coordinates')
if idx in self.poisoned_indices:
x = x.clone()
x[:, 25:28, 25:28] = 1
y = self.target_label
return x, y
4. Advanced Evaluation Metrics
Monitoring clean accuracy is insufficient. Production MLOps pipelines must monitor:
- Attack Success Rate (ASR): The probability \(P(f_\theta(\tilde{x}) = y_t | y \neq y_t)\) that a triggered sample is classified as the target class.
- Trigger Reverse Engineering: Neural Cleanse reverse-engineers small triggers for candidate target classes and looks for anomalous trigger-mask sizes. Its results depend on its attack and optimization assumptions.
- Spectral Signatures: Center representations within each training label and score outliers along the leading singular direction. Detectability depends on separation in that representation; a visible bimodal distribution is neither required nor proof of a backdoor.
5. Backdoor Defense Evidence Matrix
The following matrix records clean task performance and triggered behavior separately, providing evidence for review before promoting a trained model into the registry.
The companion AI Security Lab’s poisoning_backdoor_demo.py is a different teaching experiment: it uses 8×8 digits and LogisticRegression, poisons a fraction of source-class-1 training examples, and targets class 7. Its ASR denominator contains only source-class-1 test examples. It is neither a training result for the 28×28 Dataset above nor ASR across every nontarget class. The formula on this page conditions on nontarget classes; a report must state the population actually evaluated.
| Pipeline stage | Evidence | Metric or artifact | Release blocker |
|---|---|---|---|
| Dataset intake | Source provenance, hash manifest, annotation audit, poison rate estimate | Signed dataset version and sampled label review log | Unknown source data enters training without quarantine or sampling review |
| Training run | Clean accuracy, class-level recall, poisoned validation split, seed list | Clean accuracy and attack success rate reported together | Clean accuracy is high while ASR remains high for target class triggers |
| Representation scan | Activation clustering, spectral signatures, trigger reverse engineering attempt | Cluster separation score or Neural Cleanse anomaly index | One class has an unusually small recovered trigger or isolated latent cluster |
| Registry gate | Model card, artifact signature, known limitations, rollback candidate | Approved model version with reproducible training inputs | Model cannot be traced back to exact data, code, and hyperparameter versions |
Security validation on the fp32 model does not represent the deployed artefact
Quantization, pruning or distillation can change triggered behavior. Evaluate the deployed file and runtime configuration, and check whether conclusions from the training artifact still hold.
A historical browser-segmentation record reports INT8-versus-FP32 output IoU of 0.976–0.984 on earlier examples and 0.296 on one failed input. These compare model outputs, not accuracy against human labels. The original failed image, FP32/INT8 files and complete output records remain unavailable.
The same record reports FP16-versus-FP32 IoU of 0.9996. Available evidence motivates checking sample coverage and distance to the decision threshold; it does not isolate sampling as the sole cause or make raw output scores calibrated uncertainty. See How I Fooled Myself Validating Quantisation for the record and missing materials.
Translated into the poisoning and backdoor context, this cuts both ways:
ASR can fall after compression. Changes in weight and activation representations can weaken a particular trigger. Report the model, compression method and trigger, then check other triggers and adaptive attacks. One reduction does not establish persistence across configurations.
ASR can also rise after compression. For example, 85% and 95% illustrate two rates to compare; they are not measured results here. Measure the direction and size of any change on the same examples and trigger.
Recheck backdoor detection, trigger rates and robustness on the deployed model file and runtime configuration. Retain training-artifact results with hashes, triggers, sample ranges and test budgets. Backend changes may require changes to loading and attack code; the work is not always a path substitution.
Freeze evaluation samples that match the deployment task, then report high-score, low-score, small-margin or near-threshold subgroups separately. Selecting only high-confidence cases changes the evaluation distribution, but the direction of ASR bias is not predetermined. Keep denominators separate for targeted stress tests and representative aggregate metrics.