File size: 9,504 Bytes
c8ddb9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
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
234
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
"""Helper functions for models."""

import pathlib
import pickle
from copy import deepcopy
from pathlib import Path
from typing import Any, List, Dict

import matplotlib.pyplot as plt
import numpy as np
import torch
from PIL import Image
from torch import optim

from src.models.modules.discriminator import Discriminator
from src.models.modules.generator import Generator
from src.models.modules.image_encoder import InceptionEncoder
from src.models.modules.text_encoder import TextEncoder

# pylint: disable=too-many-arguments
# pylint: disable=too-many-locals


def copy_gen_params(generator: Generator) -> Any:
    """
    Function to copy the parameters of the generator
    """
    params = deepcopy(list(p.data for p in generator.parameters()))
    return params


def define_optimizers(
    generator: Generator,
    discriminator: Discriminator,
    image_encoder: InceptionEncoder,
    text_encoder: TextEncoder,
    lr_config: Dict[str, float],
) -> Any:
    """
    Function to define the optimizers for the generator and discriminator
    :param generator: Generator model
    :param image_encoder: Image encoder model
    :param text_encoder: Text encoder model
    :param discriminator: Discriminator model
    :param lr_config: Dictionary containing the learning rates for the optimizers

    """
    img_encoder_lr = lr_config["img_encoder_lr"]
    text_encoder_lr = lr_config["text_encoder_lr"]
    gen_lr = lr_config["gen_lr"]
    disc_lr = lr_config["disc_lr"]

    optimizer_g = optim.Adam(
        [{"params": generator.parameters()}],
        lr=gen_lr,
        betas=(0.5, 0.999),
    )
    optimizer_d = optim.Adam(
        [{"params": discriminator.parameters()}],
        lr=disc_lr,
        betas=(0.5, 0.999),
    )
    optimizer_text_encoder = optim.Adam(text_encoder.parameters(), lr=text_encoder_lr)
    optimizer_image_encoder = optim.Adam(image_encoder.parameters(), lr=img_encoder_lr)

    return optimizer_g, optimizer_d, optimizer_text_encoder, optimizer_image_encoder


def prepare_labels(batch_size: int, max_seq_len: int, device: torch.device) -> Any:
    """
    Function to prepare the labels for the discriminator and generator.
    """
    real_labels = torch.FloatTensor(batch_size, 1).fill_(1).to(device)
    fake_labels = torch.FloatTensor(batch_size, 1).fill_(0).to(device)
    match_labels = torch.LongTensor(range(batch_size)).to(device)
    fake_word_labels = torch.FloatTensor(batch_size, max_seq_len).fill_(0).to(device)

    return real_labels, fake_labels, match_labels, fake_word_labels


def load_params(generator: Generator, new_params: Any) -> Any:
    """
    Function to load new parameters to the generator
    """
    for param, new_p in zip(generator.parameters(), new_params):
        param.data.copy_(new_p)


def get_image_arr(image_tensor: torch.Tensor) -> Any:
    """
    Function to convert a tensor to an image array.
    :param image_tensor: Tensor containing the image (shape: (batch_size, channels, height, width))
    """

    image = image_tensor.cpu().detach().numpy()
    image = (image + 1) * (255 / 2.0)
    image = np.transpose(image, (0, 2, 3, 1))  # (B,C,H,W) -> (B,H,W,C)
    image = image.astype(np.uint8)
    return image  # (B,H,W,C)


def get_captions(captions: torch.Tensor, ix2word: Dict[int, str]) -> Any:
    """
    Function to convert a tensor to a list of captions.
    :param captions: Tensor containing the captions (shape: (batch_size, max_seq_len))
    :param ix2word: Dictionary mapping indices to words
    """
    captions = captions.cpu().detach().numpy()
    captions = [[ix2word[ix] for ix in cap if ix != 0] for cap in captions]  # type: ignore
    return captions


def save_model(
    generator: Generator,
    discriminator: Discriminator,
    image_encoder: InceptionEncoder,
    text_encoder: TextEncoder,
    epoch: int,
    output_dir: pathlib.PosixPath,
) -> None:
    """
    Function to save the model.
    :param generator: Generator model
    :param discriminator: Discriminator model
    :param image_encoder: Image encoder model
    :param text_encoder: Text encoder model
    :param params: Parameters of the generator
    :param epoch: Epoch number
    :param output_dir: Output directory
    """
    output_path = output_dir / "weights/"
    Path(output_path / "generator").mkdir(parents=True, exist_ok=True)
    torch.save(
        generator.state_dict(), output_path / f"generator/generator_epoch_{epoch}.pth"
    )
    Path(output_path / "discriminator").mkdir(parents=True, exist_ok=True)
    torch.save(
        discriminator.state_dict(),
        output_path / f"discriminator/discriminator_epoch_{epoch}.pth",
    )
    Path(output_path / "image_encoder").mkdir(parents=True, exist_ok=True)
    torch.save(
        image_encoder.state_dict(),
        output_path / f"image_encoder/image_encoder_epoch_{epoch}.pth",
    )
    Path(output_path / "text_encoder").mkdir(parents=True, exist_ok=True)
    torch.save(
        text_encoder.state_dict(),
        output_path / f"text_encoder/text_encoder_epoch_{epoch}.pth",
    )
    print(f"Model saved at epoch {epoch}.")


