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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 the Llamole team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import numpy as np
|
| 17 |
+
from torch.nn import functional as F
|
| 18 |
+
from torch_geometric.utils import to_dense_adj, to_dense_batch, remove_self_loops
|
| 19 |
+
import os
|
| 20 |
+
import json
|
| 21 |
+
import yaml
|
| 22 |
+
from types import SimpleNamespace
|
| 23 |
+
|
| 24 |
+
def dict_to_namespace(d):
|
| 25 |
+
return SimpleNamespace(
|
| 26 |
+
**{k: dict_to_namespace(v) if isinstance(v, dict) else v for k, v in d.items()}
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
class DataInfos:
|
| 30 |
+
def __init__(self, meta_filename="data.meta.json"):
|
| 31 |
+
self.all_targets = ['CH4', 'CO2', 'H2', 'N2', 'O2']
|
| 32 |
+
self.task_type = "gas_permeability"
|
| 33 |
+
if os.path.exists(meta_filename):
|
| 34 |
+
with open(meta_filename, "r") as f:
|
| 35 |
+
meta_dict = json.load(f)
|
| 36 |
+
else:
|
| 37 |
+
raise FileNotFoundError(f"Meta file {meta_filename} not found.")
|
| 38 |
+
|
| 39 |
+
self.active_atoms = meta_dict["active_atoms"]
|
| 40 |
+
self.max_n_nodes = meta_dict["max_node"]
|
| 41 |
+
self.original_max_n_nodes = meta_dict["max_node"]
|
| 42 |
+
self.n_nodes = torch.Tensor(meta_dict["n_atoms_per_mol_dist"])
|
| 43 |
+
self.edge_types = torch.Tensor(meta_dict["bond_type_dist"])
|
| 44 |
+
self.transition_E = torch.Tensor(meta_dict["transition_E"])
|
| 45 |
+
|
| 46 |
+
self.atom_decoder = meta_dict["active_atoms"]
|
| 47 |
+
node_types = torch.Tensor(meta_dict["atom_type_dist"])
|
| 48 |
+
active_index = (node_types > 0).nonzero().squeeze()
|
| 49 |
+
self.node_types = torch.Tensor(meta_dict["atom_type_dist"])[active_index]
|
| 50 |
+
self.nodes_dist = DistributionNodes(self.n_nodes)
|
| 51 |
+
self.active_index = active_index
|
| 52 |
+
|
| 53 |
+
val_len = 3 * self.original_max_n_nodes - 2
|
| 54 |
+
meta_val = torch.Tensor(meta_dict["valencies"])
|
| 55 |
+
self.valency_distribution = torch.zeros(val_len)
|
| 56 |
+
val_len = min(val_len, len(meta_val))
|
| 57 |
+
self.valency_distribution[:val_len] = meta_val[:val_len]
|
| 58 |
+
## for all
|
| 59 |
+
self.input_dims = {"X": len(self.active_atoms), "E": 5, "y": 5}
|
| 60 |
+
self.output_dims = {"X": len(self.active_atoms), "E": 5, "y": 5}
|
| 61 |
+
# self.input_dims = {"X": 11, "E": 5, "y": 5}
|
| 62 |
+
# self.output_dims = {"X": 11, "E": 5, "y": 5}
|
| 63 |
+
|
| 64 |
+
def load_config(config_path, data_meta_info_path):
|
| 65 |
+
if not os.path.exists(config_path):
|
| 66 |
+
raise FileNotFoundError(f"Configuration file not found: {config_path}")
|
| 67 |
+
|
| 68 |
+
if not os.path.exists(data_meta_info_path):
|
| 69 |
+
raise FileNotFoundError(f"Data meta info file not found: {data_meta_info_path}")
|
| 70 |
+
|
| 71 |
+
with open(config_path, "r") as file:
|
| 72 |
+
cfg_dict = yaml.safe_load(file)
|
| 73 |
+
|
| 74 |
+
cfg = dict_to_namespace(cfg_dict)
|
| 75 |
+
|
| 76 |
+
data_info = DataInfos(data_meta_info_path)
|
| 77 |
+
return cfg, data_info
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
#### graph utils
|
| 81 |
+
class PlaceHolder:
|
| 82 |
+
def __init__(self, X, E, y):
|
| 83 |
+
self.X = X
|
| 84 |
+
self.E = E
|
| 85 |
+
self.y = y
|
| 86 |
+
|
| 87 |
+
def type_as(self, x: torch.Tensor, categorical: bool = False):
|
| 88 |
+
"""Changes the device and dtype of X, E, y."""
|
| 89 |
+
self.X = self.X.type_as(x)
|
| 90 |
+
self.E = self.E.type_as(x)
|
| 91 |
+
if categorical:
|
| 92 |
+
self.y = self.y.type_as(x)
|
| 93 |
+
return self
|
| 94 |
+
|
| 95 |
+
def mask(self, node_mask, collapse=False):
|
| 96 |
+
x_mask = node_mask.unsqueeze(-1) # bs, n, 1
|
| 97 |
+
e_mask1 = x_mask.unsqueeze(2) # bs, n, 1, 1
|
| 98 |
+
e_mask2 = x_mask.unsqueeze(1) # bs, 1, n, 1
|
| 99 |
+
|
| 100 |
+
if collapse:
|
| 101 |
+
self.X = torch.argmax(self.X, dim=-1)
|
| 102 |
+
self.E = torch.argmax(self.E, dim=-1)
|
| 103 |
+
|
| 104 |
+
self.X[node_mask == 0] = -1
|
| 105 |
+
self.E[(e_mask1 * e_mask2).squeeze(-1) == 0] = -1
|
| 106 |
+
else:
|
| 107 |
+
self.X = self.X * x_mask
|
| 108 |
+
self.E = self.E * e_mask1 * e_mask2
|
| 109 |
+
assert torch.allclose(self.E, torch.transpose(self.E, 1, 2))
|
| 110 |
+
return self
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def to_dense(x, edge_index, edge_attr, batch, max_num_nodes=None):
|
| 114 |
+
X, node_mask = to_dense_batch(x=x, batch=batch, max_num_nodes=max_num_nodes)
|
| 115 |
+
# node_mask = node_mask.float()
|
| 116 |
+
edge_index, edge_attr = remove_self_loops(edge_index, edge_attr)
|
| 117 |
+
if max_num_nodes is None:
|
| 118 |
+
max_num_nodes = X.size(1)
|
| 119 |
+
E = to_dense_adj(
|
| 120 |
+
edge_index=edge_index,
|
| 121 |
+
batch=batch,
|
| 122 |
+
edge_attr=edge_attr,
|
| 123 |
+
max_num_nodes=max_num_nodes,
|
| 124 |
+
)
|
| 125 |
+
E = encode_no_edge(E)
|
| 126 |
+
return PlaceHolder(X=X, E=E, y=None), node_mask
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def encode_no_edge(E):
|
| 130 |
+
assert len(E.shape) == 4
|
| 131 |
+
if E.shape[-1] == 0:
|
| 132 |
+
return E
|
| 133 |
+
no_edge = torch.sum(E, dim=3) == 0
|
| 134 |
+
first_elt = E[:, :, :, 0]
|
| 135 |
+
first_elt[no_edge] = 1
|
| 136 |
+
E[:, :, :, 0] = first_elt
|
| 137 |
+
diag = (
|
| 138 |
+
torch.eye(E.shape[1], dtype=torch.bool).unsqueeze(0).expand(E.shape[0], -1, -1)
|
| 139 |
+
)
|
| 140 |
+
E[diag] = 0
|
| 141 |
+
return E
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
#### diffusion utils
|
| 145 |
+
class DistributionNodes:
|
| 146 |
+
def __init__(self, histogram):
|
| 147 |
+
"""Compute the distribution of the number of nodes in the dataset, and sample from this distribution.
|
| 148 |
+
historgram: dict. The keys are num_nodes, the values are counts
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
if type(histogram) == dict:
|
| 152 |
+
max_n_nodes = max(histogram.keys())
|
| 153 |
+
prob = torch.zeros(max_n_nodes + 1)
|
| 154 |
+
for num_nodes, count in histogram.items():
|
| 155 |
+
prob[num_nodes] = count
|
| 156 |
+
else:
|
| 157 |
+
prob = histogram
|
| 158 |
+
|
| 159 |
+
self.prob = prob / prob.sum()
|
| 160 |
+
self.m = torch.distributions.Categorical(prob)
|
| 161 |
+
|
| 162 |
+
def sample_n(self, n_samples, device):
|
| 163 |
+
idx = self.m.sample((n_samples,))
|
| 164 |
+
return idx.to(device)
|
| 165 |
+
|
| 166 |
+
def log_prob(self, batch_n_nodes):
|
| 167 |
+
assert len(batch_n_nodes.size()) == 1
|
| 168 |
+
p = self.prob.to(batch_n_nodes.device)
|
| 169 |
+
|
| 170 |
+
probas = p[batch_n_nodes]
|
| 171 |
+
log_p = torch.log(probas + 1e-30)
|
| 172 |
+
return log_p
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
class PredefinedNoiseScheduleDiscrete(torch.nn.Module):
|
| 176 |
+
def __init__(self, noise_schedule, timesteps):
|
| 177 |
+
super(PredefinedNoiseScheduleDiscrete, self).__init__()
|
| 178 |
+
self.timesteps = timesteps
|
| 179 |
+
|
| 180 |
+
betas = cosine_beta_schedule_discrete(timesteps)
|
| 181 |
+
self.register_buffer("betas", torch.from_numpy(betas).float())
|
| 182 |
+
|
| 183 |
+
# 0.9999
|
| 184 |
+
self.alphas = 1 - torch.clamp(self.betas, min=0, max=1)
|
| 185 |
+
|
| 186 |
+
log_alpha = torch.log(self.alphas)
|
| 187 |
+
log_alpha_bar = torch.cumsum(log_alpha, dim=0)
|
| 188 |
+
self.alphas_bar = torch.exp(log_alpha_bar)
|
| 189 |
+
|
| 190 |
+
def forward(self, t_normalized=None, t_int=None):
|
| 191 |
+
assert int(t_normalized is None) + int(t_int is None) == 1
|
| 192 |
+
if t_int is None:
|
| 193 |
+
t_int = torch.round(t_normalized * self.timesteps)
|
| 194 |
+
self.betas = self.betas.type_as(t_int)
|
| 195 |
+
return self.betas[t_int.long()]
|
| 196 |
+
|
| 197 |
+
def get_alpha_bar(self, t_normalized=None, t_int=None):
|
| 198 |
+
assert int(t_normalized is None) + int(t_int is None) == 1
|
| 199 |
+
if t_int is None:
|
| 200 |
+
t_int = torch.round(t_normalized * self.timesteps)
|
| 201 |
+
self.alphas_bar = self.alphas_bar.type_as(t_int)
|
| 202 |
+
return self.alphas_bar[t_int.long()]
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class DiscreteUniformTransition:
|
| 206 |
+
def __init__(self, x_classes: int, e_classes: int, y_classes: int):
|
| 207 |
+
self.X_classes = x_classes
|
| 208 |
+
self.E_classes = e_classes
|
| 209 |
+
self.y_classes = y_classes
|
| 210 |
+
self.u_x = torch.ones(1, self.X_classes, self.X_classes)
|
| 211 |
+
if self.X_classes > 0:
|
| 212 |
+
self.u_x = self.u_x / self.X_classes
|
| 213 |
+
|
| 214 |
+
self.u_e = torch.ones(1, self.E_classes, self.E_classes)
|
| 215 |
+
if self.E_classes > 0:
|
| 216 |
+
self.u_e = self.u_e / self.E_classes
|
| 217 |
+
|
| 218 |
+
self.u_y = torch.ones(1, self.y_classes, self.y_classes)
|
| 219 |
+
if self.y_classes > 0:
|
| 220 |
+
self.u_y = self.u_y / self.y_classes
|
| 221 |
+
|
| 222 |
+
def get_Qt(self, beta_t, device, X=None, flatten_e=None):
|
| 223 |
+
"""Returns one-step transition matrices for X and E, from step t - 1 to step t.
|
| 224 |
+
Qt = (1 - beta_t) * I + beta_t / K
|
| 225 |
+
|
| 226 |
+
beta_t: (bs) noise level between 0 and 1
|
| 227 |
+
returns: qx (bs, dx, dx), qe (bs, de, de), qy (bs, dy, dy).
|
| 228 |
+
"""
|
| 229 |
+
beta_t = beta_t.unsqueeze(1)
|
| 230 |
+
beta_t = beta_t.to(device)
|
| 231 |
+
self.u_x = self.u_x.to(device)
|
| 232 |
+
self.u_e = self.u_e.to(device)
|
| 233 |
+
self.u_y = self.u_y.to(device)
|
| 234 |
+
|
| 235 |
+
q_x = beta_t * self.u_x + (1 - beta_t) * torch.eye(
|
| 236 |
+
self.X_classes, device=device
|
| 237 |
+
).unsqueeze(0)
|
| 238 |
+
q_e = beta_t * self.u_e + (1 - beta_t) * torch.eye(
|
| 239 |
+
self.E_classes, device=device
|
| 240 |
+
).unsqueeze(0)
|
| 241 |
+
q_y = beta_t * self.u_y + (1 - beta_t) * torch.eye(
|
| 242 |
+
self.y_classes, device=device
|
| 243 |
+
).unsqueeze(0)
|
| 244 |
+
|
| 245 |
+
return PlaceHolder(X=q_x, E=q_e, y=q_y)
|
| 246 |
+
|
| 247 |
+
def get_Qt_bar(self, alpha_bar_t, device, X=None, flatten_e=None):
|
| 248 |
+
"""Returns t-step transition matrices for X and E, from step 0 to step t.
|
| 249 |
+
Qt = prod(1 - beta_t) * I + (1 - prod(1 - beta_t)) / K
|
| 250 |
+
|
| 251 |
+
alpha_bar_t: (bs) Product of the (1 - beta_t) for each time step from 0 to t.
|
| 252 |
+
returns: qx (bs, dx, dx), qe (bs, de, de), qy (bs, dy, dy).
|
| 253 |
+
"""
|
| 254 |
+
alpha_bar_t = alpha_bar_t.unsqueeze(1)
|
| 255 |
+
alpha_bar_t = alpha_bar_t.to(device)
|
| 256 |
+
self.u_x = self.u_x.to(device)
|
| 257 |
+
self.u_e = self.u_e.to(device)
|
| 258 |
+
self.u_y = self.u_y.to(device)
|
| 259 |
+
|
| 260 |
+
q_x = (
|
| 261 |
+
alpha_bar_t * torch.eye(self.X_classes, device=device).unsqueeze(0)
|
| 262 |
+
+ (1 - alpha_bar_t) * self.u_x
|
| 263 |
+
)
|
| 264 |
+
q_e = (
|
| 265 |
+
alpha_bar_t * torch.eye(self.E_classes, device=device).unsqueeze(0)
|
| 266 |
+
+ (1 - alpha_bar_t) * self.u_e
|
| 267 |
+
)
|
| 268 |
+
q_y = (
|
| 269 |
+
alpha_bar_t * torch.eye(self.y_classes, device=device).unsqueeze(0)
|
| 270 |
+
+ (1 - alpha_bar_t) * self.u_y
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
return PlaceHolder(X=q_x, E=q_e, y=q_y)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class MarginalTransition:
|
| 277 |
+
def __init__(
|
| 278 |
+
self, x_marginals, e_marginals, xe_conditions, ex_conditions, y_classes, n_nodes
|
| 279 |
+
):
|
| 280 |
+
self.X_classes = len(x_marginals)
|
| 281 |
+
self.E_classes = len(e_marginals)
|
| 282 |
+
self.y_classes = y_classes
|
| 283 |
+
self.x_marginals = x_marginals # Dx
|
| 284 |
+
self.e_marginals = e_marginals # Dx, De
|
| 285 |
+
self.xe_conditions = xe_conditions
|
| 286 |
+
# print('e_marginals.dtype', e_marginals.dtype)
|
| 287 |
+
# print('x_marginals.dtype', x_marginals.dtype)
|
| 288 |
+
# print('xe_conditions.dtype', xe_conditions.dtype)
|
| 289 |
+
|
| 290 |
+
self.u_x = (
|
| 291 |
+
x_marginals.unsqueeze(0).expand(self.X_classes, -1).unsqueeze(0)
|
| 292 |
+
) # 1, Dx, Dx
|
| 293 |
+
self.u_e = (
|
| 294 |
+
e_marginals.unsqueeze(0).expand(self.E_classes, -1).unsqueeze(0)
|
| 295 |
+
) # 1, De, De
|
| 296 |
+
self.u_xe = xe_conditions.unsqueeze(0) # 1, Dx, De
|
| 297 |
+
self.u_ex = ex_conditions.unsqueeze(0) # 1, De, Dx
|
| 298 |
+
self.u = self.get_union_transition(
|
| 299 |
+
self.u_x, self.u_e, self.u_xe, self.u_ex, n_nodes
|
| 300 |
+
) # 1, Dx + n*De, Dx + n*De
|
| 301 |
+
|
| 302 |
+
def get_union_transition(self, u_x, u_e, u_xe, u_ex, n_nodes):
|
| 303 |
+
u_e = u_e.repeat(1, n_nodes, n_nodes) # (1, n*de, n*de)
|
| 304 |
+
u_xe = u_xe.repeat(1, 1, n_nodes) # (1, dx, n*de)
|
| 305 |
+
u_ex = u_ex.repeat(1, n_nodes, 1) # (1, n*de, dx)
|
| 306 |
+
u0 = torch.cat([u_x, u_xe], dim=2) # (1, dx, dx + n*de)
|
| 307 |
+
u1 = torch.cat([u_ex, u_e], dim=2) # (1, n*de, dx + n*de)
|
| 308 |
+
u = torch.cat([u0, u1], dim=1) # (1, dx + n*de, dx + n*de)
|
| 309 |
+
return u
|
| 310 |
+
|
| 311 |
+
def index_edge_margin(self, X, q_e, n_bond=5):
|
| 312 |
+
# q_e: (bs, dx, de) --> (bs, n, de)
|
| 313 |
+
bs, n, n_atom = X.shape
|
| 314 |
+
node_indices = X.argmax(-1) # (bs, n)
|
| 315 |
+
ind = node_indices[:, :, None].expand(bs, n, n_bond)
|
| 316 |
+
q_e = torch.gather(q_e, 1, ind)
|
| 317 |
+
return q_e
|
| 318 |
+
|
| 319 |
+
def get_Qt(self, beta_t, device):
|
| 320 |
+
"""Returns one-step transition matrices for X and E, from step t - 1 to step t.
|
| 321 |
+
Qt = (1 - beta_t) * I + beta_t / K
|
| 322 |
+
beta_t: (bs)
|
| 323 |
+
returns: q (bs, d0, d0)
|
| 324 |
+
"""
|
| 325 |
+
bs = beta_t.size(0)
|
| 326 |
+
d0 = self.u.size(-1)
|
| 327 |
+
self.u = self.u.to(device)
|
| 328 |
+
u = self.u.expand(bs, d0, d0)
|
| 329 |
+
|
| 330 |
+
beta_t = beta_t.to(device)
|
| 331 |
+
beta_t = beta_t.view(bs, 1, 1)
|
| 332 |
+
q = beta_t * u + (1 - beta_t) * torch.eye(d0, device=device, dtype=self.u.dtype).unsqueeze(0)
|
| 333 |
+
|
| 334 |
+
return PlaceHolder(X=q, E=None, y=None)
|
| 335 |
+
|
| 336 |
+
def get_Qt_bar(self, alpha_bar_t, device):
|
| 337 |
+
"""Returns t-step transition matrices for X and E, from step 0 to step t.
|
| 338 |
+
Qt = prod(1 - beta_t) * I + (1 - prod(1 - beta_t)) * K
|
| 339 |
+
alpha_bar_t: (bs, 1) roduct of the (1 - beta_t) for each time step from 0 to t.
|
| 340 |
+
returns: q (bs, d0, d0)
|
| 341 |
+
"""
|
| 342 |
+
bs = alpha_bar_t.size(0)
|
| 343 |
+
d0 = self.u.size(-1)
|
| 344 |
+
alpha_bar_t = alpha_bar_t.to(device)
|
| 345 |
+
alpha_bar_t = alpha_bar_t.view(bs, 1, 1)
|
| 346 |
+
self.u = self.u.to(device)
|
| 347 |
+
q = (
|
| 348 |
+
alpha_bar_t * torch.eye(d0, device=device, dtype=self.u.dtype).unsqueeze(0)
|
| 349 |
+
+ (1 - alpha_bar_t) * self.u
|
| 350 |
+
)
|
| 351 |
+
|
| 352 |
+
return PlaceHolder(X=q, E=None, y=None)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def sum_except_batch(x):
|
| 356 |
+
return x.reshape(x.size(0), -1).sum(dim=-1)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def assert_correctly_masked(variable, node_mask):
|
| 360 |
+
assert (
|
| 361 |
+
variable * (1 - node_mask.long())
|
| 362 |
+
).abs().max().item() < 1e-4, "Variables not masked properly."
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def cosine_beta_schedule_discrete(timesteps, s=0.008):
|
| 366 |
+
"""Cosine schedule as proposed in https://openreview.net/forum?id=-NEXDKk8gZ."""
|
| 367 |
+
steps = timesteps + 2
|
| 368 |
+
x = np.linspace(0, steps, steps)
|
| 369 |
+
|
| 370 |
+
alphas_cumprod = np.cos(0.5 * np.pi * ((x / steps) + s) / (1 + s)) ** 2
|
| 371 |
+
alphas_cumprod = alphas_cumprod / alphas_cumprod[0]
|
| 372 |
+
alphas = alphas_cumprod[1:] / alphas_cumprod[:-1]
|
| 373 |
+
betas = 1 - alphas
|
| 374 |
+
return betas.squeeze()
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def sample_discrete_features(probX, probE, node_mask, step=None, add_nose=True):
|
| 378 |
+
"""Sample features from multinomial distribution with given probabilities (probX, probE, proby)
|
| 379 |
+
:param probX: bs, n, dx_out node features
|
| 380 |
+
:param probE: bs, n, n, de_out edge features
|
| 381 |
+
:param proby: bs, dy_out global features.
|
| 382 |
+
"""
|
| 383 |
+
bs, n, _ = probX.shape
|
| 384 |
+
|
| 385 |
+
# Noise X
|
| 386 |
+
# The masked rows should define probability distributions as well
|
| 387 |
+
probX[~node_mask] = 1 / probX.shape[-1]
|
| 388 |
+
|
| 389 |
+
# Flatten the probability tensor to sample with multinomial
|
| 390 |
+
probX = probX.reshape(bs * n, -1) # (bs * n, dx_out)
|
| 391 |
+
|
| 392 |
+
# Sample X
|
| 393 |
+
probX = probX.clamp_min(1e-5)
|
| 394 |
+
probX = probX / probX.sum(dim=-1, keepdim=True)
|
| 395 |
+
X_t = probX.multinomial(1) # (bs * n, 1)
|
| 396 |
+
X_t = X_t.reshape(bs, n) # (bs, n)
|
| 397 |
+
|
| 398 |
+
# Noise E
|
| 399 |
+
# The masked rows should define probability distributions as well
|
| 400 |
+
inverse_edge_mask = ~(node_mask.unsqueeze(1) * node_mask.unsqueeze(2))
|
| 401 |
+
diag_mask = torch.eye(n).unsqueeze(0).expand(bs, -1, -1)
|
| 402 |
+
|
| 403 |
+
probE[inverse_edge_mask] = 1 / probE.shape[-1]
|
| 404 |
+
probE[diag_mask.bool()] = 1 / probE.shape[-1]
|
| 405 |
+
probE = probE.reshape(bs * n * n, -1) # (bs * n * n, de_out)
|
| 406 |
+
probE = probE.clamp_min(1e-5)
|
| 407 |
+
probE = probE / probE.sum(dim=-1, keepdim=True)
|
| 408 |
+
|
| 409 |
+
# Sample E
|
| 410 |
+
E_t = probE.multinomial(1).reshape(bs, n, n) # (bs, n, n)
|
| 411 |
+
E_t = torch.triu(E_t, diagonal=1)
|
| 412 |
+
E_t = E_t + torch.transpose(E_t, 1, 2)
|
| 413 |
+
|
| 414 |
+
return PlaceHolder(X=X_t, E=E_t, y=torch.zeros(bs, 0).type_as(X_t))
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def mask_distributions(true_X, true_E, pred_X, pred_E, node_mask):
|
| 418 |
+
# Add a small value everywhere to avoid nans
|
| 419 |
+
pred_X = pred_X.clamp_min(1e-5)
|
| 420 |
+
pred_X = pred_X / torch.sum(pred_X, dim=-1, keepdim=True)
|
| 421 |
+
|
| 422 |
+
pred_E = pred_E.clamp_min(1e-5)
|
| 423 |
+
pred_E = pred_E / torch.sum(pred_E, dim=-1, keepdim=True)
|
| 424 |
+
|
| 425 |
+
# Set masked rows to arbitrary distributions, so it doesn't contribute to loss
|
| 426 |
+
row_X = torch.ones(true_X.size(-1), dtype=true_X.dtype, device=true_X.device)
|
| 427 |
+
row_E = torch.zeros(
|
| 428 |
+
true_E.size(-1), dtype=true_E.dtype, device=true_E.device
|
| 429 |
+
).clamp_min(1e-5)
|
| 430 |
+
row_E[0] = 1.0
|
| 431 |
+
|
| 432 |
+
diag_mask = ~torch.eye(
|
| 433 |
+
node_mask.size(1), device=node_mask.device, dtype=torch.bool
|
| 434 |
+
).unsqueeze(0)
|
| 435 |
+
true_X[~node_mask] = row_X
|
| 436 |
+
true_E[~(node_mask.unsqueeze(1) * node_mask.unsqueeze(2) * diag_mask), :] = row_E
|
| 437 |
+
pred_X[~node_mask] = row_X.type_as(pred_X)
|
| 438 |
+
pred_E[~(node_mask.unsqueeze(1) * node_mask.unsqueeze(2) * diag_mask), :] = (
|
| 439 |
+
row_E.type_as(pred_E)
|
| 440 |
+
)
|
| 441 |
+
|
| 442 |
+
return true_X, true_E, pred_X, pred_E
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def forward_diffusion(X, X_t, Qt, Qsb, Qtb, X_dim):
|
| 446 |
+
bs, n, d = X.shape
|
| 447 |
+
|
| 448 |
+
Qt_X_T = torch.transpose(Qt.X, -2, -1) # (bs, d, d)
|
| 449 |
+
left_term = X_t @ Qt_X_T # (bs, N, d)
|
| 450 |
+
right_term = X @ Qsb.X # (bs, N, d)
|
| 451 |
+
|
| 452 |
+
numerator = left_term * right_term # (bs, N, d)
|
| 453 |
+
denominator = X @ Qtb.X # (bs, N, d) @ (bs, d, d) = (bs, N, d)
|
| 454 |
+
denominator = denominator * X_t
|
| 455 |
+
|
| 456 |
+
num_X = numerator[:, :, :X_dim]
|
| 457 |
+
num_E = numerator[:, :, X_dim:].reshape(bs, n * n, -1)
|
| 458 |
+
|
| 459 |
+
deno_X = denominator[:, :, :X_dim]
|
| 460 |
+
deno_E = denominator[:, :, X_dim:].reshape(bs, n * n, -1)
|
| 461 |
+
|
| 462 |
+
denominator = denominator.unsqueeze(-1) # (bs, N, 1)
|
| 463 |
+
|
| 464 |
+
deno_X = deno_X.sum(dim=-1, keepdim=True)
|
| 465 |
+
deno_E = deno_E.sum(dim=-1, keepdim=True)
|
| 466 |
+
|
| 467 |
+
deno_X[deno_X == 0.0] = 1
|
| 468 |
+
deno_E[deno_E == 0.0] = 1
|
| 469 |
+
prob_X = num_X / deno_X
|
| 470 |
+
prob_E = num_E / deno_E
|
| 471 |
+
|
| 472 |
+
prob_E = prob_E / prob_E.sum(dim=-1, keepdim=True)
|
| 473 |
+
prob_X = prob_X / prob_X.sum(dim=-1, keepdim=True)
|
| 474 |
+
return PlaceHolder(X=prob_X, E=prob_E, y=None)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def reverse_diffusion(predX_0, X_t, Qt, Qsb, Qtb):
|
| 478 |
+
"""M: X or E
|
| 479 |
+
Compute xt @ Qt.T * x0 @ Qsb / x0 @ Qtb @ xt.T for each possible value of x0
|
| 480 |
+
X_t: bs, n, dt or bs, n, n, dt
|
| 481 |
+
Qt: bs, d_t-1, dt
|
| 482 |
+
Qsb: bs, d0, d_t-1
|
| 483 |
+
Qtb: bs, d0, dt.
|
| 484 |
+
"""
|
| 485 |
+
Qt_T = Qt.transpose(-1, -2) # bs, N, dt
|
| 486 |
+
assert Qt.dim() == 3
|
| 487 |
+
left_term = X_t @ Qt_T # bs, N, d_t-1
|
| 488 |
+
right_term = predX_0 @ Qsb
|
| 489 |
+
numerator = left_term * right_term # bs, N, d_t-1
|
| 490 |
+
|
| 491 |
+
denominator = Qtb @ X_t.transpose(-1, -2) # bs, d0, N
|
| 492 |
+
denominator = denominator.transpose(-1, -2) # bs, N, d0
|
| 493 |
+
return numerator / denominator.clamp_min(1e-5)
|
| 494 |
+
|
| 495 |
+
def reverse_tensor(x):
|
| 496 |
+
return x[torch.arange(x.size(0) - 1, -1, -1)]
|
| 497 |
+
|
| 498 |
+
def sample_discrete_feature_noise(limit_dist, node_mask):
|
| 499 |
+
"""Sample from the limit distribution of the diffusion process"""
|
| 500 |
+
bs, n_max = node_mask.shape
|
| 501 |
+
x_limit = limit_dist.X[None, None, :].expand(bs, n_max, -1)
|
| 502 |
+
x_limit = x_limit.to(node_mask.device)
|
| 503 |
+
|
| 504 |
+
U_X = x_limit.flatten(end_dim=-2).multinomial(1).reshape(bs, n_max)
|
| 505 |
+
U_X = F.one_hot(U_X.long(), num_classes=x_limit.shape[-1]).type_as(x_limit)
|
| 506 |
+
|
| 507 |
+
e_limit = limit_dist.E[None, None, None, :].expand(bs, n_max, n_max, -1)
|
| 508 |
+
U_E = e_limit.flatten(end_dim=-2).multinomial(1).reshape(bs, n_max, n_max)
|
| 509 |
+
U_E = F.one_hot(U_E.long(), num_classes=e_limit.shape[-1]).type_as(x_limit)
|
| 510 |
+
|
| 511 |
+
U_X = U_X.to(node_mask.device)
|
| 512 |
+
U_E = U_E.to(node_mask.device)
|
| 513 |
+
|
| 514 |
+
# Get upper triangular part of edge noise, without main diagonal
|
| 515 |
+
upper_triangular_mask = torch.zeros_like(U_E)
|
| 516 |
+
indices = torch.triu_indices(row=U_E.size(1), col=U_E.size(2), offset=1)
|
| 517 |
+
upper_triangular_mask[:, indices[0], indices[1], :] = 1
|
| 518 |
+
|
| 519 |
+
U_E = U_E * upper_triangular_mask
|
| 520 |
+
U_E = U_E + torch.transpose(U_E, 1, 2)
|
| 521 |
+
|
| 522 |
+
assert (U_E == torch.transpose(U_E, 1, 2)).all()
|
| 523 |
+
return PlaceHolder(X=U_X, E=U_E, y=None).mask(node_mask)
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def index_QE(X, q_e, n_bond=5):
|
| 527 |
+
bs, n, n_atom = X.shape
|
| 528 |
+
node_indices = X.argmax(-1) # (bs, n)
|
| 529 |
+
|
| 530 |
+
exp_ind1 = node_indices[:, :, None, None, None].expand(
|
| 531 |
+
bs, n, n_atom, n_bond, n_bond
|
| 532 |
+
)
|
| 533 |
+
exp_ind2 = node_indices[:, :, None, None, None].expand(bs, n, n, n_bond, n_bond)
|
| 534 |
+
|
| 535 |
+
q_e = torch.gather(q_e, 1, exp_ind1)
|
| 536 |
+
q_e = torch.gather(q_e, 2, exp_ind2) # (bs, n, n, n_bond, n_bond)
|
| 537 |
+
|
| 538 |
+
node_mask = X.sum(-1) != 0
|
| 539 |
+
no_edge = (~node_mask)[:, :, None] & (~node_mask)[:, None, :]
|
| 540 |
+
q_e[no_edge] = torch.tensor([1, 0, 0, 0, 0]).type_as(q_e)
|
| 541 |
+
|
| 542 |
+
return q_e
|