Skip to content

Instantly share code, notes, and snippets.

@MilesCranmer
Last active June 13, 2024 08:55
Show Gist options
  • Select an option

  • Save MilesCranmer/b59a13218cbf0d30ee459c99f2b4e26a to your computer and use it in GitHub Desktop.

Select an option

Save MilesCranmer/b59a13218cbf0d30ee459c99f2b4e26a to your computer and use it in GitHub Desktop.
Soft clipping in pytorch
def soft_clip(x, lo, hi, pct=0.1):
range = hi - lo
frac = (x - lo) / range
normalization = F.softplus(torch.ones_like(x))
for _ in ['lo', 'hi']:
frac = torch.where(frac > pct,
frac,
pct * F.softplus(frac / pct) / normalization
)
frac = 1 - frac # Switch sides
return frac * range + lo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment