Skip to content

2. Models

2.1 vq_vae

2.1.1 Decoder(in_channels, num_residuals, out_channels=3, hidden_size=256, kernel_size=4, stride=2)

Initializes a decoder with residual blocks and transpose convolutional layers.

Parameters:

Name Type Description Default
in_channels int

Number of input channels to the decoder.

required
num_residuals int

Number of residual blocks in the decoder.

required
out_channels int

Number of output channels, e.g., RGB.

3
hidden_size int

Number of channels in hidden layers.

256
kernel_size int

Size of the convolutional kernels.

4
stride int

Stride of the convolutional kernels.

2
Source code in src/cv/models/vq_vae.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def __init__(
    self,
    in_channels: int,
    num_residuals: int,
    out_channels: int = 3,  # Channel output (RGB)
    hidden_size: int = 256,
    kernel_size: int = 4,
    stride: int = 2,
) -> None:
    """
    Initializes a decoder with residual blocks and transpose
    convolutional layers.

    Args:
        in_channels: Number of input channels to the decoder.
        num_residuals: Number of residual blocks in the decoder.
        out_channels: Number of output channels, e.g., RGB.
        hidden_size: Number of channels in hidden layers.
        kernel_size: Size of the convolutional kernels.
        stride: Stride of the convolutional kernels.
    """

    super().__init__()

    self.in_channels = in_channels
    self.num_residuals = num_residuals
    self.out_channels = out_channels
    self.hidden_size = hidden_size
    self.kernel_size = kernel_size
    self.stride = stride

    self.residual_blocks = nn.ModuleList(
        [
            ResidualBlock(
                in_channels=self.in_channels, hidden_size=self.hidden_size
            )
            for _ in range(self.num_residuals)
        ]
    )

    self.model = nn.Sequential(
        nn.ConvTranspose2d(
            in_channels=self.in_channels,
            out_channels=self.hidden_size,
            kernel_size=self.kernel_size,
            stride=self.stride,
            padding=1,
        ),
        nn.ConvTranspose2d(
            in_channels=self.hidden_size,
            out_channels=self.out_channels,
            kernel_size=self.kernel_size,
            stride=self.stride,
            padding=1,
        ),
    )

2.1.1.1 forward(input_tensor)

Forward pass through the decoder.

Parameters:

Name Type Description Default
input_tensor Tensor

The input tensor to the decoder.

required

Returns:

Type Description
Tensor

A tensor processed by residual blocks and transpose

Tensor

convolutional layers.

Source code in src/cv/models/vq_vae.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def forward(self, input_tensor: torch.Tensor) -> torch.Tensor:
    """
    Forward pass through the decoder.

    Args:
        input_tensor: The input tensor to the decoder.

    Returns:
        A tensor processed by residual blocks and transpose
        convolutional layers.
    """

    decoder_output = input_tensor
    for res_block in self.residual_blocks:
        decoder_output = res_block(decoder_output)

    return self.model(decoder_output)

2.1.2 Encoder(in_channels, num_residuals, hidden_size=256, kernel_size=4, stride=2)

Initializes an encoder with convolutional layers and residual blocks.

Parameters:

Name Type Description Default
in_channels int

Number of input channels to the encoder.

required
num_residuals int

Number of residual blocks in the encoder.

required
hidden_size int

Number of channels in hidden layers.

256
kernel_size int

Size of the convolutional kernels.

4
stride int

Stride of the convolutional kernels.

2
Source code in src/cv/models/vq_vae.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def __init__(
    self,
    in_channels: int,
    num_residuals: int,
    hidden_size: int = 256,
    kernel_size: int = 4,
    stride: int = 2,
) -> None:
    """
    Initializes an encoder with convolutional layers and residual
    blocks.

    Args:
        in_channels: Number of input channels to the encoder.
        num_residuals: Number of residual blocks in the encoder.
        hidden_size: Number of channels in hidden layers.
        kernel_size: Size of the convolutional kernels.
        stride: Stride of the convolutional kernels.
    """

    super().__init__()

    self.in_channels = in_channels
    self.num_residuals = num_residuals
    self.hidden_size = hidden_size
    self.kernel_size = kernel_size
    self.stride = stride

    self.model = nn.Sequential(
        nn.Conv2d(
            in_channels=in_channels,
            out_channels=hidden_size,
            kernel_size=kernel_size,
            stride=stride,
            padding=1,
        ),
        nn.Conv2d(
            in_channels=hidden_size,
            out_channels=hidden_size,
            kernel_size=kernel_size,
            stride=stride,
            padding=1,
        ),
    )

    self.residual_blocks = nn.ModuleList(
        [
            ResidualBlock(in_channels=hidden_size, hidden_size=hidden_size)
            for _ in range(self.num_residuals)
        ]
    )

2.1.2.1 forward(input_tensor)

Forward pass through the encoder.

Parameters:

Name Type Description Default
input_tensor Tensor

The input tensor to the encoder.

required

Returns:

Type Description
Tensor

A tensor processed by convolutional layers and residual

Tensor

blocks.

Source code in src/cv/models/vq_vae.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def forward(self, input_tensor: torch.Tensor) -> torch.Tensor:
    """
    Forward pass through the encoder.

    Args:
        input_tensor: The input tensor to the encoder.

    Returns:
        A tensor processed by convolutional layers and residual
        blocks.
    """

    encoder_output = self.model(input_tensor)
    for res_block in self.residual_blocks:
        encoder_output = res_block(encoder_output)
    return encoder_output

2.1.3 ResidualBlock(in_channels, hidden_size=256)

Initializes a residual block that applies two convolutional layers and ReLU activations.

Parameters:

Name Type Description Default
in_channels int

Number of input channels for the block.

required
hidden_size int

Number of channels in the hidden layer.

256
Source code in src/cv/models/vq_vae.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
def __init__(self, in_channels: int, hidden_size: int = 256) -> None:
    """
    Initializes a residual block that applies two convolutional
    layers and ReLU activations.

    Args:
        in_channels: Number of input channels for the block.
        hidden_size: Number of channels in the hidden layer.
    """

    super().__init__()

    self.in_channels = in_channels
    self.hidden_size = hidden_size

    self.res_block = nn.Sequential(
        nn.ReLU(),
        nn.Conv2d(
            in_channels=self.in_channels,
            out_channels=self.hidden_size,
            kernel_size=3,
            stride=1,
            padding=1,
            bias=False,
        ),
        nn.ReLU(),
        nn.Conv2d(
            in_channels=self.hidden_size,
            out_channels=self.in_channels,
            kernel_size=1,
            stride=1,
            bias=False,
        ),
    )

2.1.3.1 forward(input_tensor)

Forward pass through the residual block.

Parameters:

Name Type Description Default
input_tensor Tensor

The input tensor to the block.

required

Returns:

Type Description
Tensor

A tensor that is the sum of the input tensor and the

Tensor

block's output.

Source code in src/cv/models/vq_vae.py
43
44
45
46
47
48
49
50
51
52
53
54
55
def forward(self, input_tensor: torch.Tensor) -> torch.Tensor:
    """
    Forward pass through the residual block.

    Args:
        input_tensor: The input tensor to the block.

    Returns:
        A tensor that is the sum of the input tensor and the
        block's output.
    """

    return input_tensor + self.res_block(input_tensor)

2.1.4 VQVAE(in_channels, size_discrete_space, size_embeddings, num_residuals, hidden_size, kernel_size, stride, beta=0.25)

Initializes a VQ-VAE model with encoder, decoder, and quantizer.

Parameters:

Name Type Description Default
in_channels int

Number of input channels for the model.

required
size_discrete_space int

Number of discrete embeddings.

required
size_embeddings int

Size of each embedding vector.

required
num_residuals int

Number of residual blocks in encoder/decoder.

required
hidden_size int

Number of channels in hidden layers.

required
kernel_size int

Size of convolutional kernels.

required
stride int

Stride of convolutional kernels.

required
beta float

Weighting factor for the commitment loss.

0.25
Source code in src/cv/models/vq_vae.py
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
def __init__(
    self,
    in_channels: int,
    size_discrete_space: int,
    size_embeddings: int,
    num_residuals: int,
    hidden_size: int,
    kernel_size: int,
    stride: int,
    beta: float = 0.25,
) -> None:
    """
    Initializes a VQ-VAE model with encoder, decoder, and quantizer.

    Args:
        in_channels: Number of input channels for the model.
        size_discrete_space: Number of discrete embeddings.
        size_embeddings: Size of each embedding vector.
        num_residuals: Number of residual blocks in encoder/decoder.
        hidden_size: Number of channels in hidden layers.
        kernel_size: Size of convolutional kernels.
        stride: Stride of convolutional kernels.
        beta: Weighting factor for the commitment loss.
    """

    super().__init__()

    self.in_channels = in_channels
    self.size_discrete_space = size_discrete_space
    self.size_embeddings = size_embeddings
    self.num_residuals = num_residuals
    self.hidden_size = hidden_size
    self.kernel_size = kernel_size
    self.stride = stride
    self.beta = beta

    self.encoder = Encoder(
        in_channels=self.in_channels,
        num_residuals=self.num_residuals,
        hidden_size=self.hidden_size,
        kernel_size=self.kernel_size,
        stride=self.stride,
    )
    self.decoder = Decoder(
        in_channels=self.hidden_size,
        num_residuals=self.num_residuals,
        out_channels=self.in_channels,
        hidden_size=self.hidden_size,
        kernel_size=self.kernel_size,
        stride=self.stride,
    )

    self.vector_quantizer = VectorQuantizer(
        size_discrete_space=self.size_discrete_space,
        size_embeddings=self.hidden_size,
        beta=self.beta,
    )

2.1.4.1 forward(input_tensor)

Forward pass through VQ-VAE model.

Parameters:

Name Type Description Default
input_tensor Tensor

Input tensor to the model.

required

Returns:

Type Description
Tensor

A tuple containing VQ loss, reconstructed tensor,

Tensor

and perplexity.

Source code in src/cv/models/vq_vae.py
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def forward(
    self, input_tensor: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    """
    Forward pass through VQ-VAE model.

    Args:
        input_tensor: Input tensor to the model.

    Returns:
        A tuple containing VQ loss, reconstructed tensor,
        and perplexity.
    """

    encoder_output = self.encoder(input_tensor)
    vq_loss, quantized, perplexity, _ = self.vector_quantizer(encoder_output)
    decoder_output = self.decoder(quantized)
    return vq_loss, decoder_output, perplexity

2.1.5 VectorQuantizer(size_discrete_space, size_embeddings, beta=0.25)

Initializes a vector quantizer with a learnable codebook.

Parameters:

Name Type Description Default
size_discrete_space int

Number of discrete embeddings.

required
size_embeddings int

Size of each embedding vector.

required
beta float

Weighting factor for the commitment loss.

0.25
Source code in src/cv/models/vq_vae.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def __init__(
    self, size_discrete_space: int, size_embeddings: int, beta: float = 0.25
) -> None:
    """
    Initializes a vector quantizer with a learnable codebook.

    Args:
        size_discrete_space: Number of discrete embeddings.
        size_embeddings: Size of each embedding vector.
        beta: Weighting factor for the commitment loss.
    """

    super().__init__()

    self.size_discrete_space = size_discrete_space
    self.size_embeddings = size_embeddings
    self.beta = beta

    # Definimos el codebook como una matriz de K embeddings x D tamaño de embeddings
    # Ha de ser una matriz aprendible
    self.codebook = nn.Embedding(
        num_embeddings=self.size_discrete_space, embedding_dim=self.size_embeddings
    )
    # Initialize weights uniformly
    self.codebook.weight.data.uniform_(
        -1 / self.size_discrete_space, 1 / self.size_discrete_space
    )

2.1.5.1 forward(encoder_output)

Quantizes the encoder output using the codebook.

Parameters:

Name Type Description Default
encoder_output Tensor

Tensor of encoder outputs.

required

Returns:

Type Description
Tensor

A tuple containing VQ loss, quantized tensor, perplexity,

Tensor

and encodings.

Source code in src/cv/models/vq_vae.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
def forward(
    self, encoder_output: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
    """
    Quantizes the encoder output using the codebook.

    Args:
        encoder_output: Tensor of encoder outputs.

    Returns:
        A tuple containing VQ loss, quantized tensor, perplexity,
        and encodings.
    """

    # Comentario de otras implementaciones: The channels are used as the space
    # in which to quantize.
    # Encoder output ->  (B, C, H, W) -> (0, 1, 2, 3) -> (0, 2, 3, 1) -> (0*2*3, 1)
    encoder_output = encoder_output.permute(0, 2, 3, 1).contiguous()
    b, h, w, c = encoder_output.size()
    encoder_output_flat = encoder_output.reshape(-1, c)

    # Calculamos la distancia entre ambos vectores
    distances = (
        torch.sum(encoder_output_flat**2, dim=1, keepdim=True)
        + torch.sum(self.codebook.weight**2, dim=1)
        - 2 * torch.matmul(encoder_output_flat, self.codebook.weight.t())
    )

    # Realizamos el encoding y extendemos una dimension (B*H*W, 1)
    encoding_indices = torch.argmin(distances, dim=1).unsqueeze(1)

    # Matriz de ceros de (indices, size_discrete_space)
    encodings = torch.zeros(
        encoding_indices.shape[0],
        self.size_discrete_space,
        device=encoder_output.device,
    )
    # Colocamos un 1 en los indices de los encodings con el
    # valor mínimo de distancia creando un vector one-hot
    encodings.scatter_(1, encoding_indices, 1)

    # Se cuantiza colocando un cero en los pesos no relevantes (distancias grandes)
    # del codebook y le damos formato de nuevo al tensor
    quantized = torch.matmul(encodings, self.codebook.weight).view(b, h, w, c)

    # VQ-VAE loss terms
    # L = ||sg[z_e] - e||^2 + β||z_e - sg[e]||^2
    # FIX: Corrected variable names and loss calculation
    commitment_loss = F.mse_loss(
        quantized.detach(), encoder_output
    )  # ||sg[z_e] - e||^2
    embedding_loss = F.mse_loss(
        quantized, encoder_output.detach()
    )  # ||z_e - sg[e]||^2
    vq_loss = commitment_loss + self.beta * embedding_loss

    # Straight-through estimator
    quantized = encoder_output + (quantized - encoder_output).detach()

    # Calculate perplexity
    avg_probs = torch.mean(encodings, dim=0)
    perplexity = torch.exp(-torch.sum(avg_probs * torch.log(avg_probs + 1e-10)))

    # convert quantized from BHWC -> BCHW
    return (
        vq_loss,
        quantized.permute(0, 3, 1, 2).contiguous(),
        perplexity,
        encodings,
    )