Skip to content

Conversation

awf
Copy link
Contributor

@awf awf commented Jun 26, 2024

Small change to allow the number of random bits used in stochastic rounding to be specified.
The calculation is slightly modified to avoid bias, e.g. the following graph shows how the stochastically rounded values approach the full-precision values:
image

from matplotlib import pyplot as plt
import torch
import unit_scaling
from unit_scaling.formats import FPFormat

srnumbits = 2

fmt = FPFormat(5,2, "stochastic", srnumbits)

vs = torch.arange(0.9, 2.7, 1.0 / 117, dtype=torch.float32)

# Stochastic rounding
rvs = torch.zeros_like(vs)
nsamples = 5000
for n in range(nsamples):
    rvs += fmt.quantise(vs)
rvs /= nsamples

# round to nearest
fmt_nearest = FPFormat(5,2, "nearest")
rn = fmt_nearest.quantise(vs)

plt.plot(vs, vs, label="True value", color="k")
plt.plot(vs, rn, label="Round to nearest", color="orange")
plt.plot(vs, rvs, label=f"Stochastic, {srnumbits} bits", color="green")
plt.xlabel("Input float value")
plt.ylabel(f"Average of rounded values, {nsamples} samples")
plt.legend()

@awf awf marked this pull request as draft June 27, 2024 12:43
Copy link
Contributor

@thecharlieblake thecharlieblake left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this Andrew. Keen to find a case where we need stochastic rounding and play around with how many bits

@awf awf marked this pull request as ready for review June 27, 2024 17:22
@awf awf merged commit a5b595c into main Jun 27, 2024
@awf awf deleted the stochastic-rounding-num-bits branch June 27, 2024 17:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants