AI Security Engineering / Module 00

AI, Machine Learning & LLM Foundations

The technical foundation and canonical vocabulary for the entire course. Understand what models actually learn, how LLM applications move data and authority, and where security-relevant boundaries appear.

Foundation bridgeNo advanced mathematics170+ canonical terms
Under construction. Terminology and exercises are being prepared for pilot delivery. Definitions are versioned because the field changes quickly.

Module contents

  1. Outcomes and terminology rules
  2. Learning path
  3. 1. AI, ML, and deep learning
  4. 2. How machine learning learns
  5. 3. Neural networks and optimization
  6. 4. Transformers and LLM generation
  7. 5. LLM lifecycle and adaptation
  8. 6. Embeddings and RAG
  9. 7. Agents, tools, memory, and MCP
  10. 8. Evaluation, serving, and MLOps
  11. 9. Architecture-trace practical
  12. 10. Knowledge check

Outcomes and course terminology rules

Explain the technology

Distinguish AI, ML, deep learning, generative AI, foundation models, LLMs, RAG, and agents without using them as synonyms.

Trace the system

Follow data from raw input through preprocessing, tokenization, model inference, retrieval, tools, memory, output, and telemetry.

Interpret evidence

Read training, evaluation, and performance claims with the right metrics, datasets, baselines, thresholds, and limitations.

Prepare for security

Identify assets, identities, trust boundaries, state changes, and control points before studying individual attacks.

Normative rule

The course glossary defines how terminology is used in learner work. When a source uses an overloaded term differently, quote or restate that source’s meaning. A model is never shorthand for the complete AI system.

Learning path

BlockActivity
1AI, ML, deep learning, and problem types
2Data, learning paradigms, training, and evaluation
3Neural networks and optimization
4Transformers, tokens, embeddings, and generation
5Pre-training, post-training, adaptation, and serving
6RAG architecture and retrieval evaluation
7Agents, tools, memory, and MCP
8Deployment, MLOps, performance, and observability
9Architecture trace and terminology clinic
10Knowledge check and review

Block 1

1. AI, ML, deep learning, and generative AI

Artificial Intelligence
├── rule-based, search, planning, knowledge, optimization, robotics …
└── Machine Learning
    ├── classical statistical and algorithmic ML
    └── Deep Learning
        ├── discriminative models
        └── generative models
            ├── diffusion and other families
            └── foundation models
                └── large language models

These are overlapping levels, not interchangeable labels. AI describes the broad capability and field. ML learns behavior from data or experience. Deep learning is ML using multilayer neural networks. Generative AI produces new content. A foundation model is broadly reusable. An LLM is a large language model, usually Transformer-based.

TaskTypical outputExample security use
ClassificationDiscrete class or probabilityMalicious / benign file prediction
RegressionContinuous valueExpected incident cost or anomaly score
ClusteringGroups without fixed labelsInfrastructure or behavior grouping
Ranking / retrievalOrdered candidatesRelevant threat-report passages
GenerationNew sequence or mediaReport draft, code, query, image, or audio
Policy / controlAction selectionAgent chooses a tool or next investigative step

Checkpoint

Classify five systems you use by task and technique. For each, name the complete system, the model component, the output, and whether the model can change real-world state.

Block 2

2. How machine learning learns

Supervised

Learns from input–target pairs. Typical tasks are classification and regression.

Unsupervised

Finds structure without explicit labels, such as clustering or dimensionality reduction.

Self-supervised

Derives learning targets from the data itself, such as masked-token or next-token prediction.

Semi-supervised

Combines a smaller labeled set with a larger unlabeled set.

Reinforcement learning

Learns action policy through state, action, reward, and return.

Transfer learning

Reuses representations or parameters learned on one setting for another task or domain.

Collect and document data
  → clean, transform, label, and split
  → select architecture and objective
  → initialize parameters
  → train on batches
  → validate and tune hyperparameters
  → evaluate once on held-out test conditions
  → release a specific artifact
  → monitor inputs, behavior, outcomes, cost, and drift
  → retrain, roll back, replace, or retire

Parameters versus hyperparameters

Parameters are learned values such as weights. Hyperparameters are selected configuration such as learning rate, batch size, regularization, architecture depth, and decoding settings. The distinction matters for provenance and incident reconstruction.

Generalization versus memorization

Training loss measures the optimization objective on training examples. Validation supports development choices. A test set estimates behavior on held-out data only if it has not become part of iterative tuning. Strong benchmark performance can coexist with poor deployment performance, privacy leakage, or adversarial fragility.

Checkpoint

Given a phishing classifier, define its features, labels, train/validation/test split, false-positive cost, false-negative cost, drift signal, and one way test leakage could inflate the result.

Block 3

3. Neural networks and optimization

input tensor
  → weighted transformation
  → activation function
  → hidden representations through multiple layers
  → output logits or values
  → loss against target
  → backpropagation computes gradients
  → optimizer updates parameters

A neuron or unit combines numeric inputs with learned weights and usually a bias, then applies an activation. Layers compose these transformations. A forward pass computes output. A loss function quantifies training error. Backpropagation applies the chain rule through the computation graph. An optimizer such as Adam uses gradients to update weights.

