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
    • 1.SageMaker Training Jobs: Estimator, Input Modes, Distributed Training, Spot
    • 2.Hyperparameter Tuning (AMT): Bayesian, Random, Hyperband
    • 3.Overfitting/Underfitting: Diagnosis and Regularization/Data Augmentation
    • 4.Learning Optimization: Batch Size, Learning Rate, Gradient Issues, Debugger/Profiler
    • 5.Week 8 Comprehensive Review: Training, Tuning, Generalization
  • Week 9
  • Week 10
  • Week 11
  • Week 12
SQLD · 개발자SQL Developer (SQLD)

© CertNote · 주간랩스

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

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

MLS-C01· AssociateWeek 8 · Day 4~30 min read

Day 4 - Learning Optimization: Batch Size, Learning Rate, Gradient Issues, Debugger/Profiler

📌 Key Takeaways

  • If overfitting and underfitting were about "what the model learns," today is about "how to make it converge well." Even with the same model and data, training diverges or stalls depending on batch size, learning rate, and gradient stability.
  • Loss NaN, divergence, oscillation → learning rate too high or exploding gradients. The remedy is a lower learning rate + gradient clipping.
  • Early layers do not learn and loss stalls → vanishing gradients. The remedy is ReLU-family activations, batch normalization, residual connections, and proper initialization.
  • OOM → reduce batch size, gradient accumulation, mixed precision. The rule of thumb is that when you increase the batch size, you increase the learning rate with it (linear scaling).
  • One-line tool distinction: training quality anomalies = Debugger, resources/bottlenecks/cost = Profiler. Post-deployment drift is Model Monitor.

The Training Loop at a Glance

       ┌──────────────── 1 step ────────────────┐
Data →│ Sample batch → Forward → Compute loss → Backprop (gradients) → Update weights │→ Next step
       └──────────────────────────────────────────────┘
          ↑batch size     ↑activation fn  ↑vanishing/exploding  ↑learning rate/schedule
 
  Batch size    : Number of samples used in one update → affects memory, GPU utilization, generalization
  Learning rate : How far weights move in one step → separates divergence from stalling
  Gradient      : Multiplied back through the layers, vanishing to 0 (vanishing) or blowing up (exploding)
  1 epoch       : One full pass over the training data = (number of samples / batch size) steps

Batch Size

The number of samples used in one weight update.

Batch sizeAdvantagesDisadvantages
Small (e.g., 32)Noise helps generalization, lower memoryFrequent updates can be slow, noisy
Large (e.g., 1024+)Better GPU utilization, stable updatesHigher memory, may miss flat minima and generalize worse

Batch Size ↔ Learning Rate ↔ Generalization Trade-off

CombinationConvergence speedMemoryGeneralizationWhen to choose
Small batch + small learning rateSlowLowGenerally goodGPU memory is tight and stability comes first
Small batch + large learning rateUnstableLowRisk of divergenceNot recommended (worst mix of noise + big steps)
Large batch + large learning rateFastHighNeeds tuningRaising throughput on large GPUs (linear scaling rule of thumb)
Large batch + small learning rateVery slowHighRisk of stallingThe classic mistake of raising only the batch without raising the learning rate
  • When you increase the batch size, you usually need to increase the learning rate too, to keep the convergence speed (linear scaling rule of thumb).
  • A common cause of GPU out-of-memory (OOM) is an excessive batch size → reduce the batch or use gradient accumulation.

One view is that the gradient noise of small batches helps the model escape sharp minima of the loss surface and head toward flatter regions that generalize better. Conversely, a very large batch gives accurate, stable gradients but loses this exploratory quality, so generalization can drop. That is why batch size is not merely a speed issue but an optimization-versus-generalization trade-off.

Learning Rate and Schedules

The learning rate is how far the weights move in one step. It is the most sensitive hyperparameter in training.

Too large → loss diverges or oscillates (NaN loss)
Too small → convergence is very slow and gets stuck in local minima
Right     → decreases steadily
ScheduleBehaviorWhen to use
Step decayDecreases by a fixed ratio every fixed number of epochsWhen you need simple, predictable decay
Exponential decayDecreases gradually, exponentiallyWhen you want a smooth, continuous reduction
Cosine annealingDecreases smoothly along a cosine curveWhen you want to preserve fine adjustment in the later stages
WarmupStarts with a small learning rate and gradually raises itSuppresses early instability — common in large models and Transformers

Distinguishing signals:

  • "Loss is NaN / diverges / oscillates widely" → the learning rate is too high.
  • "Training barely moves / is too slow" → the learning rate is too low, or vanishing gradients.

Gradient Problems: Vanishing and Exploding

These are problems caused by gradients being multiplied during backpropagation in deep neural networks.

ProblemSymptomResponse
Vanishing gradientEarly layers barely learn, loss stallsReLU-family activations, batch normalization, residual connections (ResNet), proper weight initialization
Exploding gradientLoss NaN/diverges, weights surgeGradient clipping, lower learning rate, batch normalization

Symptom → Cause → Remedy Table

SymptomMost likely causeFirst remedyResponse often used as a wrong option
Loss is NaN within a few stepsLearning rate too high / exploding gradientsLower learning rate + gradient clippingReduce batch to 1, remove all normalization
Loss just oscillates widelyLearning rate too highLower learning rate, introduce a schedule (cosine/step)Just adding epochs
Loss flat from the start, early-layer weights frozenVanishing gradientsReLU family, batch normalization, residual connections, initializationReplace all activations with sigmoid (makes it worse)
Loss decreases only very slowlyLearning rate too lowRaise learning rate, warmup then decayMaking the model even bigger
OOM right after training startsBatch size too large / model sizeReduce batch, gradient accumulation, mixed precisionAdjusting the learning rate (irrelevant)
Loss decreases but GPU utilization is 30%Data loading / I/O bottleneckIdentify the bottleneck with Profiler, then improve the pipelineTouching learning rate/regularization (irrelevant)
hyperparameters = {
    "gradient_clipping": 1.0,   # upper bound on the gradient norm
    "lr_scheduler": "cosine",
}

Sigmoid and tanh have derivatives close to 0 in their saturated regions, so in a deep network gradients converge to 0 in a chain reaction (vanishing). ReLU has a derivative of 1 in the positive region, which mitigates this. Explosion is the opposite: values greater than 1 are multiplied in a chain and diverge, and gradient clipping suppresses it by setting an upper bound on the norm. Batch normalization and residual connections are structural devices that mitigate both problems.

SageMaker Debugger

It captures tensors during training (gradients, weights, loss, etc.) and automatically detects training anomalies.

Built-in ruleWhat it catchesResponse
vanishing_gradientGradients converging to 0ReLU, batch normalization, residual connections, initialization
exploding_tensorTensor values surging / NaN·InfLower learning rate, gradient clipping
overfitGrowing gap between training and validationMore regularization, augmentation, early stopping
overtrainingValidation metric stops improving and worsensStop training early
loss_not_decreasingLoss stallsCheck learning rate, initialization, data
class_imbalanceSkewed class distributionOversampling, class weights, re-selecting metrics
saturated_activationSaturated activations (sigmoid/tanh)Replace the activation function, normalization
  • When a rule is violated, a CloudWatch event is emitted → it can trigger automatic notification or early stopping of training.
  • Tensors are stored in S3 for post-hoc analysis.
from sagemaker.debugger import Rule, rule_configs
 
rules = [
    Rule.sagemaker(rule_configs.vanishing_gradient()),
    Rule.sagemaker(rule_configs.loss_not_decreasing()),
]
est = Estimator(..., rules=rules)

Distinguishing signal: "automatically detect and alert on vanishing/exploding gradients, overfitting, and stalled loss during training" → Debugger.

SageMaker Profiler

It analyzes system resources and performance bottlenecks of training (efficiency, not model quality).

