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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
# Copyright (c) 2025 Max Planck Institute for Polymer Research
# Copyright (c) 2024 HITS gGmbH
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

import functools as fn
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F

import gafl.models.utils as mu
from gafl.data import utils as du

from gafl.models.ipa_pytorch import Linear
from gafl.models.utils import get_index_embedding, get_time_embedding, get_length_embedding

class MLP(nn.Module):
    def __init__(self, c1, c2, num_layers=2, use_layer_norm=True, dropout=0) -> None:
        super(MLP, self).__init__()

        self.layers = []
        for _ in range(num_layers-1):
            self.layers.append(Linear(c1, c1, init="relu"))
            self.layers.append(nn.ReLU())
            self.layers.append(nn.Dropout(dropout))
        self.layers.append(Linear(c1, c1, init="final"))
        self.layers = nn.Sequential(*self.layers)

        if c1 != c2:
            self.final_layer = nn.Linear(c1, c2)
        else:
            self.final_layer = nn.Identity()
        
        self.use_layer_norm = use_layer_norm
        if use_layer_norm:
            self.layer_norm = nn.LayerNorm(c2)

    def forward(self, x):
        x = self.layers(x) + x
        x = self.final_layer(x)
        if self.use_layer_norm:
            x = self.layer_norm(x)
        return x


def embed_direction(trans, rots, dist_cutoff=np.inf):
    """
    Compute the position of the other residues from the
    perspective of each residue.
    
    Args:
        trans: [B, N, 3] translation vectors
        rots: [B, N, 3, 3] rotation matrices
    Returns:
        [B, N, N, 3] relative positions from each residue to each other residue
    """

    B, N, _ = trans.shape
    device = trans.device

    frames = du.create_rigid(rots, trans)
    rel_pos = frames[:,:,None].invert_apply(trans[:,None,:])
    # rel_pos.shape = [B, N, N, 3]
    distances = torch.linalg.norm(rel_pos, dim=-1)
    rel_pos = rel_pos / (distances[...,None] + 1e-6)
    indices = torch.arange(N, device=device)
    rel_pos[:, indices, indices, :] = torch.zeros(3, device=device)
    if dist_cutoff < np.inf:
        # Set all direction vectors to zero if the distance is greater than dist_cutoff
        mask = distances > dist_cutoff
        rel_pos[mask,:] = 0

    return rel_pos




