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
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
305
306
307
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
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
| import logging
import os
from typing import Any, Dict, Optional, Union
import subprocess # New
import numpy as np # New
import yaml # New
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from sssd.core.model_specs import MASK_FN
from sssd.training.utils import training_loss
from sssd.utils.logger import setup_logger
from sssd.utils.utils import find_max_epoch, sampling # New
LOGGER = setup_logger()
class DiffusionTrainer:
"""
Train Diffusion Models
Args:
dataloader (DataLoader): The training dataloader.
diffusion_hyperparams (Dict[str, Any]): Hyperparameters for the diffusion process.
net (nn.Module): The neural network model to be trained.
device (torch.device): The device to be used for training.
output_directory (str): Directory to save model checkpoints.
ckpt_iter (Optional[int, str]): The checkpoint iteration to be loaded; 'max' selects the maximum iteration.
n_iters (int): Number of iterations to train.
iters_per_ckpt (int): Number of iterations to save checkpoint.
iters_per_logging (int): Number of iterations to save training log and compute validation loss.
learning_rate (float): Learning rate for training.
only_generate_missing (int): Option to generate missing portions of the signal only.
masking (str): Type of masking strategy: 'mnr' for Missing Not at Random, 'bm' for Blackout Missing, 'rm' for Random Missing.
missing_k (int): K missing time steps for each feature across the sample length.
batch_size (int): Size of each training batch.
logger (Optional[logging.Logger]): Logger object for logging, defaults to None.
"""
def __init__(
self,
dataloader: DataLoader,
diffusion_hyperparams: Dict[str, Any],
net: nn.Module,
device: Optional[Union[torch.device, str]],
output_directory: str,
ckpt_iter: Union[str, int],
n_iters: int,
iters_per_ckpt: int,
iters_per_logging: int,
learning_rate: float,
only_generate_missing: int,
masking: str,
missing_k: int,
batch_size: int,
enable_spatial_prediction: bool, # New
n_cores: Union[int, str], # New
autoFRK_period: int, # New
location_path: str, # New
logger: Optional[logging.Logger] = None,
) -> None:
self.dataloader = dataloader
self.diffusion_hyperparams = diffusion_hyperparams
self.net = nn.DataParallel(net).to(device)
self.device = device
self.output_directory = output_directory
self.ckpt_iter = ckpt_iter
self.n_iters = n_iters
self.iters_per_ckpt = iters_per_ckpt
self.iters_per_logging = iters_per_logging
self.learning_rate = learning_rate
self.only_generate_missing = only_generate_missing
self.masking = masking
self.missing_k = missing_k
self.writer = SummaryWriter(f"{output_directory}/log")
self.batch_size = batch_size
self.optimizer = torch.optim.Adam(self.net.parameters(), lr=self.learning_rate)
self.enable_spatial_prediction = enable_spatial_prediction # New
self.n_cores = n_cores # New
self.autoFRK_period = autoFRK_period # New
self.location_path = location_path # New
self.real_data = self.dataloader.dataset.tensors[0].to(self.device) # New
self.real_data_shape = self.real_data.shape # New
self.logger = logger or LOGGER
if self.masking not in MASK_FN:
raise KeyError(f"Please enter a correct masking, but got {self.masking}")
def _load_checkpoint(self) -> None:
if self.ckpt_iter == "max":
self.ckpt_iter = find_max_epoch(self.output_directory)
if self.ckpt_iter >= 0:
try:
model_path = os.path.join(
self.output_directory, f"{self.ckpt_iter}.pkl"
)
checkpoint = torch.load(model_path, map_location="cpu")
self.net.load_state_dict(checkpoint["model_state_dict"])
if "optimizer_state_dict" in checkpoint:
self.optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
self.logger.info(
f"Successfully loaded model at iteration {self.ckpt_iter}"
)
except Exception as e:
self.ckpt_iter = -1
self.logger.error(f"No valid checkpoint model found. Error: {e}")
else:
self.ckpt_iter = -1
self.logger.info(
"No valid checkpoint model found, start training from initialization."
)
def _save_model(self, n_iter: int) -> None:
if n_iter > 0 and n_iter % self.iters_per_ckpt == 0:
torch.save(
{
"model_state_dict": self.net.state_dict(),
"optimizer_state_dict": self.optimizer.state_dict(),
},
os.path.join(self.output_directory, f"{n_iter}.pkl"),
)
def _update_mask(self, batch: torch.Tensor) -> torch.Tensor:
transposed_mask = MASK_FN[self.masking](batch[0], self.missing_k)
return (
transposed_mask.permute(1, 0)
.repeat(batch.size()[0], 1, 1)
.to(self.device, dtype=torch.float32)
)
def _sssd_prediction_step(self,
) -> torch.Tensor:
# SSSD prediction
LOGGER.info(f"Start SSSD prediction step")
all_generated = []
with torch.no_grad():
for (batch,) in tqdm(self.dataloader, desc=f"{self.n_iter}-th predicting TS"):
batch = batch.to(self.device)
mask = self._update_mask(batch)
batch = batch.permute(0, 2, 1)
generated_series = (
sampling(
net=self.net,
size=batch.shape,
diffusion_hyperparams=self.diffusion_hyperparams,
cond=batch,
mask=mask,
only_generate_missing=self.only_generate_missing,
device=self.device,
)
)
all_generated.append(generated_series)
sssd_prediction = torch.cat(all_generated, dim=0).permute(1, 2, 0)
del all_generated
return sssd_prediction
def _autoFRK_step(self,
sssd_prediction,
) -> torch.Tensor:
# autoFRK
LOGGER.info(f"Start autoFRK inference step")
## config paths
sssd_pred_save_path = "sssd_prediction.npy"
autoFRK_config_path = "autoFRK_config.yaml"
autoFRK_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "utils", "autoFRK.R")
autoFRK_result_path = "autoFRK_result.npy"
## save sssd prediction and location config
sssd_prediction = sssd_prediction.detach().cpu().numpy()
np.save(sssd_pred_save_path, sssd_prediction)
del sssd_prediction
autoFRK_config = {
'ncores': self.n_cores,
'known_location_path': self.location_path
}
with open(autoFRK_config_path, "w") as f:
yaml.dump(autoFRK_config, f)
## run autoFRK
subprocess.run(["Rscript", autoFRK_path],
stdout=subprocess.DEVNULL, # 忽略標準輸出
#stderr=subprocess.DEVNULL # 忽略錯誤輸出
)
## load autoFRK inference result
autoFRK_result = np.load(autoFRK_result_path).transpose(2, 1, 0).astype(np.float32)
autoFRK_result = torch.from_numpy(autoFRK_result).to(self.device)
## clean up
if os.path.exists(sssd_pred_save_path):
os.remove(sssd_pred_save_path)
if os.path.exists(autoFRK_config_path):
os.remove(autoFRK_config_path)
if os.path.exists(autoFRK_result_path):
os.remove(autoFRK_result_path)
# return
if autoFRK_result.shape != self.real_data_shape:
raise ValueError(f"Shape mismatch: autoFRK_result {autoFRK_result.shape} != real_data {self.real_data_shape}")
return autoFRK_result
def _autoFRK_surrogate_layer(self,
sssd_prediction: torch.Tensor,
autoFRK_result: torch.Tensor,
epochs: int = 0,
lr: float = 1e-3,
element_wise: bool = True,
loss_function: nn.Module = nn.MSELoss(),
) -> torch.Tensor:
"""
Surrogate layer: 將 sssd_prediction 逼近 autoFRK_result。
Args:
sssd_prediction: Tensor 或 list of Tensors, shape (V,T,L)
autoFRK_result: Tensor, shape (V,T,L),用作監督目標
epochs: int,微調 surrogate 的迭代次數
lr: float,Adam optimizer learning rate
element_wise: bool,如果 True,對每個元素使用單獨 scale/bias
loss_function: torch loss function, 預設使用 MSELoss
Returns:
result: Tensor, shape (V,T,L),經 surrogate 層逼近 autoFRK_result
"""
LOGGER.info(f"Start autoFRK surrogate step")
# -----------------------------
# 取最後一個 batch 或 tensor
# -----------------------------
last_sssd = sssd_prediction[-1] if isinstance(sssd_prediction, list) else sssd_prediction
# -----------------------------
# 確認 shape 與 real_data_shape 一致
# -----------------------------
if (last_sssd.shape != self.real_data_shape) or (self.real_data_shape != autoFRK_result.shape):
msg = (
f"Shape mismatch: sssd_prediction {last_sssd.shape}, "
f"expected {self.real_data_shape}, "
f"autoFRK_result {None if autoFRK_result is None else autoFRK_result.shape}"
)
LOGGER.error(msg)
raise ValueError(msg)
V, T, L = self.real_data_shape
# -----------------------------
# 初始化 surrogate 參數
# -----------------------------
if not hasattr(self, 'surrogate_scale'):
if element_wise:
# 每個元素對應一個 scale/bias
self.surrogate_scale = nn.Parameter(torch.ones((V, T, L), device=self.device))
self.surrogate_bias = nn.Parameter(torch.zeros((V, T, L), device=self.device))
else:
# 每個變數一個 scale/bias
self.surrogate_scale = nn.Parameter(torch.ones(V, device=self.device))
self.surrogate_bias = nn.Parameter(torch.zeros(V, device=self.device))
# -----------------------------
# 定義 surrogate 前向函數
# -----------------------------
def surrogate_forward(x: torch.Tensor) -> torch.Tensor:
if element_wise:
# element-wise scale/bias
return x * self.surrogate_scale + self.surrogate_bias
else:
# per-variable scale/bias (broadcast)
return x * self.surrogate_scale[:, None, None] + self.surrogate_bias[:, None, None]
# -----------------------------
# closed-form 初始化(不進梯度圖)
# -----------------------------
x = last_sssd.detach()
y = autoFRK_result.detach()
if element_wise:
# 對每個元素單獨計算 scale/bias: y = a*x + b
a = torch.ones_like(x)
b = torch.zeros_like(x)
# 避免除以 0
mask = x != 0
a[mask] = y[mask] / x[mask]
b = y - a * x
else:
# 對每個變數計算 scale/bias
x_flat = x.reshape(V, -1)
y_flat = y.reshape(V, -1)
x_mean = x_flat.mean(dim=1, keepdim=True)
y_mean = y_flat.mean(dim=1, keepdim=True)
cov = ((x_flat - x_mean) * (y_flat - y_mean)).sum(dim=1)
var = ((x_flat - x_mean)**2).sum(dim=1) + 1e-8
a = cov / var
b = (y_mean.squeeze() - a * x_mean.squeeze())
with torch.no_grad():
self.surrogate_scale.copy_(a.to(self.device))
self.surrogate_bias.copy_(b.to(self.device))
# -----------------------------
# 微調 (保持可微分)
# -----------------------------
if epochs > 0:
optimizer = torch.optim.Adam([self.surrogate_scale, self.surrogate_bias], lr=lr)
with tqdm(range(epochs), desc="[autoFRK surrogate]") as pbar:
for epoch in pbar:
optimizer.zero_grad()
surrogate_out = surrogate_forward(last_sssd)
loss = loss_function(surrogate_out, autoFRK_result)
loss.backward()
optimizer.step()
pbar.set_postfix({"Loss": f"{loss.item():.6f}"})
# -----------------------------
# 前向傳遞 (保持可微)
# -----------------------------
result = surrogate_forward(last_sssd)
return result
def _train_per_epoch(self) -> torch.Tensor:
# SSSD training
for (batch,) in tqdm(self.dataloader, desc=f"{self.n_iter}-th training TS"):
batch = batch.to(self.device)
mask = self._update_mask(batch)
loss_mask = ~mask.bool()
loss_function=nn.MSELoss()
batch = batch.permute(0, 2, 1)
assert batch.size() == mask.size() == loss_mask.size()
self.optimizer.zero_grad()
loss = training_loss(
model=self.net,
loss_function=loss_function,
training_data=(batch, batch, mask, loss_mask),
diffusion_parameters=self.diffusion_hyperparams,
generate_only_missing=self.only_generate_missing,
device=self.device,
)
loss.backward()
self.optimizer.step()
if self.enable_spatial_prediction and self.n_iter % self.autoFRK_period == 0:
LOGGER.info(f"Iteration {self.n_iter}: Start Spatial Prediction step")
sssd_prediction = self._sssd_prediction_step()
autoFRK_result = self._autoFRK_step(sssd_prediction=sssd_prediction)
autoFRK_surrogate = self._autoFRK_surrogate_layer(sssd_prediction=sssd_prediction.permute(2, 1, 0),
autoFRK_result=autoFRK_result,
loss_function=loss_function,
epochs=50,
lr=1e-3
)
# compute loss
self.optimizer.zero_grad()
loss = loss_function(
autoFRK_surrogate,
self.real_data
)
# update model
loss.backward()
self.optimizer.step()
LOGGER.info(f"Iteration {self.n_iter}: Spatial Prediction step done, loss: {loss.item()}")
return loss
def train(self) -> None:
self._load_checkpoint()
n_iter_start = (
self.ckpt_iter + 2 if self.ckpt_iter == -1 else self.ckpt_iter + 1
)
self.logger.info(f"Start the {n_iter_start} iteration")
for n_iter in range(n_iter_start, self.n_iters + 1):
self.n_iter = n_iter
loss = self._train_per_epoch()
self.writer.add_scalar("Train/Loss", loss.item(), n_iter)
if n_iter % self.iters_per_logging == 0:
self.logger.info(f"Iteration: {n_iter} \tLoss: { loss.item()}")
self._save_model(n_iter)
|