Skip to content

Commit

Permalink
add sampler: log uniform
Browse files Browse the repository at this point in the history
  • Loading branch information
christophmluscher committed Dec 17, 2024
1 parent e22c46a commit 3825aeb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
Empty file added i6_models/samplers/__init__.py
Empty file.
30 changes: 30 additions & 0 deletions i6_models/samplers/log_uniform.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
__all__ = ["LogUniformSampler"]


import math

import torch
from torch import nn


class LogUniformSampler(nn.Module):
def __init__(self, num_classes):
super().__init__()

# assumes count-sorted vocabulary, descending
self.num_classes = num_classes

# approximately zipf distribution
self._distribution = [
(math.log1p(w + 1) - math.log1p(w)) / math.log1p(self.num_classes) for w in range(self.num_classes)
]
self._distribution = torch.tensor(self._distribution).clamp(min=1e-10)
self._distribution /= self._distribution.sum()

self._cat_sampler = torch.distributions.categorical.Categorical(probs=self._distribution.cuda())

def sample(self, num_samples):
return self._cat_sampler.sample(torch.Size([num_samples]))

def log_prob(self, indices):
return self._cat_sampler.log_prob(indices)

0 comments on commit 3825aeb

Please sign in to comment.