code
stringlengths
17
6.64M
class ELMClassifier(ELMRegressor): '\n ELMClassifier is a classifier based on the Extreme Learning Machine.\n\n An Extreme Learning Machine (ELM) is a single layer feedforward\n network with a random hidden layer components and ordinary linear\n least squares fitting of the hidden->output weights by d...
def eval_batch_mlp(mlp, data, batch_idxs, criterion, device_id=0): ' evaluate a batch for the baseline mlp ' atom_types = to_one_hot(data['features']['atom_types'][(batch_idxs, ...)], NUM_ATOM_TYPES) targets = data['targets'][(batch_idxs, ...)] atom_types = Variable(atom_types) targets = Variable(...
def eval_batch_s2cnn(mlp, s2cnn, data, batch_idxs, criterion, device_id=0): ' evaluate a batch for the s2cnn ' geometry = data['features']['geometry'][(batch_idxs, ...)] atom_types = data['features']['atom_types'][(batch_idxs, ...)] atom_types_one_hot = to_one_hot(atom_types, NUM_ATOM_TYPES) targe...
def train_baseline(mlp, data, train_batches, test_batches, num_epochs, learning_rate_mlp, device_id=0): ' train the baseline model ' optim = OPTIMIZER(mlp.parameters(), lr=learning_rate_mlp) criterion = nn.MSELoss() if torch.cuda.is_available(): criterion = criterion.cuda(device_id) for ep...
def train_s2cnn(mlp, s2cnn, data, train_batches, test_batches, num_epochs, init_learning_rate_s2cnn, learning_rate_decay_epochs, device_id=0): ' train the s2cnn keeping the baseline frozen ' optim = OPTIMIZER(s2cnn.parameters(), lr=init_learning_rate_s2cnn) criterion = nn.MSELoss() if torch.cuda.is_av...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--data_path', type=str, default='data.joblib') parser.add_argument('--test_strat', type=int, default=0) parser.add_argument('--device_id', type=int, default=0) parser.add_argument('--num_epochs_s2cnn', type=int, default=30) pa...
class S2Block(nn.Module): ' simple s2 convolution block ' def __init__(self, b_in, b_out, f_in, f_out): ' b_in/b_out: bandwidth of input/output signals\n f_in/f_out: filters in input/output signals ' super(S2Block, self).__init__() self.grid_s2 = s2_near_identity_grid(n_alp...
class So3Block(nn.Module): ' simple so3 convolution block ' def __init__(self, b_in, b_out, f_in, f_out): ' b_in/b_out: bandwidth of input/output signals\n f_in/f_out: filters in input/output signals ' super(So3Block, self).__init__() self.grid_so3 = so3_near_identity_grid(...
class DeepSet(nn.Module): ' deep set block ' def __init__(self, f, h1, h_latent, h2, n_objs): ' f: input filters\n h1, h2: hidden units for encoder/decoder mlps\n h_latent: dimensions\n n_objs: of objects to aggregate in latent space ' super(Dee...
class S2CNNRegressor(nn.Module): ' approximate energy using spherical representations ' def __init__(self): super(S2CNNRegressor, self).__init__() n_objs = 23 self.blocks = [S2Block(b_in=10, f_in=5, b_out=8, f_out=8), So3Block(b_in=8, b_out=6, f_in=8, f_out=16), So3Block(b_in=6, b_out...
class IndexBatcher(): def __init__(self, indices, n_batch, cuda=None): self.indices = indices.astype(np.int64) self.n_batch = n_batch self.pos = 0 self.cuda = cuda self.internal_indices = np.arange(len(indices)).astype(np.int64) np.random.shuffle(self.internal_indi...
def to_one_hot(x, n): x_ = torch.unsqueeze(x, 2) dims = (*x.size(), n) one_hot = torch.FloatTensor(*dims).zero_() one_hot.scatter_(2, x_, 1) return one_hot
def load_data(path, test_strat_id=None, cuda=None): '\n Loads the data\n\n path: path to the molecule .gz\n batch_size: size of a mini batch\n test_strat_id: id of strat being used as test set\n ' data = joblib.load(path) type_remap = (- np.ones((int(data['feature...
def exp_lr_scheduler(optimizer, epoch, init_lr=0.005, lr_decay_epoch=40): 'Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs.' lr = (init_lr * (0.1 ** (epoch // lr_decay_epoch))) if ((epoch % lr_decay_epoch) == 0): print('LR is set to {}'.format(lr)) for param_group in opt...
def count_params(model): return sum([np.prod(p.size()) for p in model.parameters() if p.requires_grad])
class Model(nn.Module): def __init__(self, nclasses): super().__init__() self.features = [6, 100, 100, nclasses] self.bandwidths = [64, 16, 10] assert (len(self.bandwidths) == (len(self.features) - 1)) sequence = [] grid = s2_equatorial_grid(max_beta=0, n_alpha=(2 ...
class Model(nn.Module): def __init__(self, nclasses): super().__init__() self.features = [6, 50, 70, 350, nclasses] self.bandwidths = [128, 32, 22, 7] assert (len(self.bandwidths) == (len(self.features) - 1)) sequence = [] grid = s2_equatorial_grid(max_beta=0, n_al...
class KeepName(): def __init__(self, transform): self.transform = transform def __call__(self, file_name): return (file_name, self.transform(file_name))
def main(log_dir, augmentation, dataset, batch_size, num_workers): print(check_output(['nodejs', '--version']).decode('utf-8')) torch.backends.cudnn.benchmark = True transform = torchvision.transforms.Compose([CacheNPY(prefix='b64_', repeat=augmentation, pick_randomly=False, transform=torchvision.transfor...
def main(log_dir, model_path, augmentation, dataset, batch_size, learning_rate, num_workers): arguments = copy.deepcopy(locals()) os.mkdir(log_dir) shutil.copy2(__file__, os.path.join(log_dir, 'script.py')) shutil.copy2(model_path, os.path.join(log_dir, 'model.py')) logger = logging.getLogger('tra...
def s2_near_identity_grid(max_beta=(np.pi / 8), n_alpha=8, n_beta=3): '\n :return: rings around the north pole\n size of the kernel = n_alpha * n_beta\n ' beta = ((np.arange(start=1, stop=(n_beta + 1), dtype=np.float) * max_beta) / n_beta) alpha = np.linspace(start=0, stop=(2 * np.pi), num=n_alph...
def s2_equatorial_grid(max_beta=0, n_alpha=32, n_beta=1): '\n :return: rings around the equator\n size of the kernel = n_alpha * n_beta\n ' beta = np.linspace(start=((np.pi / 2) - max_beta), stop=((np.pi / 2) + max_beta), num=n_beta, endpoint=True) alpha = np.linspace(start=0, stop=(2 * np.pi), n...
def s2_soft_grid(b): beta = (((np.arange((2 * b)) + 0.5) / (2 * b)) * np.pi) alpha = np.linspace(start=0, stop=(2 * np.pi), num=(2 * b), endpoint=False) (B, A) = np.meshgrid(beta, alpha, indexing='ij') B = B.flatten() A = A.flatten() grid = np.stack((B, A), axis=1) return tuple((tuple(ba) ...
def s2_mm(x, y): '\n :param x: [l * m, batch, feature_in, complex]\n :param y: [l * m, feature_in, feature_out, complex]\n :return: [l * m * n, batch, feature_out, complex]\n ' from s2cnn.utils.complex import complex_mm assert (y.size(3) == 2) assert (x.size(3) == 2) ...
class _cuda_S2_mm(torch.autograd.Function): @staticmethod def forward(ctx, x, y): ctx.save_for_backward(x, y) return _cuda_s2_mm(x, y) @staticmethod def backward(ctx, gradz): import s2cnn.utils.cuda as cuda_utils (x, y) = ctx.saved_tensors nl = round((x.size(0...
def _cuda_s2_mm(x, y): '\n :param x: [l * m, batch, feature_in, complex]\n :param y: [l * m, feature_in, feature_out, complex]\n :return: [l * m * n, batch, feature_out, complex]\n ' import s2cnn.utils.cuda as cuda_utils assert (x.is_cuda and (x.dtype == torch.float32)) ...
@lru_cache(maxsize=32) def _setup_s2mm_cuda_kernel(nbatch, nspec, nfeature_in, nfeature_out, device=0): kernel = Template('\n#define COMPUTE_LMN(s) int l = powf(3.0/4.0 * s, 1.0/3.0) - 0.5; int L = l * (4 * l * l - 1) / 3; int rest = s - L; if (rest >= (2 * l + 1) * (2 * l + 1)) { ++l; ...
@lru_cache(maxsize=32) def _setup_s2mm_gradx_cuda_kernel(nbatch, nspec, nl, nfeature_in, nfeature_out, device=0): kernel = Template('\n#define COMPUTE_LM(s) int l = sqrtf(s); int L = (4 * l * l - 1) * l / 3; int m = s - l * l - l;\n\n#define EXTRACT(i1, i2, n2, i3, n3) int i1 = index; int i3 =...
@lru_cache(maxsize=32) def _setup_s2mm_grady_cuda_kernel(nbatch, nspec, nl, nfeature_in, nfeature_out, device=0): kernel = Template('\n#define COMPUTE_LM(s) int l = powf(s, 0.5); int L = (4 * l * l - 1) * l / 3; int m = s - l * l - l;\n\n#define EXTRACT(i1, i2, n2, i3, n3) int i1 = index; int ...
def test_compare_cuda_cpu(): x = torch.rand((((1 + 3) + 5) + 7), 2, 3, 2) y = torch.rand((((1 + 3) + 5) + 7), 3, 5, 2) z1 = s2_mm(x, y) z2 = s2_mm(x.cuda(), y.cuda()).cpu() q = ((z1 - z2).abs().max().item() / z1.std().item()) print(q) assert (q < 0.0001)
def so3_rft(x, b, grid): '\n Real Fourier Transform\n :param x: [..., beta_alpha_gamma]\n :param b: output bandwidth signal\n :param grid: tuple of (beta, alpha, gamma) tuples\n :return: [l * m * n, ..., complex]\n ' F = _setup_so3_ft(b, grid, device_type=x.device.type, device_index=x.device...
@cached_dirpklgz('cache/setup_so3_ft') def __setup_so3_ft(b, grid): from lie_learn.representations.SO3.wigner_d import wigner_D_matrix n_spatial = len(grid) n_spectral = np.sum([(((2 * l) + 1) ** 2) for l in range(b)]) F = np.zeros((n_spatial, n_spectral), dtype=complex) for (i, (beta, alpha, gamm...
@lru_cache(maxsize=32) def _setup_so3_ft(b, grid, device_type, device_index): F = __setup_so3_ft(b, grid) F = torch.tensor(F.astype(np.float32), dtype=torch.float32, device=torch.device(device_type, device_index)) return F
def so3_mm(x, y): '\n :param x: [l * m * n, batch, feature_in, complex]\n :param y: [l * m * n, feature_in, feature_out, complex]\n :return: [l * m * n, batch, feature_out, complex]\n ' from s2cnn.utils.complex import complex_mm import math assert (y.size(3) == 2) assert (x...
class _cuda_SO3_mm(torch.autograd.Function): @staticmethod def forward(ctx, x, y): '\n :param x: [l * m * n, batch, feature_in, complex]\n :param y: [l * m * n, feature_in, feature_out, complex]\n :return: [l * m * n, batch, feature_out, complex]\n ' as...
@lru_cache(maxsize=32) def _setup_so3mm_cuda_kernel(nl, ni, nj, nk, conj_x=False, conj_y=False, trans_x_spec=False, trans_x_feature=False, trans_y_spec=False, trans_y_feature=False, trans_out_feature=False, device=0): '\n return a function that computes\n out[l*m*n, i, j] = sum_k sum_p x[l*m*p, i, k] y[...
def test_compare_cuda_cpu(): x = torch.rand((((1 + 9) + 25) + 49), 2, 3, 2) y = torch.rand((((1 + 9) + 25) + 49), 3, 5, 2) z1 = so3_mm(x, y) z2 = so3_mm(x.cuda(), y.cuda()).cpu() q = ((z1 - z2).abs().max().item() / z1.std().item()) print(q) assert (q < 0.0001)
class S2Convolution(Module): def __init__(self, nfeature_in, nfeature_out, b_in, b_out, grid): "\n :param nfeature_in: number of input fearures\n :param nfeature_out: number of output features\n :param b_in: input bandwidth (precision of the input SOFT grid)\n :param b_out: ou...
class SO3Convolution(Module): def __init__(self, nfeature_in, nfeature_out, b_in, b_out, grid): "\n :param nfeature_in: number of input fearures\n :param nfeature_out: number of output features\n :param b_in: input bandwidth (precision of the input SOFT grid)\n :param b_out: o...
class SO3Shortcut(Module): '\n Useful for ResNet\n ' def __init__(self, nfeature_in, nfeature_out, b_in, b_out): super(SO3Shortcut, self).__init__() assert (b_out <= b_in) if ((nfeature_in != nfeature_out) or (b_in != b_out)): self.conv = SO3Convolution(nfeature_in=n...
def so3_integrate(x): '\n Integrate a signal on SO(3) using the Haar measure\n \n :param x: [..., beta, alpha, gamma] (..., 2b, 2b, 2b)\n :return y: [...] (...)\n ' assert (x.size((- 1)) == x.size((- 2))) assert (x.size((- 2)) == x.size((- 3))) b = (x.size((- 1)) // 2) w = _setup_so...
@lru_cache(maxsize=32) @show_running def _setup_so3_integrate(b, device_type, device_index): import lie_learn.spaces.S3 as S3 return torch.tensor(S3.quadrature_weights(b), dtype=torch.float32, device=torch.device(device_type, device_index))
def so3_rotation(x, alpha, beta, gamma): '\n :param x: [..., beta, alpha, gamma] (..., 2b, 2b, 2b)\n ' b = (x.size()[(- 1)] // 2) x_size = x.size() Us = _setup_so3_rotation(b, alpha, beta, gamma, device_type=x.device.type, device_index=x.device.index) x = SO3_fft_real.apply(x) Fz_list = ...
@cached_dirpklgz('cache/setup_so3_rotation') def __setup_so3_rotation(b, alpha, beta, gamma): from lie_learn.representations.SO3.wigner_d import wigner_D_matrix Us = [wigner_D_matrix(l, alpha, beta, gamma, field='complex', normalization='quantum', order='centered', condon_shortley='cs') for l in range(b)] ...
@lru_cache(maxsize=32) def _setup_so3_rotation(b, alpha, beta, gamma, device_type, device_index): Us = __setup_so3_rotation(b, alpha, beta, gamma) Us = [torch.tensor(U, dtype=torch.float32, device=torch.device(device_type, device_index)) for U in Us] return Us
def get_blocks(n, num_threads): n_per_instance = (((n + (num_threads * CUDA_MAX_GRID_DIM)) - 1) // (num_threads * CUDA_MAX_GRID_DIM)) return (((n + (num_threads * n_per_instance)) - 1) // (num_threads * n_per_instance))
def compile_kernel(kernel, filename, functioname): program = Program(kernel, filename) ptx = program.compile() m = function.Module() m.load(bytes(ptx.encode())) f = m.get_function(functioname) return f
class WaitPrint(threading.Thread): def __init__(self, t, message): super().__init__() self.t = t self.message = message self.running = True def stop(self): self.running = False def run(self): for _ in range(int((self.t // 0.1))): time.sleep(0....
def show_running(func): @wraps(func) def g(*args, **kargs): x = WaitPrint(2, '{}({})... '.format(func.__name__, ', '.join(([repr(x) for x in args] + ['{}={}'.format(key, repr(value)) for (key, value) in kargs.items()])))) x.start() t = time.perf_counter() r = func(*args, **kar...
def cached_dirpklgz(dirname): '\n Cache a function with a directory\n ' def decorator(func): '\n The actual decorator\n ' @lru_cache(maxsize=None) @wraps(func) def wrapper(*args): '\n The wrapper of the function\n ' ...
def test_so3_rfft(b_in, b_out, device): x = torch.randn((2 * b_in), (2 * b_in), (2 * b_in), dtype=torch.float, device=device) from s2cnn.soft.so3_fft import so3_rfft y1 = so3_rfft(x, b_out=b_out) from s2cnn import so3_rft, so3_soft_grid import lie_learn.spaces.S3 as S3 weights = torch.tensor(S...
def test_inverse(f, g, b_in, b_out, device, complex): if complex: x = torch.randn((2 * b_in), (2 * b_in), (2 * b_in), 2, dtype=torch.float, device=device) else: x = torch.randn((2 * b_in), (2 * b_in), (2 * b_in), dtype=torch.float, device=device) x = g(f(x, b_out=b_out), b_out=b_in) y ...
def test_inverse2(f, g, b_in, b_out, device): x = torch.randn(((b_in * ((4 * (b_in ** 2)) - 1)) // 3), 2, dtype=torch.float, device=device) x = g(f(x, b_out=b_out), b_out=b_in) y = g(f(x, b_out=b_out), b_out=b_in) assert ((x - y).abs().max().item() < (0.0001 * y.abs().mean().item()))
def compare_cpu_gpu(f, x): z1 = f(x.cpu()) z2 = f(x.cuda()).cpu() q = ((z1 - z2).abs().max().item() / z1.std().item()) assert (q < 0.0001)
def eval_batch_mlp(mlp, data, batch_idxs, criterion, device_id=0): ' evaluate a batch for the baseline mlp ' atom_types = to_one_hot(data['features']['atom_types'][(batch_idxs, ...)], NUM_ATOM_TYPES) targets = data['targets'][(batch_idxs, ...)] atom_types = Variable(atom_types) targets = Variable(...
def eval_batch_s2cnn(mlp, s2cnn, data, batch_idxs, criterion, device_id=0): ' evaluate a batch for the s2cnn ' geometry = data['features']['geometry'][(batch_idxs, ...)] atom_types = data['features']['atom_types'][(batch_idxs, ...)] atom_types_one_hot = to_one_hot(atom_types, NUM_ATOM_TYPES) targe...
def train_baseline(mlp, data, train_batches, test_batches, num_epochs, learning_rate_mlp, device_id=0): ' train the baseline model ' optim = OPTIMIZER(mlp.parameters(), lr=learning_rate_mlp) criterion = nn.MSELoss() if torch.cuda.is_available(): criterion = criterion.cuda(device_id) for ep...
def train_s2cnn(mlp, s2cnn, data, train_batches, test_batches, num_epochs, init_learning_rate_s2cnn, learning_rate_decay_epochs, device_id=0): ' train the s2cnn keeping the baseline frozen ' optim = OPTIMIZER(s2cnn.parameters(), lr=init_learning_rate_s2cnn) criterion = nn.MSELoss() if torch.cuda.is_av...
def main(): parser = argparse.ArgumentParser() parser.add_argument('--data_path', type=str, default='data.joblib') parser.add_argument('--test_strat', type=int, default=0) parser.add_argument('--device_id', type=int, default=0) parser.add_argument('--num_epochs_s2cnn', type=int, default=30) pa...
class S2Block(nn.Module): ' simple s2 convolution block ' def __init__(self, b_in, b_out, f_in, f_out): ' b_in/b_out: bandwidth of input/output signals\n f_in/f_out: filters in input/output signals ' super(S2Block, self).__init__() self.grid_s2 = s2_near_identity_grid(n_alp...
class So3Block(nn.Module): ' simple so3 convolution block ' def __init__(self, b_in, b_out, f_in, f_out): ' b_in/b_out: bandwidth of input/output signals\n f_in/f_out: filters in input/output signals ' super(So3Block, self).__init__() self.grid_so3 = so3_near_identity_grid(...
class DeepSet(nn.Module): ' deep set block ' def __init__(self, f, h1, h_latent, h2, n_objs): ' f: input filters\n h1, h2: hidden units for encoder/decoder mlps\n h_latent: dimensions\n n_objs: of objects to aggregate in latent space ' super(Dee...
class S2CNNRegressor(nn.Module): ' approximate energy using spherical representations ' def __init__(self): super(S2CNNRegressor, self).__init__() n_objs = 23 self.blocks = [S2Block(b_in=10, f_in=5, b_out=8, f_out=8), So3Block(b_in=8, b_out=6, f_in=8, f_out=16), So3Block(b_in=6, b_out...
class IndexBatcher(): def __init__(self, indices, n_batch, cuda=None): self.indices = indices.astype(np.int64) self.n_batch = n_batch self.pos = 0 self.cuda = cuda self.internal_indices = np.arange(len(indices)).astype(np.int64) np.random.shuffle(self.internal_indi...
def to_one_hot(x, n): x_ = torch.unsqueeze(x, 2) dims = (*x.size(), n) one_hot = torch.FloatTensor(*dims).zero_() one_hot.scatter_(2, x_, 1) return one_hot
def load_data(path, test_strat_id=None, cuda=None): '\n Loads the data\n\n path: path to the molecule .gz\n batch_size: size of a mini batch\n test_strat_id: id of strat being used as test set\n ' data = joblib.load(path) type_remap = (- np.ones((int(data['feature...
def exp_lr_scheduler(optimizer, epoch, init_lr=0.005, lr_decay_epoch=40): 'Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs.' lr = (init_lr * (0.1 ** (epoch // lr_decay_epoch))) if ((epoch % lr_decay_epoch) == 0): print('LR is set to {}'.format(lr)) for param_group in opt...
def count_params(model): return sum([np.prod(p.size()) for p in model.parameters() if p.requires_grad])
class Model(nn.Module): def __init__(self, nclasses): super().__init__() self.features = [6, 100, 100, nclasses] self.bandwidths = [64, 16, 10] assert (len(self.bandwidths) == (len(self.features) - 1)) sequence = [] grid = s2_equatorial_grid(max_beta=0, n_alpha=(2 ...
class Model(nn.Module): def __init__(self, nclasses): super().__init__() self.features = [6, 50, 70, 350, nclasses] self.bandwidths = [128, 32, 22, 7] assert (len(self.bandwidths) == (len(self.features) - 1)) sequence = [] grid = s2_equatorial_grid(max_beta=0, n_al...
class KeepName(): def __init__(self, transform): self.transform = transform def __call__(self, file_name): return (file_name, self.transform(file_name))
def main(log_dir, augmentation, dataset, batch_size, num_workers): print(check_output(['nodejs', '--version']).decode('utf-8')) torch.backends.cudnn.benchmark = True transform = torchvision.transforms.Compose([CacheNPY(prefix='b64_', repeat=augmentation, pick_randomly=False, transform=torchvision.transfor...
def main(log_dir, model_path, augmentation, dataset, batch_size, learning_rate, num_workers): arguments = copy.deepcopy(locals()) os.mkdir(log_dir) shutil.copy2(__file__, os.path.join(log_dir, 'script.py')) shutil.copy2(model_path, os.path.join(log_dir, 'model.py')) logger = logging.getLogger('tra...
def s2_near_identity_grid(max_beta=(np.pi / 8), n_alpha=8, n_beta=3): '\n :return: rings around the north pole\n size of the kernel = n_alpha * n_beta\n ' beta = ((np.arange(start=1, stop=(n_beta + 1), dtype=np.float) * max_beta) / n_beta) alpha = np.linspace(start=0, stop=(2 * np.pi), num=n_alph...
def s2_equatorial_grid(max_beta=0, n_alpha=32, n_beta=1): '\n :return: rings around the equator\n size of the kernel = n_alpha * n_beta\n ' beta = np.linspace(start=((np.pi / 2) - max_beta), stop=((np.pi / 2) + max_beta), num=n_beta, endpoint=True) alpha = np.linspace(start=0, stop=(2 * np.pi), n...
def s2_soft_grid(b): beta = (((np.arange((2 * b)) + 0.5) / (2 * b)) * np.pi) alpha = np.linspace(start=0, stop=(2 * np.pi), num=(2 * b), endpoint=False) (B, A) = np.meshgrid(beta, alpha, indexing='ij') B = B.flatten() A = A.flatten() grid = np.stack((B, A), axis=1) return tuple((tuple(ba) ...
def s2_mm(x, y): '\n :param x: [l * m, batch, feature_in, complex]\n :param y: [l * m, feature_in, feature_out, complex]\n :return: [l * m * n, batch, feature_out, complex]\n ' from s2cnn.utils.complex import complex_mm assert (y.size(3) == 2) assert (x.size(3) == 2) ...
class _cuda_S2_mm(torch.autograd.Function): @staticmethod def forward(ctx, x, y): ctx.save_for_backward(x, y) return _cuda_s2_mm(x, y) @staticmethod def backward(ctx, gradz): import s2cnn.utils.cuda as cuda_utils (x, y) = ctx.saved_tensors nl = round((x.size(0...
def _cuda_s2_mm(x, y): '\n :param x: [l * m, batch, feature_in, complex]\n :param y: [l * m, feature_in, feature_out, complex]\n :return: [l * m * n, batch, feature_out, complex]\n ' import s2cnn.utils.cuda as cuda_utils assert (x.is_cuda and (x.dtype == torch.float32)) ...
@lru_cache(maxsize=32) def _setup_s2mm_cuda_kernel(nbatch, nspec, nfeature_in, nfeature_out, device=0): kernel = Template('\n#define COMPUTE_LMN(s) int l = powf(3.0/4.0 * s, 1.0/3.0) - 0.5; int L = l * (4 * l * l - 1) / 3; int rest = s - L; if (rest >= (2 * l + 1) * (2 * l + 1)) { ++l; ...
@lru_cache(maxsize=32) def _setup_s2mm_gradx_cuda_kernel(nbatch, nspec, nl, nfeature_in, nfeature_out, device=0): kernel = Template('\n#define COMPUTE_LM(s) int l = sqrtf(s); int L = (4 * l * l - 1) * l / 3; int m = s - l * l - l;\n\n#define EXTRACT(i1, i2, n2, i3, n3) int i1 = index; int i3 =...
@lru_cache(maxsize=32) def _setup_s2mm_grady_cuda_kernel(nbatch, nspec, nl, nfeature_in, nfeature_out, device=0): kernel = Template('\n#define COMPUTE_LM(s) int l = powf(s, 0.5); int L = (4 * l * l - 1) * l / 3; int m = s - l * l - l;\n\n#define EXTRACT(i1, i2, n2, i3, n3) int i1 = index; int ...
def test_compare_cuda_cpu(): x = torch.rand((((1 + 3) + 5) + 7), 2, 3, 2) y = torch.rand((((1 + 3) + 5) + 7), 3, 5, 2) z1 = s2_mm(x, y) z2 = s2_mm(x.cuda(), y.cuda()).cpu() q = ((z1 - z2).abs().max().item() / z1.std().item()) print(q) assert (q < 0.0001)
def so3_rft(x, b, grid): '\n Real Fourier Transform\n :param x: [..., beta_alpha_gamma]\n :param b: output bandwidth signal\n :param grid: tuple of (beta, alpha, gamma) tuples\n :return: [l * m * n, ..., complex]\n ' F = _setup_so3_ft(b, grid, device_type=x.device.type, device_index=x.device...
@cached_dirpklgz('cache/setup_so3_ft') def __setup_so3_ft(b, grid): from lie_learn.representations.SO3.wigner_d import wigner_D_matrix n_spatial = len(grid) n_spectral = np.sum([(((2 * l) + 1) ** 2) for l in range(b)]) F = np.zeros((n_spatial, n_spectral), dtype=complex) for (i, (beta, alpha, gamm...
@lru_cache(maxsize=32) def _setup_so3_ft(b, grid, device_type, device_index): F = __setup_so3_ft(b, grid) F = torch.tensor(F.astype(np.float32), dtype=torch.float32, device=torch.device(device_type, device_index)) return F
def so3_mm(x, y): '\n :param x: [l * m * n, batch, feature_in, complex]\n :param y: [l * m * n, feature_in, feature_out, complex]\n :return: [l * m * n, batch, feature_out, complex]\n ' from s2cnn.utils.complex import complex_mm import math assert (y.size(3) == 2) assert (x...
class _cuda_SO3_mm(torch.autograd.Function): @staticmethod def forward(ctx, x, y): '\n :param x: [l * m * n, batch, feature_in, complex]\n :param y: [l * m * n, feature_in, feature_out, complex]\n :return: [l * m * n, batch, feature_out, complex]\n ' as...
@lru_cache(maxsize=32) def _setup_so3mm_cuda_kernel(nl, ni, nj, nk, conj_x=False, conj_y=False, trans_x_spec=False, trans_x_feature=False, trans_y_spec=False, trans_y_feature=False, trans_out_feature=False, device=0): '\n return a function that computes\n out[l*m*n, i, j] = sum_k sum_p x[l*m*p, i, k] y[...
def test_compare_cuda_cpu(): x = torch.rand((((1 + 9) + 25) + 49), 2, 3, 2) y = torch.rand((((1 + 9) + 25) + 49), 3, 5, 2) z1 = so3_mm(x, y) z2 = so3_mm(x.cuda(), y.cuda()).cpu() q = ((z1 - z2).abs().max().item() / z1.std().item()) print(q) assert (q < 0.0001)
class S2Convolution(Module): def __init__(self, nfeature_in, nfeature_out, b_in, b_out, grid): "\n :param nfeature_in: number of input fearures\n :param nfeature_out: number of output features\n :param b_in: input bandwidth (precision of the input SOFT grid)\n :param b_out: ou...
class SO3Convolution(Module): def __init__(self, nfeature_in, nfeature_out, b_in, b_out, grid): "\n :param nfeature_in: number of input fearures\n :param nfeature_out: number of output features\n :param b_in: input bandwidth (precision of the input SOFT grid)\n :param b_out: o...
class SO3Shortcut(Module): '\n Useful for ResNet\n ' def __init__(self, nfeature_in, nfeature_out, b_in, b_out): super(SO3Shortcut, self).__init__() assert (b_out <= b_in) if ((nfeature_in != nfeature_out) or (b_in != b_out)): self.conv = SO3Convolution(nfeature_in=n...
def so3_integrate(x): '\n Integrate a signal on SO(3) using the Haar measure\n \n :param x: [..., beta, alpha, gamma] (..., 2b, 2b, 2b)\n :return y: [...] (...)\n ' assert (x.size((- 1)) == x.size((- 2))) assert (x.size((- 2)) == x.size((- 3))) b = (x.size((- 1)) // 2) w = _setup_so...
@lru_cache(maxsize=32) @show_running def _setup_so3_integrate(b, device_type, device_index): import lie_learn.spaces.S3 as S3 return torch.tensor(S3.quadrature_weights(b), dtype=torch.float32, device=torch.device(device_type, device_index))
def so3_rotation(x, alpha, beta, gamma): '\n :param x: [..., beta, alpha, gamma] (..., 2b, 2b, 2b)\n ' b = (x.size()[(- 1)] // 2) x_size = x.size() Us = _setup_so3_rotation(b, alpha, beta, gamma, device_type=x.device.type, device_index=x.device.index) x = SO3_fft_real.apply(x) Fz_list = ...
@cached_dirpklgz('cache/setup_so3_rotation') def __setup_so3_rotation(b, alpha, beta, gamma): from lie_learn.representations.SO3.wigner_d import wigner_D_matrix Us = [wigner_D_matrix(l, alpha, beta, gamma, field='complex', normalization='quantum', order='centered', condon_shortley='cs') for l in range(b)] ...
@lru_cache(maxsize=32) def _setup_so3_rotation(b, alpha, beta, gamma, device_type, device_index): Us = __setup_so3_rotation(b, alpha, beta, gamma) Us = [torch.tensor(U, dtype=torch.float32, device=torch.device(device_type, device_index)) for U in Us] return Us
def get_blocks(n, num_threads): n_per_instance = (((n + (num_threads * CUDA_MAX_GRID_DIM)) - 1) // (num_threads * CUDA_MAX_GRID_DIM)) return (((n + (num_threads * n_per_instance)) - 1) // (num_threads * n_per_instance))
def compile_kernel(kernel, filename, functioname): program = Program(kernel, filename) ptx = program.compile() m = function.Module() m.load(bytes(ptx.encode())) f = m.get_function(functioname) return f