Everything to recall on one screen
Each line maps an exam phrase to the answer it usually points to.
If the question says… pick
| “Tabular data, classification or regression, best accuracy” | XGBoost (also LightGBM, CatBoost) |
| “Fast, cheap baseline; interpretable coefficients” | Linear Learner |
| “Huge, sparse one‑hot data; click or recommendation” | Factorization Machines |
| “Anomalies without labels” | Random Cut Forest |
| “Unusual IP address for this user” | IP Insights |
| “Group similar items, no labels” | K‑Means |
| “Too many correlated features” | PCA |
| “Forecast many related time series” | DeepAR |
| “Word vectors or fast text classification” | BlazingText |
| “Topics in documents” | LDA or NTM |
| “Translate or summarize sequences” | Seq2Seq (or a foundation model) |
| “Label, box or mask objects in images” | Image Classification, Object Detection, Semantic Segmentation |
| “Extract text and tables from scanned forms” | Amazon Textract, not a custom model |
| “Custom loss, custom architecture, standard framework” | Script Mode (PyTorch, TensorFlow, scikit‑learn) |
| “Library or runtime no AWS container provides” | Bring your own container (ECR image) |
| “Positive class under 1%” | scale_pos_weight or class weights; score with PR‑AUC |
| “Mistakes cost different amounts per row” | Sample weights (XGBoost csv_weights=1) |
| “Validation set has almost no positives” | Stratified split or StratifiedKFold |
| “Track parameters, metrics and artifacts for every run” | MLflow on SageMaker (managed MLflow) |
| “Cut training cost up to 90%” | Managed Spot Training + checkpoints |
| “Container must not reach the internet or AWS APIs” | enable_network_isolation=True |
| “Training must reach data in private subnets” | VPC config (subnets + security groups) and VPC endpoints |
| “Encrypt traffic between training nodes” | encrypt_inter_container_traffic=True |
| “Dataset too big or slow for one machine” | Data parallelism |
| “Model doesn’t fit in one GPU’s memory” | Model parallelism |
| “Find the CPU, GPU or memory bottleneck” | CloudWatch training metrics (Debugger is closed to new customers) |
| “Validation loss rises while training loss falls” | Overfitting: early stopping, regularization, simpler model |
Numbers and paths
- scale_pos_weight ≈ negatives / positives; at 0.5% fraud that is about 199
- Built‑in XGBoost CSV: label in column 1, no header
- Data channels: /opt/ml/input/data/<channel> (env
SM_CHANNEL_TRAIN) - Model output: /opt/ml/model (env
SM_MODEL_DIR) →model.tar.gzin S3 - Checkpoints: /opt/ml/checkpoints synced to
checkpoint_s3_uri - Spot: max_wait ≥ max_run; no automatic fallback to on‑demand
- Steps per epoch = training rows / batch size
Rare classes in one breath
- Don’t judge by accuracy; use PR‑AUC, recall, precision, F1
- Weight the rare class first; resample only the training set
- Stratify every split (or split by time, stratified within)
- Pick the decision threshold after training, from business costs
Training security in one breath
- Execution role: read the input prefix, write the output prefix, nothing more
volume_kms_keyandoutput_kms_keyfor customer managed keys- VPC for private data; network isolation to cut the container off entirely
- Tag and name every job (
base_job_name, tags)
MLA‑C02 tasks this module covers
Domain 2, ML Model and FM Development (24%). Also touches 1.3.5 (imbalance) and 4.2.6 (purchasing options).
The module on one page
From a business question to a versioned model, in the order you make the decisions.
Frame the problem before you pick a tool
The same data can answer different questions. Decide what the business will do with the output, then choose the problem type.
Real systems layer more than one model
SageMaker built‑in algorithms
Built‑ins are AWS‑maintained containers: you supply data and hyperparameters, AWS keeps the code patched. Stay on them while your problem fits; move to Script Mode when it doesn’t.
Algorithm picker
The four you’ll compare most
| XGBoost | Linear Learner | k‑NN | Random Cut Forest | |
|---|---|---|---|---|
| How it learns | Many small trees, each fixing the last one’s errors | A weighted sum of features, fit with SGD | Looks up the closest training rows at prediction time | Random trees; anomalies get isolated in few cuts |
| Needs labels | Yes | Yes | Yes | No |
| Explain it with | Feature importance, SHAP | Coefficients | The neighbours themselves | Anomaly score |
| Rare classes | scale_pos_weight | Class weights (positive_example_weight_mult) | No built‑in lever | Not applicable |
| Prediction speed | Fast | Fastest | Slows as data grows | Fast |
| Typical role | Main tabular model | Baseline to beat | Offline analysis, small sets | Watch for new patterns |
XGBoost hyperparameters, and which way to turn them
| Hyperparameter | What it controls | Typical | If overfitting |
|---|---|---|---|
objective | Task and loss | binary:logistic | n/a |
num_round | Number of trees | 100–1,000 | Fewer, or use early_stopping_rounds |
max_depth | Tree depth (capacity) | 3–10 | Lower |
eta | Learning rate per tree | 0.01–0.3 | Lower (add rounds) |
min_child_weight | Minimum weight to make a split | 1–10 | Higher |
subsample, colsample_bytree | Share of rows and columns per tree | 0.5–1.0 | Lower |
alpha, lambda | L1 and L2 regularization | 0–10 | Higher |
scale_pos_weight | Weight of the positive class | negatives / positives | n/a |
eval_metric | What validation reports | aucpr for rare classes | n/a |
What a training job actually does
One API call starts a sequence. You pay per second from the moment instances start until they shut down, so every stage costs money.
/opt/ml/output/failure, which shows up in the job’s failure reason.The minimum you specify
| Setting | Example | Why it matters |
|---|---|---|
| Container image | XGBoost 1.7‑1 via image_uris.retrieve | Pin a version; never rely on “latest” |
| Execution role | Read input prefix, write output prefix | Everything the job touches goes through it |
| Instance type and count | ml.m5.xlarge × 1 | Cost and speed |
| Input channels | train, validation with content type | Validation enables early stopping and model selection |
| Output path | s3://bucket/models/ | Where model.tar.gz lands |
| Name and tags | base_job_name, project tags | Find the job, and its cost, months later |
ModelTrainer; many examples still use the v2 Estimator. The concepts (image, role, channels, hyperparameters, Spot, checkpoints) are the same, and the exam tests the concepts.Training when the positive class is rare
Standard loss functions treat every mistake the same, so with 0.5% positives the cheapest thing a model can learn is “always negative”. These levers make the rare class count.
scale_pos_weight calculator
Per‑row costs without custom code
The built‑in XGBoost reads a weight per row when you set csv_weights=1: put the weight in the column right after the label. A missed $8,000 fraud can then count far more than a missed $6 one, with no Script Mode needed.
label, weight, f1, f2, ...
1, 42.0, ... ← expensive fraud
1, 1.3, ... ← small fraud
0, 1.0, ...
- Split first, then resample only the training data. Synthetic rows in validation or test inflate every metric.
- Inside cross‑validation, resample within each training fold, not before the folds are made.
Why PR‑AUC, not ROC‑AUC
100,000 transactions, 500 frauds, the model catches 400. Slide the number of false alarms.
The false‑positive rate (ROC’s x‑axis) divides by 99,500 negatives, so it barely moves. Precision (PR’s axis) divides by flagged rows, so it shows the damage.
Validation you can trust
One train/validation split can be lucky or unlucky, especially with few positives. K‑fold cross‑validation trains k times, holding out a different fold each time, and averages the scores.
| Split method | Use when |
|---|---|
| Stratified split / StratifiedKFold | Rows are independent and the positive class is rare |
| Time‑based split (TimeSeriesSplit) | You predict the future: fraud, demand, churn. Train on earlier periods, validate on later ones |
| Group split (GroupKFold) | Several rows per customer or device; keep each group on one side |
Experiment tracking
Every training run should be traceable: which data, which code, which settings, which result. On SageMaker the current answer is managed MLflow; the older SageMaker Experiments SDK lives on in Studio Classic.
mlflow.log_param, mlflow.log_metric and mlflow.log_artifact.Script Mode and your own containers
The contract between your script and SageMaker
| What | Path in the container | Environment variable |
|---|---|---|
| Each input channel | /opt/ml/input/data/<name> | SM_CHANNEL_<NAME> |
| Hyperparameters | passed as command‑line arguments | SM_HPS (all as JSON) |
| Model to keep | /opt/ml/model | SM_MODEL_DIR |
| Checkpoints | /opt/ml/checkpoints | synced to checkpoint_s3_uri |
| Other outputs | /opt/ml/output/data | SM_OUTPUT_DATA_DIR |
Anything left only on the instance disappears when the job ends; only /opt/ml/model becomes the model artifact.
Scaling out: data and model parallelism
| Tool | What to know |
|---|---|
| Built‑in XGBoost on several instances | Split the input into many files and set the channel to ShardedByS3Key, or each instance reads everything. GPU training uses tree_method=gpu_hist; multi‑GPU Dask training needs version 1.5‑1 or later. |
| SMDDP (SageMaker distributed data parallel) | PyTorch only; runs on ml.p4d.24xlarge and ml.p4de.24xlarge (ml.p3dn.24xlarge with no further optimization). TensorFlow support has ended. |
| SMP (SageMaker model parallel) | Shards large models across GPUs. |
| SageMaker HyperPod | Persistent, resilient clusters for long foundation‑model training runs. |
Security and cost for training
VPC is not the same as network isolation
Managed Spot Training
Spot uses spare capacity at up to 90% off. AWS can reclaim it, so the job must be able to resume.
| Parameter | Purpose |
|---|---|
use_spot_instances=True | Opt in |
max_run | Limit on training time |
max_wait | Limit on waiting plus training; must be at least max_run |
checkpoint_s3_uri | Where checkpoints sync. Built‑ins that support checkpointing use it; your own scripts must save to and reload from /opt/ml/checkpoints |
Spot savings estimate
Example inputs only. Check current SageMaker training prices and actual Spot savings for your instance and Region.
Match the instance to the algorithm
| Workload | Start with | Why |
|---|---|---|
| XGBoost, Linear Learner, scikit‑learn | General purpose CPU (ml.m5, ml.m6i) | Memory‑bound; GPUs sit idle unless you set GPU training |
| Big tabular data with GPU XGBoost | Single‑GPU (ml.g5) | gpu_hist can be cheaper per run on large data |
| Small neural networks | ml.m5 or ml.g4dn / ml.g5 | GPU helps, not required |
| Large deep learning | ml.g5/g6 multi‑GPU, ml.p4d/p5 | Fast GPU interconnect for distributed training |
| Cheapest deep‑learning training at scale | ml.trn1 (AWS Trainium) | Purpose‑built training chips |
Hands‑on project: decide like an engineer
Three situations you will meet when training for real. Pick an answer, then open the reasoning.
1. The validation curve turns
Training PR‑AUC keeps rising for all 800 rounds. Validation PR‑AUC peaks around round 120 and then slowly falls.
- Train for more rounds
- Use early stopping on the validation metric, and lower max_depth or eta
- Remove the validation channel to save time
Suggested answer
early_stopping_rounds keeps the best round automatically; lower depth, a smaller learning rate or more regularization reduce the urge to overfit. Without a validation channel you can’t see this at all.2. A Spot job that never finishes
A custom PyTorch job on Spot is interrupted twice and starts from epoch 1 each time, then hits max_wait and stops.
- Switch off Spot permanently
- Save checkpoints to /opt/ml/checkpoints each epoch, set checkpoint_s3_uri, and load the latest checkpoint at start
- Set max_wait equal to max_run
Suggested answer
3. Four instances, no faster
XGBoost on four ml.m5.2xlarge instances takes as long as on one. The training data is a single 20 GB CSV.
- Use bigger instances
- Split the data into many files and set the channel distribution to ShardedByS3Key
- Switch to Pipe mode
Suggested answer
ShardedByS3Key give each instance its own share. Also ask whether one instance was already fast enough.The build, step by step
- Split the engineered features by time (train, validation, test), checking each part still contains fraud.
- Baseline: Linear Learner with positive‑class weighting. Record PR‑AUC and recall.
- Main model: built‑in XGBoost with
scale_pos_weight,eval_metric=aucprand early stopping, on Spot with checkpoints. - Costs: a second XGBoost run with per‑row weights by amount (
csv_weights=1). Compare dollars of fraud caught, not just recall. - Track every run in MLflow with parameters, metrics and the model artifact.
- Lock down: rerun the winner inside a VPC with network isolation and KMS keys, and confirm the results match.
- Register the winner in the Model Registry with its metrics, ready for tuning.
- See why the metric matters: train once with
eval_metric=error(accuracy) and early stopping, once withaucpr. Compare the round each run stops at and the recall at the same threshold. The accuracy run looks great and catches far less fraud.
The rest of the exam guide for this module
Every skill MLA‑C02 lists for Tasks 2.1 and 2.2, where it’s covered, then a short lesson for each one the sections above don’t fully reach.
| Skill in the exam guide | Where |
|---|---|
| 2.1.1 Evaluate and select Bedrock foundation models | Deep dive 3 |
| 2.1.2 Fine‑tuning strategies for foundation models | Deep dive 4 |
| 2.1.3 Compare ML models, GenAI models, algorithms, solution templates | Sections 2–3, deep dive 8 |
| 2.1.4 Custom vs managed vs pre‑trained vs foundation models | Deep dive 2 |
| 2.1.5 RAG architecture patterns | Deep dive 5 |
| 2.1.6 Performance vs training time vs cost | Sections 9–10 |
| 2.1.7 AI performance vs latency vs cost | Deep dives 2–3 |
| 2.1.8 AWS AI services (Textract, Rekognition, Comprehend, Transcribe) | Deep dive 1 |
| 2.2.1 Built‑in algorithms and common libraries | Section 3 |
| 2.2.2 Script Mode with supported frameworks | Section 8 |
| 2.2.3 Hyperparameter optimization (AMT) | Deep dive 9, next module |
| 2.2.4 Early stopping, distributed training | Section 9, deep dive 6 |
| 2.2.5 Overfitting, underfitting, catastrophic forgetting | Deep dives 4 and 6 |
| 2.2.6 Combine models (ensembles) | Deep dive 7 |
| 2.2.7 Epochs, steps, batch size | Deep dive 6 |
| 2.2.8 Prompt engineering and fine‑tuning | Deep dives 2 and 4 |
| 2.2.9 Optimize retrieval and embedding models | Deep dive 5 |
| 2.3.1 Reproducible experiments (MLflow, Bedrock evaluations) | Section 7 |
Deep dive 1: use an AI service before building a model
| If the task is… | Service |
|---|---|
| Text, forms, tables from scanned documents | Amazon Textract |
| Objects, faces, labels, unsafe content in images and video | Amazon Rekognition (Custom Labels for your own classes) |
| Sentiment, entities, key phrases, PII in text | Amazon Comprehend (custom classifiers too) |
| Medical entities in clinical notes | Amazon Comprehend Medical |
| Speech to text | Amazon Transcribe |
| Text to speech | Amazon Polly |
| Translation | Amazon Translate |
| Chatbots with intents and slots | Amazon Lex |
| Recommendations from user‑item interactions | Amazon Personalize |
Deep dive 2: build, buy or adapt
| Need | Prompting | RAG | Fine‑tuning |
|---|---|---|---|
| Up‑to‑date or private facts | Only what fits the prompt | Best | Poor; facts go stale |
| Consistent format, tone or task skill | Often enough | Doesn’t help | Best |
| Data needed | None | Documents | Labeled pairs |
| Time and cost to start | Lowest | Medium | Highest |
Deep dive 3: choosing a Bedrock foundation model
- Fit: modality (text, image, embeddings), languages, context window, tool use.
- Quality: test on your own examples with Bedrock model evaluations (automatic metrics, human review, or LLM‑as‑a‑judge).
- Latency and cost: price per input and output token; smaller models are faster and cheaper; consider batch inference for offline jobs.
- Customization: only some models support fine‑tuning or distillation; check before committing.
- Constraints: Region availability, data handling and licence terms.
Deep dive 4: fine‑tuning strategies and catastrophic forgetting
| Strategy | What changes | Use when |
|---|---|---|
| Supervised fine‑tuning (Bedrock or SageMaker) | Model weights, from prompt‑response pairs | A task or format the base model does poorly |
| Parameter‑efficient (LoRA and similar) | Small adapter weights only | Cheaper training, keeps base knowledge, many adapters per base |
| Continued pre‑training | Weights, from unlabeled domain text | Domain vocabulary and style; available for selected models |
| Distillation | A smaller student learns from a larger teacher | Teacher quality at lower latency and cost |
| Reinforcement fine‑tuning | Weights, from rewards a function assigns | Quality is easy to score but hard to label |
Deep dive 5: RAG patterns in brief
- Basic RAG: embed the question, retrieve the top chunks from a vector store, add them to the prompt.
- Hybrid search: keyword plus vector search; better for exact terms like product codes.
- Reranking: retrieve many, let a reranker model order them, keep the best few.
- Metadata filtering: restrict retrieval by date, department or access rights.
- Agentic RAG: an agent decides when and what to retrieve, possibly several times.
- Improve retrieval first: chunking, embedding model choice and reranking usually matter more than swapping the generator model. Bedrock Knowledge Bases manages most of this.
Deep dive 6: overfitting, underfitting, epochs and batches
| Symptom | Fixes |
|---|---|
| Underfitting: training and validation both poor | More capacity (deeper trees, bigger network), better features, train longer, less regularization |
| Overfitting: training good, validation poor | Early stopping, regularization (L1/L2, dropout), simpler model, more data or augmentation |
Epochs, steps and batch size
One epoch is one pass over the data; one step is one batch. Larger batches mean fewer, smoother steps and usually need a larger learning rate; too large can generalize worse.
Deep dive 7: combining models
| Method | How | Example |
|---|---|---|
| Bagging | Train many models on random samples, average them | Random forest; lowers variance |
| Boosting | Train models in sequence, each fixing the last one’s errors | XGBoost, LightGBM; lowers bias |
| Stacking | A meta‑model learns from several models’ predictions | Linear model on XGBoost + neural net outputs |
| Cascades | A cheap model handles easy cases, an expensive one the rest | Cuts inference cost |
Deep dive 8: managed shortcuts
- SageMaker JumpStart: pre‑trained models (including foundation models) and solution templates you can deploy or fine‑tune in a few clicks.
- SageMaker Autopilot / Canvas: AutoML that tries algorithms and settings for tabular data and explains the result; Canvas adds a no‑code interface.
- AutoGluon‑Tabular: a built‑in that stacks and ensembles many models automatically.
Deep dive 9: hyperparameter tuning, a preview
SageMaker Automatic Model Tuning (AMT) runs many training jobs and searches the settings for you: grid, random, Bayesian or Hyperband search, with early stopping of poor trials. The next module covers it with evaluation and thresholds.
Self‑check questions
Answer each one aloud first, then open it to check.
1. When is a built‑in algorithm the right choice, and when do you move to Script Mode?
Use a built‑in when the problem fits its task, loss and data format: you get an AWS‑maintained, patched container with almost no code. Move to Script Mode when you need a custom loss, a new architecture or a library the built‑ins lack, using an AWS framework container with your own script. Only build your own container when no AWS container can run your code. Each step up adds maintenance you own.
2. What does scale_pos_weight do, and how do you set it?
It multiplies the weight of positive examples in XGBoost’s loss, so missing a positive costs more. A common starting value is the number of negatives divided by positives in the training data: about 199 when positives are 0.5%. Tune it from there, and pair it with a PR‑based metric.
3. Why can ROC‑AUC look great on a rare‑class problem while PR‑AUC looks poor?
ROC plots recall against the false‑positive rate, which divides false alarms by all negatives. With 99.5% negatives, thousands of false alarms barely move that rate. PR plots precision against recall; precision divides by everything flagged, so false alarms show up immediately. PR‑AUC reflects what a fraud team actually experiences.
4. How do you split data for a rare, time‑ordered problem like fraud?
Split by time so training data comes before validation and test data, as in production. Check each split still contains enough positives; within a period, stratify. For cross‑validation use time‑ordered folds, or StratifiedKFold when rows are independent. Keep the test set out of everything until the end.
5. What do you need to set for Managed Spot Training to work safely?
use_spot_instances=True, max_run, a max_wait at least as long as max_run to allow waiting for capacity, and checkpoint_s3_uri. Your own scripts must write checkpoints to /opt/ml/checkpoints and reload them at start. If max_wait runs out, the job stops.
6. Data parallelism or model parallelism: how do you choose?
If the model fits on one GPU and the limit is data size or time, use data parallelism: each device holds a full copy and processes part of the data, then gradients are averaged. If the model itself doesn’t fit in one GPU’s memory, use model parallelism to split it across devices. Profile first; many slow jobs are data‑loading bound.
7. How is network isolation different from running a training job in a VPC?
A VPC config attaches the job to your subnets and security groups so it can reach private resources; the container can still make outbound calls if routing allows. Network isolation blocks all outbound calls from the container, including to S3 and AWS APIs, and gives it no credentials; SageMaker moves the data for it. You can use both together.
8. What should every experiment run record, and where?
Parameters, metrics computed by the code, artifacts (model file, plots), and lineage (data version, code commit, job name). On SageMaker, managed MLflow is the current choice; the best run’s model goes into the Model Registry with its metrics and an approval status.
9. A business needs extraction of fields from invoices. Why not train a model?
Amazon Textract already extracts text, forms and tables from documents with no training data or ML maintenance. Building a custom model costs labeled data, training and upkeep for a solved problem. Climb to custom models only when a managed service or foundation model can’t meet the requirement.
10. What is catastrophic forgetting, and how do you limit it?
After fine‑tuning on a narrow dataset, a model can lose general abilities it had before. Limit it with a lower learning rate, fewer epochs, parameter‑efficient methods such as LoRA, and some general examples in the training mix, then re‑test general tasks.
Exam drill
Scenario questions in the exam’s style. Tap an answer to see why.
0 / 0Common traps and outdated advice
Mistakes that show up often in tutorials and sample code, with the fix.
- “You can’t rank customers with a classifier” is wrong: classifiers output probabilities, and sorting by probability is the standard way to spend a fixed review budget.
- A stratified random split on time‑ordered data lets the model learn from the future. For fraud, churn and demand, split by time and check each period still has positives.
- Cross‑validating on the full dataset, test rows included, leaks the test set. Cross‑validate on training data only.
- Recommending PR‑AUC but setting
eval_metric='auc'is a common mismatch. For rare classes, useaucprfor early stopping and model selection. - Experiment logs must hold metrics your code computed. Typed‑in example numbers make the whole audit trail meaningless.
- Per‑row weights don’t require Script Mode: the built‑in XGBoost reads them from the column after the label when
csv_weights=1. - Putting a job in a VPC does not, by itself, stop the container reaching the internet.
enable_network_isolation=Truedoes. - SMDDP supports PyTorch on ml.p4d.24xlarge and ml.p4de.24xlarge, with ml.p3dn.24xlarge still usable but no longer optimized. TensorFlow support has ended.
- SageMaker Debugger is closed to new customers. Use CloudWatch for system metrics, MLflow for tracking and TensorBoard for model internals.
- Spot checkpointing is automatic only for built‑ins that support it. Custom scripts must save and load checkpoints themselves.
- “XGBoost can’t use GPUs” is outdated: the built‑in supports
tree_method=gpu_hist, and multi‑GPU Dask training from version 1.5‑1. - Resampling (SMOTE or undersampling) before splitting puts synthetic copies of training rows into validation and test. Split first.
- SageMaker Python SDK v3 replaces the v2
EstimatorwithModelTrainer. Older examples still work on v2; the concepts are the same.