MCPcopy Create free account
hub / github.com/VisionXLab/OF-Diff / DiagonalGaussianDistribution

Class DiagonalGaussianDistribution

ldm/modules/distributions/distributions.py:24–62  ·  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):
36 x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device)
37 return x
38
39 def kl(self, other=None):
40 if self.deterministic:
41 return torch.Tensor([0.])
42 else:
43 if other is None:
44 return 0.5 * torch.sum(torch.pow(self.mean, 2)
45 + self.var - 1.0 - self.logvar,
46 dim=[1, 2, 3])
47 else:
48 return 0.5 * torch.sum(
49 torch.pow(self.mean - other.mean, 2) / other.var
50 + self.var / other.var - 1.0 - self.logvar + other.logvar,
51 dim=[1, 2, 3])
52
53 def nll(self, sample, dims=[1,2,3]):
54 if self.deterministic:
55 return torch.Tensor([0.])
56 logtwopi = np.log(2.0 * np.pi)
57 return 0.5 * torch.sum(
58 logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
59 dim=dims)
60
61 def mode(self):
62 return self.mean
63
64
65def normal_kl(mean1, logvar1, mean2, logvar2):

Callers 1

encodeMethod · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected