MaykaGR commited on
Commit
5da3a76
·
verified ·
1 Parent(s): 7de8f32

Upload vae.py

Browse files
Files changed (1) hide show
  1. vae/vae.py +131 -0
vae/vae.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """The causal continuous video tokenizer with VAE or AE formulation for 3D data.."""
16
+
17
+ import logging
18
+ import torch
19
+ from torch import nn
20
+ from enum import Enum
21
+ import math
22
+
23
+ from .cosmos_tokenizer.layers3d import (
24
+ EncoderFactorized,
25
+ DecoderFactorized,
26
+ CausalConv3d,
27
+ )
28
+
29
+
30
+ class IdentityDistribution(torch.nn.Module):
31
+ def __init__(self):
32
+ super().__init__()
33
+
34
+ def forward(self, parameters):
35
+ return parameters, (torch.tensor([0.0]), torch.tensor([0.0]))
36
+
37
+
38
+ class GaussianDistribution(torch.nn.Module):
39
+ def __init__(self, min_logvar: float = -30.0, max_logvar: float = 20.0):
40
+ super().__init__()
41
+ self.min_logvar = min_logvar
42
+ self.max_logvar = max_logvar
43
+
44
+ def sample(self, mean, logvar):
45
+ std = torch.exp(0.5 * logvar)
46
+ return mean + std * torch.randn_like(mean)
47
+
48
+ def forward(self, parameters):
49
+ mean, logvar = torch.chunk(parameters, 2, dim=1)
50
+ logvar = torch.clamp(logvar, self.min_logvar, self.max_logvar)
51
+ return self.sample(mean, logvar), (mean, logvar)
52
+
53
+
54
+ class ContinuousFormulation(Enum):
55
+ VAE = GaussianDistribution
56
+ AE = IdentityDistribution
57
+
58
+
59
+ class CausalContinuousVideoTokenizer(nn.Module):
60
+ def __init__(
61
+ self, z_channels: int, z_factor: int, latent_channels: int, **kwargs
62
+ ) -> None:
63
+ super().__init__()
64
+ self.name = kwargs.get("name", "CausalContinuousVideoTokenizer")
65
+ self.latent_channels = latent_channels
66
+ self.sigma_data = 0.5
67
+
68
+ # encoder_name = kwargs.get("encoder", Encoder3DType.BASE.name)
69
+ self.encoder = EncoderFactorized(
70
+ z_channels=z_factor * z_channels, **kwargs
71
+ )
72
+ if kwargs.get("temporal_compression", 4) == 4:
73
+ kwargs["channels_mult"] = [2, 4]
74
+ # decoder_name = kwargs.get("decoder", Decoder3DType.BASE.name)
75
+ self.decoder = DecoderFactorized(
76
+ z_channels=z_channels, **kwargs
77
+ )
78
+
79
+ self.quant_conv = CausalConv3d(
80
+ z_factor * z_channels,
81
+ z_factor * latent_channels,
82
+ kernel_size=1,
83
+ padding=0,
84
+ )
85
+ self.post_quant_conv = CausalConv3d(
86
+ latent_channels, z_channels, kernel_size=1, padding=0
87
+ )
88
+
89
+ # formulation_name = kwargs.get("formulation", ContinuousFormulation.AE.name)
90
+ self.distribution = IdentityDistribution() # ContinuousFormulation[formulation_name].value()
91
+
92
+ num_parameters = sum(param.numel() for param in self.parameters())
93
+ logging.debug(f"model={self.name}, num_parameters={num_parameters:,}")
94
+ logging.debug(
95
+ f"z_channels={z_channels}, latent_channels={self.latent_channels}."
96
+ )
97
+
98
+ latent_temporal_chunk = 16
99
+ self.latent_mean = nn.Parameter(torch.zeros([self.latent_channels * latent_temporal_chunk], dtype=torch.float32))
100
+ self.latent_std = nn.Parameter(torch.ones([self.latent_channels * latent_temporal_chunk], dtype=torch.float32))
101
+
102
+
103
+ def encode(self, x):
104
+ h = self.encoder(x)
105
+ moments = self.quant_conv(h)
106
+ z, posteriors = self.distribution(moments)
107
+ latent_ch = z.shape[1]
108
+ latent_t = z.shape[2]
109
+ in_dtype = z.dtype
110
+ mean = self.latent_mean.view(latent_ch, -1)
111
+ std = self.latent_std.view(latent_ch, -1)
112
+
113
+ mean = mean.repeat(1, math.ceil(latent_t / mean.shape[-1]))[:, : latent_t].reshape([1, latent_ch, -1, 1, 1]).to(dtype=in_dtype, device=z.device)
114
+ std = std.repeat(1, math.ceil(latent_t / std.shape[-1]))[:, : latent_t].reshape([1, latent_ch, -1, 1, 1]).to(dtype=in_dtype, device=z.device)
115
+ return ((z - mean) / std) * self.sigma_data
116
+
117
+ def decode(self, z):
118
+ in_dtype = z.dtype
119
+ latent_ch = z.shape[1]
120
+ latent_t = z.shape[2]
121
+ mean = self.latent_mean.view(latent_ch, -1)
122
+ std = self.latent_std.view(latent_ch, -1)
123
+
124
+ mean = mean.repeat(1, math.ceil(latent_t / mean.shape[-1]))[:, : latent_t].reshape([1, latent_ch, -1, 1, 1]).to(dtype=in_dtype, device=z.device)
125
+ std = std.repeat(1, math.ceil(latent_t / std.shape[-1]))[:, : latent_t].reshape([1, latent_ch, -1, 1, 1]).to(dtype=in_dtype, device=z.device)
126
+
127
+ z = z / self.sigma_data
128
+ z = z * std + mean
129
+ z = self.post_quant_conv(z)
130
+ return self.decoder(z)
131
+