Spaces:
Sleeping
Sleeping
File size: 14,310 Bytes
5b557cf | 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 | from typing import Union, Tuple
from torch_geometric.typing import OptTensor, OptPairTensor, Adj, Size
import torch
from torch import Tensor
from torch.nn.functional import conv2d
from torch_sparse import SparseTensor, matmul
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.utils.loop import contains_self_loops
from torch.nn.parameter import Parameter
from torch_geometric.nn.inits import glorot, zeros
from math import sqrt
import numpy as np
def intersect1d(tensor1,tensor2):
device = tensor1.device
result, ind1, ind2 = np.intersect1d(tensor1.cpu().numpy(),tensor2.cpu().numpy(),return_indices=True)
return torch.tensor(result).to(device), torch.tensor(ind1).to(device), torch.tensor(ind2).to(device)
def setdiff1d(tensor1,tensor2):
device = tensor1.device
result = np.setdiff1d(tensor1.cpu().numpy(),tensor2.cpu().numpy())
return torch.tensor(result).to(device)
class SelectionConv(MessagePassing):
def __init__(self, in_channels: int, out_channels: int, kernel_size: int = 3, dilation = 1, padding_mode = 'zeros', **kwargs):
super(SelectionConv, self).__init__(**kwargs)
self.kernel_size = kernel_size
self.in_channels = in_channels
self.out_channels = out_channels
self.dilation = dilation
self.padding_mode = padding_mode
self.selection_count = kernel_size * kernel_size
#self.has_self_loops = has_self_loops
self.weight = Parameter(torch.randn(self.selection_count,in_channels,out_channels,dtype=torch.float))
torch.nn.init.uniform_(self.weight, a=-0.1, b=0.1)
#torch.nn.init.normal_(self.weight)
self.bias = Parameter(torch.randn(out_channels,dtype=torch.float))
torch.nn.init.uniform_(self.bias, a=0.0, b=0.1)
def forward(self, x: Union[Tensor, OptPairTensor], edge_index: Adj, selections: Tensor, interps = None) -> Tensor:
""""""
all_nodes = torch.arange(x.shape[0]).to(x.device)
if self.padding_mode == 'constant':
# Constant value of the average of the all the nodes
x_mean = torch.mean(x,dim=0)
out = torch.zeros((x.shape[0],self.out_channels)).to(x.device)
if self.padding_mode == 'normalize':
dir_count = torch.zeros((x.shape[0],1)).to(x.device)
if self.kernel_size == 1 or self.kernel_size == 3:
# Find the appropriate node for each selection by stepping through connecting edges
for s in range(self.selection_count):
cur_dir = torch.where(selections == s)[0]
cur_source = edge_index[0,cur_dir]
cur_target = edge_index[1,cur_dir]
if interps is not None:
cur_interps = interps[cur_dir]
cur_interps = torch.unsqueeze(cur_interps,dim=1)
#print(torch.amin(cur_interps),torch.amax(cur_interps))
if self.dilation > 1:
for _ in range(1, self.dilation):
vals, ind1, ind2 = intersect1d(cur_target,edge_index[0,cur_dir])
cur_source = cur_source[ind1]
cur_target = edge_index[1,cur_dir][ind2]
if interps is not None:
cur_interps = cur_interps[ind1]
# Main Calculation
if interps is None:
#out[cur_source] += torch.matmul(x[cur_target], self.weight[s])
result = torch.matmul(x[cur_target], self.weight[s])
else:
#out[cur_source] += cur_interps*torch.matmul(x[cur_target], self.weight[s])
result = cur_interps*torch.matmul(x[cur_target], self.weight[s])
# Adding with duplicate indices
out.index_add_(0,cur_source,result)
# Sanity check
#from tqdm import tqdm
#for i,node in enumerate(tqdm(cur_source)):
# out[node] += result[i]
if self.padding_mode == 'constant':
missed_nodes = setdiff1d(all_nodes, cur_source)
#out[missed_nodes] += torch.matmul(x_mean, self.weight[s])
out.index_add_(0,missed_nodes,torch.matmul(x_mean, self.weight[s]))
if self.padding_mode == 'replicate':
missed_nodes = setdiff1d(all_nodes, cur_source)
#out[missed_nodes] += torch.matmul(x[missed_nodes], self.weight[s])
out.index_add_(0,missed_nodes,torch.matmul(x[missed_nodes], self.weight[s]))
if self.padding_mode == 'reflect':
missed_nodes = setdiff1d(all_nodes, cur_source)
opposite = s+4
if opposite > 8:
opposite = opposite % 9 + 1
op_dir = torch.where(selections == opposite)[0]
op_source = edge_index[0,op_dir]
op_target = edge_index[1,op_dir]
if interps is not None:
op_interps = interps[op_dir]
op_interps = torch.unsqueeze(op_interps,dim=1)
# Only take edges that are part of missed nodes
vals, ind1, ind2 = intersect1d(op_source,missed_nodes)
op_source = op_source[ind1]
op_target = op_target[ind1]
if interps is not None:
op_interps = op_interps[ind1]
if self.dilation > 1:
for _ in range(1, self.dilation):
vals, ind1, ind2 = intersect1d(op_target,edge_index[0,op_dir])
op_source = op_source[ind1]
op_target = edge_index[1,op_dir][ind2]
if interps is not None:
op_interps = op_interps[ind1]
# Main Calculation
if interps is None:
result = torch.matmul(x[op_target], self.weight[s])
else:
result = op_interps * torch.matmul(x[op_target], self.weight[s])
out.index_add_(0,op_source,result)
if self.padding_mode == 'normalize':
dir_count[torch.unique(cur_source)] += 1
else:
width = self.kernel_size//2
horiz = torch.arange(-width,width+1).to(x.device)
vert = torch.arange(-width,width+1).to(x.device)
right = torch.where(selections == 1)[0]
left = torch.where(selections == 5)[0]
down = torch.where(selections == 7)[0]
up = torch.where(selections == 3)[0]
center = torch.where(selections == 0)[0]
# Find the appropriate node for each selection by stepping through connecting edges
s = 0
for i in range(self.kernel_size):
for j in range(self.kernel_size):
x_loc = horiz[j]
y_loc = vert[i]
cur_source = edge_index[0,center] #Starting location
cur_target = edge_index[1,center]
if interps is not None:
cur_interps = interps[center]
cur_interps = torch.unsqueeze(cur_interps,dim=1)
#print(torch.sum(cur_target-cur_source))
#print(cur_target.shape)
if x_loc < 0:
for _ in range(self.dilation*abs(x_loc)):
vals, ind1, ind2 = intersect1d(cur_target,edge_index[0,left])
cur_source = cur_source[ind1]
cur_target = edge_index[1,left][ind2]
if interps is not None:
cur_interps = cur_interps[ind1]
if x_loc > 0:
for _ in range(self.dilation*abs(x_loc)):
vals, ind1, ind2 = intersect1d(cur_target,edge_index[0,right])
cur_source = cur_source[ind1]
cur_target = edge_index[1,right][ind2]
if interps is not None:
cur_interps = cur_interps[ind1]
if y_loc < 0:
for _ in range(self.dilation*abs(y_loc)):
vals, ind1, ind2 = intersect1d(cur_target,edge_index[0,up])
cur_source = cur_source[ind1]
cur_target = edge_index[1,up][ind2]
if interps is not None:
cur_interps = cur_interps[ind1]
if y_loc > 0:
for _ in range(self.dilation*abs(y_loc)):
vals, ind1, ind2 = intersect1d(cur_target,edge_index[0,down])
cur_source = cur_source[ind1]
cur_target = edge_index[1,down][ind2]
if interps is not None:
cur_interps = cur_interps[ind1]
# Main Calculation
if interps is None:
#out[cur_source] += torch.matmul(x[cur_target], self.weight[s])
result = torch.matmul(x[cur_target], self.weight[s])
else:
#out[cur_source] += cur_interps*torch.matmul(x[cur_target], self.weight[s])
result = cur_interps*torch.matmul(x[cur_target], self.weight[s])
# Adding with duplicate indices
out.index_add_(0,cur_source,result)
if self.padding_mode == 'constant':
missed_nodes = setdiff1d(all_nodes, cur_source)
#out[missed_nodes] += torch.matmul(x_mean, self.weight[s])
out.index_add_(0,missed_nodes,torch.matmul(x_mean, self.weight[s]))
if self.padding_mode == 'replicate':
missed_nodes = setdiff1d(all_nodes, cur_source)
#out[missed_nodes] += torch.matmul(x[missed_nodes], self.weight[s])
out.index_add_(0,missed_nodes,torch.matmul(x[missed_nodes], self.weight[s]))
if self.padding_mode == 'reflect':
raise ValueError("Reflect padding not yet implemented for larger kernels")
if self.padding_mode == 'normalize':
dir_count[torch.unique(cur_source)] += 1
s+=1
#print(self.selection_count/(dir_count + 1e-8))
#test_val = self.selection_count/(dir_count + 1e-8)
# print(torch.max(test_val),torch.min(test_val),torch.mean(test_val))
if self.padding_mode == 'zeros':
pass # Already accounted for in the graph structure, no further computation needed
elif self.padding_mode == 'normalize':
out *= self.selection_count/(dir_count + 1e-8)
elif self.padding_mode == 'constant':
pass # Processed earlier
elif self.padding_mode == 'replicate':
pass
elif self.padding_mode == 'reflect':
pass
elif self.padding_mode == 'circular':
raise ValueError("Circular padding cannot be generalized on a graph. Instead, create a graph with edges connecting to the wrapped around nodes")
else:
raise ValueError(f"Unknown padding mode: {self.padding_mode}")
# Add bias if applicable
out += self.bias
return out
def copy_weightsNxN(self,weight,bias=None):
width = int(sqrt(self.selection_count))
# Assumes weight comes in as [output channels, input channels, row, col]
for i in range(self.selection_count):
self.weight[i] = weight[:,:,i//width,i%width].permute(1,0)
def copy_weights3x3(self,weight,bias=None):
# Assumes weight comes in as [output channels, input channels, row, col]
# Assumes weight is a 3x3
# Current Ordering
# 4 3 2
# 5 0 1
# 6 7 8
# Need to flip horizontally per implementation of convolution
#self.weight[5] = weight[:,:,1,2].permute(1,0)
#self.weight[7] = weight[:,:,0,1].permute(1,0)
#self.weight[1] = weight[:,:,1,0].permute(1,0)
#self.weight[3] = weight[:,:,2,1].permute(1,0)
#self.weight[6] = weight[:,:,0,2].permute(1,0)
#self.weight[8] = weight[:,:,0,0].permute(1,0)
#self.weight[2] = weight[:,:,2,0].permute(1,0)
#self.weight[4] = weight[:,:,2,2].permute(1,0)
#self.weight[0] = weight[:,:,1,1].permute(1,0)
self.weight[1] = weight[:,:,1,2].permute(1,0)
self.weight[3] = weight[:,:,0,1].permute(1,0)
self.weight[5] = weight[:,:,1,0].permute(1,0)
self.weight[7] = weight[:,:,2,1].permute(1,0)
self.weight[2] = weight[:,:,0,2].permute(1,0)
self.weight[4] = weight[:,:,0,0].permute(1,0)
self.weight[6] = weight[:,:,2,0].permute(1,0)
self.weight[8] = weight[:,:,2,2].permute(1,0)
self.weight[0] = weight[:,:,1,1].permute(1,0)
def copy_weights1x1(self, weight, bias=None):
self.weight[0] = weight[:,:,0,0].permute(1, 0)
def copy_weights(self,weight,bias=None):
if self.kernel_size == 3:
self.copy_weights3x3(weight,bias)
elif self.kernel_size == 1:
self.copy_weights1x1(weight, bias)
else:
self.copy_weightsNxN(weight,bias)
if bias is None:
self.bias[:] = 0.0
else:
self.bias = bias
def __repr__(self):
return '{}({}, {})'.format(self.__class__.__name__, self.in_channels,
self.out_channels)
|