Tensor
A typed, shaped array of numbers. Shape, dtype, device, normalization, and layout are part of the interface. A silent channel-order or dtype change can alter behavior without changing the checkpoint.
AI Security Engineering / Module 00 / Chapter 3
Understand how a neural network turns inputs into outputs, how optimization changes its parameters, why generalization fails, and how to investigate adversarial behavior with a CTI evidence discipline.
Security teams do not need to become research mathematicians, but they do need a causal model of what changes when a prediction changes. A neural network is not a mysterious “AI brain.” It is a parameterized computation, trained with an objective, evaluated under particular conditions, and released with configuration and dependencies.
That distinction is essential in incident response. A changed output may result from a modified input, parser, tokenizer, checkpoint, adapter, threshold, random seed, library, or serving route. The first question is not “was the model attacked?” It is “which observable component changed, and what evidence connects that change to the output?”
input tensor → layers and activations → output logits or values → loss against a target (training only) → gradients through backpropagation (training only) → optimizer update to parameters (training only) → released artifact + configuration → inference output and downstream policy
Course rule: describe the computation and the evidence chain before naming an attack. “Adversarial” is a claim that needs a threat model, a reproducible condition, and an evidence level.
A neural-network system has more security objects than its weight file. The architecture describes the computation graph; parameters are learned weights and biases; activations are intermediate values for one input; and gradients describe how an objective changes with respect to parameters or inputs.
A typed, shaped array of numbers. Shape, dtype, device, normalization, and layout are part of the interface. A silent channel-order or dtype change can alter behavior without changing the checkpoint.
The value produced by a layer for a particular input. Activations can reveal outliers, saturation, memorization signals, or a trigger pattern during authorized testing.
A logit is an unnormalized model score. A probability is produced by a transformation such as softmax or sigmoid. Thresholding a score is a separate policy decision.
The checkpoint, tokenizer, preprocessing code, framework, custom loader, adapter, and runtime together determine the released behavior. Record their digests and versions.
For a malware classifier, the same executable can be represented as bytes, an n-gram vector, an API-call sequence, or an embedding. For a language model, the same sentence can become different token IDs under a tokenizer revision. Security analysis must identify the representation actually used.
The forward pass applies the network to an input. In a simple layer, the model computes a weighted sum, adds a bias, and applies an activation function:
z = W · x + b a = activation(z) output = f(a)
Many layers compose this pattern. Convolutional networks learn local spatial filters; recurrent networks maintain a state over sequences; Transformer blocks use attention and feed-forward transformations. The security principle is the same: the output depends on the input, the ordered operations, and the exact parameter/configuration state.
During an investigation, capture a minimal request fixture and rerun it with the approved artifact. Compare preprocessing output, intermediate shapes, logits, post-processing, and final policy. This separates “the network produced a different score” from “the application sent a different tensor.”
A loss function turns a prediction and target into a number that the training process tries to minimize. Cross-entropy is common for classification; mean-squared error is common for regression; ranking and contrastive objectives are common for retrieval and representation learning.
The objective encodes what “better” means. Class weights, focal loss, label smoothing, reward models, safety penalties, and data filtering can all move the system toward different behavior. Security questions therefore include: who chose the objective, which examples had the greatest influence, and were safety constraints measured separately from task performance?
A lower aggregate loss does not prove lower security risk. A model can improve its average score while becoming less calibrated, more vulnerable to a rare trigger, or worse for a high-cost minority class. Always report the slice, threat model, and consequence.
Backpropagation applies the chain rule to compute how the loss changes with respect to each parameter. A gradient is not an attacker by itself; it is information about local sensitivity. In a white-box evasion test, an authorized evaluator may use input gradients to search for a small change that alters the prediction.
forward: x → activations → loss backward: loss → gradients for each operation update: parameter ← parameter − learning_rate × gradient
Gradients can also support diagnostics. Exploding gradients, vanishing gradients, saturated activations, or unstable validation loss may indicate an implementation or data problem. Preserve training logs and representative fixtures so a later analyst can tell a numerical failure from intentional manipulation.
An optimizer chooses how parameter updates use gradients. Stochastic gradient descent (SGD) uses batches of examples; momentum smooths updates; Adam adapts step sizes using running statistics. The learning rate, batch size, number of epochs, schedule, weight decay, initialization, and random seed can materially change the resulting artifact.
| Setting | What it changes | Evidence to retain |
|---|---|---|
| Learning rate / schedule | Step size and stability of parameter updates | Config, scheduler state, per-step loss, checkpoint lineage |
| Batch size / epochs | Gradient noise, exposure to examples, compute budget | Dataset version, batch policy, run metadata, stop reason |
| Initialization / seed | Starting point and reproducibility | Seed policy, framework version, hardware and determinism flags |
| Regularization | Trade-off between fit and generalization | Weight decay, dropout, augmentation, early-stopping decision |
Optimization is a build process. Treat the training runner, dependencies, data manifest, configuration, logs, and checkpoint as a software supply chain. A model digest without its build context cannot fully explain behavior.
Generalization is performance on conditions not used to fit or repeatedly tune the model. Overfitting occurs when the model learns training-specific patterns that do not transfer. Underfitting means the model has not captured enough useful structure. Both are security-relevant: overfitting can hide a backdoor or leak memorized data, while underfitting can create an evasion gap.
Regularization methods—weight decay, dropout, data augmentation, label smoothing, early stopping, and simpler architectures—can improve generalization, but they are not a security guarantee. Evaluate rare classes, campaign-held-out samples, temporal drift, and authorized adversarial transformations separately.
Deployment inputs or labels differ from development conditions. Example: a phishing detector trained on one language or mail gateway sees a new campaign family.
The relationship between input and target changes. Example: a malicious domain pattern becomes common in legitimate infrastructure, or a control changes the meaning of a label.
Training fits parameters. Validation supports configuration choices. Testing estimates behavior on held-out conditions. Production monitoring checks whether those conditions still apply. Reusing a test set during tuning turns it into validation data and weakens the claim.
For a phishing detector, random splitting can place near-duplicate messages from the same campaign in both train and test. A time-based, sender-held-out, or campaign-held-out split provides stronger evidence. For a RAG system, test authorization boundaries, not only answer quality. For an LLM classifier, record tokenizer and prompt-template revisions.
| Claim | Minimum evidence | Common failure |
|---|---|---|
| “The model is accurate” | Independent split, metric definition, class and time slices | Leakage, duplicates, or an unreported threshold |
| “The behavior is reproducible” | Artifact, code, config, data manifest, seed, runtime | Only a screenshot or model filename |
| “The model is robust” | Threat model, perturbation budget, attack knowledge, failure rate | One demo or an average score without attack conditions |
An adversarial example is an input intentionally modified to cause an unwanted model result under a specified threat model. The change may be visually or semantically small while being large in the representation consumed by the model. In security operations, this is an evasion capability—not automatically evidence of a real intrusion.
Goodfellow, Shlens, and Szegedy demonstrated gradient-based adversarial examples; Madry and colleagues framed robust optimization against first-order adversaries. These are foundational research results. To claim that a production detector is vulnerable, reproduce the result against the released artifact, document access assumptions, record the transformation, and measure the operational consequence.
Observed: a production event or provider report. Reproduced: the same failure under documented conditions. Demonstrated: a research proof-of-concept on a stated model. Inferred: a hypothesis connecting observations. Keep these categories separate in CTI and incident reports.
Poisoning changes training data or the training process so the learned model behaves incorrectly. A backdoor is a hidden condition—such as a trigger pattern—that causes a targeted behavior while ordinary validation appears normal. The attacker may target a dataset, labeling workflow, augmentation step, dependency, checkpoint, or model loader.
Security controls should therefore cover the full build: authenticated data sources, append-only manifests, reviewer separation for labels, isolated runners, pinned dependencies, signed artifacts, safe model loading, release approvals, and rollback. A clean model hash does not prove a clean dataset or training run.
When investigating a suspected poisoning event, preserve the original dataset and manifest, compare lineage against the approved version, search for unusual clusters or trigger correlations, rerun with a clean reference, and record what remains unknown. Do not overwrite the only copy by “cleaning” it in place.
Consider a classifier that scores Windows binaries for triage. It consumes byte n-grams and imported API names, then routes high-scoring files to quarantine. A threat-intelligence report describes a new loader family, and analysts add samples to the next dataset.
reported sample and provenance → extraction version and feature manifest → training run and checkpoint → held-out campaign test → score, threshold, and quarantine decision → analyst disposition and feedback
Several hypotheses can explain a missed sample:
Map the report to the exact observable claim: sample hash, collection source, timestamp, behavior, confidence, and corroboration. Then connect it to local evidence—feature output, model digest, configuration, inference event, and side effect. The CTI report guides the hypothesis; it does not replace local evidence.
| Security question | Control focus | Evidence |
|---|---|---|
| What was trained? | Data provenance, immutable manifests, label review | Source hashes, split IDs, label history, exclusions |
| How was it trained? | Isolated, reproducible build and least privilege | Code commit, lockfile, runner identity, seed, logs |
| What was released? | Signed artifact, loader isolation, approval and rollback | Checkpoint digest, signature, dependency SBOM, approval |
| What happened at inference? | Input validation, authorization, bounded policy effects | Caller, input hash, model/config IDs, score, decision, action |
Choose a local classifier or course-owned demo. Draw its computation graph, identify one parameter and one hyperparameter, rerun a fixed fixture, and write an evidence-based hypothesis for one changed output. Do not upload confidential data or test systems without authorization.
Chapter 4 will connect this mechanism to Transformers, tokenization, embeddings, attention, and LLM generation—then trace the new attack surfaces and CTI evidence requirements.