class Embedder(nn.Module):
    def __init__(self, model_conf, latent_cfg=None):
        super(Embedder, self).__init__()
        self.model_conf = model_conf
        self.embed_aatype = model_conf.embed.embed_aatype
        self.latent_enabled = bool(latent_cfg is not None and getattr(latent_cfg, "enable", False))
        self.inject_embedder = bool(
            self.latent_enabled and getattr(latent_cfg, "inject_embedder", True)
        )
        self.track_condition_debug = bool(
            self.latent_enabled and getattr(latent_cfg, "track_condition_debug", False)
        )

        if "time_embed_dim" in model_conf.embed:
            self.time_embed_dim = model_conf.embed.time_embed_dim
        else:
            self.time_embed_dim = 0

        if "embed_distogram" in model_conf.embed:
            self.embed_distogram = model_conf.embed.embed_distogram
        else:
            self.embed_distogram = True

        if "embed_self_conditioning" in model_conf.embed:
            self.embed_self_conditioning = model_conf.embed.embed_self_conditioning
        else:
            self.embed_self_conditioning = True


        length_embed_dim = model_conf.embed.length_embed_dim

        node_dim_in = self.time_embed_dim + length_embed_dim

        edge_dim_in = 2 * self.time_embed_dim
        edge_dim_in += 2 * model_conf.node_embed_size
        edge_dim_in += self.model_conf.embed.num_bins_distance
        if self.embed_distogram:
            edge_dim_in += self.model_conf.embed.num_bins_distance
        if self.embed_self_conditioning:
            edge_dim_in += self.model_conf.embed.num_bins_distance 

        self.embed_direction = model_conf.embed.embed_direction
        if self.embed_direction:
            if hasattr(model_conf.embed, "embed_direction_cutoff") and model_conf.embed.embed_direction_cutoff is not None:
                self.embed_direction_cutoff = model_conf.embed.embed_direction_cutoff
            else:
                self.embed_direction_cutoff = np.inf
            edge_dim_in += 3

        # positional encoding
        # if model_conf.embed.index_embed_dim > 0:
        if hasattr(model_conf.embed, "index_embed_type"):
            self.index_embed_type = model_conf.embed.index_embed_type
            self.index_embed_dim = model_conf.embed.index_embed_dim
        else:
            self.index_embed_dim = model_conf.embed.index_embed_dim
            self.index_embed_type = None if self.index_embed_dim == 0 else "full"

        if self.index_embed_type is None or self.index_embed_type == "none":
            self.index_embed_type = None
        elif self.index_embed_type == "full":
            assert self.index_embed_dim > 0, "index_embed_dim must be > 0 if index_embed_type is 'full'."
            node_dim_in += self.index_embed_dim
            edge_dim_in += self.index_embed_dim
            self.linear_relpos = nn.Linear(
                self.index_embed_dim, self.index_embed_dim
            )
        elif self.index_embed_type == "neighbor":
            edge_dim_in += 1
        else:
            raise ValueError("index_embed_type must be None/\"none\", 'full' or 'neighbor'.")


        if self.embed_aatype:
            self.aatype_embedding = nn.Linear(21, model_conf.embed.aatype_embed_dim)
            node_dim_in += model_conf.embed.aatype_embed_dim

        if self.inject_embedder:
            self.latent_dim = int(getattr(latent_cfg, "dim", 16))
            self.num_modes = int(getattr(latent_cfg, "num_modes", self.latent_dim))
            self.node_cond_dim = int(getattr(latent_cfg, "node_cond_dim", self.num_modes))
            self.edge_cond_dim = int(getattr(latent_cfg, "edge_cond_dim", self.num_modes))
            self.z_node_adapter = nn.Sequential(
                nn.Linear(self.node_cond_dim, model_conf.node_embed_size),
                nn.ReLU(),
                nn.Linear(model_conf.node_embed_size, model_conf.node_embed_size),
            )
            self.z_edge_adapter = nn.Sequential(
                nn.Linear(self.edge_cond_dim, model_conf.edge_embed_size),
                nn.ReLU(),
                nn.Linear(model_conf.edge_embed_size, model_conf.edge_embed_size),
            )
            self.disp_node_adapter = nn.Sequential(
                nn.Linear(3, model_conf.node_embed_size),
                nn.ReLU(),
                nn.Linear(model_conf.node_embed_size, model_conf.node_embed_size),
            )
            self.disp_edge_adapter = nn.Sequential(
                nn.Linear(1, model_conf.edge_embed_size),
                nn.ReLU(),
                nn.Linear(model_conf.edge_embed_size, model_conf.edge_embed_size),
            )
            nn.init.zeros_(self.z_node_adapter[-1].weight)
            nn.init.zeros_(self.z_node_adapter[-1].bias)
            nn.init.zeros_(self.z_edge_adapter[-1].weight)
            nn.init.zeros_(self.z_edge_adapter[-1].bias)
            nn.init.zeros_(self.disp_node_adapter[-1].weight)
            nn.init.zeros_(self.disp_node_adapter[-1].bias)
            nn.init.zeros_(self.disp_edge_adapter[-1].weight)
            nn.init.zeros_(self.disp_edge_adapter[-1].bias)
        else:
            self.latent_dim = 0
            self.num_modes = 0
            self.node_cond_dim = 0
            self.edge_cond_dim = 0
            self.z_node_adapter = None
            self.z_edge_adapter = None
            self.disp_node_adapter = None
            self.disp_edge_adapter = None

        self.linear_s_p = nn.Linear(model_conf.node_embed_size, model_conf.node_embed_size)

        self.node_embedding = MLP(node_dim_in, model_conf.node_embed_size, num_layers=2)
        self.edge_embedding = MLP(edge_dim_in, model_conf.edge_embed_size, num_layers=2)


        self.timestep_embedder = fn.partial(
            get_time_embedding,
            embedding_dim=self.time_embed_dim,
        )
        self.index_embedder = fn.partial(
            get_index_embedding,
            embed_size=self.model_conf.embed.index_embed_dim,
        )
        self.length_embedder = fn.partial(
            get_length_embedding,
            embed_size=self.model_conf.embed.length_embed_dim,
            max_len=2056
        )

    def prepare_inference_static(self, input_features):
        """Cache O(N^2) features that are constant across ODE timesteps."""
        B, N = input_features["B,N"]
        device = input_features["device"]
        cache = {}

        if self.embed_aatype:
            cache["aatype_embedding"] = self.aatype_embedding(input_features["seq"])

        cache["length_embedding"] = self.length_embedder(
            torch.empty(1, N, device=device)
        ).repeat([B, 1, 1])

        if self.index_embed_type == "full":
            seq_idx = torch.arange(N, device=device).repeat(B, 1)
            cache["index_node_embedding"] = self.index_embedder(seq_idx)
            rel_seq_offset = seq_idx[:, :, None] - seq_idx[:, None, :]
            cache["index_edge_embedding"] = self.linear_relpos(
                self.index_embedder(rel_seq_offset.reshape([B, N**2]))
            )
        elif self.index_embed_type == "neighbor":
            neighbors = (
                torch.diag_embed(torch.ones(N - 1, device=device), offset=1)
                + torch.diag_embed(torch.ones(N - 1, device=device), offset=-1)
            )
            cache["index_edge_embedding"] = (
                neighbors[None].repeat(B, 1, 1).reshape([B, N**2, 1])
            )

        if self.embed_distogram:
            cache["equilibrium_distogram"] = mu.calc_distogram(
                input_features["CA_pos"]["trans_equilibrium"],
                self.model_conf.embed.min_bin_distance,
                self.model_conf.embed.max_bin_distance,
                self.model_conf.embed.num_bins_distance,
            ).reshape([B, N**2, -1])

        if self.embed_direction:
            cache["direction_embedding"] = embed_direction(
                input_features["CA_pos"]["trans_equilibrium"],
                input_features["rotmats_equilibrium"],
                dist_cutoff=self.embed_direction_cutoff,
            ).reshape([B, N**2, -1])

        if self.inject_embedder:
            payload = input_features.get("z")
            if isinstance(payload, dict):
                node_cond = payload.get("node_cond")
                edge_cond = payload.get("edge_cond")
                disp_node_cond = payload.get("disp_node_cond")
                disp_edge_cond = payload.get("disp_edge_cond")
            else:
                node_cond = payload
                edge_cond = payload
                disp_node_cond = None
                disp_edge_cond = None
            if node_cond is None:
                node_cond = torch.zeros(B, N, self.node_cond_dim, device=device)
            if edge_cond is None:
                edge_cond = torch.zeros(B, N, N, self.edge_cond_dim, device=device)
            if disp_node_cond is None:
                disp_node_cond = torch.zeros(B, N, 3, device=device)
            if disp_edge_cond is None:
                disp_edge_cond = torch.zeros(B, N, N, 1, device=device)
            if node_cond.dim() == 2:
                node_cond = node_cond[:, None, :].expand(B, N, -1)
            if edge_cond.dim() == 2:
                edge_cond = edge_cond[:, None, None, :].expand(B, N, N, -1)
            cache["node_condition_embedding"] = (
                self.z_node_adapter(node_cond)
                + self.disp_node_adapter(disp_node_cond)
            )
            cache["edge_condition_embedding"] = (
                self.z_edge_adapter(edge_cond)
                + self.disp_edge_adapter(disp_edge_cond)
            )
        return cache

    def forward(self, input_features):
        """
        Args:
            t:
                [*, ] time step sampled from [0, 1]
            fixed_mask:
                [*, N_res] mask of fixed (motif) residues
            self_conditioning_ca:
                [*, N_res, 3] Ca positions of self-conditioning input
            rigids:
                [*, N_res] Frame object
        Returns:
            [*, N_res, node_dim] initial node features
            [*, N_res, N_res, edge_dim] initial edge features
        """
        B, N = input_features["B,N"]
        device = input_features["device"]
        static = input_features.get("inference_static")
        
        h_0 = []
        z_0 = []

        if self.time_embed_dim > 0:
            t_embed = self.timestep_embedder(input_features["time"][:,0])[:, None, :].repeat(1, N, 1)
            h_0.append(t_embed)
            z_0.append(self._cross_concat(t_embed, B, N))
        
        if self.embed_aatype:
            if static is not None and "aatype_embedding" in static:
                h_0.append(static["aatype_embedding"])
            else:
                h_0.append(self.aatype_embedding(input_features["seq"]))

        if self.inject_embedder:
            z_payload = input_features.get("z", None)
            self._last_z_seen = z_payload is not None
            if isinstance(z_payload, dict):
                node_cond = z_payload.get("node_cond")
                edge_cond = z_payload.get("edge_cond")
                disp_node_cond = z_payload.get("disp_node_cond")
                disp_edge_cond = z_payload.get("disp_edge_cond")
            else:
                node_cond = z_payload
                edge_cond = z_payload
                disp_node_cond = None
                disp_edge_cond = None
            if node_cond is None:
                node_cond = torch.zeros(B, N, self.node_cond_dim, device=device)
            if edge_cond is None:
                edge_cond = torch.zeros(B, N, N, self.edge_cond_dim, device=device)
            if disp_node_cond is None:
                disp_node_cond = torch.zeros(B, N, 3, device=device)
            if disp_edge_cond is None:
                disp_edge_cond = torch.zeros(B, N, N, 1, device=device)
            if node_cond.dim() == 2:
                node_cond = node_cond[:, None, :].expand(B, N, -1)
            if edge_cond.dim() == 2:
                edge_cond = edge_cond[:, None, None, :].expand(B, N, N, -1)
            self._last_z_requires_grad = bool(node_cond.requires_grad or edge_cond.requires_grad or disp_node_cond.requires_grad or disp_edge_cond.requires_grad)
            self._last_z_shape = {
                "node_cond": tuple(node_cond.shape),
                "edge_cond": tuple(edge_cond.shape),
                "disp_node_cond": tuple(disp_node_cond.shape),
                "disp_edge_cond": tuple(disp_edge_cond.shape),
            }
            if self.track_condition_debug:
                self._last_z_abs_mean = float(
                    ((node_cond.detach().float().abs().mean()
                      + edge_cond.detach().float().abs().mean()
                      + disp_node_cond.detach().float().abs().mean()
                      + disp_edge_cond.detach().float().abs().mean()) / 4.0).cpu().item()
                )

        for ca_pos_name, ca_pos in input_features["CA_pos"].items():
            if not self.embed_distogram and ca_pos_name == "trans_equilibrium":
                continue
            if (
                static is not None
                and ca_pos_name == "trans_equilibrium"
                and "equilibrium_distogram" in static
            ):
                z_0.append(static["equilibrium_distogram"])
            else:
                ca_dgram = mu.calc_distogram(
                    ca_pos,
                    self.model_conf.embed.min_bin_distance,
                    self.model_conf.embed.max_bin_distance,
                    self.model_conf.embed.num_bins_distance,
                )
                z_0.append(ca_dgram.reshape([B, N**2, -1]))

        if self.embed_direction:
            if static is not None and "direction_embedding" in static:
                z_0.append(static["direction_embedding"])
            else:
                direction_embedding = embed_direction(
                    input_features["CA_pos"]["trans_equilibrium"],
                    input_features["rotmats_equilibrium"],
                    dist_cutoff=self.embed_direction_cutoff
                )
                z_0.append(direction_embedding.reshape([B, N**2, -1]))


        # TODO: get_length_embedding expects a tensor of shape [...,N]. 
        # It ignores elements and just uses .shape[-1] and device.
        # Don't want to change it, so we just pass in an empty tensor.
        if static is not None and "length_embedding" in static:
            length_embedding = static["length_embedding"]
        else:
            length_embedding = self.length_embedder(
                torch.empty(1, N).to(device=device)
            )
            length_embedding = length_embedding.repeat([B, 1, 1])
        h_0.append(length_embedding)

        if self.index_embed_type is None:
            pass
        elif self.index_embed_type == "full":
            if static is not None and "index_node_embedding" in static:
                h_0.append(static["index_node_embedding"])
                z_0.append(static["index_edge_embedding"])
            else:
                seq_idx = torch.arange(N).repeat(B, 1).to(device=device)
                h_0.append(self.index_embedder(seq_idx))
                rel_seq_offset = seq_idx[:, :, None] - seq_idx[:, None, :]
                rel_seq_offset = rel_seq_offset.reshape([B, N**2])
                z_0.append(self.linear_relpos(self.index_embedder(rel_seq_offset)))
        elif self.index_embed_type == "neighbor":
            if static is not None and "index_edge_embedding" in static:
                z_0.append(static["index_edge_embedding"])
            else:
                neighbors = torch.diag_embed(torch.ones(N-1, device=device), offset=1) + \
                    torch.diag_embed(torch.ones(N-1, device=device), offset=-1)
                neighbors = neighbors[None].repeat(B, 1, 1).reshape([B, N**2])[...,None]
                z_0.append(neighbors)
        else:
            raise ValueError("index_embed_type must be None/'none', 'full' or 'neighbor'.")

        h_0 = torch.cat(h_0, dim=-1)
        h_0 = self.node_embedding(h_0)
        if self.inject_embedder:
            if static is not None and "node_condition_embedding" in static:
                h_0 = h_0 + static["node_condition_embedding"].to(dtype=h_0.dtype)
            else:
                h_0 = h_0 + self.z_node_adapter(node_cond.to(dtype=h_0.dtype))
                h_0 = h_0 + self.disp_node_adapter(disp_node_cond.to(dtype=h_0.dtype))

        z_0.append(self._cross_concat(self.linear_s_p(h_0), B, N))

        z_0 = torch.cat(z_0, dim=-1)
        z_0 = self.edge_embedding(z_0)
        z_0 = z_0.reshape([B, N, N, -1])
        if self.inject_embedder:
            if static is not None and "edge_condition_embedding" in static:
                z_0 = z_0 + static["edge_condition_embedding"].to(dtype=z_0.dtype)
            else:
                z_0 = z_0 + self.z_edge_adapter(edge_cond.to(dtype=z_0.dtype))
                z_0 = z_0 + self.disp_edge_adapter(disp_edge_cond.to(dtype=z_0.dtype))

        return h_0, z_0

    def _cross_concat(self, feats_1d, B, N):
        return torch.cat([
            feats_1d[:, :, None, :].expand(-1, -1, N, -1),
            feats_1d[:, None, :, :].expand(-1, N, -1, -1),
        ], dim=-1).float().reshape([B, N**2, -1])