To calculate an exact histogram in PyTorch where each unique value (even with very small differences) gets its own count, you can use the torch.unique function combined with torch.bincount. Here's how you can do it:
- Use
torch.unique to get the unique values and their indices.
- Use
torch.bincount to count the occurrences of each unique value.
Here's a step-by-step example:
import torch
# Example tensor with bfloat16 values
tensor = torch.tensor([1.0, 2.0, 2.0, 3.0, 3.0, 3.0, 1.0, 1.0], dtype=torch.bfloat16)
# Get unique values and their indices
unique_values, inverse_indices = torch.unique(tensor, return_inverse=True)
# Count the occurrences of each unique value
histogram = torch.bincount(inverse_indices)
# If you want the histogram to have the same length as the number of unique values
# and fill missing indices with zeros, you can do:
full_histogram = torch.zeros(tensor.max().item() + 1, dtype=torch.int64)
full_histogram[inverse_indices] = histogram
# Print the results
print("Unique values:", unique_values)
print("Histogram:", histogram)
print("Full Histogram:", full_histogram)
Explanation:
-
torch.unique(tensor, return_inverse=True):
- This function returns the unique values in
tensor and the indices that reconstruct the original tensor from these unique values.
-
torch.bincount(inverse_indices):
- This function counts the number of occurrences of each value in
inverse_indices, which corresponds to the counts of each unique value in the original tensor.
-
torch.zeros(tensor.max().item() + 1, dtype=torch.int64):
- This creates a zero-filled tensor with the length equal to the maximum value in the original tensor plus one. This is to ensure that the histogram has an entry for each possible value.
-
full_histogram[inverse_indices] = histogram:
- This assigns the counts to the correct positions in the
full_histogram.
This approach ensures that each unique value in the original tensor gets its own count, even if the differences are very small.