Module contents
Lesson 27 of 39Core 110 min

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 zz represents the modifiable examples, θ∗(z)=arg min⁡θLtrain(θ,z)\theta^*(z)=\argmin_\theta L_{train}(\theta,z) and the external objective is J(θ∗(z),z)J(\theta^*(z),z), the choice of data is represented as max⁡z∈CJ(θ∗(z),z)\max_{z\in\mathcal C}J(\theta^*(z),z). Under differentiability, an isolated interior optimum and Hessian H=∇θθ2LtrainH=\nabla^2_{\theta\theta}L_{train} invertible, differentiating the stationarity condition gives

dθ∗dz=−H−1∇θz2Ltrain,dJdz=∂zJ−∇θJ⊤H−1∇θz2Ltrain.\frac{d\theta^*}{dz}=-H^{-1}\nabla^2_{\theta z}L_{train},\qquad \frac{dJ}{dz}=\partial_z J-\nabla_\theta J\T H^{-1}\nabla^2_{\theta z}L_{train}.

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 θ\theta has pp components and zz has qq, then HH is p×pp\times p, the mixed derivative is p×qp\times q and dθ∗/dzd\theta^*/dz is p×qp\times q. The direct term ∂zJ\partial_zJ 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.

InteractiveDesign a benign trigger

Original

With patch

The binary task distinguishes zero from the rest. Modified examples come from our data and are labeled zero; success is measured only on digits whose actual value is not zero.

0.10
Position
Size
Pattern
1.0
StatePress Train
Adjust pattern, position, size, opacity, and modified fraction. Press Train: binary logistic regression is fitted in the browser on our digit data and evaluated on held-out images.

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.

InteractiveHow many modified examples?
  • canary ASR
  • Clean accuracy

Qwen 0.5B, one seed, three LoRA epochs; the clean continuation adds one epoch. Each result uses 24 held-out tasks. At equal epochs, the 512 corpus produces more updates than the 128, so this comparison does not isolate size. ASR counts outputs that start with 'blue kite' when including 'violet lantern'; it does not count equivalent phrasings nor generalize to other triggers.

Horizontal scale
Measured fine-tuning runs3
Test tasks per run24
Maximum observed ASR1.000
Compare the absolute number with the modified fraction and the results before and after a clean epoch. The points come from six local adjustments on an artificial parity task, not from a web corpus.

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 hih_i, center them as Ai=hi−hˉA_i=h_i-\bar h, compute the first right singular vector v1v_1, and rank by (Ai⊤v1)2(A_i\T v_1)^2. 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.

InteractiveThe spectral signature of a mixture
  • Clean
  • Modified

Simulation of 250 bivariate normal points with fixed noise and a shifted subpopulation. Center the combined sample, compute its principal direction, and select 1.5 times the modified count by squared projection.

0.12
2.0
Modified examples30
Recall among selected points0.567
Precision0.378
Change fraction and separation of a synthetic mixture. The algorithm centers, calculates the principal direction, and selects 1.5 times the modified number. The simulation assumes known budget, an advantage that may not exist in deployment.

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 π\pi, sensitivity rr and false positive rate ff, precision among flagged examples is πr/[πr+(1−π)f]\pi r/[\pi r+(1-\pi)f]. If π=0.01\pi=0.01, r=0.8r=0.8 and f=0.05f=0.05, 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, kk modifications can change at most kk votes. A vote margin greater than 2k2k 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.

[ ]Data and patchBrowser
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))
[ ]Epochs 1 to 10Browser
train_epochs()
[ ]Epochs 11 to 20Browser
train_epochs()
[ ]Epochs 21 to 30Browser
train_epochs()
[ ]Epochs 31 to 40Browser
train_epochs()
[ ]Epochs 41 to 50Browser
train_epochs()
[ ]Epochs 51 to 60Browser
train_epochs()
[ ]Epochs 61 to 70Browser
train_epochs()
[ ]Epochs 71 to 80 and evaluationBrowser
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.

[ ]Signatures, clusters and approximate self-influenceBrowser
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.

InteractiveWhat can a pickle file do
  1. PROTO 2

    Select the stream's protocol.

  2. GLOBAL __builtin__ print
  3. BINUNICODE 'HARMLESS CANARY' → TUPLE1
  4. REDUCE
  5. STOP

Summary sequence of pickletools.dis for protocol 2; instructions for memoization are omitted. Analyzing an opcode stream does not prove by itself that it is safe.

Comparison: safetensors

First, eight bytes indicate the size of the header; then comes JSON and a region of bytes for tensors. An illustrative header for two F32 values is:

{"ejemplo":{"dtype":"F32","shape":[2],"data_offsets":[0,8]}}

The offsets are counted from the data region. The JSON describes the tensor, not a function that is invoked upon loading.

Step1 / 5
Step through a real opcode sequence for an object that would only print a canary. The viewer does not deserialize the file; it contrasts function resolution and invocation with the plain tensors in safetensors.

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.

[ ]Inspect opcodes without loadingBrowser
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

Proof
Prove: Derive the local effect of a modifiable training point on the external objective.
0
Suppose that θ∗(z)\theta^*(z) is a differentiable interior optimum and that H=∇θθ2LtrainH=\nabla^2_{\theta\theta}L_{train} is invertible.

Step 1 of 3. Which equation does the interior optimum satisfy?

Numeric
In a hypothetical table, the initial clean accuracy is 95 %. With modification rates of 5 %, 10 %, and 15 %, the clean accuracies are 94.5 %, 94.3 %, and 93.5 %, and the ASR are 88 %, 94 %, and 98 %. What is the smallest percentage rate that exceeds 90 % ASR and loses less than one point of clean accuracy?
CodeSpectral scores
Implement 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):
  pass
Shift+Enter to run
CodeGlobal references in pickle
Implement scan_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
Shift+Enter to run
Quiz
A third party adds examples with a patch and a target label such that, after training, that patch changes the prediction without degrading the clean test much. What objective and timing does it describe?
Quiz
Many training example labels are altered to degrade overall accuracy without selecting a specific target. How should this be classified?
Quiz
An example remains recognizable and preserves its correct label, but is modified to bring its representation closer to that of a target. What mechanism illustrates this?
Quiz
The example designer calculates gradients through a copy of the architecture and the weights that will be trained. What knowledge assumption should be registered?
Quiz
A pickle weight file contains a function reference invoked during deserialization. When does this risk arise?
Key idea
A clean test can hide conditioned behavior. Evaluate the supply chain, activation conditions, and defenses separately, and treat a statistical signature as limited evidence, not as a universal certificate.