CertNote/ Commute Study Notes
Roadmap
KOEN
CLF-C02 · FoundationalCloud Practitioner - Foundational
DVA-C02 · AssociateDeveloper - Associate
SAA-C03 · AssociateSolutions Architect - Associate
SOA-C02 · AssociateCloudOps Engineer - Associate
SAP-C02 · ProfessionalSolutions Architect - Professional
DOP-C02 · ProfessionalDevOps Engineer - Professional
Linux Master 2 · 2급KAIT Linux Master - Level 2
SCS-C03 · SpecialtySecurity - Specialty
Linux Master 1 · 1급KAIT Linux Master - Level 1
MLA-C01 · AssociateMachine Learning Engineer - Associate
AIF-C01 · FoundationalAI Practitioner - Foundational
DEA-C01 · AssociateData Engineer - Associate
MLS-C01 · SpecialtyMachine Learning - Specialty
  • Week 1
    • 1.The ML Lifecycle (from a Specialty Perspective)
    • 2.Data Storage for ML: S3, EFS, FSx for Lustre, and Data Formats
    • 3.Data Ingestion: Kinesis, Glue, Batch vs. Streaming
    • 4.Data Labeling: SageMaker Ground Truth, Active Learning, Label Quality
    • 5.Week 1 Comprehensive Review: ML Overview & Data Engineering 1
  • Week 2
  • Week 3
  • Week 4
  • Week 5
  • Week 6
  • Week 7
  • Week 8
  • Week 9
    • 1.Classification Evaluation Metrics: Accuracy, Precision, Recall, F1, and the Confusion Matrix
    • 2.ROC/AUC and Threshold Tuning: Reading Model Performance from Curves
    • 3.Regression Evaluation Metrics: RMSE, MAE, MAPE, R², and Residual Analysis
    • 4.Model Debugging and Bias: SageMaker Debugger and Clarify
    • 5.Week 9 Comprehensive Review: Evaluation and Debugging
  • Week 10
  • Week 11
  • Week 12
SQLD · 개발자SQL Developer (SQLD)

© CertNote · 주간랩스

  • About
  • Changelog
  • Contact
  • Terms
  • Privacy
← MLS-C01/Week 9/Day 4

Based on the MLS-C01 exam guide·Report an error

MLS-C01· AssociateWeek 9 · Day 4~31 min read

Day 4 - Model Debugging and Bias: SageMaker Debugger and Clarify

📌 Key Takeaways

  • Even when the metrics look good, a model can break during training (vanishing gradients, overfitting), be unfair to certain groups, or be an inexplicable black box.
  • Debugger = the health of the training process. It captures tensors (weights, gradients, loss, activations), detects anomalies with rules, and automatically stops broken jobs to save cost.
  • Clarify = bias + explainability. It measures pre-training (data) and post-training (prediction) bias with metrics and explains predictions with SHAP.
  • Even if the data looks fair before training, the model can amplify bias, so check both the pre and post stages.
  • The last layer is the error analysis done by humans. Group the wrong cases and fix the largest error bucket first.

Three Layers of Model Debugging

Fixing a model splits into three different questions. The exam hints at which layer it is through the keywords planted in the passage.

LayerToolQuestion it answersPassage keywords
Training processSageMaker DebuggerIs training converging normally?gradients, loss, tensors, overfitting, job stop
Fairness and trustSageMaker ClarifyAre outcomes fair across groups? / Why this prediction?gender/race, regulation, Disparate Impact, SHAP
Error patternsError analysis (human)Where and how does it go wrong?performance plunges only in a certain range

The three layers have an order. If training never converged in the first place (layer 1), measuring bias metrics (layer 2) is meaningless, and if training is normal but only a certain range is bad (layer 3), the cause is the data rather than the hyperparameters.

SageMaker Debugger: Looking Inside the Training Process

Debugger periodically captures tensors during training (weights, gradients, loss, activations, and so on), saves them to S3, and automatically detects anomalies with Rules. It notices early when training is heading in the wrong direction.

from sagemaker.debugger import Rule, rule_configs, DebuggerHookConfig
 
rules = [
    Rule.sagemaker(rule_configs.vanishing_gradient()),   # Vanishing gradients
    Rule.sagemaker(rule_configs.overfit()),              # Overfitting
    Rule.sagemaker(rule_configs.loss_not_decreasing()),  # Loss stagnation
    Rule.sagemaker(rule_configs.exploding_tensor()),     # Divergence
]
 
