To calculate an exact histogram in PyTorch where every distinct bfloat16 value gets its own bin (no grouping), you can use the following approach:
Key Idea:
- Flatten the input tensor (if not already 1D).
- Find unique values (since
bfloat16 has limited precision, exact matches can be detected).
- Count occurrences of each unique value.
Solution:
import torch
def exact_histogram_bfloat16(tensor):
# Flatten the tensor to 1D and convert to bfloat16 (if not already)
tensor_flat = tensor.flatten().to(torch.bfloat16)
# Get unique values and their counts
unique_values, counts = torch.unique(tensor_flat, return_counts=True)
return unique_values, counts
# Example usage:
if __name__ == "__main__":
# Create a tensor with some bfloat16 values (including duplicates)
x = torch.tensor([1.0, 1.0001, 1.0, 2.0, 1.0001], dtype=torch.float32).to(torch.bfloat16)
unique_values, counts = exact_histogram_bfloat16(x)
print("Unique values:", unique_values)
print("Counts:", counts)
Explanation:
tensor.flatten(): Ensures the input is 1D.
.to(torch.bfloat16): Guarantees the values are in bfloat16 (in case the input was a higher-precision type).
torch.unique(..., return_counts=True): Returns each distinct bfloat16 value and its count.
Notes:
- This works because
bfloat16 has finite precision (16 bits), so exact equality comparisons are possible.
- If your input has values that are very close but not identical in
bfloat16, they will be treated as separate bins (as requested).
- For large tensors, this method is memory-efficient since it relies on PyTorch's optimized
unique().
Alternative (Manual Counting):
If you need even more control (e.g., handling edge cases), you can manually count using a dictionary:
def exact_histogram_bfloat16_manual(tensor):
tensor_flat = tensor.flatten().to(torch.bfloat16)
counts = {}
for val in tensor_flat:
key = val.item() # Convert to Python float for hashing
counts[key] = counts.get(key, 0) + 1
unique_values = torch.tensor(list(counts.keys()), dtype=torch.bfloat16)
counts_tensor = torch.tensor(list(counts.values()), dtype=torch.long)
return unique_values, counts_tensor
This gives identical results but may be slower for very large tensors. Choose the method based on your use case!