text
stringlengths
1
93.6k
@functools.cached_property
def mode(self):
return self.mean
@functools.cached_property
def mean(self):
return self.mean
def sample(self, sample_shape=torch.Size([])):
return self.mean
class Categorical(DiscreteDistribution):
def __init__(self, logits):
self.categorical = torch_Categorical(logits=logits, validate_args=False)
self.n_classes = logits.size(-1)
@functools.cached_property
def probs(self):
return self.categorical.probs
@functools.cached_property
def mode(self):
return self.categorical.mode
def log_prob(self, x):
return self.categorical.log_prob(x)
def sample(self, sample_shape=torch.Size([])):
return self.categorical.sample(sample_shape)
class DiscretizedCategorical(DiscretizedDistribution):
def __init__(self, logits=None, probs=None):
assert (logits is not None) or (probs is not None)
if logits is not None:
super().__init__(logits.size(-1), logits.device)
self.categorical = torch_Categorical(logits=logits, validate_args=False)
else:
super().__init__(probs.size(-1), probs.device)
self.categorical = torch_Categorical(probs=probs, validate_args=False)
@functools.cached_property
def probs(self):
return self.categorical.probs
@functools.cached_property
def mode(self):
return idx_to_float(self.categorical.mode, self.num_bins)
def log_prob(self, x):
return self.categorical.log_prob(float_to_idx(x, self.num_bins))
def sample(self, sample_shape=torch.Size([])):
return idx_to_float(self.categorical.sample(sample_shape), self.num_bins)
class CtsDistributionFactory:
@abstractmethod
def get_dist(self, params: torch.Tensor, input_params=None, t=None) -> CtsDistribution:
"""Note: input_params and t are not used but kept here to be consistency with DiscreteDistributionFactory."""
pass
class GMMFactory(CtsDistributionFactory):
def __init__(self, min_std_dev=1e-3, max_std_dev=10, log_dev=True):
self.min_std_dev = min_std_dev
self.max_std_dev = max_std_dev
self.log_dev = log_dev
def get_dist(self, params, input_params=None, t=None):
mix_wt_logits, means, std_devs = params.chunk(3, -1)
if self.log_dev:
std_devs = safe_exp(std_devs)
std_devs = std_devs.clamp(min=self.min_std_dev, max=self.max_std_dev)
return GMM(mix_wt_logits, means, std_devs)
class NormalFactory(CtsDistributionFactory):
def __init__(self, min_std_dev=1e-3, max_std_dev=10):
self.min_std_dev = min_std_dev
self.max_std_dev = max_std_dev
def get_dist(self, params, input_params=None, t=None):
mean, log_std_dev = params.split(1, -1)[:2]
std_dev = safe_exp(log_std_dev).clamp(min=self.min_std_dev, max=self.max_std_dev)
return Normal(mean.squeeze(-1), std_dev.squeeze(-1), validate_args=False)
class DeltaFactory(CtsDistributionFactory):
def __init__(self, clip_range=1.0):
self.clip_range = clip_range
def get_dist(self, params, input_params=None, t=None):
return DeltaDistribution(params.squeeze(-1), self.clip_range)
class DiscreteDistributionFactory:
@abstractmethod