| 1 |
import time |
| 2 |
import os.path as osp |
| 3 |
import itertools |
| 4 |
|
| 5 |
import argparse |
| 6 |
import wget |
| 7 |
import torch |
| 8 |
from scipy.io import loadmat |
| 9 |
|
| 10 |
from torch_scatter import scatter, segment_coo, segment_csr |
| 11 |
|
| 12 |
short_rows = [ |
| 13 |
('DIMACS10', 'citationCiteseer'), |
| 14 |
('SNAP', 'web-Stanford'), |
| 15 |
] |
| 16 |
long_rows = [ |
| 17 |
('Janna', 'StocF-1465'), |
| 18 |
('GHS_psdef', 'ldoor'), |
| 19 |
] |
| 20 |
|
| 21 |
|
| 22 |
def download(dataset): |
| 23 |
url = 'https://sparse.tamu.edu/mat/{}/{}.mat' |
| 24 |
for group, name in itertools.chain(long_rows, short_rows): |
| 25 |
if not osp.exists(f'{name}.mat'): |
| 26 |
print(f'Downloading {group}/{name}:') |
| 27 |
wget.download(url.format(group, name)) |
| 28 |
print('') |
| 29 |
|
| 30 |
|
| 31 |
def bold(text, flag=True): |
| 32 |
return f'\033[1m{text}\033[0m' if flag else text |
| 33 |
|
| 34 |
|
| 35 |
@torch.no_grad() |
| 36 |
def correctness(dataset): |
| 37 |
group, name = dataset |
| 38 |
mat = loadmat(f'{name}.mat')['Problem'][0][0][2].tocsr() |
| 39 |
rowptr = torch.from_numpy(mat.indptr).to(args.device, torch.long) |
| 40 |
row = torch.from_numpy(mat.tocoo().row).to(args.device, torch.long) |
| 41 |
dim_size = rowptr.size(0) - 1 |
| 42 |
|
| 43 |
for size in sizes: |
| 44 |
try: |
| 45 |
x = torch.randn((row.size(0), size), device=args.device) |
| 46 |
x = x.squeeze(-1) if size == 1 else x |
| 47 |
|
| 48 |
out1 = scatter(x, row, dim=0, dim_size=dim_size, reduce='add') |
| 49 |
out2 = segment_coo(x, row, dim_size=dim_size, reduce='add') |
| 50 |
out3 = segment_csr(x, rowptr, reduce='add') |
| 51 |
|
| 52 |
assert torch.allclose(out1, out2, atol=1e-4) |
| 53 |
assert torch.allclose(out1, out3, atol=1e-4) |
| 54 |
|
| 55 |
out1 = scatter(x, row, dim=0, dim_size=dim_size, reduce='mean') |
| 56 |
out2 = segment_coo(x, row, dim_size=dim_size, reduce='mean') |
| 57 |
out3 = segment_csr(x, rowptr, reduce='mean') |
| 58 |
|
| 59 |
assert torch.allclose(out1, out2, atol=1e-4) |
| 60 |
assert torch.allclose(out1, out3, atol=1e-4) |
| 61 |
|
| 62 |
out1 = scatter(x, row, dim=0, dim_size=dim_size, reduce='min') |
| 63 |
out2 = segment_coo(x, row, reduce='min') |
| 64 |
out3 = segment_csr(x, rowptr, reduce='min') |
| 65 |
|
| 66 |
assert torch.allclose(out1, out2, atol=1e-4) |
| 67 |
assert torch.allclose(out1, out3, atol=1e-4) |
| 68 |
|
| 69 |
out1 = scatter(x, row, dim=0, dim_size=dim_size, reduce='max') |
| 70 |
out2 = segment_coo(x, row, reduce='max') |
| 71 |
out3 = segment_csr(x, rowptr, reduce='max') |
| 72 |
|
| 73 |
assert torch.allclose(out1, out2, atol=1e-4) |
| 74 |
assert torch.allclose(out1, out3, atol=1e-4) |
| 75 |
|
| 76 |
except RuntimeError as e: |
| 77 |
if 'out of memory' not in str(e): |
| 78 |
raise RuntimeError(e) |
| 79 |
torch.cuda.empty_cache() |
| 80 |
|
| 81 |
|
| 82 |
def time_func(func, x): |
| 83 |
try: |
| 84 |
if torch.cuda.is_available(): |
| 85 |
torch.cuda.synchronize() |
| 86 |
t = time.perf_counter() |
| 87 |
|
| 88 |
if not args.with_backward: |
| 89 |
with torch.no_grad(): |
| 90 |
for _ in range(iters): |
| 91 |
func(x) |
| 92 |
else: |
| 93 |
x = x.requires_grad_() |
| 94 |
for _ in range(iters): |
| 95 |
out = func(x) |
| 96 |
out = out[0] if isinstance(out, tuple) else out |
| 97 |
torch.autograd.grad(out, x, out, only_inputs=True) |
| 98 |
|
| 99 |
if torch.cuda.is_available(): |
| 100 |
torch.cuda.synchronize() |
| 101 |
return time.perf_counter() - t |
| 102 |
except RuntimeError as e: |
| 103 |
if 'out of memory' not in str(e): |
| 104 |
raise RuntimeError(e) |
| 105 |
torch.cuda.empty_cache() |
| 106 |
return float('inf') |
| 107 |
|
| 108 |
|
| 109 |
def timing(dataset): |
| 110 |
group, name = dataset |
| 111 |
mat = loadmat(f'{name}.mat')['Problem'][0][0][2].tocsr() |
| 112 |
rowptr = torch.from_numpy(mat.indptr).to(args.device, torch.long) |
| 113 |
row = torch.from_numpy(mat.tocoo().row).to(args.device, torch.long) |
| 114 |
row2 = row[torch.randperm(row.size(0))] |
| 115 |
dim_size = rowptr.size(0) - 1 |
| 116 |
avg_row_len = row.size(0) / dim_size |
| 117 |
|
| 118 |
def sca1_row(x): |
| 119 |
out = x.new_zeros(dim_size, *x.size()[1:]) |
| 120 |
row_tmp = row.view(-1, 1).expand_as(x) if x.dim() > 1 else row |
| 121 |
return out.scatter_add_(0, row_tmp, x) |
| 122 |
|
| 123 |
def sca1_col(x): |
| 124 |
out = x.new_zeros(dim_size, *x.size()[1:]) |
| 125 |
row2_tmp = row2.view(-1, 1).expand_as(x) if x.dim() > 1 else row2 |
| 126 |
return out.scatter_add_(0, row2_tmp, x) |
| 127 |
|
| 128 |
def sca2_row(x): |
| 129 |
return scatter(x, row, dim=0, dim_size=dim_size, reduce=args.reduce) |
| 130 |
|
| 131 |
def sca2_col(x): |
| 132 |
return scatter(x, row2, dim=0, dim_size=dim_size, reduce=args.reduce) |
| 133 |
|
| 134 |
def seg_coo(x): |
| 135 |
return segment_coo(x, row, reduce=args.reduce) |
| 136 |
|
| 137 |
def seg_csr(x): |
| 138 |
return segment_csr(x, rowptr, reduce=args.reduce) |
| 139 |
|
| 140 |
def dense1(x): |
| 141 |
return getattr(torch, args.reduce)(x, dim=-2) |
| 142 |
|
| 143 |
def dense2(x): |
| 144 |
return getattr(torch, args.reduce)(x, dim=-1) |
| 145 |
|
| 146 |
t1, t2, t3, t4, t5, t6, t7, t8 = [], [], [], [], [], [], [], [] |
| 147 |
|
| 148 |
for size in sizes: |
| 149 |
try: |
| 150 |
x = torch.randn((row.size(0), size), device=args.device) |
| 151 |
x = x.squeeze(-1) if size == 1 else x |
| 152 |
|
| 153 |
t1 += [time_func(sca1_row, x)] |
| 154 |
t2 += [time_func(sca1_col, x)] |
| 155 |
t3 += [time_func(sca2_row, x)] |
| 156 |
t4 += [time_func(sca2_col, x)] |
| 157 |
t5 += [time_func(seg_coo, x)] |
| 158 |
t6 += [time_func(seg_csr, x)] |
| 159 |
|
| 160 |
del x |
| 161 |
|
| 162 |
except RuntimeError as e: |
| 163 |
if 'out of memory' not in str(e): |
| 164 |
raise RuntimeError(e) |
| 165 |
torch.cuda.empty_cache() |
| 166 |
for t in (t1, t2, t3, t4, t5, t6): |
| 167 |
t.append(float('inf')) |
| 168 |
|
| 169 |
try: |
| 170 |
x = torch.randn((dim_size, int(avg_row_len + 1), size), |
| 171 |
device=args.device) |
| 172 |
|
| 173 |
t7 += [time_func(dense1, x)] |
| 174 |
x = x.view(dim_size, size, int(avg_row_len + 1)) |
| 175 |
t8 += [time_func(dense2, x)] |
| 176 |
|
| 177 |
del x |
| 178 |
|
| 179 |
except RuntimeError as e: |
| 180 |
if 'out of memory' not in str(e): |
| 181 |
raise RuntimeError(e) |
| 182 |
torch.cuda.empty_cache() |
| 183 |
for t in (t7, t8): |
| 184 |
t.append(float('inf')) |
| 185 |
|
| 186 |
ts = torch.tensor([t1, t2, t3, t4, t5, t6, t7, t8]) |
| 187 |
winner = torch.zeros_like(ts, dtype=torch.bool) |
| 188 |
winner[ts.argmin(dim=0), torch.arange(len(sizes))] = 1 |
| 189 |
winner = winner.tolist() |
| 190 |
|
| 191 |
name = f'{group}/{name}' |
| 192 |
print(f'{bold(name)} (avg row length: {avg_row_len:.2f}):') |
| 193 |
print('\t'.join([' '] + [f'{size:>5}' for size in sizes])) |
| 194 |
print('\t'.join([bold('SCA1_ROW')] + |
| 195 |
[bold(f'{t:.5f}', f) for t, f in zip(t1, winner[0])])) |
| 196 |
print('\t'.join([bold('SCA1_COL')] + |
| 197 |
[bold(f'{t:.5f}', f) for t, f in zip(t2, winner[1])])) |
| 198 |
print('\t'.join([bold('SCA2_ROW')] + |
| 199 |
[bold(f'{t:.5f}', f) for t, f in zip(t3, winner[2])])) |
| 200 |
print('\t'.join([bold('SCA2_COL')] + |
| 201 |
[bold(f'{t:.5f}', f) for t, f in zip(t4, winner[3])])) |
| 202 |
print('\t'.join([bold('SEG_COO ')] + |
| 203 |
[bold(f'{t:.5f}', f) for t, f in zip(t5, winner[4])])) |
| 204 |
print('\t'.join([bold('SEG_CSR ')] + |
| 205 |
[bold(f'{t:.5f}', f) for t, f in zip(t6, winner[5])])) |
| 206 |
print('\t'.join([bold('DENSE1 ')] + |
| 207 |
[bold(f'{t:.5f}', f) for t, f in zip(t7, winner[6])])) |
| 208 |
print('\t'.join([bold('DENSE2 ')] + |
| 209 |
[bold(f'{t:.5f}', f) for t, f in zip(t8, winner[7])])) |
| 210 |
print() |
| 211 |
|
| 212 |
|
| 213 |
if __name__ == '__main__': |
| 214 |
parser = argparse.ArgumentParser() |
| 215 |
parser.add_argument('--reduce', type=str, required=True, |
| 216 |
choices=['sum', 'mean', 'min', 'max']) |
| 217 |
parser.add_argument('--with_backward', action='store_true') |
| 218 |
parser.add_argument('--device', type=str, default='cuda') |
| 219 |
args = parser.parse_args() |
| 220 |
iters = 1 if args.device == 'cpu' else 20 |
| 221 |
sizes = [1, 16, 32, 64, 128, 256, 512] |
| 222 |
sizes = sizes[:3] if args.device == 'cpu' else sizes |
| 223 |
|
| 224 |
for _ in range(10): # Warmup. |
| 225 |
torch.randn(100, 100, device=args.device).sum() |
| 226 |
for dataset in itertools.chain(short_rows, long_rows): |
| 227 |
download(dataset) |
| 228 |
correctness(dataset) |
| 229 |
timing(dataset) |