Signal Profiler looks atInterpretationDirection of action
Low GPU utilization, high CPU utilizationData preprocessing is CPU-boundOffload preprocessing, adjust the number of workers
GPU idle periodicallyData loading / I/O wait bottleneckChange input mode (Pipe/FastFile), prefetching
Large amount of free GPU memoryBatch is small and resources go unusedIncrease batch size (adjust the learning rate together)
Low utilization of resources throughoutInstance oversizedSave cost with smaller/fewer instances
  • It collects system metrics such as CPU/GPU utilization, GPU memory, I/O wait, and data loading bottlenecks.
  • It produces diagnostics and recommendation reports such as "the GPU is idle (underutilized)," "data loading is the bottleneck," and "CPU-bound."
  • Cost optimization: if instances are used inefficiently, it recommends smaller or fewer instances.

Comparing Observation Tools — The Confusing Three

ToolWhat it watchesWhenWhen not to use it
DebuggerTensors during training = model quality anomaliesWhile the training job runsUnsuitable for resource bottleneck/cost analysis
ProfilerCPU/GPU, I/O = resources/performanceWhile the training job runsUnsuitable for detecting vanishing gradients or overfitting
Model MonitorInput/prediction drift of deployed endpointsPost-deployment operations, not trainingPicking it to detect anomalies during training is the wrong answer

Distinguishing signals:

  • "Training quality anomalies (vanishing/exploding/overfitting)" → Debugger.
  • "Resource utilization, bottlenecks, GPU underutilization, training speed/cost inefficiency" → Profiler.

⚠️ Trap: Some options mix Debugger, Profiler, and Model Monitor. Quality = Debugger / resources = Profiler / post-deployment drift = Model Monitor — this one line settles most of them.

Additional Training Optimization Techniques

TechniqueEffectWhen to useCaution
Mixed precision (FP16/BF16)Lower memory, higher speedLarge batches, large modelsNumerical stability must be verified
Gradient accumulationCollects several small batches for a large-batch effectWhen memory constraints rule out a large batchTime per step increases
CheckpointingResume from the point of interruptionLong training, preparing for Spot interruptions (linked to Day 1)Meaningless without an S3 path configured

⚠️ Trap: "GPU out of memory" does not automatically mean model parallelism is the answer. If the model itself does not fit, model parallelism; if it is because of the batch, gradient accumulation, mixed precision, or a smaller batch.

Diagnostic Tree When Training Is Not Going Well