Underfitting

The model does not learn enough structure; both training and validation performance remain inadequate.

Overfitting

The model fits training-specific patterns and fails to generalize. It can also increase privacy risk.

Regularization

Constraints such as weight decay, dropout, augmentation, or early stopping intended to improve generalization.

Distribution shift

Deployment inputs, targets, or environment differ from development conditions—naturally or adversarially.

Security connection

White-box attackers may use gradients to craft adversarial inputs. Poisoning changes what the model learns. Model extraction approximates behavior. Membership inference and inversion target information encoded by learning.

Block 4

4. Transformers, tokenization, and LLM generation

From text to tokens

A tokenizer converts raw text into token IDs using a versioned vocabulary and algorithm. Tokens may be words, fragments, bytes, punctuation, or special control markers. Tokenization changes length, cost, truncation, multilingual behavior, and attack representation.

From tokens to representations

Token IDs are mapped to embeddings. Positional information represents order. Transformer layers combine self-attention, feed-forward transformations, residual connections, and normalization to build contextual representations.

messages and application context
  → model-specific chat template
  → tokenizer → token IDs
  → token and position representations
  → repeated Transformer layers
      self-attention: query–key relevance weights value information
      feed-forward network: transforms each position
  → logits for possible next tokens
  → decoding policy selects one token
  → append token and repeat until stop condition

For one attention head, the common conceptual form is Attention(Q,K,V) = softmax(QKᵀ / √d) V. Learners do not need to derive it, but must understand that attention is learned weighted information flow—not a factuality or authorization mechanism.

Decoding controlMeaningImportant limitation
TemperatureRescales logits before samplingLow temperature does not guarantee service-level determinism
Top-kRestricts sampling to k highest-probability tokensCan remove low-ranked but correct alternatives
Top-pUses the smallest set reaching cumulative probability pThe candidate set changes at every step
Maximum tokensBounds generated lengthDoes not bound tool loops or total workflow cost
Stop sequenceStops on configured token patternsTokenization and encoding can affect matching

What an LLM does not provide by itself

A language model does not inherently provide current knowledge, tenant authorization, secret handling, factual verification, stable identity, policy enforcement, transactional integrity, or safe action execution. The application must provide those controls.

Block 5

5. LLM lifecycle: from pre-training to serving

data collection and filtering
  → tokenizer and architecture selection
  → large-scale pre-training
  → base checkpoint
  → supervised / instruction fine-tuning
  → preference alignment: RLHF, DPO, or related methods
  → safety, capability, and task evaluation
  → optional domain adaptation: full fine-tune, LoRA/PEFT, adapters
  → quantization or distillation
  → registry and release approval
  → serving, routing, monitoring, updates, and retirement
TechniqueChanges weights?Primary use
Prompting / few-shot examplesNoChange current-context behavior
RAGNormally noAdd external knowledge at inference time
Fine-tuning / SFTYesAdapt task, domain, style, or instruction behavior
LoRA / PEFTAdds or updates a smaller parameter setCheaper adaptation
RLHF / DPOYesOptimize preferences or desired behavior
QuantizationChanges numeric representationReduce memory, latency, or cost
DistillationTrains a new studentTransfer selected teacher behavior to a smaller model

Artifact inventory

For one LLM release, list the base checkpoint, tokenizer, configuration, adapter, prompt template, evaluation set, decoding configuration, quantization, runtime, registry entry, and serving route. Which change could explain an unexpected behavior change?

Block 6

6. Embeddings and retrieval-augmented generation

RAG combines a generative model’s parametric knowledge with retrieved external information. Ordinary RAG does not retrain the LLM. It changes inference context.

OFFLINE / INGESTION
source → parse → normalize → split into chunks → preserve metadata and ACL
       → embedding model → vector / lexical index

ONLINE / QUERY
user and tenant identity → query → optional rewrite/decomposition
  → dense, sparse, or hybrid retrieval with authorization filters
  → optional reranking → selected chunks with provenance
  → prompt augmentation → LLM generation
  → citation and support validation → response
MeasureQuestion answered
Recall@kDid the top k retrieved items include the relevant evidence?
Precision@kHow much of the top k was relevant?
Mean reciprocal rankHow early did the first relevant item appear?
Groundedness / faithfulnessAre generated claims supported by supplied evidence?
Citation precision / recallAre citations supportive, and are relied-upon sources cited?
Authorization correctnessWas every retrieved item permitted for the initiating identity and tenant?

Security connection

Chunks and embeddings inherit data sensitivity and access requirements. Retrieval can create cross-tenant exposure, poisoning, stale-data use, indirect prompt injection, and provenance loss. Authorization must occur before sensitive content enters model context.

Block 7

7. Agents, tools, memory, and MCP

An agent is a system pattern, not a special magical model. It connects model output to state, tools, and repeated execution.

goal and initiating identity
  → observe context and state
  → plan or choose next step
  → propose tool and structured arguments
  → application validates policy and authorization
  → optional human approval bound to exact action
  → execute with scoped workload identity
  → observe result and write controlled memory
  → repeat within time, cost, step, and authority limits

