Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parametrize the number of random bits used in stochastic rounding #56

Merged
merged 3 commits into from
Jun 27, 2024

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
Collaborator

@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
1 check passed
@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.

None yet

2 participants