Training is not going as expected
├─ Does the job fail outright?
│    └─ OOM error → memory problem
│         ├─ The model itself does not fit on a single GPU → model parallelism (Day 1)
│         └─ Because of the batch → reduce batch / gradient accumulation / mixed precision
├─ Is the loss NaN, diverging, or oscillating widely?
│    └─ Yes → learning rate too high or exploding gradients
│              → lower learning rate + gradient clipping (+ batch normalization)
├─ Is the loss barely decreasing and flat?
│    ├─ Early-layer weights barely change → vanishing gradients
│    │      → ReLU family / batch normalization / residual connections / revisit initialization
│    └─ Decreasing only slowly throughout → learning rate too low → raise learning rate, warmup
├─ Does the loss decrease well, but training is slow and expensive?
│    └─ Yes → resource problem → identify the bottleneck with Profiler
│              ├─ GPU idle / I/O wait → improve the input pipeline
│              └─ Low utilization throughout → shrink instances to save cost
└─ Does the loss decrease but validation gets worse?
     └─ Yes → generalization problem (Day 3) → regularization, augmentation, early stopping
              (can be detected automatically with Debugger's overfit / overtraining rules)

Passage Clue → Answer Mapping

Passage clueAnswer to chooseReason
"Loss diverges to NaN within a few steps"Lower learning rate + gradient clippingClassic symptom of a too-high learning rate / explosion
"Early-layer weights are not updated and loss stalls"ReLU, batch normalization, residual connections, initializationTechniques that mitigate vanishing gradients
"Replace all activations with sigmoid"Wrong optionSaturation makes vanishing worse
"Automatically detect vanishing, overfitting, and loss not decreasing, with alerts and early stopping"SageMaker DebuggerBuilt-in rules + CloudWatch event triggers
"GPU utilization is low and a data loading bottleneck is suspected"SageMaker ProfilerDiagnoses bottlenecks and cost through system metrics
"OOM with a large batch, but we want to keep the batch effect"Gradient accumulationCollects gradients from several small batches and updates once
"We increased the batch and convergence got slower"Increase the learning rate tooLinear scaling rule of thumb
"The input distribution seems to have changed after deployment"Model MonitorOperational monitoring, not a training tool

Tomorrow we review all of Week 8 (training jobs, AMT, generalization, optimization) together and tie it up from the exam perspective.

📖 Glossary

  • Batch size: The number of samples used when updating weights once. It affects memory, GPU utilization, and generalization at the same time.
  • Learning rate: The value that determines how far the weights move in one step. The most sensitive hyperparameter in training.
  • Learning rate schedule / warmup: A rule that gradually decreases the learning rate as training progresses (step, exponential, cosine) / conversely, a phase that starts very small and slowly raises it to reduce early instability.
  • Vanishing gradient: A phenomenon where gradients approach 0 as they pass through layers during backpropagation, so early layers do not learn. Saturation of sigmoid and tanh is the main culprit.
  • Exploding gradient: The opposite, where gradients grow in a chain and the loss diverges to NaN. It is suppressed by gradient clipping, which caps the norm.
  • Residual connection / batch normalization: A structure that skips the input over several layers and adds it back so gradients flow along a shortcut (ResNet) / a technique that normalizes layer outputs per batch to stabilize training. Both mitigate vanishing and exploding gradients.
  • Mixed precision / gradient accumulation: A method that mixes FP16/BF16 to cut memory and raise speed / a technique that collects gradients from small batches and updates at once to get a large-batch effect. Both are used to avoid OOM.
  • SageMaker Debugger: A feature that captures tensors during training and automatically detects quality anomalies such as vanishing, exploding, and overfitting with built-in rules, raising CloudWatch events.
  • SageMaker Profiler: A feature that analyzes system resources such as CPU/GPU utilization and I/O, pointing out bottlenecks and cost inefficiencies.
  • OOM (Out Of Memory): A GPU out-of-memory error. It occurs when the batch is too large or the model itself does not fit on the device.

📝 Practice Questions

Click a choice to reveal the answer and explanation.

Question 1

While training a deep learning model, the loss diverges to NaN within a few steps. What are the most likely cause and response?

Question 2

In a very deep neural network, the weights of the early layers are barely updated and the loss stagnates from the start. Which of the following techniques is the LEAST helpful for mitigating this vanishing gradient problem?

Question 3

You want to automatically detect training quality issues such as vanishing gradients, overfitting, and non-decreasing loss, and trigger alerts or early stopping when a rule is violated. Which SageMaker feature is MOST suitable?

Question 4

A training job shows low GPU utilization and you suspect a data loading bottleneck. You want to analyze system resource utilization and bottlenecks to improve cost and speed. Which tool is MOST suitable?

Question 5

During large model training, a large batch size causes GPU out-of-memory (OOM). Which technique keeps the effect of the batch size while avoiding the memory constraint?

PreviousOverfitting/Underfitting: Diagnosis and Regularization/Data AugmentationWeek 8 · Day 3Next Week 8 Comprehensive Review: Training, Tuning, GeneralizationWeek 8 · Day 5

Official references

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

On this page

  • Key Takeaways
  • The Training Loop at a Glance
  • Batch Size
  • Batch Size ↔ Learning Rate ↔ Generalization Trade-off
  • Learning Rate and Schedules
  • Gradient Problems: Vanishing and Exploding
  • Symptom → Cause → Remedy Table
  • SageMaker Debugger
  • SageMaker Profiler
  • Comparing Observation Tools — The Confusing Three
  • Additional Training Optimization Techniques
  • Diagnostic Tree When Training Is Not Going Well
  • Passage Clue → Answer Mapping
  • Glossary
  • Practice Questions