- Wed 10 April 2024
- Neuron
A Simple Tensor Comparison Utility for Accuracy Debugging
When two tensors that are expected to match do not, the investigation should establish the size of the worst and the typical difference, whether the argmax agrees, and whether sampling from each distribution gives the same result. The utility below answers each of these questions.
The utility is most useful in numerics debugging. Typical cases
include comparing logits between hardware paths, validating
quantization, and checking a kernel against a reference. It serves as
the next step when torch.allclose returns
False and the cause of the mismatch is unknown.
The comparator
import torch
import csv
from datetime import datetime, timezone
def compare_logits(first: torch.Tensor, second: torch.Tensor, name: str):
"""Compare two tensors element-wise. Prints summary stats and argmax agreement."""
diff = torch.abs(first - second)
max_diff = diff.max()
min_diff = diff.min()
avg_diff = diff.mean()
stddev = diff.std()
first_min, first_max = first.min(), first.max()
second_min, second_max = second.min(), second.max()
print(f"{name.upper()}: "
f"max_diff={max_diff:.5f}, min_diff={min_diff:.5f}, "
f"avg_diff={avg_diff:.5f}, stddev={stddev:.5f}, "
f"first range=[{first_min:.5f}, {first_max:.5f}], "
f"second range=[{second_min:.5f}, {second_max:.5f}]")
print(f"ArgMax first={torch.argmax(first)}, second={torch.argmax(second)}")A typical call:
compare_logits(cpu_logits, neuron_logits, "fp32-vs-bf16-bf-decode-step-0")Output:
FP32-VS-BF16-BF-DECODE-STEP-0: max_diff=0.13281, min_diff=0.00000,
avg_diff=0.00742, stddev=0.01089, first range=[-20.3125, 18.5000],
second range=[-20.4063, 18.5000]
ArgMax first=842, second=842
Each value has the following interpretation:
max_diffis the largest element-wise difference. Near a logit value of 18, one BF16 ULP is0.125. The value of0.13281here is just over one ULP, which is acceptable for BF16.avg_diffis the typical difference. When it is much smaller thanmax_diff, a few outliers account for the worst case.stddevis the spread of the differences. For spread-out rounding noise, the standard deviation of the absolute difference is close to the mean. A standard deviation several times the mean indicates that the error is concentrated in a few elements.- Argmax agreement indicates whether greedy decoding
selects the same token. If the argmax differs, the generated output will
differ.
torch.argmaxwithout adimargument returns an index into the flattened tensor, so the check applies to the logits of a single step.
Top-K sampling check
When generation uses top-K sampling instead of greedy decoding, the sampled tokens should also be compared:
def printTop(next_token_scores, name, top_k=5, seed=0):
torch.manual_seed(seed)
topk_values, topk_indices = torch.topk(next_token_scores, top_k)
probs = torch.nn.functional.softmax(topk_values, dim=-1)
inputs_in_topk = torch.multinomial(probs, num_samples=1, replacement=True)
inputs = torch.gather(topk_indices, 0, inputs_in_topk)
print(f"TopK-{top_k} for {name}: {inputs}")
# inside compare_logits, optionally:
printTop(first, "first")
printTop(second, "second")This function samples one token from the top-K distribution of each tensor. Both calls use the same seed, so identical distributions produce the same token. If the argmax agrees but the sampled tokens differ for several seeds, the two distributions differ in shape even though their peaks match.
Bulk comparison with CSV output
Comparing many tensors at once, such as the output of every layer, calls for a version that writes a CSV file:
def write_to_csv(results, filename=None):
csv_headers = ["Param", "Max Diff", "Min Diff", "Mean Diff", "Std. Dev Diff"]
if filename is None:
ts = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S')
filename = f"tensor-diffs-{ts}.csv"
with open(filename, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(csv_headers)
for row in results:
writer.writerow(row)
def get_statistics(name: str, bf16: torch.Tensor, fp32: torch.Tensor):
"""Compute summary statistics for one bf16 vs fp32 comparison and return the CSV row."""
print(f"\n{name} ...")
diff = torch.abs(bf16 - fp32)
mean_diff = torch.mean(diff)
std_diff = torch.std(diff)
max_diff = torch.max(diff)
min_diff = torch.min(diff)
print(f" Max_diff: {max_diff}, Min_diff: {min_diff}, "
f"Mean_diff: {mean_diff}, StdDev: {std_diff}")
return [name, max_diff.item(), min_diff.item(), mean_diff.item(), std_diff.item()]A typical loop over layers:
def compare_tensors():
layer_count = 32
results = []
for layer_idx in range(layer_count):
bf16 = torch.load(f'/tmp/bf16_layer_{layer_idx}_out.pt')
fp32 = torch.load(f'/tmp/fp32_layer_{layer_idx}_out.pt')
results.append(get_statistics(f'layer_{layer_idx}_out', bf16, fp32))
write_to_csv(results)Output CSV:
Param,Max Diff,Min Diff,Mean Diff,Std. Dev Diff
layer_0_out,0.0078125,0.0,0.001234,0.000874
layer_1_out,0.0107422,0.0,0.002145,0.001231
layer_2_out,0.0146484,0.0,0.003012,0.001682
...Plotting these columns shows how the error grows from layer to layer, and the shape of the curve usually indicates the cause:
- Gradual, steady growth is expected. Each layer adds its own BF16 rounding error to the residual stream.
- A sudden jump or rapid growth indicates a bug. Some operation amplifies the error instead of allowing it to dissipate, and the first layer with the jump is where to look.
- Flat or very slow growth indicates that the implementation limits error accumulation, for example by accumulating matrix multiplications or collectives in FP32.
Use cases
The utility applies to three common debugging scenarios.
Quantization validation. A model is cast from BF16 to FP8, and the per-layer outputs of the two versions are compared. The CSV records the error that each layer adds, which shows whether the quantization is too lossy.
Cross-hardware comparison. The same model runs on GPU and on Neuron, and the logits are saved after each batch and compared. A layer with a much larger difference than the others is the first candidate for investigation.
Kernel validation. The output of a new NKI kernel is
compared against a PyTorch reference. A mismatched argmax at a step
where the top token clearly leads indicates incorrect math. A large
max_diff with a matching argmax indicates correct math with
numeric inaccuracy.
The utility deliberately omits plotting, tolerance settings and a pass/fail verdict. The appropriate tolerance depends on the use case, so that decision belongs to the caller.
Limitations
- Whether the difference matters for the model’s output. Two outputs can differ by 5% and still sample the same token. Two others can differ by 0.1% and produce different sequences, when that small difference falls on a step where the top two tokens are nearly tied. The utility measures numeric similarity, not behavioral similarity.
- Where the divergence started. Locating the first divergent layer requires calling the utility at several layer boundaries.
- Whether the difference is structured. A
max_diffof 0.1 can come from a single outlier or from a uniform 0.1 offset across the tensor. The standard deviation offers a hint, and a histogram provides a definitive answer.
If you found this useful, please cite this post using
Senthilkumar Gopal. (Apr 2024). A Simple Tensor Comparison Utility for Accuracy Debugging. sengopal.me. https://sengopal.me/posts/a-simple-tensor-comparison-utility-for-accuracy-debugging
or
@article{gopal2024simpletensor,
title = {A Simple Tensor Comparison Utility for Accuracy Debugging},
author = {Senthilkumar Gopal},
journal = {sengopal.me},
year = {2024},
month = {Apr},
url = {https://sengopal.me/posts/a-simple-tensor-comparison-utility-for-accuracy-debugging}
}