Analysis of Primary Sources and Phenomena of Precision Issues
Training a model is influenced by factors such as the dataset, model architecture, parallelism strategies, and hyperparameters. During the training process, issues like NaN, overflow/underflow, and loss divergence may occur, requiring precision debugging. When training models on Ascend processors, the loss generally shows an overall downward convergence trend. Even if occasional spikes occur, they can be mitigated by skipping dataset batches or resuming training from checkpoints. When the trained weights are used to evaluate the model's scores on standard datasets and the results align with the expected performance reported in the community, the precision debugging process can be considered complete.
This document summarizes common issues encountered during model training and their debugging methods, aiming to help users eliminate problems before training begins and shorten the time required to locate model precision issues.
Dataset
Data is one of the decisive factors in enhancing model capabilities. Models are sensitive to dataset quality; invalid or low-quality data can cause the model to learn incorrect patterns and even affect model convergence. Duplicate data exacerbates content repetition in language models and leads to overfitting. In terms of metrics, dataset issues may cause spikes in the gradient norm, indicating an abnormal increase in the gradient norm that leads to training instability.
- Training instability triggered by anomalous data: Corpus that triggers training anomalies includes bytecode, Unicode garbled text, pure numeric text, and the like. Such corpus is silently tokenized by mainstream subword tokenizers into tokens and converted into ID sequences, which then enter the normal training iteration steps. However, because this corpus lacks grammatical and semantic regularity, updating parameters based on it may interfere with the model's normal learning process. When the volume of anomalous corpus is significant, the model may fail to converge properly.
- Corpus mixing ratio and type: The mixing ratios and scale of different languages and corpus types (code, text) also have a significant impact on model training precision. The mixing ratios of corpus from different sources must be adjusted, and raw corpus should not be directly merged for training. A balanced corpus ratio helps improve the model's generalization ability, while specific types of corpus can enhance the model's capabilities in particular areas.
- Matching data scale with model parameter scale: Larger parameter scale is not always better. Research by Hoffmann et al. on the Chinchilla series of models shows that, given a fixed computational budget, the model performs relatively better when the number of corpus tokens is comparable to the number of model parameters. Therefore, one should not blindly pursue large-scale corpus; instead, emphasis should also be placed on controlling scale, improving quality, and ensuring sufficient training.
Hyperparameter Configuration
Hyperparameters have a critical impact on model training convergence. The hyperparameters discussed here primarily include: optimizer selection, learning rate setting, gradient clipping threshold, loss scale, and others.
-
Optimizer and learning rate: The choice of optimizer directly affects the update strategy during model training. As one of the core hyperparameters, an improperly set learning rate may lead to issues such as sudden changes in the global gradient norm (
GNorm), failure of the loss curve to converge, upward trends, or even severe fluctuations. Therefore, when training large models, it is necessary to carefully search for an appropriate learning rate to ensure convergence performance. -
Gradient clipping threshold: Gradient clipping is also critical to the stability of model training. Using an excessively high gradient clipping threshold may cause
GNormto remain persistently high, as shown by the blue line in Figure 1. Gradient clipping can reduce the gradient values of certain tensors after backward propagation is complete, which helps prevent gradient explosion and makes the training process more stable. The clipping range can be configured through experimentation, by using common values from the literature, or by observing the range through experiments and then selecting a reasonable value. All layers in the network typically use the same gradient clipping configuration; generally, the output layer allows a larger gradient range than the hidden layers.Figure 1 Excessively high gradient clipping threshold
-
Dynamic loss scale adjustment: During training, the loss scale acts as a dynamically adjusted scaling factor, and its magnitude changes also reflect the stability state of training. If the loss scale remains below 1 for an extended period, it usually means that some gradient values are too large and prone to overflow. At the same time, smaller gradient values are also more likely to underflow to 0, causing training to remain in an unstable state.
-
Impact of batch size: Batch size is another hyperparameter that significantly affects training performance, striking a balance between meeting memory requirements and improving training efficiency. In distributed model training scenarios, it is common to choose larger batch sizes to shorten training duration. However, an excessively large batch size may also cause the loss curve to show an upward trend. Therefore, when adjusting batch size, it is necessary to comprehensively consider its impact on both training efficiency and convergence to achieve an optimal configuration.
Floating-Point Computation
Precision issues in floating-point computation stem from the fact that computers use binary numbers in specific formats to represent real numbers, and binary can only represent a finite set of discrete real numbers. As a result, certain decimal fractions can only be represented approximately. Precision issues in floating-point computation can be mitigated but not eliminated, so understanding the differences between various floating-point types is crucial for model training.
In CPU-based computing scenarios, the double-precision floating-point type, also known as FP64 or float64, is frequently used. However, in machine learning and AI accelerator-based computing scenarios, due to the massive scale of parameters, it is difficult and unnecessary to use double-precision numbers for storage and computation. Single-precision floating-point numbers and half-precision floating-point numbers are the commonly used data types in model training.
Single-Precision Floating-Point Number
FP32, or float32, is a floating-point format defined by the IEEE 754 standard. It uses 32 bits to represent a floating-point number, consisting of a 1-bit sign bit, an 8-bit exponent, and a 23-bit fraction. The bit layout is as follows:

