File size: 6,359 Bytes
83034b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import wandb
import os
import matplotlib.pyplot as plt
import random

is_wandb_enabled = os.getenv("WANDB_DISABLED", "false").lower() != "true"

def get_next_directory(base_dir="results", sub_dir="train"):
    result_dir = os.path.join(base_dir, sub_dir)
    if not os.path.exists(result_dir):
        os.makedirs(result_dir)

    run_id = 0
    while True:
        run_dir = os.path.join(result_dir, f"VAL_Images_StyleTransfer_{run_id}")
        if not os.path.exists(run_dir):
            os.makedirs(run_dir)
            return run_dir, run_id
        run_id += 1


def init_project(base_dir="results", sub_dir="train"):
    project_dir, run_id = get_next_directory(base_dir, sub_dir)

    if is_wandb_enabled:
        # `name` là cố định, còn `project` sẽ là VAL_Images_StyleTransfer_{run_id}
        wandb.init(project=f"VAL_Images_StyleTransfer", name=f"VAL_Images_StyleTransfer_{run_id}r")

    return project_dir


def upload_images(images, iters, img_index, epoch):
    dir_name = f"epoch_{epoch}_iters_{iters}"
    if not os.path.exists(dir_name):
        os.makedirs(dir_name)

    for i, img in enumerate(images):
        img_name = f"img_{img_index}_{iters}_{epoch}.png"
        img_path = os.path.join(dir_name, img_name)
        plt.figure()
        plt.imshow(img)
        plt.title(f"Image {img_index} | Iter {iters} | Epoch {epoch}")
        plt.axis('off')

        plt.savefig(img_path)
        plt.close()

        if is_wandb_enabled:
            wandb.log({f"epoch_{epoch}/img_{img_index}_{iters}_{epoch}": wandb.Image(img_path)})


#### ON ONE IMAGES
previous_iters_all_images = -1
last_iters=0


def reset_iters_if_needed(iters_all_images):
    global previous_iters_all_images

    if iters_all_images > previous_iters_all_images:
        previous_iters_all_images = iters_all_images
        return True  # Cần reset cho section mới
    return False


def get_section_name(epoch, iters_all_images):
    return f"Iters on all Images_epoch{epoch}_iters{iters_all_images}"


def define_wandb_metrics(epoch, iters_all_images):
    section_name = get_section_name(epoch, iters_all_images)
    if is_wandb_enabled:
        # Định nghĩa metric cho từng section (epoch + iters_all_images)
        wandb.define_metric(f"{section_name}/All_loss_on_one_images", step_metric=f"{section_name}_step")
        wandb.define_metric(f"{section_name}/L1_loss_on_one_images", step_metric=f"{section_name}_step")
        wandb.define_metric(f"{section_name}/L2_loss_on_one_images", step_metric=f"{section_name}_step")
        wandb.define_metric(f"{section_name}/Content_loss_on_one_images", step_metric=f"{section_name}_step")
        wandb.define_metric(f"{section_name}/Style_loss_on_one_images", step_metric=f"{section_name}_step")


def upload_all_loss_on_one_images(loss_value, iters_one_imgs, iters_all_images, epoch):
    if reset_iters_if_needed(iters_all_images):
        iters_one_imgs = last_iters+iters_one_imgs
        define_wandb_metrics(epoch, iters_all_images)  # Định nghĩa các metric cho section mới

    section_name = get_section_name(epoch, iters_all_images)

    if is_wandb_enabled:
        wandb.log({f"{section_name}/All_loss_on_one_images": loss_value, f"{section_name}_step": iters_one_imgs})


def upload_l1_loss_on_one_images(loss_value, iters_one_imgs, iters_all_images, epoch):
    section_name = get_section_name(epoch, iters_all_images)

    if is_wandb_enabled:
        wandb.log({f"{section_name}/L1_loss_on_one_images": loss_value, f"{section_name}_step": iters_one_imgs})


def upload_l2_loss_on_one_images(loss_value, iters_one_imgs, iters_all_images, epoch):
    section_name = get_section_name(epoch, iters_all_images)

    if is_wandb_enabled:
        wandb.log({f"{section_name}/L2_loss_on_one_images": loss_value, f"{section_name}_step": iters_one_imgs})


def upload_content_loss_on_one_images(loss_value, iters_one_imgs, iters_all_images, epoch):
    section_name = get_section_name(epoch, iters_all_images)

    if is_wandb_enabled:
        wandb.log({f"{section_name}/Content_loss_on_one_images": loss_value, f"{section_name}_step": iters_one_imgs})


def upload_style_loss_on_one_images(loss_value, iters_one_imgs, iters_all_images, epoch):
    section_name = get_section_name(epoch, iters_all_images)

    if is_wandb_enabled:
        wandb.log({f"{section_name}/Style_loss_on_one_images": loss_value, f"{section_name}_step": iters_one_imgs})




### ON ALL IMAGES

def upload_l1_loss_all(loss_values, iters_images, epoch):
    if is_wandb_enabled:
        wandb.log({f"epoch_{epoch}/L1_loss": loss_values}, step=iters_images)



def upload_l2_loss(loss_values, iters, epoch):
    if is_wandb_enabled:
        wandb.log({f"epoch_{epoch}/L2_loss": loss_values}, step=iters)


def upload_content_loss(loss_c, iters, epoch):
    if is_wandb_enabled:
        wandb.log({f"epoch_{epoch}/Content_loss": loss_c}, step=iters)


def upload_style_loss(loss_s, iters, epoch):
    if is_wandb_enabled:
        wandb.log({f"epoch_{epoch}/Style_loss": loss_s}, step=iters)


def upload_epoch(epoch,iter_images):
    if is_wandb_enabled:
        wandb.log({"epoch": epoch})


def upload_lr(lr,epoch):
    if is_wandb_enabled:
        wandb.log({"learning_rate": lr})


def upload_loss_all(loss_all, iters, epoch):
    if is_wandb_enabled:
        wandb.log({f"epoch_{epoch}/Total_loss": loss_all}, step=iters)


def logs_model(model_params):
    """Ghi log các tham số của mô hình lên Wandb."""
    if is_wandb_enabled:
        wandb.log({"model_parameters": model_params})


def logs_params(params):
    """Ghi log các tham số khác lên Wandb."""
    if is_wandb_enabled:
        wandb.log({"params": params})


# def save_model_weights(model, epoch, project_dir):
#     """Lưu weights của model theo từng epoch."""
#     weights_dir = os.path.join(project_dir, f"epoch_{epoch}")
#     if not os.path.exists(weights_dir):
#         os.makedirs(weights_dir)
#
#     weights_path = os.path.join(weights_dir, f"weights_epoch_{epoch}.pth")
#     torch.save(model.state_dict(), weights_path)  # Lưu weights vào file .pth
#
#     if is_wandb_enabled:
#         wandb.save(weights_path)


def logs_running(terminal_output):
    if is_wandb_enabled:
        wandb.log({"terminal_output": wandb.Html(terminal_output)})

def stop():
    if is_wandb_enabled:
        wandb.finish()