def save_image_and_caption(
    fake_img_tensor: torch.Tensor,
    img_tensor: torch.Tensor,
    captions: torch.Tensor,
    ix2word: Dict[int, str],
    batch_idx: int,
    epoch: int,
    output_dir: pathlib.PosixPath,
) -> None:
    """
    Function to save an image and its corresponding caption.
    :param fake_img_tensor: Tensor containing the generated image
    (shape: (batch_size, channels, height, width))

    :param img_tensor: Tensor containing the image
    (shape: (batch_size, channels, height, width))

    :param captions: Tensor containing the captions
    (shape: (batch_size, max_seq_len))

    :param ix2word: Dictionary mapping indices to words
    :param batch_idx: Batch index
    :param epoch: Epoch number
    :param output_dir: Output directory
    """
    output_path = output_dir
    output_path_text = output_dir
    capt_list = get_captions(captions, ix2word)
    img_arr = get_image_arr(img_tensor)
    fake_img_arr = get_image_arr(fake_img_tensor)
    for i in range(img_arr.shape[0]):
        img = Image.fromarray(img_arr[i])
        fake_img = Image.fromarray(fake_img_arr[i])

        fake_img_path = (
            output_path / f"generated/{epoch}_epochs/{batch_idx}_batch/{i+1}.png"
        )
        img_path = output_path / f"real/{epoch}_epochs/{batch_idx}_batch/{i+1}.png"
        text_path = (
            output_path_text / f"text/{epoch}_epochs/{batch_idx}_batch/captions.txt"
        )

        Path(fake_img_path).parent.mkdir(parents=True, exist_ok=True)
        Path(img_path).parent.mkdir(parents=True, exist_ok=True)
        Path(text_path).parent.mkdir(parents=True, exist_ok=True)

        fake_img.save(fake_img_path)
        img.save(img_path)

        with open(text_path, "a", encoding="utf-8") as txt_file:
            text_str = str(i + 1) + ": " + " ".join(capt_list[i])
            txt_file.write(text_str)
            txt_file.write("\n")


def save_plot(
    gen_loss: List[float],
    disc_loss: List[float],
    epoch: int,
    batch_idx: int,
    output_dir: pathlib.PosixPath,
) -> None:
    """
    Function to save the plot of the loss.
    :param gen_loss: List of generator losses
    :param disc_loss: List of discriminator losses
    :param epoch: Epoch number
    :param batch_idx: Batch index
    :param output_dir: Output directory
    """
    pickle_path = output_dir / "losses/"
    output_path = output_dir / "plots" / f"{epoch}_epochs/{batch_idx}_batch/"
    Path(output_path).mkdir(parents=True, exist_ok=True)
    Path(pickle_path).mkdir(parents=True, exist_ok=True)

    with open(pickle_path / "gen_loss.pkl", "wb") as pickl_file:
        pickle.dump(gen_loss, pickl_file)

    with open(pickle_path / "disc_loss.pkl", "wb") as pickl_file:
        pickle.dump(disc_loss, pickl_file)

    plt.style.use("fivethirtyeight")
    plt.figure(figsize=(24, 12))
    plt.plot(gen_loss, label="Generator Loss")
    plt.plot(disc_loss, label="Discriminator Loss")
    plt.xlabel("No of Iterations")
    plt.ylabel("Loss")
    plt.legend()
    plt.savefig(output_path / "loss.png", bbox_inches="tight")
    plt.clf()
    plt.close()


def load_model(
    generator: Generator,
    discriminator: Discriminator,
    image_encoder: InceptionEncoder,
    text_encoder: TextEncoder,
    output_dir: pathlib.Path,
    device: torch.device
) -> None:
    """
    Function to load the model.
    :param generator: Generator model
    :param discriminator: Discriminator model
    :param image_encoder: Image encoder model
    :param text_encoder: Text encoder model
    :param output_dir: Output directory
    :param device: device to map the location of weights
    """
    if (output_dir / "generator.pth").exists():
        generator.load_state_dict(torch.load(output_dir / "generator.pth", map_location=device))
        print("Generator loaded.")
    if (output_dir / "discriminator.pth").exists():
        discriminator.load_state_dict(torch.load(output_dir / "discriminator.pth", map_location=device))
        print("Discriminator loaded.")
    if (output_dir / "image_encoder.pth").exists():
        image_encoder.load_state_dict(torch.load(output_dir / "image_encoder.pth", map_location=device))
        print("Image Encoder loaded.")

    if (output_dir / "text_encoder.pth").exists():
        text_encoder.load_state_dict(torch.load(output_dir / "text_encoder.pth", map_location=device))
        print("Text Encoder loaded.")