estimator = Estimator(
    ...,
    rules=rules,
    debugger_hook_config=DebuggerHookConfig(s3_output_path="s3://bucket/debug"),
)

Symptom → Rule → Action

Symptom during trainingRule that firesProblem detectedTypical action
Loss barely moves and the deep layers aren't learningvanishing_gradientGradients converge to 0 → training stallsChange activation function/initialization, residual connections, normalization layers
Loss jumps to NaN/Infexploding_tensorValues diverge (NaN/Inf)Lower the learning rate, gradient clipping, input scaling
Training loss ↓ validation loss ↑overfitGap between validation and training lossEarly stopping, regularization, data augmentation
Loss stays the same over many stepsloss_not_decreasingLoss isn't decreasingRevisit learning rate, optimizer, features
The minority class is effectively ignoredclass_imbalanceClass imbalanceResampling, class weights, switch metrics
Training looks off from the startpoor_weight_initializationBad initializationChange the initialization method (He/Xavier, etc.)

When a rule fires, it can send a notification through CloudWatch Events/EventBridge, or automatically stop (early stopping) the broken training job to save cost.

The value of Debugger is "catching failures early to reduce cost." GPU time for deep learning training is expensive, so discovering a job with vanishing gradients or diverging loss only after running it to the end is a big waste. Debugger rules detect this midway through training and trigger automatic stop/notification, solving both "debugging why it doesn't work" and "preventing wasted money."

⚠️ Pitfall: Debugger looks at the state during training. Operational drift, where the input distribution of a deployed model changes, is the domain of Model Monitor, and group fairness is the domain of Clarify. Some answer choices mix the three.

SageMaker Clarify: Bias and Explainability

Clarify does two things: bias detection and explainability (SHAP). It is essential in domains where fairness regulation or model trust matters.

Pre-training Bias

Before building the model, it measures the bias of the data itself. Using sensitive attributes (gender, race, age, and so on) as the basis, it checks whether the class/label distribution is skewed.

MetricNameWhat it measures
CIClass ImbalanceHow over- or under-represented a group's samples are
DPLDifference in Positive Proportions in LabelsDifference in the proportion of positive labels between groups
KL / JS DivergenceKullback-Leibler / Jensen-ShannonThe distance between label distributions across groups

Post-training Bias

It measures whether the trained model's predictions are unfair across groups.

MetricNameWhat it measures
DPPLDifference in Positive Proportions in Predicted LabelsDifference in the proportion of positive predictions between groups
DIDisparate ImpactThe ratio of positive prediction rates between groups
RDRecall DifferenceDifference in recall between groups
ADAccuracy DifferenceDifference in accuracy between groups

Even if the data looks fair before training, the model can amplify bias, so check both stages.

Which Bias Metric to Look at by Situation

SituationMetric to look atReason
A certain group's samples are too few to begin withCI (pre-training)The data is already skewed before the model is even built
The approval/acceptance labels in the data differ by groupDPL (pre-training)The bias of past decisions is embedded in the labels
You must report the "approval rate ratio between groups" for regulatory complianceDI (post-training)Being a ratio, it's easy to use for reporting against a baseline
Many missed cases (FN) occur in only one groupRD (post-training)A recall difference is exactly "who gets missed more"
You want to summarize performance differences by group in one numberAD (post-training)But always look at the pitfall below together

⚠️ Pitfall: An accuracy difference (AD) near zero does not mean fair. If a minority group has extremely few positive cases, accuracy comes out high even when the model labels that entire group negative. That is, AD can look fine while RD (recall difference) is dismal. The principle "don't trust accuracy on imbalanced data" applies to group metrics as well: you must look at DI, DPPL, and RD together.

At Which Stage Is Bias Mitigated

Clarify is a tool for measuring bias. Actual mitigation depends on which point in the pipeline you intervene.

TimingWhat you touchTypical meansLimitation
Pre-processingTraining dataResampling, reweighting, removing proxy variablesBias in the original labels may remain
In-processingObjective function and training procedureAdd fairness constraints/penalties to the lossLimits the choice of algorithm
Post-processingPrediction results and thresholdsPer-group threshold adjustmentThe causes of bias inside the model remain

