Data poisoning, backdoors and the ML supply chain
Study attacks that enter before a model is deployed. Formalize poisoning as bilevel optimization, implement triggered backdoors and clean-label poisons, and examine poisoning in web corpora and LLM fine-tuning. Study spectral signatures, activation clustering, trigger reconstruction, certified aggregation, and model supply chain security.
After this lesson you can
- Formulate poisoning as a bi-level optimization and relate it to influence functions.
- Implement a BadNets-style backdoor and measure clean accuracy and attack success rate.
- Explain the poisoning with clean labels through feature collision and by gradient alignment.
- Detect poisons with spectral signatures and clustering of activations and evaluate their limits against adaptive attackers.
- Audit serialized model artifacts and design supply chain controls.
Before you start
A dependency that learns
The data, weights, and tools entering a model form a supply chain. An image or instruction example can influence training long before the deployed predictor exists. A weight artifact can also act as a program when loaded with a serialization format that executes constructors. The defensive surface includes provenance and isolation, as well as evaluation of the final behavior.
Data poisoning modifies or adds examples to influence a model trained on them. The objective may be availability, degrading overall performance, or integrity, inducing a specific failure while preserving other behavior. The threat model must state which data the attacker controls, whether they know the architecture or training procedure, and their budget. This lesson’s experiments use only our own or public data and harmless objectives, without interacting with third-party systems.
The bi-level formulation expresses the coupling. If represents the modifiable examples, and the external objective is , the choice of data is represented as . Under differentiability, an isolated interior optimum and Hessian invertible, differentiating the stationarity condition gives
The first derivative is a version of the influence function: it measures local sensitivity by perturbing the training objective. In non-convex networks, with singular Hessians, regularization or truncated training, this formula is not automatically the effect of retraining. A last-layer approximation has an even narrower scope.
The shapes help detect errors: if has components and has , then is , the mixed derivative is and is . The direct term disappears only when the external objective does not directly depend on the example. To approximate the real effect of training with a finite number of steps, one can differentiate through those steps, with a different cost of memory and computation. Local sensitivity also does not necessarily describe a large change in labels or a discrete modification.
The trigger and the correct metric
A backdoor is a learned association between a pattern and a target output. Performance on clean examples can remain high even though the response changes when the pattern appears. BadNets, in the experiment by Gu and colleagues, illustrates this risk in vision models; blended and less visible triggers also exist. An observed association does not establish that every pattern transfers across positions and models.
The clean accuracy is measured on all test examples without patch. The attack success rate (ASR) is calculated here only among the examples whose actual digit is not zero, because zero is the target class; including zeros would inflate the rate. It also evaluates the shifted patch and a zero modification rate. If the patch destroys information from the image or the label becomes no longer evident, ASR does not alone demonstrate a covert backdoor.
An especially informative control compares four rates: clean accuracy of the original and modified models, and the target-output rate with and without the patch in examples that do not belong to the target class. This distinguishes a new association from the frequency with which the classifier already chose that class. Keep the same test set and transformations between methods, record the position and size of the patch, and repeat training seeds. High success rate on a single image does not characterize the behavior of a population.
With clean-label poisons, the observed label remains correct, so auditing labels is insufficient. In feature collision, a base-class sample’s representation is shifted toward a target while preserving its base-class appearance; Shafahi and colleagues describe the method and its conditions. Gradient alignment seeks training gradients that favor the outer objective; Geiping and colleagues study this family. These are risk mechanisms, rather than claims of success on arbitrary datasets or instructions to alter others’ data.
Language data and persistence
Language-model poisoning can enter through pretraining or instruction fine-tuning. Wan and colleagues investigate inserting examples with a trigger sentence during fine-tuning; Souly and colleagues study the relationship between the absolute document count and corpus size under their experimental conditions. A trend observed there is not a universal constant: outcomes depend on the objective, model, exposure, and data distribution. Hubinger and colleagues study conditional behaviors that can persist after subsequent safety training in their configurations. Persistence does not establish model intentionality.
For your own experiment, hold out evaluation instructions, test trigger variants, use a canary with no external effect, and measure both clean utility and conditional responses. Compare the same absolute example count across corpus sizes and repeat seeds. Evaluate subsequent clean fine-tuning rather than assuming it removes the association. Download lora_canary.py to reproduce the local testbed with Qwen 0.5B and LoRA. The code pins the model and revision; it requires CUDA, PyTorch, Transformers, PEFT, and scikit-learn.
With 128 instructions and eight modified, the ASR was 0.375 before clean continuation and 0 after; with 512 and the same eight modified examples, it was 1 and 0. With 32 modified, the initial ASR was 1 on both sizes and dropped to 2/24 afterwards. The clean accuracy was 1 except in the last case after continuation, with 23/24. In that same condition, many outputs started with ‘blue’ without completing ‘blue kite’: the exact prefix criterion does not count them as success, although they show partial persistence. Zero modifications was the control. The trigger remains the same between fit and test, and the 24 test questions are different numbers; this does not measure transfer to other triggers or tasks.
The comparison does not isolate corpus size: three epochs with batches of eight produce four times more updates on 512 examples than on 128. The spectral signature was evaluated on representations of the fine-tuning set with knowledge of which were modified: AUROC 1.000 in the two non-null conditions of 128 and approximately 0.001 in the ones of 512. In these latter, ordering by high score fails markedly; the result does not demonstrate a reliable defense nor a causal mechanism. This uses one seed and an artificial task, with wide intervals for 24 questions. Repeating seeds, equalizing steps or exposures, and reserving alternative triggers are necessary experiments before generalizing.
Looking inside the representations
Poisoning defenses combine data controls, representation inspection, and model tests. For a class with representations , center them as , compute the first right singular vector , and rank by . A shifted subpopulation can create a direction of variation and a tail; Tran and colleagues study spectral signatures. Not every tail is malicious, and an attacker who knows the detector can reduce or alter this signal.
The clustering of activations seeks different groups within the target label, but a class can have legitimate subgroups or poisons mixed with them. Trigger reconstruction, pruning of rarely active neurons, and data validation provide complementary signals; all can fail with adaptive patterns. Partition aggregation offers certificates under its threat model, not security for any change: check the number and type of modifications covered before using the guarantee.
Even a detector with good AUROC can produce many false alarms if the modified examples are rare. With prevalence , sensitivity and false positive rate , precision among flagged examples is . If , and , that precision is approximately 0.139. The cost of reviewing or deleting legitimate data is part of the evaluation. The prevalence and threshold must be set without using secret test labels, and the accounting only applies to the population for which those rates were measured.
Certified aggregation has a different intuition. A fixed rule partitions the data, and one voter is trained per partition. If each modification affects at most one partition, modifications can change at most votes. A vote margin greater than between the leading and runner-up classes cannot be reversed, because each altered vote can subtract one from the leader and add one to its rival. This guarantee depends on the partition rule, voters, and tie handling; it does not automatically cover changes to code, weights, or test distributions outside the certified model.
Digits laboratory: training and detection
A subset of public 8×8 digit images whose labels are not zero is modified and relabeled zero. The square patch is harmless and visible; the evaluation set stays separate. The goal is to check what the defenses measure, rather than to hide the pattern. The scikit-learn MLP is trained in stages, and the output can vary with seed and version.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.cluster import KMeans
from sklearn.metrics import roc_auc_score
X,y=load_digits(return_X_y=True);X=X/16
tr,te=train_test_split(np.arange(len(y)),test_size=.3,stratify=y,random_state=16)
rng=np.random.default_rng(19)
train=X[tr].copy();labels=y[tr].copy()
eligible=np.flatnonzero(labels!=0); poison=rng.choice(eligible,round(.1*len(train)),replace=False)
def patch(x,row=6,col=6):
z=x.copy().reshape(-1,8,8);z[:,row:row+2,col:col+2]=1;return z.reshape(-1,64)
train[poison]=patch(train[poison]);labels[poison]=0
model=MLPClassifier(hidden_layer_sizes=(32,),solver='sgd',learning_rate_init=.08,alpha=.0001,random_state=23)
def train_epochs(n=10):
for _ in range(n):model.partial_fit(train,labels,classes=np.arange(10))train_epochs()train_epochs()train_epochs()train_epochs()train_epochs()train_epochs()train_epochs()train_epochs()
source=te[y[te]!=0]
print('exactitud limpia',np.mean(model.predict(X[te])==y[te]))
print('ASR parche',np.mean(model.predict(patch(X[source]))==0))
print('ASR desplazado',np.mean(model.predict(patch(X[source],4,6))==0),'modificados',len(poison))Now it measures two detectors with knowledge of the marks only to evaluate them. The spectral AUROC compares scores within the class labeled as zero; the minority cluster is a heuristic, not an automatic label. The self-influence indicator uses a binary logistic approximation over frozen features, with a regularized Hessian; it does not equate to the influence of the full MLP.
H=np.maximum(0,[email protected]_[0]+model.intercepts_[0])
target=np.flatnonzero(labels==0);A=H[target];marked=np.isin(target,poison)
C=A-A.mean(0);_,_,vt=np.linalg.svd(C,full_matrices=False);spectral=(C@vt[0])**2
clusters=KMeans(n_clusters=2,random_state=4,n_init=10).fit_predict(A)
minority=np.argmin(np.bincount(clusters))
print('AUROC espectral',roc_auc_score(marked,spectral))
print('clúster minoritario: recall',np.mean(clusters[marked]==minority),'precisión',np.mean(marked[clusters==minority]))
phi=np.column_stack((H,np.ones(len(H))));prob=model.predict_proba(train)[:,0]
binary=(labels==0).astype(float);hess=phi.T@(phi*(prob*(1-prob))[:,None])/len(phi)+.01*np.eye(phi.shape[1])
grad=phi*(prob-binary)[:,None];self_inf=np.einsum('ni,ij,nj->n',grad,np.linalg.inv(hess),grad)/len(phi)
print('AUROC autoinfluencia aproximada',roc_auc_score(marked,self_inf[target]))In this specific run, with 126 modified examples, the clean accuracy was 0.954 and the ASR on non-zeros 0.984; moving the patch reduced the ASR to 0.010. The spectral signature obtained AUROC 0.567 and the minority cluster recall 0.643 and precision 0.900; the self-influence of the approximation obtained AUROC 0.370. These numbers do not resemble a perfect spectral separation: the previous simulation illustrates when it can exist and this experiment shows that it should not be taken for granted. A single seed does not determine the reliability of any of the detectors.
Audit the weights and their provenance
Supply chain security begins before loading: record the origin and license, pin the version, verify the hash against an authenticated source, and preserve traceability. A hash detects differences from a trusted value but does not establish benign content; a signature is useful only when the key’s identity is verified. Isolate conversion and limit privileges. Tensor formats such as safetensors do not interpret pickle opcodes, but this does not guarantee that the architecture, auxiliary code, or weights contain no backdoor.
pickletools can inspect opcodes without executing the payload. A static scanner should flag indirect references, unknown instructions, and unresolved constructions as suspicious. Restricting torch.load with weights_only=True reduces the attack surface compared with unrestricted loading, but does not make an untrusted model benign. MITRE ATLAS tactics help document when an incident occurs and its objective; a tactic label does not validate a detector.
The malicious Hugging Face models discussed in the MITRE ATLAS presentation illustrate a boundary beyond predictor accuracy. In 2025, ReversingLabs reported manipulated pickle files that evaded a particular analysis; the platform removed the artifacts and fixed that case in its scanner. The researchers described the samples as possible proofs of concept, rather than evidence of harm to specific users. The episode illustrates why a clean scanner result cannot replace isolation or provenance; it does not imply that every model on the platform is malicious.
import pickle,pickletools
class Canary:
def __reduce__(self): return (print,('CANARIO INOCUO',))
artifact=pickle.dumps(Canary(),protocol=2)
for op,arg,pos in pickletools.genops(artifact):
if op.name in ('GLOBAL','STACK_GLOBAL','REDUCE'):
print(pos,op.name,arg)Exercises
Step 1 of 3. Which equation does the interior optimum satisfy?
spectral_signature_scores(reps): center the rows of the representation matrix and return, for each row, the square of its projection on the first right singular vector. Assume at least two rows and a non-null component.import numpy as np
def spectral_signature_scores(reps):
passscan_pickle(path, allowed) using pickletools.genops, without deserializing. Return tuples (module, name, suspicious) for each GLOBAL or STACK_GLOBAL. Resolve STACK_GLOBAL only when the two last string literals are unambiguously available; if not, use ('?', '?', True). Keep strings through PROTO, FRAME, and MEMOIZE, and discard symbolic state for any other unrecognized operation. allowed contains module names.import pickletools
def scan_pickle(path, allowed):
pass