MCPcopy Create free account
hub / github.com/TencentARC/MotionCtrl / DiagonalGaussianDistribution

Class DiagonalGaussianDistribution

lvdm/distributions.py:24–65  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

22
23
24class DiagonalGaussianDistribution(object):
25 def __init__(self, parameters, deterministic=False):
26 self.parameters = parameters
27 self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
28 self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
29 self.deterministic = deterministic
30 self.std = torch.exp(0.5 * self.logvar)
31 self.var = torch.exp(self.logvar)
32 if self.deterministic:
33 self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)
34
35 def sample(self, noise=None):
36 if noise is None:
37 noise = torch.randn(self.mean.shape)
38
39 x = self.mean + self.std * noise.to(device=self.parameters.device)
40 return x
41
42 def kl(self, other=None):
43 if self.deterministic:
44 return torch.Tensor([0.])
45 else:
46 if other is None:
47 return 0.5 * torch.sum(torch.pow(self.mean, 2)
48 + self.var - 1.0 - self.logvar,
49 dim=[1, 2, 3])
50 else:
51 return 0.5 * torch.sum(
52 torch.pow(self.mean - other.mean, 2) / other.var
53 + self.var / other.var - 1.0 - self.logvar + other.logvar,
54 dim=[1, 2, 3])
55
56 def nll(self, sample, dims=[1,2,3]):
57 if self.deterministic:
58 return torch.Tensor([0.])
59 logtwopi = np.log(2.0 * np.pi)
60 return 0.5 * torch.sum(
61 logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
62 dim=dims)
63
64 def mode(self):
65 return self.mean
66
67
68def normal_kl(mean1, logvar1, mean2, logvar2):

Callers 1

encodeMethod · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected