ptsd/utils/metrics.py SHA256 b58e56a3787895cb265b549630c845b7caeae0d9db64b4c7b729a0d0e364aa6f
1: import torch
2: import ot as pot
3: import numpy as np
4: import math
5: 
6: from ptsd.targets.base_target import TargetDistribution
7: from ptsd.utils.se3_utils import calculate_rmsd_matrix
8: 
9: 
10: def maximum_mean_discrepancy(
11:     source: torch.Tensor,
12:     target: torch.Tensor,
13:     kernel_mul: float = 2.0,
14:     kernel_num: int = 1,
15:     fix_sigma=None,
16: ):
17:     assert source.shape == target.shape and len(source.shape) <= 2
18:     # assert source.ndim == target.ndim and source.ndim <= 2
19:     if len(source.shape) == 1:
20:         source = source.unsqueeze(-1)
21:         target = target.unsqueeze(-1)
22: 
23:     def gaussian_kernel(x, y):
24:         n_samples = int(x.size()[0]) + int(y.size()[0])
25:         total = torch.cat([x, y], dim=0)
26: 
27:         total0 = total.unsqueeze(0).expand(
28:             int(total.size(0)), int(total.size(0)), int(total.size(1))
29:         )
30:         total1 = total.unsqueeze(1).expand(
31:             int(total.size(0)), int(total.size(0)), int(total.size(1))
32:         )
33:         L2_distance = ((total0 - total1) ** 2).sum(2)
34:         if fix_sigma:
35:             bandwidth = fix_sigma
36:         else:
37:             bandwidth = torch.sum(L2_distance.data) / (n_samples**2 - n_samples)
38:         bandwidth /= kernel_mul ** (kernel_num // 2)
39:         bandwidth_list = [bandwidth * (kernel_mul**i) for i in range(kernel_num)]
40:         #         print(bandwidth_list)
41:         kernel_val = [
42:             torch.exp(-L2_distance / bandwidth_temp)
43:             for bandwidth_temp in bandwidth_list
44:         ]
45:         return sum(kernel_val)
46: 
47:     batch_size = int(source.size()[0])
48:     kernels = gaussian_kernel(source, target)
49:     XX = kernels[:batch_size, :batch_size]
50:     YY = kernels[batch_size:, batch_size:]
51:     XY = kernels[:batch_size, batch_size:]
52:     YX = kernels[batch_size:, :batch_size]
53:     mmd = torch.mean(XX + YY - XY - YX)
54:     return mmd
55: 
56: 
57: def total_variation(source: torch.Tensor, target: torch.Tensor, num_bins: int = 200):
58:     """for 1d inputs now"""
59:     # assert source.shape == target.shape and len(source.shape) <= 2
60:     assert source.ndim == target.ndim and source.ndim <= 2
61:     if len(source.shape) == 1:
62:         H_data_set, x_data_set = np.histogram(target.cpu(), bins=num_bins)
63:         H_generated_samples, _ = np.histogram(source.cpu(), bins=(x_data_set))
64:         total_var = (
65:             0.5
66:             * np.abs(
67:                 H_data_set / H_data_set.sum()
68:                 - H_generated_samples / H_generated_samples.sum()
69:             ).sum()
70:         )
71:         total_var = torch.tensor(total_var, device=source.device)
72:     else:
73:         dim = math.prod(source.shape[1:])
74:         bins = (200,) * dim
75:         all_data = torch.cat([target, source], dim=0)
76:         min_vals, _ = all_data.min(dim=0)
77:         max_vals, _ = all_data.max(dim=0)
78:         ranges = tuple(
79:             (min_vals[i].item(), max_vals[i].item()) for i in range(dim)
80:         )  # tuple of (min, max) for each dimension
81:         ranges = tuple(item for subtuple in ranges for item in subtuple)
82:         hist_p, _ = torch.histogramdd(target.cpu(), bins=bins, range=ranges)
83:         hist_q, _ = torch.histogramdd(source.cpu(), bins=bins, range=ranges)
84: 
85:         p_dist = hist_p / hist_p.sum()
86:         q_dist = hist_q / hist_q.sum()
87: 
88:         total_var = 0.5 * torch.abs(p_dist - q_dist).sum()
89: 
90:     return total_var
91: 
92: 
93: def wasserstain2_dist(source: torch.Tensor, target: torch.Tensor):
94:     """
95:     For different length of source's shape:
96:         1: W2 distance on energy or interatomic distance
97:         2: W2 distance on non-SE(3) data
98:         3: W2 distance on SE(3) data
99:     """
100:     assert source.ndim == target.ndim
101:     if len(source.shape) == 1:
102:         return torch.tensor(
103:             pot.emd2_1d(source.cpu().numpy(), target.cpu().numpy()),
104:             device=source.device,
105:         )
106:     elif len(source.shape) == 2:
107:         distance_matrix = pot.dist(
108:             target.cpu().numpy(), source.cpu().numpy(), metric='euclidean'
109:         )
110:     elif len(source.shape) == 3:
111:         # For molecules
112:         distance_matrix = calculate_rmsd_matrix(target, source).cpu().numpy()
113:     else:
114:         raise "Incorrect data shape..."
115:     src, dist = np.ones(len(target)) / len(target), np.ones(len(source)) / len(source)
116:     G = pot.emd(src, dist, distance_matrix)
117:     w2_dist = np.sum(G * distance_matrix) / G.sum()
118:     w2_dist = torch.tensor(w2_dist, device=target.device)
119:     return w2_dist
120: 
121: 
122: class Metric:
123:     def __init__(self, name, target: TargetDistribution):
124:         self.__name__ = name
125:         self.target = target
126: 
127:     def __call__(self, source: torch.Tensor, target: torch.Tensor):
128:         pass
129: 
130: 
131: class MMD_energy(Metric):
132:     def __init__(
133:         self,
134:         target: TargetDistribution,
135:         kernel_mul: float = 2.0,
136:         kernel_num: int = 1,
137:         fix_sigma=None,
138:     ):
139:         super().__init__("MMD_energy", target)
140:         self.kernel_mul = kernel_mul
141:         self.kernel_num = kernel_num
142:         self.fix_sigma = fix_sigma
143: 
144:     def __call__(self, source: torch.Tensor, target: torch.Tensor):
145:         return maximum_mean_discrepancy(
146:             -self.target.log_prob(source),
147:             -self.target.log_prob(target),
148:             self.kernel_mul,
149:             self.kernel_num,
150:             self.fix_sigma,
151:         )
152: 
153: 
154: class MMD_interatomic(Metric):
155:     def __init__(
156:         self,
157:         target: TargetDistribution,
158:         kernel_mul: float = 2.0,
159:         kernel_num: int = 1,
160:         fix_sigma=None,
161:     ):
162:         super().__init__("MMD_interatomic", target)
163:         self.kernel_mul = kernel_mul
164:         self.kernel_num = kernel_num
165:         self.fix_sigma = fix_sigma
166:         if not hasattr(self.target, "interatomic_dist"):
167:             raise "Energy function does not have interatomic_dist method..."
168: 
169:     def __call__(self, source: torch.Tensor, target: torch.Tensor):
170:         return maximum_mean_discrepancy(
171:             self.target.interatomic_dist(source),
172:             self.target.interatomic_dist(target),
173:             self.kernel_mul,
174:             self.kernel_num,
175:             self.fix_sigma,
176:         )
177: 
178: 
179: class TVD_energy(Metric):
180:     def __init__(self, target: TargetDistribution, num_bins: int = 200):
181:         super().__init__("TVD_energy", target)
182:         self.num_bins = num_bins
183: 
184:     def __call__(self, source: torch.Tensor, target: torch.Tensor):
185:         return total_variation(
186:             -self.target.log_prob(source), -self.target.log_prob(target), self.num_bins
187:         )
188: 
189: 
190: class TVD_interatomic(Metric):
191:     def __init__(self, target: TargetDistribution, num_bins: int = 200):
192:         super().__init__("TVD_interatomic", target)
193:         self.num_bins = num_bins
194:         if not hasattr(self.target, "interatomic_dist"):
195:             raise "Energy function does not have interatomic_dist method..."
196: 
197:     def __call__(self, source: torch.Tensor, target: torch.Tensor):
198:         return total_variation(
199:             self.target.interatomic_dist(source),
200:             self.target.interatomic_dist(target),
201:             self.num_bins,
202:         )
203: 
204: 
205: class Wasserstain2_energy(Metric):
206:     def __init__(self, target):
207:         super().__init__("Wasserstain2_energy", target)
208: 
209:     def __call__(self, source: torch.Tensor, target: torch.Tensor):
210:         return wasserstain2_dist(
211:             -self.target.log_prob(source), -self.target.log_prob(target)
212:         )
213: 
214: 
215: class Wasserstain2_data(Metric):
216:     def __init__(self, target: TargetDistribution):
217:         super().__init__("Wasserstain2_data", target)
218: 
219:     def __call__(self, source: torch.Tensor, target: torch.Tensor):
220:         return wasserstain2_dist(source, target)
221: 
222: 
223: class MMD_data(Metric):
224:     def __init__(
225:         self,
226:         target: TargetDistribution,
227:         kernel_mul: float = 2.0,
228:         kernel_num: int = 1,
229:         fix_sigma=None,
230:     ):
231:         super().__init__("MMD_data", target)
232:         self.kernel_mul = kernel_mul
233:         self.kernel_num = kernel_num
234:         self.fix_sigma = fix_sigma
235: 
236:     def __call__(self, source: torch.Tensor, target: torch.Tensor):
237:         return maximum_mean_discrepancy(
238:             source, target, self.kernel_mul, self.kernel_num, self.fix_sigma
239:         )
ptsd/utils/diffusion_utils.py SHA256 cb86cbff69e41d0338318bddc94de642dba5ef6a92b2761d24462fec46cbf8f0
137: def Euler_solve_with_log_pdf(
138:     target: TargetDistribution,
139:     model: torch.nn.Module,
140:     start_samples: torch.Tensor,
141:     tmax: float = 40.0,
142:     tmin: float = 1e-3,
143:     rho: float = 7,
144:     num_steps: int = 2000,
145: ):
146: 
147:     ts = tmin ** (1 / rho) + np.arange(num_steps) / (num_steps - 1) * (
148:         tmax ** (1 / rho) - tmin ** (1 / rho)
149:     )
150:     ts = ts**rho
151: 
152:     # Calculate effective dimensionality for centered molecules
153:     if target.is_se3:
154:         d = (
155:             np.prod(start_samples.shape[1:]) - target.n_dimensions
156:         )  # subtract degrees of freedom from centering
157:     else:
158:         d = np.prod(start_samples.shape[1:])
159: 
160:     # Initialize with centered Gaussian log pdf
161:     log_prob = -0.5 * d * np.log(2 * np.pi) - d * np.log(tmax)
162:     if target.is_se3:
163:         # For centered configurations, use the norm in the centered subspace
164:         start_samples = remove_mean(
165:             start_samples, target.n_particles, target.n_dimensions
166:         )
167:         log_prob = log_prob - torch.sum(
168:             start_samples**2, dim=tuple(range(1, len(start_samples.shape)))
169:         ) / (2 * tmax**2)
170:     else:
171:         log_prob = log_prob - torch.sum(
172:             start_samples**2, dim=tuple(range(1, len(start_samples.shape)))
173:         ) / (2 * tmax**2)
174: 
175:     with torch.enable_grad():
176:         samples = start_samples.requires_grad_(True)
177: 
178:         for i in range(ts.shape[0] - 1, 0, -1):
179:             t = torch.ones(samples.shape[0], 1).to(samples.device) * ts[i]
180:             t_1 = torch.ones(samples.shape[0], 1).to(samples.device) * ts[i - 1]
181: 
182:             x_hat = model(t.squeeze(-1).log(), samples)
183:             f = -(x_hat - samples) / t
184: 
185:             epsilon = (
186:                 torch.randint(0, 2, samples.shape, device=samples.device).float() * 2
187:                 - 1
188:             )
189: 
190:             # For molecules, we need to account for the centering constraint in our Jacobian calculations.
191:             # Let P be the projection matrix that centers the molecules (removes mean).
192:             # We want to estimate Tr(PJP^T) where J is the Jacobian of our drift.
193:             # Using the Hutchinson estimator, E[ε^T PJP^T ε] = Tr(PJP^T).
194:             # This can be computed by simply projecting (centering) ε before using it
195:             # in our trace estimation.
196:             if target.is_se3:
197:                 # Center the epsilon to ensure we're estimating trace in the correct subspace
198:                 epsilon = remove_mean(epsilon, target.n_particles, target.n_dimensions)
199: 
200:             vjp = torch.autograd.grad(
201:                 f, samples, epsilon, create_graph=False, retain_graph=False
202:             )[0]
203:             trace_est = (vjp * epsilon).sum(dim=tuple(range(1, len(samples.shape))))
204: 
205:             dt = t_1 - t
206:             log_prob = log_prob - trace_est * dt.squeeze(-1)
207: 
208:             # Euler step
209:             samples = samples * t_1 / t + (1 - t_1 / t) * x_hat
210:             if target.is_se3:
211:                 samples = remove_mean(samples, target.n_particles, target.n_dimensions)
212: 
213:             samples = samples.detach().requires_grad_(True)
214: 
215:         return samples.detach(), log_prob
430:             "Sampling from diffusion. Total samples {}. Batch size {}. num_iters {}".format(
431:                 start_samples.shape[0], num_samples_per_batch, num_iters
432:             )
433:         )
434:         for i in range(num_iters):
435:             suboutputs = sample_func(
436:                 target=target,
437:                 model=model,
438:                 start_samples=start_samples[
439:                     i * num_samples_per_batch : (i + 1) * num_samples_per_batch
440:                 ],
441:                 tmax=tmax,
442:                 tmin=tmin,
443:                 rho=rho,
444:                 num_steps=num_steps,
445:             )
446:             if isinstance(suboutputs, tuple):
447:                 outputs1.append(suboutputs[0])
448:                 outputs2.append(suboutputs[1])
449:             else:
450:                 outputs1.append(suboutputs)
451:         if num_iters * num_samples_per_batch < num_generate_samples:
452:             suboutputs = sample_func(
453:                 target=target,
454:                 model=model,
455:                 start_samples=start_samples[num_iters * num_samples_per_batch :],
456:                 tmax=tmax,
457:                 tmin=tmin,
458:                 rho=rho,
459:                 num_steps=num_steps,
460:             )
461:             if isinstance(suboutputs, tuple):
462:                 outputs1.append(suboutputs[0])
463:                 outputs2.append(suboutputs[1])
464:             else:
465:                 outputs1.append(suboutputs)
466:         outputs1 = torch.cat(outputs1, dim=0)
467:         if outputs2:
468:             outputs2 = torch.cat(outputs2, dim=0)
469:             return outputs1, outputs2
470:         else:
471:             return outputs1
472: 
473:     return wrapped_sample_func
474: 
475: 
476: def evaluate_log_likelihood(
477:     target: TargetDistribution,
478:     model: torch.nn.Module,
479:     samples: torch.Tensor,
480:     tmax: float = 40.0,
481:     tmin: float = 1e-3,
482:     rho: float = 7,
483:     num_steps: int = 2000,
484: ):
485:     """
486:     Evaluate the log likelihood of given samples under the diffusion model.
487: 
488:     Args:
489:         target: Target distribution
490:         model: Score-based model that approximates the score function
491:         samples: Input samples to evaluate [batch_size, ...]
492:         tmax: Maximum diffusion time
493:         tmin: Minimum diffusion time
494:         rho: Parameter controlling the time schedule
495:         num_steps: Number of integration steps
496: 
497:     Returns:
498:         log_likelihood: Log likelihood of the input samples
499:     """
500:     # Generate time steps from tmin to tmax
501:     ts = tmin ** (1 / rho) + np.arange(num_steps) / (num_steps - 1) * (
502:         tmax ** (1 / rho) - tmin ** (1 / rho)
503:     )
504:     ts = ts**rho
505: 
506:     # Calculate effective dimensionality for centered molecules
507:     if target.is_se3:
508:         d = (
509:             np.prod(samples.shape[1:]) - target.n_dimensions
510:         )  # subtract degrees of freedom from centering
511:     else:
512:         d = np.prod(samples.shape[1:])
513: 
514:     with torch.enable_grad():
515:         current_samples = samples.clone().detach().requires_grad_(True)
516:         if target.is_se3:
517:             current_samples = remove_mean(
518:                 current_samples, target.n_particles, target.n_dimensions
519:             )
520: 
521:         # Start with the log probability under the data distribution
522:         # Initialize this to zero as we'll track the change in log probability
523:         log_likelihood = torch.zeros(samples.shape[0], device=samples.device)
524: 
525:         # Forward diffusion process (ODE from data to noise)
526:         for i in range(1, ts.shape[0]):
527:             t_prev = (
528:                 torch.ones(current_samples.shape[0], 1).to(current_samples.device)
529:                 * ts[i - 1]
530:             )
531:             t = (
532:                 torch.ones(current_samples.shape[0], 1).to(current_samples.device)
533:                 * ts[i]
534:             )
535: 
536:             # Get score estimate from the model
537:             x_hat = model(t_prev.squeeze(-1).log(), current_samples)
538:             f = -(x_hat - current_samples) / t_prev
539: 
540:             # Estimate trace of Jacobian using Hutchinson's estimator
541:             epsilon = (
542:                 torch.randint(
543:                     0, 2, current_samples.shape, device=current_samples.device
544:                 ).float()
545:                 * 2
ptsd/train.py SHA256 16bb0985bec0fe1aaa3d01051769d113f8d930aace19105cd784a35b7bb58b90
488:         # Sample from the model with Taylor guidance for the next buffer
489:         def taylor_guided_model(t, x):
490:             d_temp = high_temp - low_temp
491:             next_temp = all_temps[temp_idx - 2]
492:             low_temp_model_output = models[temp_idx - 1](t, x)
493:             high_temp_model_output = models[temp_idx](t, x)
494:             temp_gradient = (high_temp_model_output - low_temp_model_output) / d_temp
495:             return low_temp_model_output + temp_gradient * (next_temp - low_temp)
496: 
497:         with torch.no_grad():
498:             # Generate samples for the next temperature using the diffusion model
499:             if hparams.importance_resample and (temp_idx > 2 or hparams.is_last_step):
500:                 sample_func = Euler_solve_wrapper(
501:                     Euler_solve_with_log_pdf,
502:                     num_samples_per_batch=hparams.num_samples_to_generate_per_batch,
503:                 )
504:                 print(f"Generating {hparams.num_dm_samples} samples, with IS weights")
505:                 generate_samples, generate_log_probs = sample_func(
506:                     target,
507:                     model=taylor_guided_model,
508:                     start_samples=torch.randn(
509:                         hparams.num_dm_samples, target.dim, device=hparams.device
510:                     )
511:                     * hparams.tmax,
512:                     tmax=hparams.tmax,
513:                     tmin=hparams.tmin,
514:                     num_steps=hparams.is_integration_steps,
515:                 )
516:                 generate_samples = generate_samples * hparams.normalization
517:                 if isinstance(target, AldpPotentialCart):
518:                     generate_samples = target.reflect_d_to_l_cartesian(generate_samples)
519:                 target_log_probs = (
520:                     target.log_prob(generate_samples) / all_temps[temp_idx - 2]
521:                 )
522:                 # Cap the maximum IS weight
523:                 log_prob_threshold = torch.quantile(
524:                     target_log_probs - generate_log_probs,
525:                     hparams.is_weight_max_quantile,
526:                 )
527:                 log_prob_diff = target_log_probs - generate_log_probs
528:                 capped_diff = torch.minimum(log_prob_diff, log_prob_threshold)
529:                 generate_log_probs = target_log_probs - capped_diff
530:                 dm_samples, ess_ratio, weights = importance_sample_with_reweighting(
531:                     samples=generate_samples,
532:                     model_log_probs=generate_log_probs,
533:                     target_log_probs=target_log_probs,
534:                 )
ptsd/eval.py SHA256 d69cddaf008077875a4f4c9fa46e7a23268451b55ba11b91ac6ccc9b93bd30c2
1: import torch
2: from typing import List
3: import matplotlib.pyplot as plt
4: from tqdm import tqdm
5: import wandb
6: import torch
7: from ptsd.utils.metrics import (
8:     MMD_energy,
9:     TVD_energy,
10:     Wasserstain2_energy,
11:     Wasserstain2_data,
12: )
13: from ptsd.utils.diffusion_utils import Eular_solve, Euler_solve_wrapper
14: from ptsd.utils.metrics import Metric
15: import os
16: from ptsd.targets.aldp import AldpPotential
17: 
18: 
19: def get_samples_from_all_temps(
20:     target_name, temp_schedule, total_n_temp, temp_low, temp_high, device
21: ):
22:     """
23:     Load all the samples for a given temperature schedule.
24:     """
25:     all_temps_reference_file = f"data/pt/{target_name}_schedule_{temp_schedule}_total_n_temp_{total_n_temp}_temp_low_{temp_low}_temp_high_{temp_high}.pt"
26:     if os.path.exists(all_temps_reference_file):
27:         samples = torch.load(all_temps_reference_file, map_location=device)
28:         return samples
29:     else:
30:         return None
31: 
32: 
33: def evaluate_samples(target_func, t1_samples, pt_samples, save_path):
34:     """
35:     Evaluate generated samples against baseline and ground truth.
36:     A wrapper function to combine all the evaluation metrics.
37:     """
38:     eval(
39:         gt_samples=target_func.sample([10000]),
40:         sample_dict=(
41:             {"ptsd": t1_samples.unsqueeze(0)} | {"pt": pt_samples.unsqueeze(0)}
42:             if pt_samples is not None
43:             else {}
44:         ),
45:         metric_list=[
46:             MMD_energy(target_func, kernel_num=5, fix_sigma=1),
47:             TVD_energy(target_func),
48:             Wasserstain2_energy(target_func),
49:             Wasserstain2_data(target_func),
50:         ],
51:         save_path=save_path,
52:     )
53: 
54: 
55: def get_eval_metrics(target_func, samples, reference_samples):
56:     """
57:     samples: shape [N, dim]
58:     reference_samples: shape [M, dim]
59:     output: list of metrics comparing these two sets of samples
60:     """
61:     metrics = (
62:         {
63:             "MMD_energy": MMD_energy(target_func, kernel_num=5, fix_sigma=1),
64:             "TVD_energy": TVD_energy(target_func),
65:             "Wasserstain2_energy": Wasserstain2_energy(target_func),
66:             "Wasserstain2_data": Wasserstain2_data(target_func),
67:         }
68:         if not isinstance(target_func, AldpPotential)
69:         else {"Wasserstain2_data": Wasserstain2_data(target_func)}
70:     )
71:     results = {}
72:     for metric_name, metric in metrics.items():
73:         results[metric_name] = (
74:             metric(samples.clone().detach(), reference_samples.clone().detach())
75:             .detach()
76:             .cpu()
77:             .item()
78:         )
79:     return results
80: 
81: 
82: def write_metrics_to_csv(metrics_file: str, eval_metrics: dict):
83:     """
84:     Write evaluation metrics to a CSV file. Creates header if file doesn't exist,
85:     otherwise appends metrics as a new row.
86: 
87:     Args:
88:         metrics_file (str): Path to the CSV file
89:         eval_metrics (dict): Dictionary containing metric names and values
90:     """
91:     # Create header if file doesn't exist
92:     if not os.path.exists(metrics_file):
93:         with open(metrics_file, "w") as f:
94:             f.write(",".join(eval_metrics.keys()) + "\n")
95: 
96:     # Append metrics as new row
97:     with open(metrics_file, "a") as f:
98:         f.write(",".join(str(v) for v in eval_metrics.values()) + "\n")
99: 
100: 
101: def generate_samples(
102:     target_func, model, target_name, dim, device, hparams, num_samples=10000
103: ):
104:     """
105:     Generate samples using the appropriate sampling method for the target.
106:     A wrapper function to unify the interface for sampling for different targets.
107:     """
108:     with torch.no_grad():
109:         if target_name == 'lj55':
110:             sample_func = Euler_solve_wrapper(