AI fine-tuning failures need different fixes depending on when the run fails and what the held-out evaluation shows. A dataset-format rejection is not a learning-rate problem. A CUDA out-of-memory error is not evidence of a faulty GPU. A falling training loss with worsening validation results is different from a loss that becomes NaN on the first batch. Start by recording the first failing step, the exact message, the model and dataset versions, and a baseline result before changing a setting.
This guide covers common PyTorch and Hugging Face training workflows, including full-model fine-tuning and parameter-efficient methods such as LoRA. Use the documentation for your installed framework and model, because valid options and useful ranges vary. The six checks below move from data and measurement to controlled configuration changes. Do not apply all six at once.

AI fine-tuning failures: quick diagnostic checklist
- Job rejects input before training: inspect schema, tokenizer output, labels, empty rows and the model’s expected format.
- Loss becomes NaN or Inf: find the first failing batch; check finite inputs and labels, loss setup, precision and learning rate. Clipping is not a substitute for identifying invalid data.
- Training improves but validation worsens: compare with the untuned model, inspect split leakage and use a task-appropriate held-out metric.
- CUDA out of memory: record the failing phase and memory measurements. Batch, sequence length, model and optimizer state need different remedies.
- Resume or deployment fails: verify that the checkpoint contains the expected model or adapter, optimizer and configuration state for the action you are attempting.
Save a short incident record: model revision, tokenizer revision, training code or configuration commit, data snapshot, seed if relevant, device, first failing step, error text, and the last successful checkpoint. Redact private training examples and credentials. A run that “works after several changes” gives little evidence about which change mattered, so alter one factor at a time and repeat the same small test.
1. Preserve a baseline and locate the first failure
Before fine-tuning, run the base model on a small, representative held-out sample with the same task metric you intend to use afterward. Record outputs as well as the metric. This comparison tells you whether tuning actually helped and provides a check for regressions on important old behavior. Keep the evaluation sample separate from examples used for training or hyperparameter selection.
Separate four stages: data preparation, first forward/backward pass, later training steps, and post-training evaluation or loading. A parser exception before the first batch points to data or configuration. A loss that becomes non-finite only after several updates points to a different path. A model that trains but performs worse on unseen examples requires evaluation work, not merely a faster training loop.
Check whether the reported “training loss” is comparable across runs. Changing batch size, loss reduction, label masking or gradient accumulation can change its scale or logging frequency. Keep the baseline’s metric definition and evaluation set stable. For generative models, inspect a few representative outputs in addition to aggregate loss; a small loss improvement may not fix the user-facing task.
Expected result: you can name the first stage that fails and the baseline the tuned model must beat. If no baseline exists, capture one before spending time on advanced optimization.
2. Validate the training data and evaluation split
Check the model and tokenizer’s required input format before changing the optimizer. Inspect a small sample from the start, middle and end of the dataset, including examples that trigger an error. Confirm that fields are present, labels refer to the intended input, tokenization produces usable lengths, and masking excludes only the parts that should not contribute to the loss. Empty or malformed examples can survive a quick glance at a file but fail inside the training loop.
For classification, compare label counts and choose metrics that reveal minority-class performance. For generation, inspect whether prompt/response boundaries, special tokens and truncation match the model’s training recipe. If a long record is truncated, check whether the answer or label was removed. Do not silently delete difficult examples just because they make training inconvenient; first decide whether they represent real user cases.
Hugging Face’s evaluation guidance distinguishes training, validation and test splits and explains why imbalance can make accuracy misleading. Group duplicates or related records so near-identical examples do not leak between splits. A validation set used repeatedly to choose settings is not an untouched final test. If only a few hundred examples exist, the uncertainty around any metric can be substantial; use a conservative comparison and inspect actual errors.
Correct a proven data issue, then rerun a short baseline comparison. If training starts but metrics remain poor, do not assume the data is the sole cause. The task, base model, adaptation method and evaluation design may also be mismatched. Our AI troubleshooting hub links to related data and model diagnostics.
Expected result: the same input passes preprocessing and one train/eval step with labels and shapes you can explain. The held-out set reflects the task you care about without obvious leakage.
3. Diagnose NaN, Inf or sudden loss spikes
A non-finite loss is a symptom, not a diagnosis. First find the earliest batch that produces it. Check that inputs and labels are finite where numeric values are expected, that targets are in the loss function’s valid range, and that padding or masks do not leave an empty supervised target. Record the model output and loss before backward, then the gradient norm before the optimizer step. Stop the run when the first invalid value appears; continuing can corrupt the checkpoint.
Next compare a small, controlled run using the model’s documented fine-tuning recipe. If loss becomes non-finite only after updates, try a lower learning rate in a limited experiment and compare curves. A warmup schedule can help some setups, but there is no universal 5–10% rule or starting learning rate. Hugging Face Trainer documents learning-rate, warmup, scheduler and gradient-norm options; choose values based on the model and task.
If mixed precision is enabled, run a short comparison at a supported alternative precision or without it to see whether the instability changes. Float16 and bfloat16 behave differently; compatibility depends on the device and model. If you clip gradients, PyTorch’s norm-clipping API reports the total norm and can flag non-finite values. In an AMP loop, unscale gradients before clipping, as PyTorch documents. Clipping after a gradient is already NaN does not repair the invalid computation.
Do not automatically resume from a checkpoint saved after the first NaN. Return to the last known finite checkpoint, change one suspected cause, and replay the failing batch when possible. For a managed fine-tuning service, collect the rejected row, job event and provider error without exporting private examples into a public forum.
Expected result: you can show whether the invalid value starts in input, forward/loss, backward or optimizer update. A controlled change removes the failure on the same reproduction and preserves a valid held-out result.
4. Compare training progress with held-out behavior
If training loss falls while validation loss rises, the model may be overfitting that task and dataset. Compare the untuned and tuned models on the same examples. Inspect per-class or per-scenario errors, not only one average. For a generative assistant, include examples of the desired new behavior and important abilities you do not want to lose. A regression in old behavior is evidence to investigate; it does not prove a single mechanism such as “catastrophic forgetting” without a controlled comparison.
Consider fewer training steps, a smaller learning rate, early stopping, a different trainable-parameter scope or more representative data, one at a time. Regularization and data augmentation may help some tasks, but a fixed weight-decay value, dropout rate or synonym replacement is not a safe universal prescription. In text tasks, synonym replacement can change intent or labels. In images, an augmentation can invalidate the target if orientation or color carries meaning.
PyTorch’s transfer-learning tutorial demonstrates full fine-tuning and fixed-feature extraction for a particular computer-vision task. It illustrates the choice; it does not establish that freezing a specific fraction of every model’s layers prevents forgetting. For LLM adapters, a different set of modules is trainable. Measure trainable parameter count and compare the task metric and regression set after any scope change.
Expected result: the tuned model improves the intended task without an unacceptable drop on the held-out regression set. If no tested setting beats the base model, keep the baseline and reconsider the task or data rather than publishing an inferior checkpoint.
5. Choose full tuning, freezing or LoRA for the actual constraint
Full fine-tuning updates many or all model weights and can require substantial device memory and checkpoint storage. Freezing layers reduces the trainable set for supported architectures, but the right layers depend on the task. Parameter-efficient fine-tuning, including LoRA, trains small adapters while keeping base weights frozen. Hugging Face documents that this can reduce gradient and optimizer-state memory and make adapter checkpoints smaller. It does not guarantee the same quality as full tuning for every task.
Choose one adaptation method before comparing hyperparameters. Record the base model revision, adapter configuration, target modules, trainable parameter count and whether a new head or embedding is also trained. If a task requires a new label head, ensure it is included in the saved artifact. If a method appears to “train” but the metric never moves, verify that the intended parameters have requires_grad=True and the optimizer actually receives them.
For LoRA, consult the current PEFT configuration reference for valid target modules and rank choices. Do not copy a target-module list from a different architecture without checking names. Compare the method against the base-model result on identical data and compute budget. If a smaller, domain-relevant base model performs better, that may be a better solution than forcing a larger mismatched model through training.
Expected result: the selected method fits the measured memory and deployment constraints and improves the intended held-out behavior. Preserve the base model and configuration needed to reload any adapter.
6. Separate GPU memory, checkpoint and resume failures
A CUDA out-of-memory error means an allocation failed. It does not by itself identify bad hardware, corrupted PyTorch or a broken driver. Record where it occurs: model load, forward pass, backward pass or optimizer step. The AI GPU memory overload guide explains how to compare device use with PyTorch allocated and reserved memory, then choose batch, sequence, checkpointing or optimizer-state changes. Gradient accumulation and activation checkpointing address different parts of training memory; neither fixes a model that cannot load before the first batch.
A saved training checkpoint is different from activation checkpointing. Activation checkpointing recomputes intermediate activations during backward to trade time for memory. A saved checkpoint records progress so a run can resume. For a custom PyTorch training loop, PyTorch’s save/load guide describes preserving model and optimizer state plus the training position. Also save the configuration, tokenizer and adapter information needed to reconstruct the same run. Validate a resume on a short test before relying on it for an expensive job.
If a recovered run changes its learning-rate schedule or data order unexpectedly, the checkpoint may not include all relevant scheduler or sampler state. A managed trainer may handle this differently. Read its current resume documentation and verify that one resumed step matches your intended learning-rate and optimizer settings. Do not call a load successful merely because the file opens; check predictions and one safe continuation step.
Expected result: the workload fits and a known-good checkpoint resumes with the expected model, optimizer and configuration. If it still fails, preserve a minimal non-sensitive reproduction for the framework or platform maintainer.
AI fine-tuning failures decision table
| Observed failure | First useful comparison |
|---|---|
| Data rejected before training | Inspect failing row, schema, tokenizer and required labels. |
| NaN on the first batch | Check finite inputs, masks, targets, loss and precision before tuning the optimizer. |
| NaN after several updates | Compare the first bad batch with a lower learning-rate or precision sanity run. |
| Training improves, validation worsens | Compare against the base model on a held-out task and regression set. |
| CUDA out of memory | Measure the failing phase, physical batch, sequence length and allocated/reserved memory. |
| Resume works but quality changes | Check model, adapter, optimizer, scheduler and data-order state. |
Frequently asked questions
What is the first step when fine-tuning loss becomes NaN?
Find the first batch with a non-finite input, output, loss or gradient. Check masks and loss targets before changing the learning rate. A lower learning rate or different precision may help a specific run, but it should be tested against the same reproduction.
Does freezing the first 80% of layers prevent forgetting?
No fixed fraction applies to all models. Freezing is one way to limit updates in supported architectures, but the effect on the new task and old behavior must be measured. LoRA and other adapter methods update a different trainable set.
Can I fine-tune with a few hundred examples?
Sometimes, depending on the task, base model, data quality and evaluation. Compare the base model with a conservative adaptation on held-out examples and report uncertainty. A small sample cannot support a broad claim that the tuned model generalizes to every user.
Are gradient clipping and saved checkpoints the same as activation checkpointing?
No. Clipping limits gradient norm before an optimizer update. A saved checkpoint lets a run resume. Activation checkpointing trades extra computation for lower activation memory during training. Choose the one that matches the observed problem.
When should I seek platform or model-maintainer help?
After a minimal, redacted reproduction still fails under the documented configuration, or immediately when private data is exposed. Include versions, the first failing step, data shapes, device capacity, non-sensitive error text and the last known-good checkpoint. Do not infer faulty hardware from an OOM error alone.
Use the first failing stage to choose the next change
AI fine-tuning failures become manageable when the data, training phase and held-out results are recorded before a fix. Validate the input, reproduce the first invalid value, compare with the untuned model, then change one configuration choice at a time. Keep the last known-good checkpoint and reject a tuned model that fails the task or regression set, even if its training loss looks better.


