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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from torch import nn, einsum
|
| 3 |
+
from torch_geometric.nn import MessagePassing
|
| 4 |
+
|
| 5 |
+
# types
|
| 6 |
+
|
| 7 |
+
from typing import Optional, List, Union
|
| 8 |
+
from torch_geometric.typing import OptPairTensor, Adj, Size, OptTensor, Tensor
|
| 9 |
+
|
| 10 |
+
# helper functions
|
| 11 |
+
|
| 12 |
+
def exists(val):
|
| 13 |
+
return val is not None
|
| 14 |
+
|
| 15 |
+
# classes
|
| 16 |
+
|
| 17 |
+
class GVP(nn.Module):
|
| 18 |
+
def __init__(
|
| 19 |
+
self,
|
| 20 |
+
*,
|
| 21 |
+
dim_vectors_in,
|
| 22 |
+
dim_vectors_out,
|
| 23 |
+
dim_feats_in,
|
| 24 |
+
dim_feats_out,
|
| 25 |
+
feats_activation = nn.Sigmoid(),
|
| 26 |
+
vectors_activation = nn.Sigmoid(),
|
| 27 |
+
vector_gating = False
|
| 28 |
+
):
|
| 29 |
+
super().__init__()
|
| 30 |
+
self.dim_vectors_in = dim_vectors_in
|
| 31 |
+
self.dim_feats_in = dim_feats_in
|
| 32 |
+
|
| 33 |
+
self.dim_vectors_out = dim_vectors_out
|
| 34 |
+
dim_h = max(dim_vectors_in, dim_vectors_out)
|
| 35 |
+
|
| 36 |
+
self.Wh = nn.Parameter(torch.randn(dim_vectors_in, dim_h))
|
| 37 |
+
self.Wu = nn.Parameter(torch.randn(dim_h, dim_vectors_out))
|
| 38 |
+
|
| 39 |
+
self.vectors_activation = vectors_activation
|
| 40 |
+
|
| 41 |
+
self.to_feats_out = nn.Sequential(
|
| 42 |
+
nn.Linear(dim_h + dim_feats_in, dim_feats_out),
|
| 43 |
+
feats_activation
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
# branching logic to use old GVP, or GVP with vector gating
|
| 47 |
+
|
| 48 |
+
self.scalar_to_vector_gates = nn.Linear(dim_feats_out, dim_vectors_out) if vector_gating else None
|
| 49 |
+
|
| 50 |
+
def forward(self, data):
|
| 51 |
+
feats, vectors = data
|
| 52 |
+
b, n, _, v, c = *feats.shape, *vectors.shape
|
| 53 |
+
|
| 54 |
+
assert c == 3 and v == self.dim_vectors_in, 'vectors have wrong dimensions'
|
| 55 |
+
assert n == self.dim_feats_in, 'scalar features have wrong dimensions'
|
| 56 |
+
Vh = einsum('b v c, v h -> b h c', vectors, self.Wh)
|
| 57 |
+
Vu = einsum('b h c, h u -> b u c', Vh, self.Wu)
|
| 58 |
+
|
| 59 |
+
sh = torch.norm(Vh, p = 2, dim = -1)
|
| 60 |
+
|
| 61 |
+
s = torch.cat((feats, sh), dim = 1)
|
| 62 |
+
|
| 63 |
+
feats_out = self.to_feats_out(s)
|
| 64 |
+
|
| 65 |
+
if exists(self.scalar_to_vector_gates):
|
| 66 |
+
gating = self.scalar_to_vector_gates(feats_out)
|
| 67 |
+
gating = gating.unsqueeze(dim = -1)
|
| 68 |
+
else:
|
| 69 |
+
gating = torch.norm(Vu, p = 2, dim = -1, keepdim = True)
|
| 70 |
+
|
| 71 |
+
vectors_out = self.vectors_activation(gating) * Vu
|
| 72 |
+
return (feats_out, vectors_out)
|
| 73 |
+
|
| 74 |
+
class GVPDropout(nn.Module):
|
| 75 |
+
""" Separate dropout for scalars and vectors. """
|
| 76 |
+
def __init__(self, rate):
|
| 77 |
+
super().__init__()
|
| 78 |
+
self.vector_dropout = nn.Dropout2d(rate)
|
| 79 |
+
self.feat_dropout = nn.Dropout(rate)
|
| 80 |
+
|
| 81 |
+
def forward(self, feats, vectors):
|
| 82 |
+
return self.feat_dropout(feats), self.vector_dropout(vectors)
|
| 83 |
+
|
| 84 |
+
class GVPLayerNorm(nn.Module):
|
| 85 |
+
""" Normal layer norm for scalars, nontrainable norm for vectors. """
|
| 86 |
+
def __init__(self, feats_h_size, eps = 1e-8):
|
| 87 |
+
super().__init__()
|
| 88 |
+
self.eps = eps
|
| 89 |
+
self.feat_norm = nn.LayerNorm(feats_h_size)
|
| 90 |
+
|
| 91 |
+
def forward(self, feats, vectors):
|
| 92 |
+
vector_norm = vectors.norm(dim=(-1,-2), keepdim=True)
|
| 93 |
+
normed_feats = self.feat_norm(feats)
|
| 94 |
+
normed_vectors = vectors / (vector_norm + self.eps)
|
| 95 |
+
return normed_feats, normed_vectors
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class GVP_MPNN(MessagePassing):
|
| 99 |
+
r"""The Geometric Vector Perceptron message passing layer
|
| 100 |
+
introduced in https://openreview.net/forum?id=1YLJDvSx6J4.
|
| 101 |
+
|
| 102 |
+
Uses a Geometric Vector Perceptron instead of the normal
|
| 103 |
+
MLP in aggregation phase.
|
| 104 |
+
|
| 105 |
+
Inputs will be a concatenation of (vectors, features)
|
| 106 |
+
|
| 107 |
+
Args:
|
| 108 |
+
* feats_x_in: int. number of scalar dimensions in the x inputs.
|
| 109 |
+
* vectors_x_in: int. number of vector dimensions in the x inputs.
|
| 110 |
+
* feats_x_out: int. number of scalar dimensions in the x outputs.
|
| 111 |
+
* vectors_x_out: int. number of vector dimensions in the x outputs.
|
| 112 |
+
* feats_edge_in: int. number of scalar dimensions in the edge_attr inputs.
|
| 113 |
+
* vectors_edge_in: int. number of vector dimensions in the edge_attr inputs.
|
| 114 |
+
* feats_edge_out: int. number of scalar dimensions in the edge_attr outputs.
|
| 115 |
+
* vectors_edge_out: int. number of vector dimensions in the edge_attr outputs.
|
| 116 |
+
* dropout: float. dropout rate.
|
| 117 |
+
* vector_dim: int. dimensions of the space containing the vectors.
|
| 118 |
+
* verbose: bool. verbosity level.
|
| 119 |
+
"""
|
| 120 |
+
def __init__(self, feats_x_in, vectors_x_in,
|
| 121 |
+
feats_x_out, vectors_x_out,
|
| 122 |
+
feats_edge_in, vectors_edge_in,
|
| 123 |
+
feats_edge_out, vectors_edge_out,
|
| 124 |
+
dropout, residual=False, vector_dim=3,
|
| 125 |
+
verbose=False, **kwargs):
|
| 126 |
+
super(GVP_MPNN, self).__init__(aggr="mean",**kwargs)
|
| 127 |
+
self.verbose = verbose
|
| 128 |
+
# record x dimensions ( vector + scalars )
|
| 129 |
+
self.feats_x_in = feats_x_in
|
| 130 |
+
self.vectors_x_in = vectors_x_in # N vectors features in input
|
| 131 |
+
self.feats_x_out = feats_x_out
|
| 132 |
+
self.vectors_x_out = vectors_x_out # N vectors features in output
|
| 133 |
+
# record edge_attr dimensions ( vector + scalars )
|
| 134 |
+
self.feats_edge_in = feats_edge_in
|
| 135 |
+
self.vectors_edge_in = vectors_edge_in # N vectors features in input
|
| 136 |
+
self.feats_edge_out = feats_edge_out
|
| 137 |
+
self.vectors_edge_out = vectors_edge_out # N vectors features in output
|
| 138 |
+
# aux layers
|
| 139 |
+
self.vector_dim = vector_dim
|
| 140 |
+
self.norm = nn.ModuleList([GVPLayerNorm(self.feats_x_out), # + self.feats_edge_out
|
| 141 |
+
GVPLayerNorm(self.feats_x_out)])
|
| 142 |
+
self.dropout = GVPDropout(dropout)
|
| 143 |
+
self.residual = residual
|
| 144 |
+
# this receives the vec_in message AND the receiver node
|
| 145 |
+
self.W_EV = nn.Sequential(GVP(
|
| 146 |
+
dim_vectors_in = self.vectors_x_in + self.vectors_edge_in,
|
| 147 |
+
dim_vectors_out = self.vectors_x_out + self.feats_edge_out,
|
| 148 |
+
dim_feats_in = self.feats_x_in + self.feats_edge_in,
|
| 149 |
+
dim_feats_out = self.feats_x_out + self.feats_edge_out
|
| 150 |
+
),
|
| 151 |
+
GVP(
|
| 152 |
+
dim_vectors_in = self.vectors_x_out + self.feats_edge_out,
|
| 153 |
+
dim_vectors_out = self.vectors_x_out + self.feats_edge_out,
|
| 154 |
+
dim_feats_in = self.feats_x_out + self.feats_edge_out,
|
| 155 |
+
dim_feats_out = self.feats_x_out + self.feats_edge_out
|
| 156 |
+
),
|
| 157 |
+
GVP(
|
| 158 |
+
dim_vectors_in = self.vectors_x_out + self.feats_edge_out,
|
| 159 |
+
dim_vectors_out = self.vectors_x_out + self.feats_edge_out,
|
| 160 |
+
dim_feats_in = self.feats_x_out + self.feats_edge_out,
|
| 161 |
+
dim_feats_out = self.feats_x_out + self.feats_edge_out
|
| 162 |
+
))
|
| 163 |
+
|
| 164 |
+
self.W_dh = nn.Sequential(GVP(
|
| 165 |
+
dim_vectors_in = self.vectors_x_out,
|
| 166 |
+
dim_vectors_out = 2*self.vectors_x_out,
|
| 167 |
+
dim_feats_in = self.feats_x_out,
|
| 168 |
+
dim_feats_out = 4*self.feats_x_out
|
| 169 |
+
),
|
| 170 |
+
GVP(
|
| 171 |
+
dim_vectors_in = 2*self.vectors_x_out,
|
| 172 |
+
dim_vectors_out = self.vectors_x_out,
|
| 173 |
+
dim_feats_in = 4*self.feats_x_out,
|
| 174 |
+
dim_feats_out = self.feats_x_out
|
| 175 |
+
))
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def forward(self, x: Union[Tensor, OptPairTensor], edge_index: Adj,
|
| 179 |
+
edge_attr: OptTensor = None, size: Size = None) -> Tensor:
|
| 180 |
+
""""""
|
| 181 |
+
x_size = list(x.shape)[-1]
|
| 182 |
+
# aggregate feats and vectors separately
|
| 183 |
+
feats, vectors = self.propagate(edge_index, x=x, edge_attr=edge_attr)
|
| 184 |
+
# aggregate
|
| 185 |
+
feats, vectors = self.dropout(feats, vectors.reshape(vectors.shape[0], -1, self.vector_dim))
|
| 186 |
+
# get the information relative to the nodes - edges not returned
|
| 187 |
+
feats_nodes = feats[:, :self.feats_x_in]
|
| 188 |
+
vector_nodes = vectors[:, :self.vectors_x_in]
|
| 189 |
+
# reshapes the vector part to last 3d
|
| 190 |
+
x_vectors = x[:, :self.vectors_x_in * self.vector_dim].reshape(x.shape[0], -1, self.vector_dim)
|
| 191 |
+
feats, vectors = self.norm[0]( x[:, self.vectors_x_in * self.vector_dim:]+feats_nodes, x_vectors+vector_nodes )
|
| 192 |
+
# update position-wise feedforward
|
| 193 |
+
feats_, vectors_ = self.dropout( *self.W_dh( (feats, vectors) ) )
|
| 194 |
+
feats, vectors = self.norm[1]( feats+feats_, vectors+vectors_ )
|
| 195 |
+
# make it residual
|
| 196 |
+
new_x = torch.cat( [feats, vectors.flatten(start_dim=-2)], dim=-1 )
|
| 197 |
+
if self.residual:
|
| 198 |
+
return new_x + x
|
| 199 |
+
return new_x
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def message(self, x_j, edge_attr) -> Tensor:
|
| 203 |
+
feats = torch.cat([ x_j[:, self.vectors_x_in * self.vector_dim:],
|
| 204 |
+
edge_attr[:, self.vectors_edge_in * self.vector_dim:] ], dim=-1)
|
| 205 |
+
vectors = torch.cat([ x_j[:, :self.vectors_x_in * self.vector_dim],
|
| 206 |
+
edge_attr[:, :self.vectors_edge_in * self.vector_dim] ], dim=-1).reshape(x_j.shape[0],-1,self.vector_dim)
|
| 207 |
+
feats, vectors = self.W_EV( (feats, vectors) )
|
| 208 |
+
return feats, vectors.flatten(start_dim=-2)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def propagate(self, edge_index: Adj, size: Size = None, **kwargs):
|
| 212 |
+
r"""The initial call to start propagating messages.
|
| 213 |
+
Args:
|
| 214 |
+
adj (Tensor or SparseTensor): `edge_index` holds the indices of a general (sparse)
|
| 215 |
+
assignment matrix of shape :obj:`[N, M]`.
|
| 216 |
+
size (tuple, optional): If set to :obj:`None`, the size will be automatically inferred
|
| 217 |
+
and assumed to be quadratic.
|
| 218 |
+
This argument is ignored in case :obj:`edge_index` is a
|
| 219 |
+
:obj:`torch_sparse.SparseTensor`. (default: :obj:`None`)
|
| 220 |
+
**kwargs: Any additional data which is needed to construct and
|
| 221 |
+
aggregate messages, and to update node embeddings.
|
| 222 |
+
"""
|
| 223 |
+
size = self.__check_input__(edge_index, size)
|
| 224 |
+
coll_dict = self.__collect__(self.__user_args__,
|
| 225 |
+
edge_index, size, kwargs)
|
| 226 |
+
msg_kwargs = self.inspector.distribute('message', coll_dict)
|
| 227 |
+
feats, vectors = self.message(**msg_kwargs)
|
| 228 |
+
# aggregate them
|
| 229 |
+
aggr_kwargs = self.inspector.distribute('aggregate', coll_dict)
|
| 230 |
+
out_feats = self.aggregate(feats, **aggr_kwargs)
|
| 231 |
+
out_vectors = self.aggregate(vectors, **aggr_kwargs)
|
| 232 |
+
# return tuple
|
| 233 |
+
update_kwargs = self.inspector.distribute('update', coll_dict)
|
| 234 |
+
return self.update((out_feats, out_vectors), **update_kwargs)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def __repr__(self):
|
| 238 |
+
dict_print = { "feats_x_in": self.feats_x_in,
|
| 239 |
+
"vectors_x_in": self.vectors_x_in,
|
| 240 |
+
"feats_x_out": self.feats_x_out,
|
| 241 |
+
"vectors_x_out": self.vectors_x_out,
|
| 242 |
+
"feats_edge_in": self.feats_edge_in,
|
| 243 |
+
"vectors_edge_in": self.vectors_edge_in,
|
| 244 |
+
"feats_edge_out": self.feats_edge_out,
|
| 245 |
+
"vectors_edge_out": self.vectors_edge_out,
|
| 246 |
+
"vector_dim": self.vector_dim }
|
| 247 |
+
return 'GVP_MPNN Layer with the following attributes: ' + str(dict_print)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
class GVP_Network(nn.Module):
|
| 251 |
+
r"""Sample GNN model architecture that uses the Geometric Vector Perceptron
|
| 252 |
+
message passing layer to learn over point clouds.
|
| 253 |
+
Main MPNN layer introduced in https://openreview.net/forum?id=1YLJDvSx6J4.
|
| 254 |
+
|
| 255 |
+
Inputs will be standard GNN: x, edge_index, edge_attr, batch, ...
|
| 256 |
+
|
| 257 |
+
Args:
|
| 258 |
+
* n_layers: int. number of MPNN layers
|
| 259 |
+
* feats_x_in: int. number of scalar dimensions in the x inputs.
|
| 260 |
+
* vectors_x_in: int. number of vector dimensions in the x inputs.
|
| 261 |
+
* feats_x_out: int. number of scalar dimensions in the x outputs.
|
| 262 |
+
* vectors_x_out: int. number of vector dimensions in the x outputs.
|
| 263 |
+
* feats_edge_in: int. number of scalar dimensions in the edge_attr inputs.
|
| 264 |
+
* vectors_edge_in: int. number of vector dimensions in the edge_attr inputs.
|
| 265 |
+
* feats_edge_out: int. number of scalar dimensions in the edge_attr outputs.
|
| 266 |
+
* embedding_nums: list. number of unique keys to embedd. for pointsedge_embedding_dims
|
| 267 |
+
1 entry per embedding needed.
|
| 268 |
+
* embedding_dims: list. point - number of dimensions of
|
| 269 |
+
the resulting embedding. 1 entry per embedding needed.
|
| 270 |
+
* edge_embedding_nums: list. number of unique keys to embedd. for edges.
|
| 271 |
+
1 entry per embedding needed.
|
| 272 |
+
* edge_embedding_dims: list. point - number of dimensions of
|
| 273 |
+
the resulting embedding. 1 entry per embedding needed.
|
| 274 |
+
* vectors_edge_out: int. number of vector dimensions in the edge_attr outputs.
|
| 275 |
+
* dropout: float. dropout rate.
|
| 276 |
+
* vector_dim: int. dimensions of the space containing the vectors.
|
| 277 |
+
* recalc: bool. Whether to recalculate edge features between MPNN layers.
|
| 278 |
+
* verbose: bool. verbosity level.
|
| 279 |
+
"""
|
| 280 |
+
def __init__(self, n_layers,
|
| 281 |
+
feats_x_in, vectors_x_in,
|
| 282 |
+
feats_x_out, vectors_x_out,
|
| 283 |
+
feats_edge_in, vectors_edge_in,
|
| 284 |
+
feats_edge_out, vectors_edge_out,
|
| 285 |
+
embedding_nums=[], embedding_dims=[],
|
| 286 |
+
edge_embedding_nums=[], edge_embedding_dims=[],
|
| 287 |
+
dropout=0.0, residual=False, vector_dim=3,
|
| 288 |
+
recalc=1, verbose=False,device=None):
|
| 289 |
+
super().__init__()
|
| 290 |
+
|
| 291 |
+
self.n_layers = n_layers
|
| 292 |
+
# Embeddings? solve here
|
| 293 |
+
self.embedding_nums = embedding_nums
|
| 294 |
+
self.embedding_dims = embedding_dims
|
| 295 |
+
self.emb_layers = torch.nn.ModuleList()
|
| 296 |
+
self.edge_embedding_nums = edge_embedding_nums
|
| 297 |
+
self.edge_embedding_dims = edge_embedding_dims
|
| 298 |
+
self.edge_emb_layers = torch.nn.ModuleList()
|
| 299 |
+
# instantiate point and edge embedding layers
|
| 300 |
+
for i in range( len(self.embedding_dims) ):
|
| 301 |
+
self.emb_layers.append(nn.Embedding(num_embeddings = embedding_nums[i],
|
| 302 |
+
embedding_dim = embedding_dims[i]))
|
| 303 |
+
feats_x_in += embedding_dims[i] - 1
|
| 304 |
+
feats_x_out += embedding_dims[i] - 1
|
| 305 |
+
for i in range( len(self.edge_embedding_dims) ):
|
| 306 |
+
self.edge_emb_layers.append(nn.Embedding(num_embeddings = edge_embedding_nums[i],
|
| 307 |
+
embedding_dim = edge_embedding_dims[i]))
|
| 308 |
+
feats_edge_in += edge_embedding_dims[i] - 1
|
| 309 |
+
feats_edge_out += edge_embedding_dims[i] - 1
|
| 310 |
+
# rest
|
| 311 |
+
self.fc_layers = torch.nn.ModuleList()
|
| 312 |
+
self.gcnn_layers = torch.nn.ModuleList()
|
| 313 |
+
self.feats_x_in = feats_x_in
|
| 314 |
+
self.vectors_x_in = vectors_x_in
|
| 315 |
+
self.feats_x_out = feats_x_out
|
| 316 |
+
self.vectors_x_out = vectors_x_out
|
| 317 |
+
self.feats_edge_in = feats_edge_in
|
| 318 |
+
self.vectors_edge_in = vectors_edge_in
|
| 319 |
+
self.feats_edge_out = feats_edge_out
|
| 320 |
+
self.vectors_edge_out = vectors_edge_out
|
| 321 |
+
self.dropout = dropout
|
| 322 |
+
self.residual = residual
|
| 323 |
+
self.vector_dim = vector_dim
|
| 324 |
+
self.recalc = recalc
|
| 325 |
+
self.verbose = verbose
|
| 326 |
+
|
| 327 |
+
# instantiate layers
|
| 328 |
+
for i in range(n_layers):
|
| 329 |
+
layer = GVP_MPNN(feats_x_in, vectors_x_in,
|
| 330 |
+
feats_x_out, vectors_x_out,
|
| 331 |
+
feats_edge_in, vectors_edge_in,
|
| 332 |
+
feats_edge_out, vectors_edge_out,
|
| 333 |
+
dropout, residual=residual,
|
| 334 |
+
vector_dim=vector_dim, verbose=verbose)
|
| 335 |
+
self.gcnn_layers.append(layer)
|
| 336 |
+
def forward(self, x, edge_index, batch, edge_attr,
|
| 337 |
+
bsize=None, recalc_edge=None, verbose=0):
|
| 338 |
+
""" Embedding of inputs when necessary, then pass layers.
|
| 339 |
+
Recalculate edge features every time with the
|
| 340 |
+
`recalc_edge` function.
|
| 341 |
+
"""
|
| 342 |
+
bsize= batch
|
| 343 |
+
original_x = x.clone()
|
| 344 |
+
original_edge_index = edge_index.clone()
|
| 345 |
+
original_edge_attr = edge_attr.clone()
|
| 346 |
+
# do embeddings when needed
|
| 347 |
+
# pick to embedd. embedd sequentially and add to input
|
| 348 |
+
|
| 349 |
+
# points:
|
| 350 |
+
to_embedd = x[:, -len(self.embedding_dims):].long()
|
| 351 |
+
for i,emb_layer in enumerate(self.emb_layers):
|
| 352 |
+
# the portion corresponding to `to_embedd` part gets dropped
|
| 353 |
+
# at first iter
|
| 354 |
+
stop_concat = -len(self.embedding_dims) if i == 0 else x.shape[-1]
|
| 355 |
+
x = torch.cat([ x[:, :stop_concat],
|
| 356 |
+
emb_layer( to_embedd[:, i] )
|
| 357 |
+
], dim=-1)
|
| 358 |
+
# pass layers
|
| 359 |
+
for i,layer in enumerate(self.gcnn_layers):
|
| 360 |
+
# embedd edge items (needed everytime since edge_attr and idxs
|
| 361 |
+
# are recalculated every pass)
|
| 362 |
+
to_embedd = edge_attr[:, -len(self.edge_embedding_dims):].long()
|
| 363 |
+
for j,edge_emb_layer in enumerate(self.edge_emb_layers):
|
| 364 |
+
# the portion corresponding to `to_embedd` part gets dropped
|
| 365 |
+
# at first iter
|
| 366 |
+
stop_concat = -len(self.edge_embedding_dims) if j == 0 else x.shape[-1]
|
| 367 |
+
edge_attr = torch.cat([ edge_attr[:, :-len(self.edge_embedding_dims) + j],
|
| 368 |
+
edge_emb_layer( to_embedd[:, j] )
|
| 369 |
+
], dim=-1)
|
| 370 |
+
# pass layers
|
| 371 |
+
x = layer(x, edge_index, edge_attr, size=bsize)
|
| 372 |
+
|
| 373 |
+
# recalculate edge info every self.recalc steps
|
| 374 |
+
# but not needed if last layer of last iteration
|
| 375 |
+
if (1%self.recalc == 0) and not (i == self.n_layers-1) :
|
| 376 |
+
edge_index, edge_attr, _ = recalc_edge(x) # returns attr, idx, embedd_info
|
| 377 |
+
else:
|
| 378 |
+
edge_attr = original_edge_attr.clone()
|
| 379 |
+
edge_index = original_edge_index.clone()
|
| 380 |
+
|
| 381 |
+
if verbose:
|
| 382 |
+
print("========")
|
| 383 |
+
print("iter:", j, "layer:", i, "nlinks:", edge_attr.shape)
|
| 384 |
+
|
| 385 |
+
return x
|
| 386 |
+
|
| 387 |
+
def __repr__(self):
|
| 388 |
+
return 'GVP_Network of: {0} layers'.format(len(self.gcnn_layers))
|