The measurement points are clear. Verify the effect of pre-processing with the pre-training bias metrics (CI, DPL), and the effects of in-processing and post-processing with the post-training bias metrics (DPPL, DI, RD).

SHAP-Based Explainability

Clarify computes SHAP (SHapley Additive exPlanations) values to quantify "how much, and in which direction, each feature pushed this prediction." It distributes feature contributions fairly based on Shapley values from game theory.

from sagemaker.clarify import (
    SageMakerClarifyProcessor, BiasConfig, DataConfig, ModelConfig, SHAPConfig
)
 
bias_config = BiasConfig(
    label_values_or_threshold=[1],
    facet_name="gender",          # Sensitive attribute
    facet_values_or_threshold=[0],
)
shap_config = SHAPConfig(baseline=baseline_rows, num_samples=100)
 
clarify_processor.run_bias(data_config, bias_config, model_config)
clarify_processor.run_explainability(data_config, model_config, shap_config)
ScopeWhat it tells youTypical use
Global importanceHow important a feature is on average across all the dataModel review, feature cleanup, hunting for proxy variables
Local explanationWhy this single prediction came out the way it didExplaining individual decisions to customers and auditors

Combined with SageMaker Model Monitor, you can also track changes in feature contributions during operation (explainability drift).

Bias and explainability are different problems. Bias metrics (DI, DPPL) answer the ethical/legal question "are outcomes fair across groups," while SHAP answers the trust/debugging question "why did this prediction come out?" That is why SHAP is also used to diagnose the cause of bias: it reveals which features act as proxies for sensitive attributes and create bias.

Division of Roles Between the Two Services

This is the most confusing point on the exam. Separate them by keyword.

Keyword/questionServiceWhen not to use it
Vanishing/exploding gradients, real-time overfitting detectionDebuggerMonitoring operational drift after deployment (→ Model Monitor)
Saving cost by automatically stopping training jobsDebuggerReducing inference cost (→ choosing inference options)
Capturing tensors/weights/activationsDebuggerMeasuring outcome fairness by group
Measuring fairness across groups such as gender/raceClarify (bias)Diagnosing training convergence problems
Regulatory compliance, data and model bias reportsClarify (bias)Explaining the reason for an individual prediction (→ SHAP)
Feature contribution (SHAP), explaining predictionsClarify (explainability)When the group fairness figure itself is required

Error Analysis: Beyond the Metrics

Once you have the metrics and tools, the last step is the error analysis done by humans. You gather the cases the model got wrong and look for patterns.

Error analysis flow:
1) Collect misclassified / large-error samples
2) Group by common traits (a specific class? a specific feature range? a specific group?)
3) Cause hypotheses: insufficient data / label noise / missing features / bias
4) Use SHAP to check which features contributed to that prediction
5) Improve data, features, and model starting with the largest error bucket
  • Example: If "fraud detection recall plunges only on nighttime transactions," suspect too few nighttime samples or missing time-related features, and verify with SHAP.
  • Error analysis tells you "where to fix" before you blindly spin hyperparameters.
What the error bucket looks likeLikely causeHow to check
Performance plunges only in a certain time of day/regionInsufficient data in that range, missing featuresBreak down and compare sample counts and metrics by range
Only a certain class has poor recallClass imbalance, label noiseclass_imbalance rule, re-inspect labels
Results split by sensitive-attribute groupBias, proxy variablesClarify bias metrics + SHAP global importance
Evenly bad across all rangesTraining itself failed to convergeDebugger rules (loss, gradients)

Good error analysis is prioritization that concentrates resources on the largest error bucket. Fixing a single pattern that accounts for 40% of errors (for example, a lack of data for a certain group) is more effective than vague tuning to raise overall accuracy by 1%. SHAP and bias metrics are tools for quantitatively identifying this bucket, and Debugger determines whether the cause lies in the training process itself.

Diagnostic Pipeline

[Training data]
     │
 ① Clarify pre-training bias (CI · DPL · KL/JS)
     │     └─ Skewed → resample/reweight, then re-measure
     │
 ② Training (capture tensors with the Debugger hook)
     │     ├─ vanishing_gradient / exploding_tensor → fix learning rate/initialization
     │     └─ overfit / loss_not_decreasing → automatic stop + EventBridge notification
     │
 ③ Clarify post-training bias (DPPL · DI · RD · AD)
     │     └─ Unfair → post-processing such as threshold adjustment, then ③ again
     │
 ④ Clarify explainability (SHAP global/local)
     │     └─ Hunt for proxy variables of sensitive attributes
     │
 ⑤ Error analysis → return to ① starting with the largest error bucket
     │
 ⑥ After deployment: track drift and explainability drift with Model Monitor