When the exponent bits are not zero, the floating-point number V represented by these 32 bits is called a normalized number, defined by the following formula:

When the exponent is zero, the floating-point number is called a subnormal number, defined by the following formula:

In fast mode, NPUs or mainstream AI processors can only perform operations on normalized numbers. Subormal numbers are flushed to zero, and division and square root operations are not computed to the nearest representable floating-point value.
When the exponent bits are all ones, the floating-point number represented has a special meaning. If the fraction is 0 at this point, V is positive or negative infinity; if the fraction is not 0, V is NaN (Not a Number).
The smallest absolute normalized floating-point number that the FP32 format can represent is 2-126, approximately 1.18e-38. The largest absolute normalized floating-point number is 2127 * [1 + (223 − 1)/223], approximately 3.4e38. Around 1.0, the spacing between two adjacent floating-point numbers is 2-23, approximately 1.2e-7. The relative spacing between adjacent floating-point numbers at all positions is approximately 1.2e-7. This shows that FP32 has very high floating-point precision.
Half-Precision Floating-Point Number
Due to the massive scale of model parameters, AI accelerators have high memory requirements, so using a 16-bit half-precision format offers more advantages than 32-bit single precision. Additionally, half-precision computation is faster, and its precision is often sufficient for machine learning models. Like mainstream AI processors, the latest Ascend AI accelerators also support two half-precision floating-point formats: FP16 and BF16.
-
FP16 format
FP16, or float16, is a half-precision floating-point format defined by the IEEE 754 standard. It uses 16 bits to represent a floating-point number, including 1-bit sign, 5-bit exponent, and 10-bit fraction. The bit layout is as follows:

Similar to FP32, if the exponent is non-zero, it represents a normalized floating-point number V, defined by the following formula:

We will not elaborate further on denormalized numbers for FP16 here.
Around 1.0, the spacing between two adjacent floating-point numbers is 2-10. The relative spacing between two adjacent floating-point numbers at any position is also 2-10, which is approximately one-thousandth. A serious problem caused by the precision error of FP16 is the "large number swallowing small number" effect in addition. For example:
x = torch.tensor(1, dtype=torch.float16) y = torch.tensor(0.0001, dtype=torch.float16)x+y remains 1.0 because 1.0001 cannot be represented in FP16. The smallest number that FP16 can represent after 1 is 1.0009765625.
The maximum absolute value of the normalized floating-point number that FP16 can represent is 215 * (1+1023/1024)=65504, and the minimum absolute value is 2-14, which is approximately 6.1e-5. This means that numbers exceeding 65504 and numbers smaller than 6.1e-5 cannot be represented in FP16, yet these numbers are very common in model training. To avoid underflow, FP16 must be combined with loss scaling for model training.
-
BF16 format
To address the issue of FP16's limited representation range, the Google Brain research team proposed the bfloat16 floating-point format, also known as BF16. The bit structure layout of BF16 is as follows:

Compared to FP16, BF16 increases the exponent bit width to 8 (the same as FP32) and reduces the fraction bit width to 7. This expands the floating-point representation range but sacrifices representation precision. When the exponent is not 0, the BF16 floating-point formula is as follows:

Around 1.0, the spacing between adjacent floating-point numbers representable in BF16 is 1/128. The relative spacing between adjacent floating-point numbers at any position is 1/128, indicating that the precision of BF16 is very low, only one-eighth of the precision of FP16. The maximum representable normalized floating-point number in BF16 is 2127 * (1+127/128), approximately 3.4e38, and the normalized floating-point number with the smallest absolute value is 2-126, approximately 1.176e-38.
The precision of BF16 is still sufficient for most model training scenarios. However, care must be taken with certain operations, such as accumulation, which should be performed with higher-precision FP32.
In summary, selecting an appropriate floating-point number precision is crucial for optimizing the model training process. Especially when dealing with convergence issues caused by floating-point precision, it is necessary to combine literature research findings and practical experience, and to perform debugging and optimization through extensive comparative experiments.
Mixed-Precision Computation
Although low-precision computation can provide a very significant increase in training speed, low-precision operations can also cause numerical errors and numerical stability issues compared to FP32. Therefore, when using low-precision operations to accelerate training, understanding the numerical behavior of core tensor operations is also very important.
The representable range of FP16 is ±65504, and the smallest absolute values of normalized numbers it can represent are 2-14 and -2-14, which is +/-0.000061035. The relative spacing between two adjacent floating-point numbers is approximately one-thousandth. For example, the first floating-point number greater than 1 is 1+1/1024, which means 1.0001 cannot be represented. FP16 incurs significantly larger precision errors compared to FP32. The following code demonstrates the relative error when computing the mean of a 10,000-dimensional random tensor (drawn from a normal distribution with mean 0 and variance 1) on a mainstream AI processor using FP32 and FP16, respectively. When computed with FP16, the average relative error is around 0.1%, and the maximum error is 23%. In model training scenarios, because many tensors are very small and have high dimensionality, attention must be paid to FP16 precision issues. If the same code is computed with BF16, the average relative error is about 1%, and the maximum error approaches 4800%. Because accumulation operations have inherent variability, running the program twice may yield different results.
python non-distributed.py --dtype fp16 --device npu
python non-distributed.py --dtype bf16 --device npu
import torch
import argparse
parser = argparse.ArgumentParser(
prog='test_mean',
description='check the effect to final result under different floating point precision')
parser.add_argument("-t", "--dtype", default="fp16",help="precision selection")
parser.add_argument("-d", "--device", default="cuda", help="accelerator selection")
args = parser.parse_args()
# accelerator selection
if args.device == 'cuda':
device = torch.device('cuda:0')
elif args.device == 'npu':
import torch_npu
device = torch.device('npu:0')
dtype = torch.bfloat16 if args.dtype == "bf16" else torch.float16
fn = torch.mean
def test(fn):
N, batch = 10000, 1000
# calculations based on FP16 or BF16
x = torch.randn((batch, N))
x_16 = x.to(device, dtype=dtype)
x_mean_16 = fn(x_16, dim=-1, dtype=dtype)
# calculations based on FP32
x_fp32 = x.to(device)
x_mean_fp32 = fn(x_fp32, dim=-1, dtype=torch.float32)
# error analysis
rel_diff = abs((x_mean_16.float() - x_mean_fp32) / x_mean_fp32)
return rel_diff
rel_diff= test(fn=fn)
max_rel_diff = rel_diff.max() # maximum calculation error
avg_rel_diff = rel_diff.mean() # average calculation error
print("average relative difference is: ", avg_rel_diff)
print("max relative difference is: ", max_rel_diff)
Because FP16 has a very limited floating-point representation range, overflow can easily occur during computation, resulting in Inf or NaN. Some hardware may convert Inf values to the maximum representable number, which alleviates overflow to a certain extent but still introduces computational errors.
BF16 expands the floating-point representable range by increasing the exponent bit width and reducing the fraction bit width, at the cost of representable precision. Its maximum finite value is approximately 3.39 × 1038, and the smallest normalized number in terms of absolute value is 2-126, approximately 1.18 × 10-38. Around 1.0, the spacing between two adjacent BF16 floating-point numbers is 1/128, about 0.78%, so 1.001 cannot be represented precisely. The precision of BF16 is lower than that of FP16, but it is less prone to overflow, and the risk of normalized number underflow is also significantly lower than FP16, making it more convenient than FP16 in precision-insensitive computation scenarios. Experiments on existing large Transformer models have shown that using BF16 for mixed-precision training generally does not significantly affect model convergence.
When distributed communication operators involve accumulation operations, error accumulation issues with low-precision numbers also arise. As shown in the code below, the average error of FP16 all_reduce across 8 ranks on a mainstream AI processor is approximately one-thousandth, with a maximum error of about 2x. When using BF16, the average relative error is around 1.5%, and the maximum relative error is 9x. Due to the non-deterministic computation of communication operators, running the same input twice will yield different results.
torchrun --nnodes=1 --nproc-per-node=8 distributed.py --dtype fp16 --device npu
torchrun --nnodes=1 --nproc-per-node=8 distributed.py --dtype bf16 --device npu
import os
import torch
import torch.distributed as dist
import argparse
parser = argparse.ArgumentParser(
prog='fp precision test',
description='check the effect to final result under different floating point precision')
parser.add_argument("-t", "--dtype", default="fp16")
parser.add_argument("-d", "--device", default="cuda", help='accelerator selection')
args = parser.parse_args()
dtype = torch.bfloat16 if args.dtype == "bf16" else torch.float16
# distributed environment
local_rank = int(os.environ['LOCAL_RANK'])
world_size = int(os.environ['WORLD_SIZE'])
# accelerator selection
if args.device == 'cuda':
device = torch.device(f"cuda:{local_rank}")
dist.init_process_group(backend='nccl', rank=local_rank, world_size=world_size)
elif args.device == 'npu':
import torch_npu
device = torch.device(f"npu:{local_rank}")
torch.npu.set_device(device)
dist.init_process_group(backend='hccl', rank=local_rank, world_size=world_size)
if __name__ == "__main__":
print("start all reduce!")
hccl_input = torch.randn(10000)
print(local_rank, hccl_input.shape)
# collective communication
hccl_input16 = hccl_input.to(device=device,dtype=dtype)
hccl_input32 = hccl_input.to(device=device)
torch.distributed.all_reduce(hccl_input16)
torch.distributed.all_reduce(hccl_input32)
if local_rank == 0:
rel_diff = abs((hccl_input16.float() - hccl_input32) / hccl_input32)
diff_mean = torch.mean(rel_diff)
diff_max = torch.max(rel_diff)
print("diff_mean=", diff_mean)
print("max diff=", diff_max)
In summary, the choice of which precision to use for mixed-precision training requires a trade-off between precision loss and training speedup based on specific task requirements, while also taking into account the error accumulation effects in distributed environments.