code stringlengths 17 6.64M |
|---|
def train(train_loader, optimizer):
model.train()
total_loss = 0
for data in train_loader:
optimizer.zero_grad()
data = data.to(device)
(S_0, S_L) = model(data.x_s, data.edge_index_s, data.edge_attr_s, data.x_s_batch, data.x_t, data.edge_index_t, data.edge_attr_t, data.x_t_batch)
... |
@torch.no_grad()
def test(test_dataset):
model.eval()
test_loader1 = DataLoader(test_dataset, args.batch_size, shuffle=True)
test_loader2 = DataLoader(test_dataset, args.batch_size, shuffle=True)
correct = num_examples = 0
while (num_examples < args.test_samples):
for (data_s, data_t) in z... |
def run(i, datasets):
datasets = [dataset.shuffle() for dataset in datasets]
train_datasets = [dataset[:20] for dataset in datasets]
test_datasets = [dataset[20:] for dataset in datasets]
train_datasets = [PairDataset(train_dataset, train_dataset, sample=False) for train_dataset in train_datasets]
... |
def set_seed():
torch.manual_seed(12345)
|
def test_dgmc_repr():
model = DGMC(psi_1, psi_2, num_steps=1)
assert (model.__repr__() == 'DGMC(\n psi_1=GIN(32, 16, num_layers=2, batch_norm=False, cat=True, lin=True),\n psi_2=GIN(8, 8, num_layers=2, batch_norm=False, cat=True, lin=True),\n num_steps=1, k=-1\n)')
model.reset_parameters()
|
def test_dgmc_on_single_graphs():
set_seed()
model = DGMC(psi_1, psi_2, num_steps=1)
(x, e) = (data.x, data.edge_index)
y = torch.arange(data.num_nodes)
y = torch.stack([y, y], dim=0)
set_seed()
(S1_0, S1_L) = model(x, e, None, None, x, e, None, None)
loss1 = model.loss(S1_0, y)
lo... |
def test_dgmc_on_multiple_graphs():
set_seed()
model = DGMC(psi_1, psi_2, num_steps=1)
batch = Batch.from_data_list([data, data])
(x, e, b) = (batch.x, batch.edge_index, batch.batch)
set_seed()
(S1_0, S1_L) = model(x, e, None, b, x, e, None, b)
assert (S1_0.size() == (batch.num_nodes, data... |
def test_dgmc_include_gt():
model = DGMC(psi_1, psi_2, num_steps=1)
S_idx = torch.tensor([[[0, 1], [1, 2]], [[1, 2], [0, 1]]])
s_mask = torch.tensor([[True, False], [True, True]])
y = torch.tensor([[0, 1], [0, 0]])
S_idx = model.__include_gt__(S_idx, s_mask, y)
assert (S_idx.tolist() == [[[0, ... |
def test_gin():
model = GIN(16, 32, num_layers=2, batch_norm=True, cat=True, lin=True)
assert (model.__repr__() == 'GIN(16, 32, num_layers=2, batch_norm=True, cat=True, lin=True)')
x = torch.randn(100, 16)
edge_index = torch.randint(100, (2, 400), dtype=torch.long)
for (cat, lin) in product([False... |
def test_mlp():
model = MLP(16, 32, num_layers=2, batch_norm=True, dropout=0.5)
assert (model.__repr__() == 'MLP(16, 32, num_layers=2, batch_norm=True, dropout=0.5)')
x = torch.randn(100, 16)
out = model(x)
assert (out.size() == (100, 32))
|
def test_rel():
model = RelCNN(16, 32, num_layers=2, batch_norm=True, cat=True, lin=True, dropout=0.5)
assert (model.__repr__() == 'RelCNN(16, 32, num_layers=2, batch_norm=True, cat=True, lin=True, dropout=0.5)')
assert (model.convs[0].__repr__() == 'RelConv(16, 32)')
x = torch.randn(100, 16)
edge... |
def test_spline():
model = SplineCNN(16, 32, dim=3, num_layers=2, cat=True, lin=True, dropout=0.5)
assert (model.__repr__() == 'SplineCNN(16, 32, dim=3, num_layers=2, cat=True, lin=True, dropout=0.5)')
x = torch.randn(100, 16)
edge_index = torch.randint(100, (2, 400), dtype=torch.long)
edge_attr =... |
def test_pair_dataset():
x = torch.randn(10, 16)
edge_index = torch.randint(x.size(0), (2, 30), dtype=torch.long)
data = Data(x=x, edge_index=edge_index)
dataset = PairDataset([data, data], [data, data], sample=True)
assert (dataset.__repr__() == 'PairDataset([Data(edge_index=[2, 30], x=[10, 16]),... |
def test_valid_pair_dataset():
x = torch.randn(10, 16)
edge_index = torch.randint(x.size(0), (2, 30), dtype=torch.long)
y = torch.randperm(x.size(0))
data = Data(x=x, edge_index=edge_index, y=y)
dataset = ValidPairDataset([data, data], [data, data], sample=True)
assert (dataset.__repr__() == '... |
def train(model, loader, optimizer):
model.train()
for (batch, *args) in loader:
batch = batch.to(model.device)
optimizer.zero_grad()
out = model(batch.x, batch.adj_t, *args)
train_mask = batch.train_mask[:out.size(0)]
loss = criterion(out[train_mask], batch.y[:out.size... |
@torch.no_grad()
def test(model, data):
model.eval()
out = model(data.x.to(model.device), data.adj_t.to(model.device)).cpu()
train_acc = compute_micro_f1(out, data.y, data.train_mask)
val_acc = compute_micro_f1(out, data.y, data.val_mask)
test_acc = compute_micro_f1(out, data.y, data.test_mask)
... |
def train(model, loader, optimizer):
model.train()
for (batch, *args) in loader:
batch = batch.to(model.device)
optimizer.zero_grad()
out = model(batch.x, batch.adj_t, *args)
train_mask = batch.train_mask[:out.size(0)]
loss = criterion(out[train_mask], batch.y[:out.size... |
@torch.no_grad()
def test(model, data):
model.eval()
out = model(data.x.to(model.device), data.adj_t.to(model.device)).cpu()
train_acc = compute_micro_f1(out, data.y, data.train_mask)
val_acc = compute_micro_f1(out, data.y, data.val_mask)
test_acc = compute_micro_f1(out, data.y, data.test_mask)
... |
class GIN(ScalableGNN):
def __init__(self, num_nodes: int, in_channels: int, hidden_channels: int, out_channels: int, num_layers: int):
super().__init__(num_nodes, hidden_channels, num_layers, pool_size=2, buffer_size=60000)
self.in_channels = in_channels
self.out_channels = out_channels
... |
def train(model, loader, optimizer):
model.train()
total_loss = total_examples = 0
for (batch, *args) in loader:
batch = batch.to(model.device)
optimizer.zero_grad()
(out, reg) = model(batch.x, batch.adj_t, *args)
loss = (criterion(out, batch.y[:out.size(0)]) + reg)
... |
@torch.no_grad()
def mini_test(model, loader, y):
model.eval()
out = model(loader=loader)
return (int((out.argmax(dim=(- 1)) == y).sum()) / y.size(0))
|
@torch.no_grad()
def full_test(model, loader):
model.eval()
total_correct = total_examples = 0
for batch in loader:
batch = batch.to(device)
(out, _) = model(batch.x, batch.adj_t)
total_correct += int((out.argmax(dim=(- 1)) == batch.y).sum())
total_examples += out.size(0)
... |
def mini_train(model, loader, criterion, optimizer, max_steps, grad_norm=None, edge_dropout=0.0):
model.train()
total_loss = total_examples = 0
for (i, (batch, batch_size, *args)) in enumerate(loader):
x = batch.x.to(model.device)
adj_t = batch.adj_t.to(model.device)
y = batch.y[:b... |
@torch.no_grad()
def full_test(model, data):
model.eval()
return model(data.x.to(model.device), data.adj_t.to(model.device)).cpu()
|
@torch.no_grad()
def mini_test(model, loader):
model.eval()
return model(loader=loader)
|
@hydra.main(config_path='conf', config_name='config')
def main(conf):
conf.model.params = conf.model.params[conf.dataset.name]
params = conf.model.params
print(OmegaConf.to_yaml(conf))
try:
edge_dropout = params.edge_dropout
except:
edge_dropout = 0.0
grad_norm = (None if isins... |
def get_extensions():
Extension = CppExtension
define_macros = []
libraries = []
extra_compile_args = {'cxx': []}
extra_link_args = []
info = parallel_info()
if (('parallel backend: OpenMP' in info) and ('OpenMP not found' not in info)):
extra_compile_args['cxx'] += ['-DAT_PARALLEL... |
def get_planetoid(root: str, name: str) -> Tuple[(Data, int, int)]:
transform = T.Compose([T.NormalizeFeatures(), T.ToSparseTensor()])
dataset = Planetoid(f'{root}/Planetoid', name, transform=transform)
return (dataset[0], dataset.num_features, dataset.num_classes)
|
def get_wikics(root: str) -> Tuple[(Data, int, int)]:
dataset = WikiCS(f'{root}/WIKICS', transform=T.ToSparseTensor())
data = dataset[0]
data.adj_t = data.adj_t.to_symmetric()
data.val_mask = data.stopping_mask
data.stopping_mask = None
return (data, dataset.num_features, dataset.num_classes)
|
def get_coauthor(root: str, name: str) -> Tuple[(Data, int, int)]:
dataset = Coauthor(f'{root}/Coauthor', name, transform=T.ToSparseTensor())
data = dataset[0]
torch.manual_seed(12345)
(data.train_mask, data.val_mask, data.test_mask) = gen_masks(data.y, 20, 30, 20)
return (data, dataset.num_featur... |
def get_amazon(root: str, name: str) -> Tuple[(Data, int, int)]:
dataset = Amazon(f'{root}/Amazon', name, transform=T.ToSparseTensor())
data = dataset[0]
torch.manual_seed(12345)
(data.train_mask, data.val_mask, data.test_mask) = gen_masks(data.y, 20, 30, 20)
return (data, dataset.num_features, da... |
def get_arxiv(root: str) -> Tuple[(Data, int, int)]:
dataset = PygNodePropPredDataset('ogbn-arxiv', f'{root}/OGB', pre_transform=T.ToSparseTensor())
data = dataset[0]
data.adj_t = data.adj_t.to_symmetric()
data.node_year = None
data.y = data.y.view((- 1))
split_idx = dataset.get_idx_split()
... |
def get_products(root: str) -> Tuple[(Data, int, int)]:
dataset = PygNodePropPredDataset('ogbn-products', f'{root}/OGB', pre_transform=T.ToSparseTensor())
data = dataset[0]
data.y = data.y.view((- 1))
split_idx = dataset.get_idx_split()
data.train_mask = index2mask(split_idx['train'], data.num_nod... |
def get_yelp(root: str) -> Tuple[(Data, int, int)]:
dataset = Yelp(f'{root}/YELP', pre_transform=T.ToSparseTensor())
data = dataset[0]
data.x = ((data.x - data.x.mean(dim=0)) / data.x.std(dim=0))
return (data, dataset.num_features, dataset.num_classes)
|
def get_flickr(root: str) -> Tuple[(Data, int, int)]:
dataset = Flickr(f'{root}/Flickr', pre_transform=T.ToSparseTensor())
return (dataset[0], dataset.num_features, dataset.num_classes)
|
def get_reddit(root: str) -> Tuple[(Data, int, int)]:
dataset = Reddit2(f'{root}/Reddit2', pre_transform=T.ToSparseTensor())
data = dataset[0]
data.x = ((data.x - data.x.mean(dim=0)) / data.x.std(dim=0))
return (data, dataset.num_features, dataset.num_classes)
|
def get_ppi(root: str, split: str='train') -> Tuple[(Data, int, int)]:
dataset = PPI(f'{root}/PPI', split=split, pre_transform=T.ToSparseTensor())
data = Batch.from_data_list(dataset)
data.batch = None
data.ptr = None
data[f'{split}_mask'] = torch.ones(data.num_nodes, dtype=torch.bool)
return ... |
def get_sbm(root: str, name: str) -> Tuple[(Data, int, int)]:
dataset = GNNBenchmarkDataset(f'{root}/SBM', name, split='train', pre_transform=T.ToSparseTensor())
data = Batch.from_data_list(dataset)
data.batch = None
data.ptr = None
return (data, dataset.num_features, dataset.num_classes)
|
def get_data(root: str, name: str) -> Tuple[(Data, int, int)]:
if (name.lower() in ['cora', 'citeseer', 'pubmed']):
return get_planetoid(root, name)
elif (name.lower() in ['coauthorcs', 'coauthorphysics']):
return get_coauthor(root, name[8:])
elif (name.lower() in ['amazoncomputers', 'amaz... |
class History(torch.nn.Module):
'A historical embedding storage module.'
def __init__(self, num_embeddings: int, embedding_dim: int, device=None):
super().__init__()
self.num_embeddings = num_embeddings
self.embedding_dim = embedding_dim
pin_memory = ((device is None) or (str(... |
class SubData(NamedTuple):
data: Data
batch_size: int
n_id: Tensor
offset: Tensor
count: Tensor
def to(self, *args, **kwargs):
return SubData(self.data.to(*args, **kwargs), self.batch_size, self.n_id, self.offset, self.count)
|
class SubgraphLoader(DataLoader):
'A simple subgraph loader that, given a pre-partioned :obj:`data` object,\n generates subgraphs from mini-batches in :obj:`ptr` (including their 1-hop\n neighbors).'
def __init__(self, data: Data, ptr: Tensor, batch_size: int=1, bipartite: bool=True, log: bool=True, **... |
class EvalSubgraphLoader(SubgraphLoader):
'A simple subgraph loader that, given a pre-partioned :obj:`data` object,\n generates subgraphs from mini-batches in :obj:`ptr` (including their 1-hop\n neighbors).\n In contrast to :class:`SubgraphLoader`, this loader does not generate\n subgraphs from random... |
def metis(adj_t: SparseTensor, num_parts: int, recursive: bool=False, log: bool=True) -> Tuple[(Tensor, Tensor)]:
'Computes the METIS partition of a given sparse adjacency matrix\n :obj:`adj_t`, returning its "clustered" permutation :obj:`perm` and\n corresponding cluster slices :obj:`ptr`.'
if log:
... |
def permute(data: Data, perm: Tensor, log: bool=True) -> Data:
'Permutes a :obj:`data` object according to a given permutation\n :obj:`perm`.'
if log:
t = time.perf_counter()
print('Permuting data...', end=' ', flush=True)
data = copy.copy(data)
for (key, value) in data:
if ... |
class APPNP(ScalableGNN):
def __init__(self, num_nodes: int, in_channels, hidden_channels: int, out_channels: int, num_layers: int, alpha: float, dropout: float=0.0, pool_size: Optional[int]=None, buffer_size: Optional[int]=None, device=None):
super().__init__(num_nodes, out_channels, num_layers, pool_si... |
class ScalableGNN(torch.nn.Module):
'An abstract class for implementing scalable GNNs via historical\n embeddings.\n This class will take care of initializing :obj:`num_layers - 1` historical\n embeddings, and provides a convenient interface to push recent node\n embeddings to the history, and to pull... |
class GAT(ScalableGNN):
def __init__(self, num_nodes: int, in_channels, hidden_channels: int, hidden_heads: int, out_channels: int, out_heads: int, num_layers: int, dropout: float=0.0, pool_size: Optional[int]=None, buffer_size: Optional[int]=None, device=None):
super().__init__(num_nodes, (hidden_channe... |
class GCN(ScalableGNN):
def __init__(self, num_nodes: int, in_channels, hidden_channels: int, out_channels: int, num_layers: int, dropout: float=0.0, drop_input: bool=True, batch_norm: bool=False, residual: bool=False, linear: bool=False, pool_size: Optional[int]=None, buffer_size: Optional[int]=None, device=Non... |
class GCN2(ScalableGNN):
def __init__(self, num_nodes: int, in_channels, hidden_channels: int, out_channels: int, num_layers: int, alpha: float, theta: float, shared_weights: bool=True, dropout: float=0.0, drop_input: bool=True, batch_norm: bool=False, residual: bool=False, pool_size: Optional[int]=None, buffer_... |
class PNAConv(MessagePassing):
def __init__(self, in_channels: int, out_channels: int, aggregators: List[str], scalers: List[str], deg: Tensor, **kwargs):
super().__init__(aggr=None, **kwargs)
self.in_channels = in_channels
self.out_channels = out_channels
self.aggregators = aggre... |
class PNA(ScalableGNN):
def __init__(self, num_nodes: int, in_channels: int, hidden_channels: int, out_channels: int, num_layers: int, aggregators: List[int], scalers: List[int], deg: Tensor, dropout: float=0.0, drop_input: bool=True, batch_norm: bool=False, residual: bool=False, pool_size: Optional[int]=None, b... |
class PNA_JK(ScalableGNN):
def __init__(self, num_nodes: int, in_channels: int, hidden_channels: int, out_channels: int, num_layers: int, aggregators: List[int], scalers: List[int], deg: Tensor, dropout: float=0.0, drop_input: bool=True, batch_norm: bool=False, residual: bool=False, pool_size: Optional[int]=None... |
class AsyncIOPool(torch.nn.Module):
def __init__(self, pool_size: int, buffer_size: int, embedding_dim: int):
super().__init__()
self.pool_size = pool_size
self.buffer_size = buffer_size
self.embedding_dim = embedding_dim
self._device = torch.device('cpu')
self._pu... |
def index2mask(idx: Tensor, size: int) -> Tensor:
mask = torch.zeros(size, dtype=torch.bool, device=idx.device)
mask[idx] = True
return mask
|
def compute_micro_f1(logits: Tensor, y: Tensor, mask: Optional[Tensor]=None) -> float:
if (mask is not None):
(logits, y) = (logits[mask], y[mask])
if (y.dim() == 1):
return (int(logits.argmax(dim=(- 1)).eq(y).sum()) / y.size(0))
else:
y_pred = (logits > 0)
y_true = (y > 0.... |
def gen_masks(y: Tensor, train_per_class: int=20, val_per_class: int=30, num_splits: int=20) -> Tuple[(Tensor, Tensor, Tensor)]:
num_classes = (int(y.max()) + 1)
train_mask = torch.zeros(y.size(0), num_splits, dtype=torch.bool)
val_mask = torch.zeros(y.size(0), num_splits, dtype=torch.bool)
for c in r... |
def dropout(adj_t: SparseTensor, p: float, training: bool=True):
if ((not training) or (p == 0.0)):
return adj_t
if (adj_t.storage.value() is not None):
value = F.dropout(adj_t.storage.value(), p=p)
adj_t = adj_t.set_value(value, layout='coo')
else:
mask = (torch.rand(adj_t... |
def train(epoch):
model.train()
total_loss = 0
for data in train_loader:
data = data.to(device)
optimizer.zero_grad()
loss = (model(data).squeeze() - data.y).abs().mean()
loss.backward()
total_loss += (loss.item() * data.num_graphs)
optimizer.step()
retu... |
@torch.no_grad()
def test(loader):
model.eval()
total_error = 0
for data in loader:
data = data.to(device)
total_error += (model(data).squeeze() - data.y).abs().sum().item()
return (total_error / len(loader.dataset))
|
def train(epoch):
model.train()
total_loss = 0
for data in train_loader:
data = data.to(device)
optimizer.zero_grad()
loss = (model(data).squeeze() - data.y).abs().mean()
loss.backward()
total_loss += (loss.item() * data.num_graphs)
optimizer.step()
retu... |
@torch.no_grad()
def test(loader):
model.eval()
total_error = 0
for data in loader:
data = data.to(device)
total_error += (model(data).squeeze() - data.y).abs().sum().item()
return (total_error / len(loader.dataset))
|
def get_extensions():
extensions = []
extensions_dir = osp.join('csrc')
main_files = glob.glob(osp.join(extensions_dir, '*.cpp'))
main_files = [path for path in main_files if ('hip' not in path)]
for (main, suffix) in product(main_files, suffices):
define_macros = [('WITH_PYTHON', None)]
... |
@torch.jit.script
def fps2(x: Tensor, ratio: Tensor) -> Tensor:
return fps(x, None, ratio, False)
|
@pytest.mark.parametrize('dtype,device', product(grad_dtypes, devices))
def test_fps(dtype, device):
x = tensor([[(- 1), (- 1)], [(- 1), (+ 1)], [(+ 1), (+ 1)], [(+ 1), (- 1)], [(- 2), (- 2)], [(- 2), (+ 2)], [(+ 2), (+ 2)], [(+ 2), (- 2)]], dtype, device)
batch = tensor([0, 0, 0, 0, 1, 1, 1, 1], torch.long, ... |
@pytest.mark.parametrize('device', devices)
def test_random_fps(device):
N = 1024
for _ in range(5):
pos = torch.randn(((2 * N), 3), device=device)
batch_1 = torch.zeros(N, dtype=torch.long, device=device)
batch_2 = torch.ones(N, dtype=torch.long, device=device)
batch = torch.c... |
def assert_correct(row, col, cluster):
(row, col, cluster) = (row.to('cpu'), col.to('cpu'), cluster.to('cpu'))
n = cluster.size(0)
assert (cluster.min() >= 0)
(_, index) = torch.unique(cluster, return_inverse=True)
count = torch.zeros_like(cluster)
count.scatter_add_(0, index, torch.ones_like(... |
@pytest.mark.parametrize('test,dtype,device', product(tests, dtypes, devices))
def test_graclus_cluster(test, dtype, device):
if ((dtype == torch.bfloat16) and (device == torch.device('cuda:0'))):
return
row = tensor(test['row'], torch.long, device)
col = tensor(test['col'], torch.long, device)
... |
@pytest.mark.parametrize('test,dtype,device', product(tests, dtypes, devices))
def test_grid_cluster(test, dtype, device):
if ((dtype == torch.bfloat16) and (device == torch.device('cuda:0'))):
return
pos = tensor(test['pos'], dtype, device)
size = tensor(test['size'], dtype, device)
start = t... |
def to_set(edge_index):
return set([(i, j) for (i, j) in edge_index.t().tolist()])
|
@pytest.mark.parametrize('dtype,device', product(grad_dtypes, devices))
def test_knn(dtype, device):
x = tensor([[(- 1), (- 1)], [(- 1), (+ 1)], [(+ 1), (+ 1)], [(+ 1), (- 1)], [(- 1), (- 1)], [(- 1), (+ 1)], [(+ 1), (+ 1)], [(+ 1), (- 1)]], dtype, device)
y = tensor([[1, 0], [(- 1), 0]], dtype, device)
b... |
@pytest.mark.parametrize('dtype,device', product(grad_dtypes, devices))
def test_knn_graph(dtype, device):
x = tensor([[(- 1), (- 1)], [(- 1), (+ 1)], [(+ 1), (+ 1)], [(+ 1), (- 1)]], dtype, device)
edge_index = knn_graph(x, k=2, flow='target_to_source')
assert (to_set(edge_index) == set([(0, 1), (0, 3), ... |
@pytest.mark.parametrize('dtype,device', product([torch.float], devices))
def test_knn_graph_large(dtype, device):
x = torch.randn(1000, 3, dtype=dtype, device=device)
edge_index = knn_graph(x, k=5, flow='target_to_source', loop=True)
tree = scipy.spatial.cKDTree(x.cpu().numpy())
(_, col) = tree.query... |
@pytest.mark.parametrize('dtype,device', product(grad_dtypes, devices))
def test_nearest(dtype, device):
x = tensor([[(- 1), (- 1)], [(- 1), (+ 1)], [(+ 1), (+ 1)], [(+ 1), (- 1)], [(- 2), (- 2)], [(- 2), (+ 2)], [(+ 2), (+ 2)], [(+ 2), (- 2)]], dtype, device)
y = tensor([[(- 1), 0], [(+ 1), 0], [(- 2), 0], [... |
def to_set(edge_index):
return set([(i, j) for (i, j) in edge_index.t().tolist()])
|
@pytest.mark.parametrize('dtype,device', product(grad_dtypes, devices))
def test_radius(dtype, device):
x = tensor([[(- 1), (- 1)], [(- 1), (+ 1)], [(+ 1), (+ 1)], [(+ 1), (- 1)], [(- 1), (- 1)], [(- 1), (+ 1)], [(+ 1), (+ 1)], [(+ 1), (- 1)]], dtype, device)
y = tensor([[0, 0], [0, 1]], dtype, device)
ba... |
@pytest.mark.parametrize('dtype,device', product(grad_dtypes, devices))
def test_radius_graph(dtype, device):
x = tensor([[(- 1), (- 1)], [(- 1), (+ 1)], [(+ 1), (+ 1)], [(+ 1), (- 1)]], dtype, device)
edge_index = radius_graph(x, r=2.5, flow='target_to_source')
assert (to_set(edge_index) == set([(0, 1), ... |
@pytest.mark.parametrize('dtype,device', product([torch.float], devices))
def test_radius_graph_large(dtype, device):
x = torch.randn(1000, 3, dtype=dtype, device=device)
edge_index = radius_graph(x, r=0.5, flow='target_to_source', loop=True, max_num_neighbors=2000)
tree = scipy.spatial.cKDTree(x.cpu().nu... |
def test_neighbor_sampler():
torch.manual_seed(1234)
start = torch.tensor([0, 1])
cumdeg = torch.tensor([0, 3, 7])
e_id = neighbor_sampler(start, cumdeg, size=1.0)
assert (e_id.tolist() == [0, 2, 1, 5, 6, 3, 4])
e_id = neighbor_sampler(start, cumdeg, size=3)
assert (e_id.tolist() == [1, 0,... |
@torch.jit._overload
def fps(src, batch, ratio, random_start, batch_size, ptr):
pass
|
def graclus_cluster(row: torch.Tensor, col: torch.Tensor, weight: Optional[torch.Tensor]=None, num_nodes: Optional[int]=None) -> torch.Tensor:
'A greedy clustering algorithm of picking an unmarked vertex and matching\n it with one its unmarked neighbors (that maximizes its edge weight).\n\n Args:\n r... |
def grid_cluster(pos: torch.Tensor, size: torch.Tensor, start: Optional[torch.Tensor]=None, end: Optional[torch.Tensor]=None) -> torch.Tensor:
'A clustering algorithm, which overlays a regular grid of user-defined\n size over a point cloud and clusters all points within a voxel.\n\n Args:\n pos (Tens... |
def knn(x: torch.Tensor, y: torch.Tensor, k: int, batch_x: Optional[torch.Tensor]=None, batch_y: Optional[torch.Tensor]=None, cosine: bool=False, num_workers: int=1, batch_size: Optional[int]=None) -> torch.Tensor:
'Finds for each element in :obj:`y` the :obj:`k` nearest points in\n :obj:`x`.\n\n Args:\n ... |
def knn_graph(x: torch.Tensor, k: int, batch: Optional[torch.Tensor]=None, loop: bool=False, flow: str='source_to_target', cosine: bool=False, num_workers: int=1, batch_size: Optional[int]=None) -> torch.Tensor:
'Computes graph edges to the nearest :obj:`k` points.\n\n Args:\n x (Tensor): Node feature m... |
def nearest(x: torch.Tensor, y: torch.Tensor, batch_x: Optional[torch.Tensor]=None, batch_y: Optional[torch.Tensor]=None) -> torch.Tensor:
'Clusters points in :obj:`x` together which are nearest to a given query\n point in :obj:`y`.\n\n Args:\n x (Tensor): Node feature matrix\n :math:`\\ma... |
def radius(x: torch.Tensor, y: torch.Tensor, r: float, batch_x: Optional[torch.Tensor]=None, batch_y: Optional[torch.Tensor]=None, max_num_neighbors: int=32, num_workers: int=1, batch_size: Optional[int]=None) -> torch.Tensor:
'Finds for each element in :obj:`y` all points in :obj:`x` within\n distance :obj:`r... |
def radius_graph(x: torch.Tensor, r: float, batch: Optional[torch.Tensor]=None, loop: bool=False, max_num_neighbors: int=32, flow: str='source_to_target', num_workers: int=1, batch_size: Optional[int]=None) -> torch.Tensor:
'Computes graph edges to all points within a given distance.\n\n Args:\n x (Tens... |
def random_walk(row: Tensor, col: Tensor, start: Tensor, walk_length: int, p: float=1, q: float=1, coalesced: bool=True, num_nodes: Optional[int]=None, return_edge_indices: bool=False) -> Union[(Tensor, Tuple[(Tensor, Tensor)])]:
'Samples random walks of length :obj:`walk_length` from all node indices\n in :ob... |
def neighbor_sampler(start: torch.Tensor, rowptr: torch.Tensor, size: float):
assert (not start.is_cuda)
factor: float = (- 1.0)
count: int = (- 1)
if (size <= 1):
factor = size
assert (factor > 0)
else:
count = int(size)
return torch.ops.torch_cluster.neighbor_sampler(... |
def tensor(x: Any, dtype: torch.dtype, device: torch.device):
return (None if (x is None) else torch.tensor(x, dtype=dtype, device=device))
|
def get_extensions():
extensions = []
extensions_dir = osp.join('csrc')
main_files = glob.glob(osp.join(extensions_dir, '*.cpp'))
main_files = [path for path in main_files if ('hip' not in path)]
for (main, suffix) in product(main_files, suffices):
define_macros = []
undef_macros =... |
@pytest.mark.parametrize('test,dtype,device', product(tests, dtypes, devices))
def test_spline_basis_forward(test, dtype, device):
if ((dtype == torch.bfloat16) and (device == torch.device('cuda:0'))):
return
pseudo = tensor(test['pseudo'], dtype, device)
kernel_size = tensor(test['kernel_size'], ... |
@pytest.mark.parametrize('test,dtype,device', product(tests, dtypes, devices))
def test_spline_conv_forward(test, dtype, device):
if ((dtype == torch.bfloat16) and (device == torch.device('cuda:0'))):
return
x = tensor(test['x'], dtype, device)
edge_index = tensor(test['edge_index'], torch.long, d... |
@pytest.mark.parametrize('degree,device', product(degrees, devices))
def test_spline_conv_backward(degree, device):
x = torch.rand((3, 2), dtype=torch.double, device=device)
x.requires_grad_()
edge_index = tensor([[0, 1, 1, 2], [1, 0, 2, 1]], torch.long, device)
pseudo = torch.rand((4, 3), dtype=torch... |
@pytest.mark.parametrize('test,dtype,device', product(tests, dtypes, devices))
def test_spline_weighting_forward(test, dtype, device):
if ((dtype == torch.bfloat16) and (device == torch.device('cuda:0'))):
return
x = tensor(test['x'], dtype, device)
weight = tensor(test['weight'], dtype, device)
... |
@pytest.mark.parametrize('device', devices)
def test_spline_weighting_backward(device):
pseudo = torch.rand((4, 2), dtype=torch.double, device=device)
kernel_size = tensor([5, 5], torch.long, device)
is_open_spline = tensor([1, 1], torch.uint8, device)
degree = 1
(basis, weight_index) = spline_bas... |
def spline_basis(pseudo: torch.Tensor, kernel_size: torch.Tensor, is_open_spline: torch.Tensor, degree: int) -> Tuple[(torch.Tensor, torch.Tensor)]:
return torch.ops.torch_spline_conv.spline_basis(pseudo, kernel_size, is_open_spline, degree)
|
def spline_conv(x: torch.Tensor, edge_index: torch.Tensor, pseudo: torch.Tensor, weight: torch.Tensor, kernel_size: torch.Tensor, is_open_spline: torch.Tensor, degree: int=1, norm: bool=True, root_weight: Optional[torch.Tensor]=None, bias: Optional[torch.Tensor]=None) -> torch.Tensor:
'Applies the spline-based co... |
def tensor(x: Any, dtype: torch.dtype, device: torch.device):
return (None if (x is None) else torch.tensor(x, dtype=dtype, device=device))
|
def spline_weighting(x: torch.Tensor, weight: torch.Tensor, basis: torch.Tensor, weight_index: torch.Tensor) -> torch.Tensor:
return torch.ops.torch_spline_conv.spline_weighting(x, weight, basis, weight_index)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.