Passage Clue → Answer Mapping

Passage clueAnswer to chooseReason
"Gradients converge to 0 and training stalls"Debugger vanishing_gradientDetecting tensor anomalies in the training process
"I want to cut a broken training job early to save GPU cost"Debugger rule + automatic stopA fired rule triggers job stop/notification
"Difference in positive prediction rates between gender groups for regulatory reporting"Clarify post-training bias (DPPL, DI)Group fairness of model predictions
"Label skew in the data before building the model"Clarify pre-training bias (CI, DPL)The stage that looks at the data itself
"Explain to the customer the reason for this one rejection"Clarify SHAP local explanationFeature contributions for an individual prediction
"Which features are important overall?"Clarify SHAP global importanceAverage contribution over all the data
"Accuracy by group is similar, so is it fair?"Pitfall: check RD and DI as wellA minority group's FN is hidden behind accuracy
"Recall plunges only on nighttime transactions"Identify the bucket with error analysis, then improveFull retraining or random tuning is inefficient
"The input distribution of the deployed model changed"Model MonitorDebugger is for during training only

Tomorrow we do a comprehensive review of all of Week 9 (classification/regression metrics, curves and thresholds, debugging and bias) as a single evaluation and debugging flow.

📖 Glossary

  • Vanishing gradient: A phenomenon where the gradient propagated by backpropagation gets closer and closer to 0 so the early layers effectively don't learn.
  • Exploding tensor: A state where values run away to NaN/Inf and training breaks.
  • Sensitive attribute (facet): A column that serves as the basis when assessing fairness, such as gender, race, or age. Specified in Clarify with facet_name.
  • CI (Class Imbalance): A pre-training bias metric that measures how skewed the sample counts per group are.
  • DPL / DPPL: Difference in the proportion of positive labels between groups (pre-training) / difference in the proportion of positive predictions (post-training).
  • Disparate Impact (DI): The ratio of positive prediction rates between groups. Often used in regulatory compliance reports.
  • SHAP: An explanation technique that uses Shapley values from game theory to split up "how much each feature pushed this prediction."
  • Global/local explanation: The average contribution over all the data (global) / why one specific case came out that way (local).
  • Proxy: A feature that effectively stands in for a sensitive attribute even without using it directly (for example, a postal code standing in for race).
  • Error bucket: A group of errors that were wrong for similar reasons. Fixing the large buckets first is the knack of error analysis.

📝 Practice Questions

Click a choice to reveal the answer and explanation.

Question 1

In a deep learning training job, you want to automatically detect in real time the problem of gradients converging to 0 and training stalling, and stop the broken job early to save cost. Which service is appropriate?

Question 2

You want to quantitatively measure, for regulatory compliance, whether a loan approval model's positive prediction rates differ greatly between gender groups. Which tool and metric type should you use?

Question 3

You must explain to a customer "which feature contributed most to the decision in this specific loan rejection prediction." What is the most appropriate technique?

Question 4

Which is correct about the purpose of pre-training bias analysis?

Question 5

A fraud detection model has good overall recall, but recall plunges only on "nighttime transactions." What is the most effective next step?

PreviousRegression Evaluation Metrics: RMSE, MAE, MAPE, R², and Residual AnalysisWeek 9 · Day 3Next Week 9 Comprehensive Review: Evaluation and DebuggingWeek 9 · Day 5

Official references

  • MLS-C01 official exam page(opens in a new tab)
  • Amazon SageMaker AI documentation(opens in a new tab)

On this page

  • Key Takeaways
  • Three Layers of Model Debugging
  • SageMaker Debugger: Looking Inside the Training Process
  • Symptom → Rule → Action
  • SageMaker Clarify: Bias and Explainability
  • Pre-training Bias
  • Post-training Bias
  • Which Bias Metric to Look at by Situation
  • At Which Stage Is Bias Mitigated
  • SHAP-Based Explainability
  • Division of Roles Between the Two Services
  • Error Analysis: Beyond the Metrics
  • Diagnostic Pipeline
  • Passage Clue → Answer Mapping
  • Glossary
  • Practice Questions