MCP architecture

An MCP host is the AI application. It creates one or more clients, each connected to a server. MCP separates a JSON-RPC data layer from transport. Servers can expose three core primitives:

Tools

Executable functions the AI application may invoke to retrieve information or change state.

Resources

Data or content managed by the application and supplied as context.

Prompts

Reusable interaction templates or workflows selected for model conversations.

Clients may also support sampling and other capabilities. “Model-controlled” does not mean “model-authorized.” Applications must authenticate endpoints, validate schemas, enforce user and tenant authorization, constrain tools, display material actions, bind approvals, log definitions and calls, and control egress.

Memory types

MemoryExampleSecurity concern
Working / contextCurrent conversation and scratch stateSensitive context, injection, truncation
EpisodicPast actions or sessionsCross-session or cross-user leakage
SemanticFacts, summaries, vector-retrieved knowledgePoisoning, staleness, provenance
ProceduralReusable workflows or policiesUnauthorized modification or shadowing

Block 8

8. Evaluation, model serving, and MLOps

Evaluate the complete system

DimensionExamples
Task qualityAccuracy, precision, recall, F1, success rate, human rubric
GenerationTask success, groundedness, citation support, format validity
RetrievalRecall@k, precision@k, ranking, authorization correctness
SecurityAttack success rate, control-bypass rate, unauthorized action rate, data exposure
ReliabilityVariance, retry behavior, availability, drift, graceful failure
OperationsLatency, time to first token, tokens/second, throughput, cost, GPU/CPU/memory

Serving path

client → authentication and quota → model gateway / router
  → prompt and policy processing → selected model runtime
  → accelerator and cache → streamed or complete output
  → validation / tool orchestration → telemetry and billing

MLOps adds versioning and governance for data, models, code, configuration, evaluation, registry stages, deployment, monitoring, rollback, and retirement. An incident record must identify the exact model, tokenizer, adapter, prompt template, retrieval index, tool definitions, policy, runtime, and route—not only a vendor model name.

Three non-equivalences

Helpful is not necessarily factual. Safe is not necessarily secure. High benchmark performance is not necessarily robust production behavior.

Block 9

9. Practical: trace three architectures

Trace the same user question through three progressively capable systems:

  1. a hosted chat LLM;
  2. a tenant-aware RAG assistant;
  3. a RAG agent that can create a ticket through MCP.

For every architecture, record

  • raw inputs, transformations, tokens, context, and outputs;
  • model, tokenizer, embedding model, reranker, and versions;
  • user, workload, tool, and data-source identities;
  • retrieval and authorization decisions;
  • state-changing tools, arguments, approval, and result;
  • trust boundaries and data sensitivity;
  • quality, security, performance, and cost metrics;
  • telemetry required to reconstruct one request.

Terminology clinic

Correct this statement using the glossary:

“The AI learned our PDF during inference, stored it in its neural-network
database, reasoned deterministically, and securely called the MCP API.
The 95% accuracy score proves the agent is safe.”
Expected corrections
  • Ordinary RAG retrieves PDF chunks into context; it does not update model parameters.
  • A vector store is not the neural network’s parametric memory.
  • Generation and tool selection are not guaranteed deterministic.
  • MCP is a protocol; security depends on authentication, authorization, validation, permissions, approval, and transport.
  • Accuracy requires a defined task, dataset, threshold, and class balance and does not prove agent safety or security.

10. Knowledge check

1. How do AI, ML, deep learning, generative AI, and LLM relate?
AI is broadest. ML is an AI approach that learns from data or experience. Deep learning is ML using multilayer neural networks. Generative AI produces content. LLMs are large language models, generally deep Transformer foundation models.
2. What changes model parameters?
Training and fine-tuning methods change parameters. Ordinary prompting, inference, and RAG do not.
3. What is the difference between a parameter and hyperparameter?
A parameter is learned during training; a hyperparameter is selected configuration controlling architecture, training, or inference.
4. What does self-attention do?
It computes learned relevance between positions and mixes value information into contextual representations. It does not validate truth or authorization.
5. Why is a token not a word?
Tokenizers can represent words, subwords, bytes, punctuation, and special markers. Boundaries vary by tokenizer and language.
6. What is the difference between RAG and fine-tuning?
RAG adds external information to inference context. Fine-tuning updates model parameters using additional training.
7. What are MCP’s server primitives?
Tools, resources, and prompts. Tools can perform actions, resources provide context, and prompts provide reusable templates.
8. Why is a tool call not authorized merely because the model selected it?
The model is not an enforcement point. The application must validate arguments and enforce user, tenant, identity, approval, and destination policy.
9. Why can a test score be misleading?
It depends on dataset, leakage, baseline, threshold, aggregation, class balance, repeated tuning, and deployment distribution. It measures only the defined task.
10. What must identify an AI production state?
At least model/checkpoint, tokenizer, configuration, adapters, prompt template, retrieval index, embedding/reranking versions, tool definitions, policies, runtime, route, and relevant data versions.

Authoritative reading