目錄

1140701 meeting

前言

在參加第 34 屆南區統計研討會後,收穫良多,對 $SSSD^S4$ 模型做出以下修改。

想法

此處想將輸入與輸出的捲基層分別乘上空間基底,並於輸出後乘上空間基底的反矩陣,用於還原。

/sssd/core/imputers/SSSDS4Imputer.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class SSSDS4Imputer(nn.Module):
    ...

    def forward(self, input_data):
    noise, conditional, mask, diffusion_steps = input_data

    # Handle mask and concatenate it to the conditional input
    conditional = conditional * mask
    conditional = torch.cat([conditional, mask.float()], dim=1)

    # Forward pass through the network
    x = noise  # Ensure x is 3D (B, C, L)
    print(f'\nInput noise shape: {x.shape}')
    x = self.init_conv(x)
    print(f'After init_conv: {x.shape}')
    x = self.residual_layer((x, conditional, diffusion_steps))
    print(f'After residual_layer: {x.shape}')
    y = self.final_conv(x)
    print(f'After final_conv: {y.shape}')

    return y

我們可以查看訓練結果,得知

執行結果參考
1
2
3
4
Input noise shape: torch.Size([1, 26, 2000])
After init_conv: torch.Size([1, 256, 2000])
After residual_layer: torch.Size([1, 256, 2000])
After final_conv: torch.Size([1, 26, 2000])

可以知道輸入的 $[1, 26, 2000]$ 為 $[B, K, L]$ 。 $B$ 為 batch size , $K$ 為 feature size , $L$ 為 time steps 。 而 $K$ 從 $26$ 轉為 $256$ ,這裡的 $256$ 為 \configs\model.yaml 設定中的 residual_channels

爾後將修改此處程式碼的 xy ,並與空間基底相乘。

修改

原 Imputer 如下

/sssd/core/imputers/SSSDS4Imputer.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class SSSDS4Imputer(nn.Module):
    ...

    def forward(self, input_data):
        noise, conditional, mask, diffusion_steps = input_data

        # Handle mask and concatenate it to the conditional input
        conditional = conditional * mask
        conditional = torch.cat([conditional, mask.float()], dim=1)

        # Forward pass through the network
        x = noise  # Ensure x is 3D (B, C, L)
        x = self.init_conv(x)
        x = self.residual_layer((x, conditional, diffusion_steps))
        y = self.final_conv(x)

        return y

修改如下 /sssd/core/imputers/SSSDS4Imputer.py

 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
class SSSDS4Imputer(nn.Module):
        def __init__(
        self,
        input_channels,
        residual_channels,
        skip_channels,
        output_channels,
        residual_layers,
        diffusion_step_embed_dim_input,
        diffusion_step_embed_dim_hidden,
        diffusion_step_embed_dim_output,
        s4_max_sequence_length,
        s4_state_dim,
        s4_dropout,
        s4_bidirectional,
        s4_use_layer_norm,
        mrts_matrix, # 新增
        device="cuda",
    ):

    ...
    self.mrts_matrix = mrts_matrix
    
    def forward(self, input_data):
        noise, conditional, mask, diffusion_steps = input_data

        # Handle mask and concatenate it to the conditional input
        conditional = conditional * mask
        conditional = torch.cat([conditional, mask.float()], dim=1)

        # Forward pass through the network
        M = self.mrts_matrix
        #print(M.shape, M.type())
        x = noise  # Ensure x is 3D (B, C, L)

        #print(f'\nInput noise shape: {x.shape}')

        x = x.transpose(1, 2)        # [B, C, L] → [B, L, C] | (1, 26, 2000) → (1, 2000, 26)
        x = torch.matmul(x, M)       # [B, L, C] @ [C, M] = [B, L, M] | (1, 2000, 26) @ (26, M) = (1, 2000, M) | M is MRTS, shape: (26, p)
        x = x.transpose(1, 2)        # [B, L, M] → [B, M, L] | (1, 2000, M) → (1, M, 2000)


        #print(f'After transpose: {x.shape}')
        x = self.init_conv(x)
        #print(f'After init_conv: {x.shape}')
        x = self.residual_layer((x, conditional, diffusion_steps))
        #print(f'After residual_layer: {x.shape}')
        y = self.final_conv(x)
        #print(f'After final_conv: {y.shape}')


        M_inv = torch.linalg.pinv(M)        # pseudo-inverse | M_inv shape: (p, 26)
        y = y.transpose(1, 2)                       # [B, M, L] → [B, L, M] | (1, M, 2000) → (1, 2000, M)
        y = torch.matmul(y, M_inv)                  # [B, L, M] @ [M_inv, C] = [B, L, C] | (1, 2000, M) @ (M_inv, 26) = (1, 2000, 26) | M is MRTS
        y = y.transpose(1, 2)                       # [B, L, C] → [B, C, L] | (1, 2000, 26) → (1, 26, 2000)

        #print(f'Final output shape: {y.shape}')

        return y

並將 /scripts/diffusion/train.py 修改如下

  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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
import argparse
import os
from typing import Optional, Union

import torch
import yaml

from sssd.core.model_specs import MODEL_PATH_FORMAT, setup_model
from sssd.data.utils import get_dataloader
from sssd.training.trainer import DiffusionTrainer
from sssd.utils.logger import setup_logger
from sssd.utils.utils import calc_diffusion_hyperparams, display_current_time


import numpy as np
import torch
import torch.nn as nn
from scipy.integrate import quad
from scipy.sparse.linalg import eigsh
from typing import Optional, Union

LOGGER = setup_logger()


def fetch_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-m",
        "--model_config",
        type=str,
        default="configs/model.yaml",
        help="Model configuration",
    )
    parser.add_argument(
        "-t",
        "--training_config",
        type=str,
        default="configs/training.yaml",
        help="Training configuration",
    )
    return parser.parse_args()


def setup_output_directory(
    model_config: dict,
    training_config: dict,
) -> str:
    # Build output directory
    local_path = MODEL_PATH_FORMAT.format(
        T=model_config["diffusion"]["T"],
        beta_0=model_config["diffusion"]["beta_0"],
        beta_T=model_config["diffusion"]["beta_T"],
    )
    output_directory = os.path.join(training_config["output_directory"], local_path)

    if not os.path.isdir(output_directory):
        os.makedirs(output_directory)
        os.chmod(output_directory, 0o775)
    LOGGER.info("Output directory %s", output_directory)
    return output_directory

# New function to load locations
def get_locations_loader(location_path, device: torch.device) -> torch.Tensor:
    locations = np.load(location_path)
    locations_tensor = torch.from_numpy(locations).float().to(device)
    return locations_tensor

def run_job(
    model_config: dict,
    training_config: dict,
    device: Optional[Union[torch.device, str]],
) -> None:
    output_directory = setup_output_directory(model_config, training_config)
    dataloader = get_dataloader(
        training_config["data"]["train_path"],
        batch_size=training_config.get("batch_size"),
        device=device,
    )

    diffusion_hyperparams = calc_diffusion_hyperparams(
        **model_config["diffusion"], device=device
    )



    LOGGER.info(display_current_time())


    locs = get_locations_loader(training_config["data"]["location_path"], device)
    mrts = MRTS(locs=locs, k=locs.shape[0], device=device).forward()

    net = setup_model(training_config["use_model"], model_config, mrts, device)


    trainer = DiffusionTrainer(
        dataloader=dataloader,
        diffusion_hyperparams=diffusion_hyperparams,
        net=net,
        device=device,
        output_directory=output_directory,
        ckpt_iter=training_config.get("ckpt_iter"),
        n_iters=training_config.get("n_iters"),
        iters_per_ckpt=training_config.get("iters_per_ckpt"),
        iters_per_logging=training_config.get("iters_per_logging"),
        learning_rate=training_config.get("learning_rate"),
        only_generate_missing=training_config.get("only_generate_missing"),
        masking=training_config.get("masking"),
        missing_k=training_config.get("missing_k"),
        batch_size=training_config.get("batch_size"),
        logger=LOGGER,
    )
    trainer.train()

    LOGGER.info(display_current_time())


class MRTS(nn.Module):
    def __init__(self, locs: torch.Tensor, 
                 k: int=None, 
                 device: Optional[Union[torch.device, str]]=None, 
                 calculate_with_spherical: bool=False, 
                 standardize: bool=True, 
                 unbiased_std: bool=False
                 ):
        """
        Multi-Resolution Thin-plate Spline basis function.
        
        Args:
            locs: [N, d] tensor of spatial locations.
            k: (Optional) parameter for controlling resolution.
            device: (Optional) PyTorch device to use.
            calculate_with_spherical: (Optional) If True, use spherical coordinates for TPS calculation (default is False) (only supported when d == 2).
            standardize: (Optional) If True, perform standardization on locs (Recommended).
            unbiased_std: (Optional) If True, use unbiased standard deviation (dividing by N-1) (Recommended); 
                          if False, use biased standard deviation (dividing by N).
        """
        self.logger = LOGGER
        logger = self.logger
        super().__init__()
        try:
            if device is None:
                self.device = torch.device('cpu')
                logger.warning(f'Parameter "device" was not set. Default value "cpu" is used.')
            else:
                self.device = torch.device(device)
                logger.info(f'Successfully using device "{self.device}".')
        except (TypeError, ValueError) as e:
            self.device = torch.device('cpu')
            logger.warning(f'Parameter "device" is not a valid device ({device}). Default value "cpu" is used. Error: {e}')

        self.register_buffer("locs", locs.to(self.device))
        self.N, self.d = locs.shape

        # number of basis
        max_k = self.N + self.d
        try:
            if k is None:
                self.k = max_k
                logger.warning(f'Parameter "k" was not set. Default value {self.k} is used.')
            elif 0 < k <= (max_k):
                self.k = k
            else:
                self.k = max_k
                logger.warning(f'Parameter "k" is out of valid range, it should be between 1 to {self.k}. Default value {self.k} is used.')
        except TypeError:
            self.k = max_k
            logger.warning(f'Parameter "k" is not an integer, the type you input is "{type(k).__name__}." Default value {self.k} is used.')

        self.calculate_with_spherical = calculate_with_spherical
        if type(self.calculate_with_spherical) is not bool:
            self.calculate_with_spherical = False
            logger.warning(f'Parameter "calculate_with_spherical" should be a boolean, the type you input is "{type(calculate_with_spherical).__name__}". Default value False is used.')
        elif self.calculate_with_spherical and self.d != 2:
            self.calculate_with_spherical = False
            logger.warning(f'Spherical TPS not implemented for d = {self.d}, only d = 2 is supported. Using rectangular coordinate system instead.')
        
        if self.calculate_with_spherical:
            logger.info(f'Calculate TPS with spherical coordinates.')
        else:
            logger.info(f'Calculate TPS with rectangular coordinates.')

        self.standardize = standardize
        if type(self.standardize) is not bool:
            self.standardize = True
            logger.warning(f'Parameter "standardize" should be a boolean, the type you input is "{type(standardize).__name__}". Default value True is used.')

        self.unbiased_std = unbiased_std
        if type(self.unbiased_std) is not bool:
            self.unbiased_std = False
            logger.warning(f'Parameter "unbiased_std" should be a boolean, the type you input is "{type(unbiased_std).__name__}". Default value False is used.')

    def _tps_phi(self, locs: torch.Tensor, calculate_with_spherical: bool=False) -> torch.Tensor:
        """
        Compute the Thin Plate Spline (TPS) radial basis matrix for input locations.

        Args:
            locs: [N, d] tensor of spatial locations.
            calculate_with_spherical: (Optional) If True, use spherical coordinates for TPS calculation (default is False) (only supported when d == 2).

        Returns:
            A [N, N] tensor representing the TPS radial basis matrix.
        """       

        # rectangular coordinate system
        if not calculate_with_spherical:
            return self.__calculate_phi_by_rectangular_coordinate(locs)
        
        # spherical coordinate system
        else:
            # convert to spherical coordinates
            ret = torch.zeros((self.N, self.N), device=locs.device)
            locs = locs * torch.pi / 180.0
            x = locs[:, 0]
            y = locs[:, 1]
            for i in range(self.N):
                for j in range(self.N):
                    ret[i, j] = self.__calculate_phi_by_spherical_coordinate(x[i], y[i], x[j], y[j])
            return ret

    def __calculate_phi_by_rectangular_coordinate(self, locs: torch.Tensor) -> torch.Tensor:
        """
        Calculate the TPS radial basis matrix using rectangular (Euclidean) coordinates.

        Args:
            locs: [N, d] tensor of spatial locations.

        Returns:
            A [N, N] tensor representing the TPS radial basis matrix.
        """
        dists = torch.cdist(locs, locs)  # Euclidean distances
        if self.d == 1:
            return (dists ** 3) / 12
        elif self.d == 2:
            mask = dists != 0
            ret = torch.zeros_like(dists)
            ret[mask] = (dists[mask] ** 2) * torch.log(dists[mask]) / (8 * torch.pi)
            return ret
        elif self.d == 3:
            return -dists / 8
        else:
            raise NotImplementedError(f"TPS not implemented for d = {self.d}")

    def __calculate_phi_by_spherical_coordinate(self, x1: float, y1: float, x2: float, y2: float) -> float:
        """
        Calculate the TPS radial basis function using spherical coordinates.
        
        Args:
            x1, y1: Spherical coordinates of the first point (in radians).
            x2, y2: Spherical coordinates of the second point (in radians). 

        Returns:
            A float representing the TPS radial basis function value.
        """
        cos_theta = torch.sin(x1) * torch.sin(x2) + torch.cos(x1) * torch.cos(x2) * torch.cos(y1 - y2)
        cos_theta = torch.clamp(cos_theta, -1.0, 1.0)
        #theta = torch.acos(cos_theta)
        ret = 1 - (torch.pi ** 2) / 6

        if not torch.isclose(cos_theta, torch.tensor(-1.0, device=cos_theta.device)):
            cos_theta = cos_theta.item()
            upper = (cos_theta + 1) / 2
            lower = 0
            result, _ = quad(self.__integrand_for_spherical_in_tps, lower, upper, epsabs=1e-6, epsrel=1e-6, limit=50)
            result = torch.tensor(result, dtype=torch.float32, device=self.device)
            ret -= result
        return ret
    
        # # method by GPT can just use tenser to calculate and efficient
        # # spherical coordinate system
        # locs_rad = locs * torch.pi / 180.0  # convert to radians
        # lat1 = locs_rad[:, 0].unsqueeze(1)  # [N, 1]
        # lon1 = locs_rad[:, 1].unsqueeze(1)  # [N, 1]
        # lat2 = locs_rad[:, 0].unsqueeze(0)  # [1, N]
        # lon2 = locs_rad[:, 1].unsqueeze(0)  # [1, N]

        # # Cosine of angular distance
        # cos_theta = (
        #     torch.sin(lat1) @ torch.sin(lat2) + torch.cos(lat1) @ torch.cos(lat2) * torch.cos(lon1 - lon2)
        # )
        # cos_theta = torch.clamp(cos_theta, -1.0, 1.0)

        # # Compute integral using trapezoidal rule
        # N = 100  # Number of steps in the integral approximation
        # x = torch.linspace(1e-6, 1.0, N, device=locs.device)  # avoid x=0
        # ln_term = torch.log(1 - x) / x  # [N]

        # def trapezoid_integrate(upper):  # upper: [N, N]
        #     upper = torch.clamp(upper, 1e-6, 1.0)
        #     area = torch.zeros_like(upper)
        #     for i in range(N - 1):
        #         x0, x1 = x[i], x[i + 1]
        #         y0, y1 = ln_term[i], ln_term[i + 1]
        #         h = x1 - x0
        #         area += h * (y0 + y1) / 2 * ((upper >= x1).float())  # only add where upper > x1
        #     return area

        # upper_bound = (cos_theta + 1) / 2  # [N, N]
        # integral_vals = trapezoid_integrate(upper_bound)  # [N, N]
        # ret = 1 - (torch.pi ** 2) / 6 - integral_vals
        # return ret
    
    def __integrand_for_spherical_in_tps(self, x):
        """
        Integrand function for the spherical TPS radial basis function.

        Args:
            x: The variable of integration.

        Returns:
            The value of the integrand at x.
        """
        return np.log(1 - x) / x
        
    def _standardize(self, x: torch.Tensor, unbiased_std: Optional[bool] = None) -> torch.Tensor:
        """
        A function to standardize the input tensor x.

        Args:
            x: Input tensor to be standardized.
            unbiased_std: (Optional) If True, use unbiased standard deviation (dividing by N-1); 
                          if False, use biased standard deviation (dividing by N).
                          Default is None, which uses the class attribute self.unbiased_std.

        Returns:
            A standardized tensor with mean 0 and standard deviation 1.
        """
        if unbiased_std is None:
            unbiased_std = self.unbiased_std
        mean = x.mean(dim=0, keepdim=True)  # keepdim=True to keep the same shape
        std = x.std(dim=0, unbiased=unbiased_std, keepdim=True)  # unbiased=False for population std
        std[std == 0] = 1.0
        x = (x - mean) / std
        return x

    def forward(self) -> torch.Tensor:
        """
        Forward pass to compute the basis functions. Constructs the basis functions based on the input locations and parameters.

        Returns:
            A tensor of shape [N, k] representing the basis functions.
        """
        logger = self.logger

        # Construct X = [1, x1, x2, ..., xd]
        ones = torch.ones(self.N, 1, device=self.device)
        X = torch.cat([ones, self.locs], dim=1)  # [N, d+1]

        if self.k == 1:
            return ones
        elif self.k <= self.d:
            if self.standardize:
                X[:, 1:self.k] = self._standardize(X[:, 1:self.k])
            return X[:, :self.k]
        

        # TPS basis
        Phi = self._tps_phi(locs=self.locs, calculate_with_spherical=self.calculate_with_spherical)  # [N, N]
        
        # Q = I - X(XᵗX)⁻¹Xᵗ
        try:
            XtX_inv = torch.inverse(X.T @ X)  # [(d+1), (d+1)]
        except RuntimeError as e:
            logger.warning(f'torch.inverse failed due to {e}, this implies "X.T @ X" didn\'t have inverse. Using torch.linalg.pinv instead.')
            XtX_inv = torch.linalg.pinv(X.T @ X)
        Q = torch.eye(self.N, device=self.device) - X @ XtX_inv @ X.T

        # Eigen-decomposition
        G = Q @ Phi @ Q
        #eigenvalues, eigenvectors = torch.linalg.eigh(G)  # ascending order
        
        G = G.detach().cpu().numpy()
        eigenvalues, eigenvectors = eigsh(G, k=self.k - self.d - 1, which='LM')  # 'LM': Largest Magnitude, max k < N
        eigenvalues = torch.from_numpy(eigenvalues).to(self.device) 
        eigenvectors = torch.from_numpy(eigenvectors).to(self.device)

        # Filter out near-zero eigenvalues and sort descending
        #valid = eigenvalues > 1e-10
        #eigenvalues[~valid] *= -1.0  # make them positive
        #eigenvectors[:, ~valid] *= -1.0  # make them positive
        idx_desc = torch.argsort(eigenvalues, descending=True)
        eigenvalues = eigenvalues[idx_desc]
        eigenvectors = eigenvectors[:, idx_desc]

        Basis_high = eigenvectors * torch.sqrt(torch.tensor(self.N, dtype=torch.float32))

        # # Construct basis functions
        # Basis_high = (Phi.T - Phi @ X @ XtX_inv @ X.T).T @ eigenvectors @ torch.diag(1.0 / eigenvalues).to(self.device)
        
        # # the for loop
        # Basis_high_1 = torch.zeros(self.N, self.N, device=self.locs.device)
        # for i in range(self.N):
        #     phi_i = Phi[i, :]
        #     x_i = X[i, :]
        #     Phi_XXtXinv_x = (phi_i.T - Phi @ X @ XtX_inv @ x_i.T).T
        #     for j in range(self.N):
        #         lambda_j = 1 / eigenvalues[j]
        #         v_j = eigenvectors[:, j]
        #         Basis_high_1[i, j] = lambda_j * Phi_XXtXinv_x @ v_j
        # print(f'Basis_high:\n{Basis_high}, \n\nBasis_high_1:\n{Basis_high_1}')
        # print(torch.mean((Basis_high - Basis_high_1)**2))

        # Concatenate [1, x1, ..., xd] and B_high

        Basis_low = X  # [N, d+1]

        # Standardize
        if self.standardize:
            Basis_low[:, 1:(self.d + 1)] = self._standardize(Basis_low[:, 1:(self.d + 1)])

        F = torch.cat([Basis_low, Basis_high], dim=1)

        # Output k basis
        F = F[:, :self.k]

        # print('1')
        # eigenvalues = eigenvalues[:self.k - self.d - 1]  # Select top k - (d + 1) eigenvalues
        # eigenvectors = eigenvectors[:, :self.k - self.d - 1]  # Select top k - (d + 1) eigenvectors

        # # compute BBBH and UZ
        # BBB = XtX_inv @ X.T
        # BBBH = BBB @ Phi
        # BBB_gamma = BBB @ eigenvectors
        # B_BBB_gamma = X @ BBB_gamma
        # gammas = (eigenvectors - B_BBB_gamma) / eigenvalues.reshape(1, -1) * torch.sqrt(torch.tensor(self.N, dtype=torch.float32))
        # print('2')
        # col_sd = self.locs.std(dim=0, unbiased=True)
        # adjustment = torch.sqrt(torch.tensor(self.N / (self.N - 1), dtype=col_sd.dtype, device=col_sd.device))
        # diag_values = (adjustment / col_sd).cpu().numpy()
        # xobs_diag = np.diag(diag_values)
        # print('3')
        # # 初始化组合矩阵
        # UZ = np.zeros((self.N + self.d + 1, self.k))
        # print('4')
        # # 区块填充
        # UZ[:self.N, :self.k - self.d - 1] = gammas      # 左上区块
        # UZ[self.N, self.k - self.d - 1] = 1.0           # 中心单位元素
        # UZ[self.N + 1:, self.k - self.d:] = xobs_diag  # 右下对角区块

        return F  # [N, d+1 + k]


if __name__ == "__main__":
    args = fetch_args()

    with open(args.model_config, "rt") as f:
        model_config = yaml.safe_load(f.read())
    with open(args.training_config, "rt") as f:
        training_config = yaml.safe_load(f.read())

    LOGGER.info(f"Model spec: {model_config}")
    LOGGER.info(f"Training spec: {training_config}")

    if torch.cuda.device_count() > 0:
        LOGGER.info(f"Using {torch.cuda.device_count()} GPUs!")
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    run_job(model_config, training_config, device)

同理, /scripts/diffusion/infer.py 也同樣修改如下

  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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
import argparse
from typing import Optional, Union

import torch
import torch.nn as nn
import yaml

from sssd.core.model_specs import MODEL_PATH_FORMAT, setup_model
from sssd.data.utils import get_dataloader
from sssd.inference.generator import DiffusionGenerator
from sssd.utils.logger import setup_logger
from sssd.utils.utils import calc_diffusion_hyperparams, display_current_time

import numpy as np
import torch
import torch.nn as nn
from scipy.integrate import quad
from scipy.sparse.linalg import eigsh
from typing import Optional, Union

LOGGER = setup_logger()


def fetch_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-m",
        "--model_config",
        type=str,
        default="configs/model.yaml",
        help="Model configuration",
    )
    parser.add_argument(
        "-i",
        "--inference_config",
        type=str,
        default="configs/inference_config.yaml",
        help="Inference configuration",
    )
    parser.add_argument(
        "-ckpt_iter",
        "--ckpt_iter",
        default="max",
        help='Which checkpoint to use; assign a number or "max" to find the latest checkpoint',
    )
    return parser.parse_args()

# New function to load locations
def get_locations_loader(location_path, device: torch.device) -> torch.Tensor:
    locations = np.load(location_path)
    locations_tensor = torch.from_numpy(locations).float().to(device)
    return locations_tensor


def run_job(
    model_config: dict,
    inference_config: dict,
    device: Optional[Union[torch.device, str]],
    ckpt_iter: Union[str, int],
) -> None:
    trials = inference_config.get("trials")
    batch_size = inference_config["batch_size"]
    dataloader = get_dataloader(
        inference_config["data"]["test_path"],
        batch_size,
        device=device,
    )

    local_path = MODEL_PATH_FORMAT.format(
        T=model_config["diffusion"]["T"],
        beta_0=model_config["diffusion"]["beta_0"],
        beta_T=model_config["diffusion"]["beta_T"],
    )

    diffusion_hyperparams = calc_diffusion_hyperparams(
        **model_config["diffusion"], device=device
    )

    LOGGER.info(display_current_time())
    
    
    locs = get_locations_loader(inference_config["data"]["location_path"], device)
    mrts = MRTS(locs=locs, k=locs.shape[0], device=device)


    net = setup_model(inference_config["use_model"], model_config, mrts, device)

    # Check if multiple GPUs are available
    if torch.cuda.device_count() > 0:
        net = nn.DataParallel(net)

    data_names = ["imputation", "original", "mask"]
    directory = inference_config["output_directory"]

    if trials > 1:
        directory += "_{trial}"

    for trial in range(1, trials + 1):
        LOGGER.info(f"The {trial}th inference trial")
        saved_data_names = data_names if trial == 0 else data_names[0]

        mses, mapes = DiffusionGenerator(
            net=net,
            device=device,
            diffusion_hyperparams=diffusion_hyperparams,
            dataloader=dataloader,
            local_path=local_path,
            output_directory=directory.format(trial=trial) if trials > 1 else directory,
            ckpt_path=inference_config["ckpt_path"],
            ckpt_iter=ckpt_iter,
            batch_size=batch_size,
            masking=inference_config["masking"],
            missing_k=inference_config["missing_k"],
            only_generate_missing=inference_config["only_generate_missing"],
            saved_data_names=saved_data_names,
        ).generate()

        LOGGER.info(f"Average MSE: {sum(mses) / len(mses)}")
        LOGGER.info(f"Average MAPE: {sum(mapes) / len(mapes)}")
        LOGGER.info(display_current_time())


class MRTS(nn.Module):
    def __init__(self, locs: torch.Tensor, 
                 k: int=None, 
                 device: Optional[Union[torch.device, str]]=None, 
                 calculate_with_spherical: bool=False, 
                 standardize: bool=True, 
                 unbiased_std: bool=False
                 ):
        """
        Multi-Resolution Thin-plate Spline basis function.
        
        Args:
            locs: [N, d] tensor of spatial locations.
            k: (Optional) parameter for controlling resolution.
            device: (Optional) PyTorch device to use.
            calculate_with_spherical: (Optional) If True, use spherical coordinates for TPS calculation (default is False) (only supported when d == 2).
            standardize: (Optional) If True, perform standardization on locs (Recommended).
            unbiased_std: (Optional) If True, use unbiased standard deviation (dividing by N-1) (Recommended); 
                          if False, use biased standard deviation (dividing by N).
        """
        self.logger = LOGGER
        logger = self.logger
        super().__init__()
        try:
            if device is None:
                self.device = torch.device('cpu')
                logger.warning(f'Parameter "device" was not set. Default value "cpu" is used.')
            else:
                self.device = torch.device(device)
                logger.info(f'Successfully using device "{self.device}".')
        except (TypeError, ValueError) as e:
            self.device = torch.device('cpu')
            logger.warning(f'Parameter "device" is not a valid device ({device}). Default value "cpu" is used. Error: {e}')

        self.register_buffer("locs", locs.to(self.device))
        self.N, self.d = locs.shape

        # number of basis
        max_k = self.N + self.d
        try:
            if k is None:
                self.k = max_k
                logger.warning(f'Parameter "k" was not set. Default value {self.k} is used.')
            elif 0 < k <= (max_k):
                self.k = k
            else:
                self.k = max_k
                logger.warning(f'Parameter "k" is out of valid range, it should be between 1 to {self.k}. Default value {self.k} is used.')
        except TypeError:
            self.k = max_k
            logger.warning(f'Parameter "k" is not an integer, the type you input is "{type(k).__name__}." Default value {self.k} is used.')

        self.calculate_with_spherical = calculate_with_spherical
        if type(self.calculate_with_spherical) is not bool:
            self.calculate_with_spherical = False
            logger.warning(f'Parameter "calculate_with_spherical" should be a boolean, the type you input is "{type(calculate_with_spherical).__name__}". Default value False is used.')
        elif self.calculate_with_spherical and self.d != 2:
            self.calculate_with_spherical = False
            logger.warning(f'Spherical TPS not implemented for d = {self.d}, only d = 2 is supported. Using rectangular coordinate system instead.')
        
        if self.calculate_with_spherical:
            logger.info(f'Calculate TPS with spherical coordinates.')
        else:
            logger.info(f'Calculate TPS with rectangular coordinates.')

        self.standardize = standardize
        if type(self.standardize) is not bool:
            self.standardize = True
            logger.warning(f'Parameter "standardize" should be a boolean, the type you input is "{type(standardize).__name__}". Default value True is used.')

        self.unbiased_std = unbiased_std
        if type(self.unbiased_std) is not bool:
            self.unbiased_std = False
            logger.warning(f'Parameter "unbiased_std" should be a boolean, the type you input is "{type(unbiased_std).__name__}". Default value False is used.')

    def _tps_phi(self, locs: torch.Tensor, calculate_with_spherical: bool=False) -> torch.Tensor:
        """
        Compute the Thin Plate Spline (TPS) radial basis matrix for input locations.

        Args:
            locs: [N, d] tensor of spatial locations.
            calculate_with_spherical: (Optional) If True, use spherical coordinates for TPS calculation (default is False) (only supported when d == 2).

        Returns:
            A [N, N] tensor representing the TPS radial basis matrix.
        """       

        # rectangular coordinate system
        if not calculate_with_spherical:
            return self.__calculate_phi_by_rectangular_coordinate(locs)
        
        # spherical coordinate system
        else:
            # convert to spherical coordinates
            ret = torch.zeros((self.N, self.N), device=locs.device)
            locs = locs * torch.pi / 180.0
            x = locs[:, 0]
            y = locs[:, 1]
            for i in range(self.N):
                for j in range(self.N):
                    ret[i, j] = self.__calculate_phi_by_spherical_coordinate(x[i], y[i], x[j], y[j])
            return ret

    def __calculate_phi_by_rectangular_coordinate(self, locs: torch.Tensor) -> torch.Tensor:
        """
        Calculate the TPS radial basis matrix using rectangular (Euclidean) coordinates.

        Args:
            locs: [N, d] tensor of spatial locations.

        Returns:
            A [N, N] tensor representing the TPS radial basis matrix.
        """
        dists = torch.cdist(locs, locs)  # Euclidean distances
        if self.d == 1:
            return (dists ** 3) / 12
        elif self.d == 2:
            mask = dists != 0
            ret = torch.zeros_like(dists)
            ret[mask] = (dists[mask] ** 2) * torch.log(dists[mask]) / (8 * torch.pi)
            return ret
        elif self.d == 3:
            return -dists / 8
        else:
            raise NotImplementedError(f"TPS not implemented for d = {self.d}")

    def __calculate_phi_by_spherical_coordinate(self, x1: float, y1: float, x2: float, y2: float) -> float:
        """
        Calculate the TPS radial basis function using spherical coordinates.
        
        Args:
            x1, y1: Spherical coordinates of the first point (in radians).
            x2, y2: Spherical coordinates of the second point (in radians). 

        Returns:
            A float representing the TPS radial basis function value.
        """
        cos_theta = torch.sin(x1) * torch.sin(x2) + torch.cos(x1) * torch.cos(x2) * torch.cos(y1 - y2)
        cos_theta = torch.clamp(cos_theta, -1.0, 1.0)
        #theta = torch.acos(cos_theta)
        ret = 1 - (torch.pi ** 2) / 6

        if not torch.isclose(cos_theta, torch.tensor(-1.0, device=cos_theta.device)):
            cos_theta = cos_theta.item()
            upper = (cos_theta + 1) / 2
            lower = 0
            result, _ = quad(self.__integrand_for_spherical_in_tps, lower, upper, epsabs=1e-6, epsrel=1e-6, limit=50)
            result = torch.tensor(result, dtype=torch.float32, device=self.device)
            ret -= result
        return ret
    
        # # method by GPT can just use tenser to calculate and efficient
        # # spherical coordinate system
        # locs_rad = locs * torch.pi / 180.0  # convert to radians
        # lat1 = locs_rad[:, 0].unsqueeze(1)  # [N, 1]
        # lon1 = locs_rad[:, 1].unsqueeze(1)  # [N, 1]
        # lat2 = locs_rad[:, 0].unsqueeze(0)  # [1, N]
        # lon2 = locs_rad[:, 1].unsqueeze(0)  # [1, N]

        # # Cosine of angular distance
        # cos_theta = (
        #     torch.sin(lat1) @ torch.sin(lat2) + torch.cos(lat1) @ torch.cos(lat2) * torch.cos(lon1 - lon2)
        # )
        # cos_theta = torch.clamp(cos_theta, -1.0, 1.0)

        # # Compute integral using trapezoidal rule
        # N = 100  # Number of steps in the integral approximation
        # x = torch.linspace(1e-6, 1.0, N, device=locs.device)  # avoid x=0
        # ln_term = torch.log(1 - x) / x  # [N]

        # def trapezoid_integrate(upper):  # upper: [N, N]
        #     upper = torch.clamp(upper, 1e-6, 1.0)
        #     area = torch.zeros_like(upper)
        #     for i in range(N - 1):
        #         x0, x1 = x[i], x[i + 1]
        #         y0, y1 = ln_term[i], ln_term[i + 1]
        #         h = x1 - x0
        #         area += h * (y0 + y1) / 2 * ((upper >= x1).float())  # only add where upper > x1
        #     return area

        # upper_bound = (cos_theta + 1) / 2  # [N, N]
        # integral_vals = trapezoid_integrate(upper_bound)  # [N, N]
        # ret = 1 - (torch.pi ** 2) / 6 - integral_vals
        # return ret
    
    def __integrand_for_spherical_in_tps(self, x):
        """
        Integrand function for the spherical TPS radial basis function.

        Args:
            x: The variable of integration.

        Returns:
            The value of the integrand at x.
        """
        return np.log(1 - x) / x
        
    def _standardize(self, x: torch.Tensor, unbiased_std: Optional[bool] = None) -> torch.Tensor:
        """
        A function to standardize the input tensor x.

        Args:
            x: Input tensor to be standardized.
            unbiased_std: (Optional) If True, use unbiased standard deviation (dividing by N-1); 
                          if False, use biased standard deviation (dividing by N).
                          Default is None, which uses the class attribute self.unbiased_std.

        Returns:
            A standardized tensor with mean 0 and standard deviation 1.
        """
        if unbiased_std is None:
            unbiased_std = self.unbiased_std
        mean = x.mean(dim=0, keepdim=True)  # keepdim=True to keep the same shape
        std = x.std(dim=0, unbiased=unbiased_std, keepdim=True)  # unbiased=False for population std
        std[std == 0] = 1.0
        x = (x - mean) / std
        return x

    def forward(self) -> torch.Tensor:
        """
        Forward pass to compute the basis functions. Constructs the basis functions based on the input locations and parameters.

        Returns:
            A tensor of shape [N, k] representing the basis functions.
        """
        logger = self.logger

        # Construct X = [1, x1, x2, ..., xd]
        ones = torch.ones(self.N, 1, device=self.device)
        X = torch.cat([ones, self.locs], dim=1)  # [N, d+1]

        if self.k == 1:
            return ones
        elif self.k <= self.d:
            if self.standardize:
                X[:, 1:self.k] = self._standardize(X[:, 1:self.k])
            return X[:, :self.k]
        

        # TPS basis
        Phi = self._tps_phi(locs=self.locs, calculate_with_spherical=self.calculate_with_spherical)  # [N, N]
        
        # Q = I - X(XᵗX)⁻¹Xᵗ
        try:
            XtX_inv = torch.inverse(X.T @ X)  # [(d+1), (d+1)]
        except RuntimeError as e:
            logger.warning(f'torch.inverse failed due to {e}, this implies "X.T @ X" didn\'t have inverse. Using torch.linalg.pinv instead.')
            XtX_inv = torch.linalg.pinv(X.T @ X)
        Q = torch.eye(self.N, device=self.device) - X @ XtX_inv @ X.T

        # Eigen-decomposition
        G = Q @ Phi @ Q
        #eigenvalues, eigenvectors = torch.linalg.eigh(G)  # ascending order
        
        G = G.detach().cpu().numpy()
        eigenvalues, eigenvectors = eigsh(G, k=self.k - self.d - 1, which='LM')  # 'LM': Largest Magnitude, max k < N
        eigenvalues = torch.from_numpy(eigenvalues).to(self.device) 
        eigenvectors = torch.from_numpy(eigenvectors).to(self.device)

        # Filter out near-zero eigenvalues and sort descending
        #valid = eigenvalues > 1e-10
        #eigenvalues[~valid] *= -1.0  # make them positive
        #eigenvectors[:, ~valid] *= -1.0  # make them positive
        idx_desc = torch.argsort(eigenvalues, descending=True)
        eigenvalues = eigenvalues[idx_desc]
        eigenvectors = eigenvectors[:, idx_desc]

        Basis_high = eigenvectors * torch.sqrt(torch.tensor(self.N, dtype=torch.float32))

        # # Construct basis functions
        # Basis_high = (Phi.T - Phi @ X @ XtX_inv @ X.T).T @ eigenvectors @ torch.diag(1.0 / eigenvalues).to(self.device)
        
        # # the for loop
        # Basis_high_1 = torch.zeros(self.N, self.N, device=self.locs.device)
        # for i in range(self.N):
        #     phi_i = Phi[i, :]
        #     x_i = X[i, :]
        #     Phi_XXtXinv_x = (phi_i.T - Phi @ X @ XtX_inv @ x_i.T).T
        #     for j in range(self.N):
        #         lambda_j = 1 / eigenvalues[j]
        #         v_j = eigenvectors[:, j]
        #         Basis_high_1[i, j] = lambda_j * Phi_XXtXinv_x @ v_j
        # print(f'Basis_high:\n{Basis_high}, \n\nBasis_high_1:\n{Basis_high_1}')
        # print(torch.mean((Basis_high - Basis_high_1)**2))

        # Concatenate [1, x1, ..., xd] and B_high

        Basis_low = X  # [N, d+1]

        # Standardize
        if self.standardize:
            Basis_low[:, 1:(self.d + 1)] = self._standardize(Basis_low[:, 1:(self.d + 1)])

        F = torch.cat([Basis_low, Basis_high], dim=1)

        # Output k basis
        F = F[:, :self.k]

        # print('1')
        # eigenvalues = eigenvalues[:self.k - self.d - 1]  # Select top k - (d + 1) eigenvalues
        # eigenvectors = eigenvectors[:, :self.k - self.d - 1]  # Select top k - (d + 1) eigenvectors

        # # compute BBBH and UZ
        # BBB = XtX_inv @ X.T
        # BBBH = BBB @ Phi
        # BBB_gamma = BBB @ eigenvectors
        # B_BBB_gamma = X @ BBB_gamma
        # gammas = (eigenvectors - B_BBB_gamma) / eigenvalues.reshape(1, -1) * torch.sqrt(torch.tensor(self.N, dtype=torch.float32))
        # print('2')
        # col_sd = self.locs.std(dim=0, unbiased=True)
        # adjustment = torch.sqrt(torch.tensor(self.N / (self.N - 1), dtype=col_sd.dtype, device=col_sd.device))
        # diag_values = (adjustment / col_sd).cpu().numpy()
        # xobs_diag = np.diag(diag_values)
        # print('3')
        # # 初始化组合矩阵
        # UZ = np.zeros((self.N + self.d + 1, self.k))
        # print('4')
        # # 区块填充
        # UZ[:self.N, :self.k - self.d - 1] = gammas      # 左上区块
        # UZ[self.N, self.k - self.d - 1] = 1.0           # 中心单位元素
        # UZ[self.N + 1:, self.k - self.d:] = xobs_diag  # 右下对角区块

        return F  # [N, d+1 + k]


if __name__ == "__main__":
    args = fetch_args()

    with open(args.model_config, "rt") as f:
        model_config = yaml.safe_load(f.read())
    with open(args.inference_config, "rt") as f:
        inference_config = yaml.safe_load(f.read())

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    if torch.cuda.device_count() > 0:
        LOGGER.info(f"Using {torch.cuda.device_count()} GPUs!")
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

    run_job(model_config, inference_config, device, args.ckpt_iter)

/sssd/core/model_specs.py 也需修改,以支援 MRTS

 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
import torch

from sssd.core.imputers.DiffWaveImputer import DiffWaveImputer
from sssd.core.imputers.SSSDS4Imputer import SSSDS4Imputer
from sssd.core.imputers.SSSDSAImputer import SSSDSAImputer
from sssd.core.utils import get_mask_bm, get_mask_forecast, get_mask_mnr, get_mask_rm

MASK_FN = {
    "rm": get_mask_rm,
    "mnr": get_mask_mnr,
    "bm": get_mask_bm,
    "forecast": get_mask_forecast,
}

MODELS = {0: DiffWaveImputer, 1: SSSDSAImputer, 2: SSSDS4Imputer}
MODEL_PATH_FORMAT = "T{T}_beta0{beta_0}_betaT{beta_T}"


def setup_model(
    use_model: int, model_config: dict, mrts_matrix, device: torch.device
) -> torch.nn.Module:
    model_settings = None
    if use_model in (0, 2):
        model_settings = model_config.get("wavenet")
    elif use_model == 1:
        model_settings = model_config.get("sashimi_config")
    else:
        raise KeyError(f"Please enter correct use-model number, but got {use_model}")
    if model_settings is None:
        raise ValueError(f"Please enter model settings in config")
    return MODELS[use_model](**model_settings, device=device, mrts_matrix=mrts_matrix).to(device)

運行環境

  • 本機作業系統:Windows 11 24H2
    • 程式語言:Python 3.12.9
  • 計算平臺:財團法人國家實驗研究院國家高速網路與計算中心臺灣 AI 雲
    • 作業系統:Ubuntu
    • Miniconda
    • GPU:NVIDIA Tesla V100 32GB GPU
    • CUDA 12.8 driver
    • 程式語言:Python 3.10.16 for Linux

延伸學習

參考資料