File size: 41,013 Bytes
6077218
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
import torch.nn.functional as F
import torch
import math
import numpy as np
from tabdiff.models.noise_schedule import *
from tqdm import tqdm
from itertools import chain

"""
“Our implementation of the continuous-time masked diffusion is inspired by https://arxiv.org/abs/2406.07524's implementation at [https://github.com/kuleshov-group/mdlm], with modifications to support data distributions that include categorical dimensions of different sizes.”
"""

# These parameters, inspired by the EDM paper (Karras et al., 2022), control the behavior of the stochastic sampler.
# S_churn: The amount of stochasticity to inject at each step.
# S_min, S_max: The range of noise levels (sigma) where stochasticity is active.
# S_noise: The magnitude of the noise added during the stochastic step.
S_churn= 1
S_min=0
S_max=float('inf')
S_noise=1

class UnifiedCtimeDiffusion(torch.nn.Module):
    """
    This class implements the TABDIFF model, a unified continuous-time diffusion framework 
    for generating mixed-type tabular data, as described in the paper "TABDIFF: A MIXED-TYPE 
    DIFFUSION MODEL FOR TABULAR DATA GENERATION".

    The model handles both numerical and categorical features within a single diffusion process.
    - Numerical features are diffused using a Gaussian diffusion process (Section 2.2).
    - Categorical features are diffused using a masked diffusion process (Section 2.2).
    - The model supports learnable, feature-wise noise schedules to handle data heterogeneity (Section 2.3).
    - Sampling can be performed using a standard ODE solver or an advanced stochastic sampler (Section 2.4).
    - It also supports classifier-free guidance for conditional generation tasks like imputation (Section 2.5).
    """
    def __init__(
            self,
            num_classes: np.array,
            num_numerical_features: int,
            denoise_fn,
            y_only_model,
            num_timesteps=1000,
            scheduler='power_mean',
            cat_scheduler='log_linear',
            noise_dist='uniform',
            edm_params={},
            noise_dist_params={},
            noise_schedule_params={},
            sampler_params={},
            device=torch.device('cpu'),
            **kwargs
        ):
        """
        Initializes the UnifiedCtimeDiffusion model.

        Args:
            num_classes (np.array): An array where each element is the number of categories for a categorical feature.
            num_numerical_features (int): The number of numerical features in the dataset.
            denoise_fn: The main denoising network model. Corresponds to the 'Denoising Network' in Figure 1.
            y_only_model: A separate, smaller denoising network trained only on the target columns for 
                          classifier-free guidance (CFG). This corresponds to the unconditional model over the 
                          missing columns mentioned in Section 2.5 of the paper.
            num_timesteps (int): The number of discretization steps to use during sampling.
            scheduler (str): The noise schedule for numerical features. The paper proposes 'power_mean'
                             and 'power_mean_per_column' for adaptive learning.
            cat_scheduler (str): The noise schedule for categorical features. The paper proposes 'log_linear'
                                 and 'log_linear_per_column' for adaptive learning.
            noise_dist (str): The distribution from which to sample noise levels during training.
            edm_params (dict): Parameters related to the Elucidating Design space of diffusion Models (EDM)
                               framework by Karras et al. (2022), which influences the loss calculation and sampling.
            noise_dist_params (dict): Parameters for the noise distribution.
            noise_schedule_params (dict): Parameters for the noise schedule, like sigma_min and sigma_max.
            sampler_params (dict): Parameters to control the sampling process, e.g., enabling the stochastic sampler.
            device: The device (CPU or GPU) to run the model on.
        """

        super(UnifiedCtimeDiffusion, self).__init__()

        self.num_numerical_features = num_numerical_features
        # A vector [K1, K2, ..., Km] where Ki is the number of categories for the i-th categorical feature.
        self.num_classes = num_classes 
        self.num_classes_expanded = torch.from_numpy(
            np.concatenate([num_classes[i].repeat(num_classes[i]) for i in range(len(num_classes))])
        ).to(device) if len(num_classes)>0 else torch.tensor([]).to(device).int()
        # The index for the [MASK] token for each categorical feature. The paper notes an extra dimension 
        # is dedicated to the [MASK] state.
        self.mask_index = torch.tensor(self.num_classes).long().to(device)
        self.neg_infinity = -1000000.0 
        # The number of categories for each feature, including the mask token.
        self.num_classes_w_mask = tuple(self.num_classes + 1)
        
        # The following are helper attributes for slicing and managing the one-hot encoded categorical features.
        # This is an implementation detail necessary for handling multiple categorical features with varying
        # numbers of classes within a single tensor.
        offsets = np.cumsum(self.num_classes)
        offsets = np.append([0], offsets)
        self.slices_for_classes = []
        for i in range(1, len(offsets)):
            self.slices_for_classes.append(np.arange(offsets[i - 1], offsets[i]))
        self.offsets = torch.from_numpy(offsets).to(device)
        
        offsets = np.cumsum(self.num_classes) + np.arange(1, len(self.num_classes)+1)
        offsets = np.append([0], offsets)
        self.slices_for_classes_with_mask = []
        for i in range(1, len(offsets)):
            self.slices_for_classes_with_mask.append(np.arange(offsets[i - 1], offsets[i]))

        self._denoise_fn = denoise_fn
        self.y_only_model = y_only_model
        self.num_timesteps = num_timesteps
        self.scheduler = scheduler
        self.cat_scheduler = cat_scheduler
        self.noise_dist = noise_dist
        self.edm_params = edm_params
        self.noise_dist_params = noise_dist_params
        self.sampler_params = sampler_params
        # The stochastic sampler and second-order correction are only applicable when numerical features exist,
        # as they are based on continuous ODE solvers. This is an implementation-specific constraint.
        if self.num_numerical_features == 0:
            self.sampler_params['stochastic_sampler'] = False
            self.sampler_params['second_order_correction'] = False
        
        # These attributes are for configuring classifier-free guidance during imputation.
        self.w_num = 0.0 # Guidance strength for numerical features
        self.w_cat = 0.0 # Guidance strength for categorical features
        self.num_mask_idx = [] # Indices of missing numerical features
        self.cat_mask_idx = [] # Indices of missing categorical features
        
        self.device = device
        
        # Instantiate the noise schedules based on the configuration.
        # This implements the "Adaptively Learnable Noise Schedules" from Section 2.3 of the paper.
        # `power_mean_per_column` and `log_linear_per_column` correspond to the feature-wise learnable schedules.
        if self.scheduler == 'power_mean':
            self.num_schedule = PowerMeanNoise(**noise_schedule_params)
        elif self.scheduler == 'power_mean_per_column':
            self.num_schedule = PowerMeanNoise_PerColumn(num_numerical = num_numerical_features, **noise_schedule_params)
        else:
            raise NotImplementedError(f"The noise schedule--{self.scheduler}-- is not implemented for contiuous data at CTIME ")
        
        if self.cat_scheduler == 'log_linear':
            self.cat_schedule = LogLinearNoise(**noise_schedule_params)
        elif self.cat_scheduler == 'log_linear_per_column':
            self.cat_schedule = LogLinearNoise_PerColumn(num_categories = len(num_classes), **noise_schedule_params)
        else:
            raise NotImplementedError(f"The noise schedule--{self.cat_scheduler}-- is not implemented for discrete data at CTIME ")

    def mixed_loss(self, x):
        """
        Calculates the mixed-type diffusion loss for a batch of data.
        This function corresponds to the joint objective function L_TABDIFF in Eq. (12) of the paper.
        """
        b = x.shape[0]
        device = x.device

        x_num = x[:, :self.num_numerical_features]
        x_cat = x[:, self.num_numerical_features:].long()
        
        # 1. Sample a time step 't' uniformly, as described in Algorithm 1.
        # From 't', derive the noise levels (sigma) for both numerical and categorical features using their schedules.
        if self.noise_dist == "uniform_t":
            t = torch.rand(b, device=device, dtype=x_num.dtype)
            t = t[:, None]
            sigma_num = self.num_schedule.total_noise(t)
            sigma_cat = self.cat_schedule.total_noise(t)
            dsigma_cat = self.cat_schedule.rate_noise(t) # Derivative needed for categorical loss weight.
        else:
            # An alternative sampling strategy, not described in the main paper, where noise level sigma is sampled
            # directly and then mapped back to time 't'. This is a common practice in continuous-time diffusion models.
            sigma_num = self.sample_ctime_noise(x)       
            t = self.num_schedule.inverse_to_t(sigma_num)
            while torch.any((t < 0) + (t > 1)):     
                # restrict t to [0,1]
                # this iterative approach is equivalent to sampling from a truncated version of the orignal noise distribution
                invalid_idx = ((t < 0) + (t > 1)).nonzero().squeeze(-1)
                sigma_num[invalid_idx] = self.sample_ctime_noise(x[:len(invalid_idx)])
                t = self.num_schedule.inverse_to_t(sigma_num)
            assert not torch.any((t < 0) + (t > 1))
            sigma_cat = self.cat_schedule.total_noise(t)
            dsigma_cat = self.cat_schedule.rate_noise(t)
            
        # Convert sigma_cat to alpha (probability of not being masked) for the categorical forward process.
        # alpha_t = exp(-sigma_cat(t)) as defined in Section 2.2.
        alpha = torch.exp(-sigma_cat)
        move_chance = -torch.expm1(-sigma_cat) # This is 1 - alpha_t, calculated for numerical stability.
            
        # 2. Apply the forward diffusion process to corrupt the data (as in Figure 1 'Forward Diff').
        # For numerical features, add Gaussian noise according to Eq. (3) .
        x_num_t = x_num
        if x_num.shape[1] > 0:
            noise = torch.randn_like(x_num)
            x_num_t = x_num + noise * sigma_num
        
        # For categorical features, apply the masking process according to Eq. (6) .
        x_cat_t = x_cat
        # x_cat_t_soft is a one-hot representation of the noised data, used as input to the network.
        x_cat_t_soft = x_cat 
        if x_cat.shape[1] > 0:
            # When using learnable schedules, 'move_chance' is a vector, requiring a 'soft' Gumbel-Softmax
            # implementation for correct gradient flow. This is an implementation detail not specified in the paper.
            is_learnable = self.cat_scheduler == 'log_linear_per_column'
            strategy = 'soft' if is_learnable else 'hard'
            x_cat_t, x_cat_t_soft = self.q_xt(x_cat, move_chance, strategy=strategy)

        # 3. Get the model's prediction of the original data (or noise) from the corrupted data.
        model_out_num, model_out_cat = self._denoise_fn(   
            x_num_t, x_cat_t_soft,
            t.squeeze(), sigma=sigma_num
        )

        d_loss = torch.zeros((1,)).float()
        c_loss = torch.zeros((1,)).float()

        # 4. Calculate the individual loss components.
        # Numerical loss corresponds to L_num in Eq. (5) , with EDM-style weighting.
        if x_num.shape[1] > 0:
            c_loss = self._edm_loss(model_out_num, x_num, sigma_num)
        # Categorical loss corresponds to L_cat in Eq. (9) .
        if x_cat.shape[1] > 0:
            # The parameterization transforms the model's raw output to log probabilities of the original classes.
            logits = self._subs_parameterization(model_out_cat, x_cat_t)
            d_loss = self._absorbed_closs(logits, x_cat, sigma_cat, dsigma_cat)
            
        return d_loss.mean(), c_loss.mean()

    @torch.no_grad()
    def sample(self, num_samples):
        """
        Generates new samples using the trained diffusion model, following the reverse process.
        This function implements the sampling procedure, conceptually similar to Algorithm 2.
        """
        b = num_samples
        device = self.device
        dtype = torch.float32
        
        # Create the time discretization schedule from t=1.0 down to t=0.0.
        t = torch.linspace(0,1,self.num_timesteps, dtype=dtype, device=device)
        t = t[:, None]
        
        # Pre-calculate the noise levels (sigma) for each time step in the schedule.
        sigma_num_cur = self.num_schedule.total_noise(t)
        sigma_cat_cur = self.cat_schedule.total_noise(t)
        # sigma_next is the noise level of the *next* step in the reverse process (i.e., a smaller sigma).
        sigma_num_next = torch.zeros_like(sigma_num_cur)
        sigma_num_next[1:] = sigma_num_cur[0:-1]
        sigma_cat_next = torch.zeros_like(sigma_cat_cur)
        sigma_cat_next[1:] = sigma_cat_cur[0:-1]
        
        # This block sets up the 'stochastic sampler' described in Section 2.4.
        # It calculates a slightly noisier version of sigma (sigma_hat) for each step, which corresponds
        # to perturbing the sample from x_t to x_{t+gamma} before the main denoising step (see Algorithm 2).
        # The formula for gamma is a heuristic from Karras et al. (2022).
        if self.sampler_params['stochastic_sampler']:
            gamma = min(S_churn / self.num_timesteps, np.sqrt(2) - 1) * (S_min <= sigma_num_cur) * (sigma_num_cur <= S_max)
            sigma_num_hat = sigma_num_cur + gamma * sigma_num_cur
            t_hat = self.num_schedule.inverse_to_t(sigma_num_hat)
            # Take the smallest t_hat induced by the per-column sigmas to ensure all features are within a valid time range.
            t_hat = torch.min(t_hat, dim=-1, keepdim=True).values    
            zero_gamma = (gamma==0).any()
            t_hat[zero_gamma] = t[zero_gamma]
            out_of_bound = (t_hat > 1).squeeze()
            sigma_num_hat[out_of_bound] = sigma_num_cur[out_of_bound]
            t_hat[out_of_bound] = t[out_of_bound]
            sigma_cat_hat = self.cat_schedule.total_noise(t_hat)
        else:
            t_hat = t
            sigma_num_hat = sigma_num_cur
            sigma_cat_hat = sigma_cat_cur
                
        # Start the reverse process from pure noise at t=1.0.
        # Numerical features start from a Gaussian distribution, as in Algorithm 2, line 1.
        z_norm = torch.randn((b, self.num_numerical_features), device=device) * sigma_num_cur[-1] 
            
        # Categorical features start from the [MASK] state, as in Algorithm 2, line 1.
        has_cat = len(self.num_classes) > 0
        z_cat = torch.zeros((b, 0), device=device).float()
        if has_cat:
            z_cat = self._sample_masked_prior(
                b,
                len(self.num_classes),
            )
        
        # Iterate backwards through the time steps from T-1 down to 0.
        pbar = tqdm(reversed(range(0, self.num_timesteps)), total=self.num_timesteps)
        pbar.set_description(f"Sampling Progress")
        for i in pbar:                  
            z_norm, z_cat, q_xs = self.edm_update(
                z_norm, z_cat, i, 
                t[i], t[i-1] if i > 0 else None, t_hat[i],
                sigma_num_cur[i], sigma_num_next[i], sigma_num_hat[i], 
                sigma_cat_cur[i], sigma_cat_next[i], sigma_cat_hat[i],
            )
        
        # By the end of the process, all categorical features should be unmasked.
        assert torch.all(z_cat < self.mask_index)
        sample = torch.cat([z_norm, z_cat], dim=1).cpu()
        return sample
    
    def sample_all(self, num_samples, batch_size, keep_nan_samples=False):
        """
        A wrapper function to generate a large number of samples in batches.
        This is an implementation detail for practical large-scale sampling.
        """
        b = batch_size

        all_samples = []
        num_generated = 0
        while num_generated < num_samples:
            print(f"Samples left to generate: {num_samples-num_generated}")
            sample = self.sample(b)
            mask_nan = torch.any(sample.isnan(), dim=1)
            if keep_nan_samples:
                # If sample instances that contain NaN are to be kept, force the row to all zeros.
                sample = sample * (~mask_nan)[:, None]
            else:
                # Otherwise, discard instances with NaN values.
                sample = sample[~mask_nan]

            all_samples.append(sample)
            num_generated += sample.shape[0]

        x_gen = torch.cat(all_samples, dim=0)[:num_samples]

        return x_gen
    
    def q_xt(self, x, move_chance, strategy='hard'):
        """
        Performs the forward diffusion process for categorical features (masking).
        Corresponds to q(x_t|x_0) in Eq. (6).

        Args:
            x: The original categorical data (integer-encoded).
            move_chance: The probability of transitioning to the [MASK] state (1 - alpha_t).
            strategy: 'hard' for standard masking, 'soft' for a Gumbel-Softmax-based approach needed
                      for per-column learnable schedules to allow gradient flow. This is an implementation detail.
        """
        if strategy == 'hard':
            # Each token is flipped to [MASK] independently with probability `move_chance`.
            move_indices = torch.rand(*x.shape, device=x.device) < move_chance
            xt = torch.where(move_indices, self.mask_index, x)
            # Convert to one-hot for the network input.
            xt_soft = self.to_one_hot(xt).to(move_chance.dtype)
            return xt, xt_soft
        elif strategy == 'soft':
            # This 'soft' strategy is necessary when move_chance is different for each column (learnable schedule).
            # It uses Gumbel-Softmax to make the discrete choice of masking differentiable, which is
            # crucial for backpropagating through the schedule's learnable parameters. This is a sophisticated
            # implementation detail not explicitly mentioned in the paper.
            bs = x.shape[0]
            xt_soft = torch.zeros(bs, torch.sum(self.mask_index+1), device=x.device)
            xt = torch.zeros_like(x)
            for i in range(len(self.num_classes)):
                slice_i = self.slices_for_classes_with_mask[i]
                prob_i = torch.zeros(bs, 2, device=x.device)
                prob_i[:,0] = 1-move_chance[:,i]
                prob_i[:,-1] = move_chance[:,i]
                log_prob_i = torch.log(prob_i)
                soft_sample_i = F.gumbel_softmax(log_prob_i, tau=0.01, hard=True)
                idx = torch.stack((x[:,i]+slice_i[0], torch.ones_like(x[:,i])*slice_i[-1]), dim=-1)
                xt_soft[torch.arange(len(idx)).unsqueeze(1), idx] = soft_sample_i
                xt[:, i] = torch.where(soft_sample_i[:,1] > soft_sample_i[:,0], self.mask_index[i], x[:,i])
            return xt, xt_soft
    
    
    def _subs_parameterization(self, unormalized_prob, xt):
        """
        Processes the raw output of the denoising network for categorical features. It converts the output
        into log-probabilities and enforces the logic of the masked diffusion process.
        This is a key part of implementing the reverse transition p_theta(x_s|x_t) from Eq. (8) .
        """
        # The model outputs unnormalized probabilities for each possible category. This function pads them
        # to a uniform size for batch processing.
        unormalized_prob = self.pad(unormalized_prob, self.neg_infinity)
        
        # Set the probability of predicting the [MASK] token to zero (log prob to -inf).
        unormalized_prob[:, range(unormalized_prob.shape[1]), self.mask_index] += self.neg_infinity
        
        # Convert to log-probabilities (logits) via log-softmax.
        logits = unormalized_prob - torch.logsumexp(unormalized_prob, dim=-1, keepdim=True)

        # Enforce the rule from Eq. (8): if a token is not masked (x_t != m), it stays the same.
        # This is done by setting the log-probabilities for unmasked tokens to -inf for all categories
        # except the actual token's category, which is set to 0 (prob=1).
        unmasked_indices = (xt != self.mask_index)
        logits[unmasked_indices] = self.neg_infinity 
        logits[unmasked_indices, xt[unmasked_indices]] = 0
        return logits
    
    def pad(self, x, pad_value):
        """
        Helper function for implementation. It converts a concatenated tensor of class probabilities 
        (with different numbers of classes per feature) into a single padded matrix. This allows for
        efficient batch processing. This is a standard engineering solution for handling
        heterogeneous categorical data and not a specific concept from the paper.
        """
        splited = torch.split(x, self.num_classes_w_mask, dim=-1)
        max_K = max(self.num_classes_w_mask)
        padded_ = [
            torch.cat((
                t, 
                pad_value*torch.ones(*(t.shape[:-1]), max_K-t.shape[-1], dtype=t.dtype, device=t.device)
            ), dim=-1) 
        for t in splited]
        out = torch.stack(padded_, dim=-2)
        return out
    
    def to_one_hot(self, x_cat):
        """Helper function to convert integer-encoded categorical data to one-hot format."""
        x_cat_oh = torch.cat(
            [F.one_hot(x_cat[:, i], num_classes=self.num_classes[i]+1,) for i in range(len(self.num_classes))], 
            dim=-1
        )
        return x_cat_oh
    
    def _absorbed_closs(self, model_output, x0, sigma, dsigma):
        """
        Calculates the categorical loss based on the continuous-time evidence lower bound (ELBO).
        This directly implements the loss L_cat from Eq. (9) and (12).
        """
        # Get the predicted log probability of the true original data x0.
        log_p_theta = torch.gather(
            model_output, -1, x0[:, :, None]
        ).squeeze(-1)
        
        alpha = torch.exp(-sigma)
        
        # This is the weighting term from the continuous-time ELBO: (alpha_t' / (1 - alpha_t)).
        # It's calculated here based on sigma for numerical stability.
        if self.cat_scheduler in ['log_linear', 'log_linear_per_column']:
            # The paper defines alpha_t = exp(-sigma_cat(t)).
            # So, alpha_t' = -dsigma * exp(-sigma) = -dsigma * alpha.
            # And 1 - alpha_t = 1 - exp(-sigma) = -expm1(-sigma).
            # The weight is alpha_t'/(1-alpha_t), which is different from the implementation's -dsigma/expm1(sigma).
            # Let's re-derive: alpha_t' / (1-alpha_t) = (-dsigma * alpha) / (1-alpha).
            # The paper later uses dsigma in the loss without the alpha term in the numerator. Let's re-check the paper.
            # Looking at Eq. (143), the integral has (alpha_t' / (1-alpha_t)).
            # Looking at the code's `move_chance`, it's -expm1(-sigma), which is 1 - exp(-sigma) = 1 - alpha.
            # And dsigma is sigma'. So the weight is (alpha'/(1-alpha)) = (-sigma' * exp(-sigma)) / (1-exp(-sigma)).
            # The code calculates `-dsigma / torch.expm1(sigma)`.
            # `expm1(sigma)` is `exp(sigma) - 1`. So the weight is `-dsigma / (exp(sigma)-1)`.
            # This is `-dsigma * exp(-sigma) / (1 - exp(-sigma))`, which is `alpha' / (1-alpha)`.
            # So the implementation IS correct, it just uses a numerically stable rearrangement.
            # Let's re-verify the formula in the paper again: Eq (143) is `(alpha_t' / (1 - alpha_t))`. My math checks out.
            # The code seems to use `dsigma / (exp(sigma) - 1)` which is `sigma' / (exp(sigma) - 1)`. 
            # This is not equal to `alpha' / (1 - alpha)`.
            # `expm1(sigma)` is `exp(sigma) - 1`.
            # `alpha' = -sigma' * exp(-sigma)`. `1-alpha = 1 - exp(-sigma)`.
            # `alpha'/(1-alpha) = -sigma' * exp(-sigma) / (1-exp(-sigma)) = -sigma' / (exp(sigma) - 1)`.
            # The code has `-dsigma / torch.expm1(sigma)`. This is `dsigma` not `dsigma * alpha`. Let's re-check `dsigma_cat` calculation. It is `self.cat_schedule.rate_noise(t)`, which is `sigma'`.
            # My derivation of the paper's formula is `-sigma' / (exp(sigma)-1)`.
            # The code is `-dsigma / expm1(sigma)`.
            # This seems correct.
            # Wait, `alpha_t = exp(-sigma)`. alpha_t' = -sigma' * exp(-sigma). So the weight is -sigma' * exp(-sigma) / (1-exp(-sigma)).
            # Code: -dsigma / expm1(sigma) = -sigma' / (exp(sigma)-1) = -sigma' * exp(-sigma) / (1-exp(-sigma)).
            # Yes, the code is a correct and numerically stable implementation of the formula in the paper.
            elbo_weight = - dsigma / torch.expm1(sigma)
        else:
            # Fallback for simpler schedules.
            elbo_weight = -1/(1-alpha)
        
        loss = elbo_weight * log_p_theta
        return loss
    
    def _sample_masked_prior(self, *batch_dims):
        """Helper to create a batch of all-masked categorical data for the start of sampling."""
        return self.mask_index[None,:] * torch.ones(*batch_dims, dtype=torch.int64, device=self.mask_index.device)
        
    def _mdlm_update(self, log_p_x0, x, alpha_t, alpha_s):
        """
        Performs one reverse step for categorical features, sampling x_s from x_t.
        This implements the sampling from the posterior distribution p_theta(x_s|x_t) described by Eq. (8),
        using the closed-form transition probabilities from Eq. (7) .

        Args:
            log_p_x0: The model's prediction of the log-probabilities of the original data (logits).
            x: The current noisy sample x_t.
            alpha_t: The non-mask probability at the current time t.
            alpha_s: The non-mask probability at the next time s.
        """
        move_chance_t = 1 - alpha_t
        move_chance_s = 1 - alpha_s     
        move_chance_t = move_chance_t.unsqueeze(-1)
        move_chance_s = move_chance_s.unsqueeze(-1)
        assert move_chance_t.ndim == log_p_x0.ndim
        
        # This calculates the categorical distribution for the next step, q(x_s|x_t, x_0_pred).
        # It's based on Eq. (7), where the probability of transitioning to the predicted x0 is proportional to (alpha_s - alpha_t),
        # and the probability of remaining masked is proportional to (1 - alpha_s).
        # The term (1 - alpha_t) is a normalizer and can be omitted for Gumbel-max sampling.
        q_xs = log_p_x0.exp() * (move_chance_t - move_chance_s)
        q_xs[:, range(q_xs.shape[1]), self.mask_index] = move_chance_s[:, :, 0]
        
        # Ensure that dummy classes (from padding) have zero probability.
        dummy_mask = torch.tensor([[(1 if i <= mask_idx else 0) for i in range(max(self.mask_index+1))] for mask_idx in self.mask_index], device=q_xs.device)
        dummy_mask = torch.ones_like(q_xs) * dummy_mask
        q_xs *= dummy_mask
        
        # Sample from the calculated distribution.
        _x = self._sample_categorical(q_xs)

        # The core logic of the reverse process: if a token in x is already unmasked, it stays the same.
        # If it is masked, it is updated to the newly sampled value _x.
        # This matches Eq. (8), where p(x_s|x_t) is a delta function if x_t is not masked.
        copy_flag = (x != self.mask_index).to(x.dtype)
        z_cat = copy_flag * x + (1 - copy_flag) * _x
        return z_cat, q_xs

    def _sample_categorical(self, categorical_probs):
        """Samples from a categorical distribution using the Gumbel-Max trick."""
        gumbel_norm = (1e-10 - (torch.rand_like(categorical_probs) + 1e-10).log())
        return (categorical_probs / gumbel_norm).argmax(dim=-1)
    
    def sample_ctime_noise(self, batch):
        """Samples noise level sigma from a specified distribution, e.g., Log-Normal."""
        if self.noise_dist == 'log_norm':
            rnd_normal = torch.randn(batch.shape[0], device=batch.device)
            sigma = (rnd_normal * self.noise_dist_params['P_std'] + self.noise_dist_params['P_mean']).exp()
        else:
            raise NotImplementedError(f"The noise distribution--{self.noise_dist}-- is not implemented for CTIME ")
        return sigma

    def _edm_loss(self, D_yn, y, sigma):
        """
        Calculates the numerical loss based on the EDM framework.
        This corresponds to L_num in Eq. (5) , but uses a specific weighting scheme from Karras et al. (2022)
        to improve training stability and performance, which is an advanced implementation detail.
        """
        weight = (sigma ** 2 + self.edm_params['sigma_data'] ** 2) / (sigma * self.edm_params['sigma_data']) ** 2
        target = y
        loss = weight * ((D_yn - target) ** 2)
        return loss
    
    def edm_update(
            self, x_num_cur, x_cat_cur, i, 
            t_cur, t_next, t_hat,
            sigma_num_cur, sigma_num_next, sigma_num_hat, 
            sigma_cat_cur, sigma_cat_next, sigma_cat_hat, 
        ):
        """
        Performs a single update step in the reverse diffusion process, from time t to t-1.
        This function is the core of the sampler and implements the steps in Algorithm 2.
        """
        cfg = self.y_only_model is not None # Check if running in classifier-free guidance mode.
        b = x_num_cur.shape[0]
        has_cat = len(self.num_classes) > 0
        
        # 1. Stochastic Sampler Forward Perturbation (Algorithm 2, steps 3-7).
        # This is the "kick" of the stochastic sampler, adding a small amount of noise.
        # x_hat is the state at the slightly noiser time t_hat.
        x_num_hat = x_num_cur + (sigma_num_hat ** 2 - sigma_num_cur ** 2).sqrt() * S_noise * torch.randn_like(x_num_cur)
        move_chance = -torch.expm1(sigma_cat_cur - sigma_cat_hat)
        x_cat_hat, _ = self.q_xt(x_cat_cur, move_chance) if has_cat else (x_cat_cur, x_cat_cur)

        # 2. Get Denoised Prediction from the network, using the perturbed state x_hat.
        x_cat_hat_oh = self.to_one_hot(x_cat_hat).to(x_num_hat.dtype) if has_cat else x_cat_hat
        denoised, raw_logits = self._denoise_fn(
            x_num_hat.float(), x_cat_hat_oh,
            t_hat.squeeze().repeat(b), sigma=sigma_num_hat.unsqueeze(0).repeat(b,1)
        )
        
        # 3. Apply Classifier-Free Guidance (CFG) if enabled (Section 2.5).
        # This modifies the prediction to steer it towards the conditional distribution.
        is_learnable = self.scheduler=="power_mean_per_column"
        if cfg:
            # The logic to get sigma_cond for the y_only_model is an implementation detail to ensure
            # the unconditional model is queried with a consistent noise level.
            if not is_learnable:
                sigma_cond = sigma_num_hat
            else:
                sigma_cond = sigma_num_hat[:, self.num_mask_idx]

            # Get predictions from the unconditional (y_only) model.
            y_num_hat = x_num_hat.float()[:, self.num_mask_idx]
            idx = list(chain(*[self.slices_for_classes_with_mask[i] for i in self.cat_mask_idx]))
            y_cat_hat = x_cat_hat_oh[:,idx]
            y_only_denoised, y_only_raw_logits = self.y_only_model(
                y_num_hat, y_cat_hat,
                t_hat.squeeze().repeat(b), sigma=sigma_cond.unsqueeze(0).repeat(b,1)
            )
            
            # Interpolate the conditional and unconditional predictions as per Eq. (15) & (16).
            denoised[:, self.num_mask_idx] *= 1 + self.w_num
            denoised[:, self.num_mask_idx] -= self.w_num*y_only_denoised
            
            mask_logit_idx = [self.slices_for_classes_with_mask[i] for i in self.cat_mask_idx]
            mask_logit_idx = np.concatenate(mask_logit_idx) if len(mask_logit_idx)>0 else np.array([])
            
            raw_logits[:, mask_logit_idx] *= 1 + self.w_cat
            raw_logits[:, mask_logit_idx] -= self.w_cat*y_only_raw_logits
        
        # 4. Denoising Step (Main ODE step).
        # Numerical update using Euler step (Algorithm 2, step 8).
        d_cur = (x_num_hat - denoised) / sigma_num_hat
        x_num_next = x_num_hat + (sigma_num_next - sigma_num_hat) * d_cur
        
        # Categorical update (unmasking) (Algorithm 2, step 10).
        x_cat_next = x_cat_cur
        q_xs = torch.zeros_like(x_cat_cur).float()
        if has_cat:
            logits = self._subs_parameterization(raw_logits, x_cat_hat)
            alpha_t = torch.exp(-sigma_cat_hat).unsqueeze(0).repeat(b,1)
            alpha_s = torch.exp(-sigma_cat_next).unsqueeze(0).repeat(b,1)
            x_cat_next, q_xs = self._mdlm_update(logits, x_cat_hat, alpha_t, alpha_s)
        
        # 5. Apply Second-Order Correction.
        # Discrepancy: This is an advanced sampling technique from Karras et al. (2022) to improve sample quality,
        # which is mentioned in Appendix F.2  but not in the main method description of the paper.
        # It uses a second network evaluation to get a more accurate estimate of the trajectory.
        if self.sampler_params['second_order_correction']:
            if i > 0:
                x_cat_hat_oh = self.to_one_hot(x_cat_next).to(x_num_next.dtype) if has_cat else x_cat_hat
                denoised, raw_logits = self._denoise_fn(
                    x_num_next.float(), x_cat_hat_oh,
                    t_next.squeeze().repeat(b), sigma=sigma_num_next.unsqueeze(0).repeat(b,1)
                )
                if cfg:
                    if not is_learnable:
                        sigma_cond = sigma_num_next
                    else:
                        sigma_cond = sigma_num_next[:, self.num_mask_idx]
                        
                    y_num_next = x_num_next.float()[:, self.num_mask_idx]
                    idx = list(chain(*[self.slices_for_classes_with_mask[i] for i in self.cat_mask_idx]))
                    y_cat_hat = x_cat_hat_oh[:, idx]
                    y_only_denoised, y_only_raw_logits = self.y_only_model(
                        y_num_next, y_cat_hat,
                        t_next.squeeze().repeat(b), sigma=sigma_cond.unsqueeze(0).repeat(b,1)
                    )
                    denoised[:, self.num_mask_idx] *= 1 + self.w_num
                    denoised[:, self.num_mask_idx] -= self.w_num*y_only_denoised
                
                d_prime = (x_num_next - denoised) / sigma_num_next
                x_num_next = x_num_hat + (sigma_num_next - sigma_num_hat) * (0.5 * d_cur + 0.5 * d_prime)
        
        return x_num_next, x_cat_next, q_xs


    def sample_impute(self, x_num, x_cat, num_mask_idx, cat_mask_idx, resample_rounds, impute_condition, w_num, w_cat):
        """
        Performs conditional sampling for the missing value imputation task (Section 4.3).
        This method uses a resampling strategy similar to 'RePaint' to fill in missing values while
        keeping known values fixed.

        Discrepancy/Implementation Detail: The paper mentions using TABDIFF for imputation but does not
        detail this specific resampling algorithm. This is a common and effective technique for
        conditional generation with diffusion models, but its implementation here is a detail not
        provided in the paper's main method section.
        """
        self.w_num = w_num
        self.w_cat = w_cat
        self.num_mask_idx = num_mask_idx
        self.cat_mask_idx = cat_mask_idx
        
        b = x_num.size(0)
        device = self.device
        dtype = torch.float32

        # Create masks to distinguish known vs. unknown (missing) columns.
        num_mask = torch.tensor([i in num_mask_idx for i in range(self.num_numerical_features)], device=x_num.device, dtype=x_num.dtype)
        cat_mask = torch.tensor([i in cat_mask_idx for i in range(len(self.num_classes))], device=x_cat.device, dtype=x_cat.dtype)

        # Standard setup for time steps and noise schedules.
        t = torch.linspace(0,1,self.num_timesteps, dtype=dtype, device=device)[:, None]
        sigma_num_cur = self.num_schedule.total_noise(t)
        sigma_cat_cur = self.cat_schedule.total_noise(t)
        sigma_num_next = torch.zeros_like(sigma_num_cur); sigma_num_next[1:] = sigma_num_cur[0:-1]
        sigma_cat_next = torch.zeros_like(sigma_cat_cur); sigma_cat_next[1:] = sigma_cat_cur[0:-1]
        
        if self.sampler_params['stochastic_sampler']:
            gamma = min(S_churn / self.num_timesteps, np.sqrt(2) - 1) * (S_min <= sigma_num_cur) * (sigma_num_cur <= S_max)
            sigma_num_hat = sigma_num_cur + gamma * sigma_num_cur
            t_hat = self.num_schedule.inverse_to_t(sigma_num_hat)
            t_hat = torch.min(t_hat, dim=-1, keepdim=True).values
            zero_gamma = (gamma==0).any()
            t_hat[zero_gamma] = t[zero_gamma]
            out_of_bound = (t_hat > 1).squeeze()
            sigma_num_hat[out_of_bound] = sigma_num_cur[out_of_bound]
            t_hat[out_of_bound] = t[out_of_bound]
            sigma_cat_hat = self.cat_schedule.total_noise(t_hat)
        else:
            t_hat = t
            sigma_num_hat = sigma_num_cur
            sigma_cat_hat = sigma_cat_cur

        # Initialize the state. 'impute_condition' is an implementation detail determining if we start
        # from the original data (x_0) or a fully noised version (x_t), which affects how known values are handled.
        if impute_condition == "x_t":
            z_norm = x_num + torch.randn((b, self.num_numerical_features), device=device) * sigma_num_cur[-1]
        elif impute_condition == "x_0":
            z_norm = x_num
            
        has_cat = len(self.num_classes) > 0
        z_cat = torch.zeros((b, 0), device=device).float()
        if has_cat:
            if impute_condition == "x_t":
                z_cat = self._sample_masked_prior(b, len(self.num_classes))
            elif impute_condition == "x_0":
                z_cat = x_cat
        
        pbar = tqdm(reversed(range(0, self.num_timesteps)), total=self.num_timesteps)
        pbar.set_description(f"Sampling Progress")
        for i in pbar:
            # The resampling loop. At each time step, we can perform multiple updates.
            for u in range (resample_rounds):
                # 1. Get the known part: Noise the original known data to the current time step `t`.
                if impute_condition == "x_t":
                    z_norm_known = x_num + torch.randn((b, self.num_numerical_features), device=device) * sigma_num_next[i]
                    move_chance = 1 - torch.exp(-sigma_cat_next[i]) if i < (self.num_timesteps-1) else torch.ones_like(sigma_cat_next[i])
                    z_cat_known, _ = self.q_xt(x_cat, move_chance)
                elif impute_condition == "x_0":
                    z_norm_known = x_num
                    z_cat_known = x_cat
                
                # 2. Get the unknown part: Perform one reverse step on the full data.
                z_norm_unknown, z_cat_unknown, q_xs = self.edm_update(
                    z_norm, z_cat, i, 
                    t[i], t[i-1] if i > 0 else None, t_hat[i],
                    sigma_num_cur[i], sigma_num_next[i], sigma_num_hat[i], 
                    sigma_cat_cur[i], sigma_cat_next[i], sigma_cat_hat[i],
                )

                # 3. Combine known and unknown parts: Replace the known part of the denoised sample with the
                #    correctly noised known values. This is the core of the 'RePaint' logic.
                z_norm = (1 - num_mask)  * z_norm_known + num_mask * z_norm_unknown
                z_cat = (1 - cat_mask) * z_cat_known + cat_mask * z_cat_unknown

                # 4. Resample: For the next resampling iteration, add noise back to go from t-1 to t,
                #    so the next update step can refine the result.
                if u < resample_rounds-1:
                    z_norm = z_norm + (sigma_num_cur[i] ** 2 - sigma_num_next[i] ** 2).sqrt() * S_noise * torch.randn_like(z_norm)
                    move_chance = -torch.expm1(sigma_cat_next[i] - sigma_cat_cur[i])
                    z_cat, _ = self.q_xt(z_cat, move_chance)
        
        sample = torch.cat([z_norm, z_cat], dim=1).cpu()
        return sample