code stringlengths 17 6.64M |
|---|
def _resnet(arch, block, layers, pretrained, progress, **kwargs):
model = ResNet(block, layers, **kwargs)
if pretrained:
state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
model.load_state_dict(state_dict)
return model
|
def resnet18(pretrained=False, progress=True, **kwargs):
'Constructs a ResNet-18 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n '
return _resnet('resnet18', BasicBlock, [... |
def resnet34(pretrained=False, progress=True, **kwargs):
'Constructs a ResNet-34 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n '
return _resnet('resnet34', BasicBlock, [... |
def resnet50(pretrained=False, progress=True, **kwargs):
'Constructs a ResNet-50 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n '
return _resnet('resnet50', Bottleneck, [... |
def resnet101(pretrained=False, progress=True, **kwargs):
'Constructs a ResNet-101 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n '
return _resnet('resnet101', Bottleneck... |
def resnet152(pretrained=False, progress=True, **kwargs):
'Constructs a ResNet-152 model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n '
return _resnet('resnet152', Bottleneck... |
def resnext50_32x4d(pretrained=False, progress=True, **kwargs):
'Constructs a ResNeXt-50 32x4d model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n '
kwargs['groups'] = 32
... |
def resnext101_32x8d(pretrained=False, progress=True, **kwargs):
'Constructs a ResNeXt-101 32x8d model.\n\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n progress (bool): If True, displays a progress bar of the download to stderr\n '
kwargs['groups'] = 32
... |
def wide_resnet50_2(pretrained=False, progress=True, **kwargs):
'Constructs a Wide ResNet-50-2 model.\n\n The model is the same as ResNet except for the bottleneck number of channels\n which is twice larger in every block. The number of channels in outer 1x1\n convolutions is the same, e.g. last block in... |
def wide_resnet101_2(pretrained=False, progress=True, **kwargs):
'Constructs a Wide ResNet-101-2 model.\n\n The model is the same as ResNet except for the bottleneck number of channels\n which is twice larger in every block. The number of channels in outer 1x1\n convolutions is the same, e.g. last block ... |
class VGGLike(nn.Module):
def __init__(self, n_classes):
super(VGGLike, self).__init__()
self.features = nn.Sequential(nn.Conv2d(1, 32, (3, 3)), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(32, 32, (3, 3)), nn.BatchNorm2d(32), nn.ReLU(inplace=True), nn.Conv2d(32, 32, (3, 3)), nn.BatchNorm... |
def parse_config(config_file: str) -> Dict:
with open(config_file, 'r') as fd:
cfg = yaml.load(fd, yaml.FullLoader)
return cfg
|
def get_data_info(cfg: Dict, augment: Optional[bool]=True) -> Dict:
try:
print('[get_data_info]', cfg)
meta_root = cfg['meta_root']
train_manifest = cfg['train_manifest']
val_manifest = cfg['val_manifest']
label_map = cfg['label_map']
train_manifest = os.path.join(m... |
class OneCycleLR(Callback):
def __init__(self, max_lr, end_percentage=0.1, scale_percentage=None, maximum_momentum=0.95, minimum_momentum=0.85, verbose=True):
' This callback implements a cyclical learning rate policy (CLR).\n This is a special case of Cyclic Learning Rates, where we have only 1 c... |
class LRFinder(Callback):
def __init__(self, num_samples, batch_size, minimum_lr=1e-05, maximum_lr=10.0, lr_scale='exp', validation_data=None, validation_sample_rate=5, stopping_criterion_factor=4.0, loss_smoothing_beta=0.98, save_dir=None, verbose=True):
"\n This class uses the Cyclic Learning Ra... |
class CosineAnnealingScheduler(Callback):
'Cosine annealing scheduler.\n '
def __init__(self, T_max, eta_max, eta_min=0, verbose=0, epoch_start=80, restart_epochs=None, gamma=1, expansion=1, flat_end=False):
super(CosineAnnealingScheduler, self).__init__()
self.epoch_start = epoch_start
... |
class CyclicLR(Callback):
'This callback implements a cyclical learning rate policy (CLR).\n The method cycles the learning rate between two boundaries with\n some constant frequency, as detailed in this paper (https://arxiv.org/abs/1506.01186).\n The amplitude of the cycle can be scaled on a per-iterati... |
class LRFinder(Callback):
def __init__(self, num_samples, batch_size, minimum_lr=1e-05, maximum_lr=10.0, lr_scale='exp', validation_data=None, validation_sample_rate=5, stopping_criterion_factor=4.0, loss_smoothing_beta=0.98, save_dir=None, verbose=True):
"\n This class uses the Cyclic Learning Ra... |
class History(object):
'\n Custom class to help get log data from keras.callbacks.History objects.\n :param history: a ``keras.callbacks.History object`` or ``None``.\n '
def __init__(self, history=None):
if (history is not None):
self.epoch = history.epoch
self.histo... |
def concatenate_history(hlist, reindex_epoch=False):
'\n A helper function to concatenate training history object (``keras.callbacks.History``) into a single one, with a help ``History`` class.\n :param hlist: a list of ``keras.callbacks.History`` objects to concatenate.\n :param reindex_epoch: True or F... |
def plot_from_history(history):
"\n Plot losses in training history.\n :param history: a ``keras.callbacks.History`` or (this module's) ``History`` object.\n "
assert isinstance(history, (keras.callbacks.History, History)), "history must be a ``keras.callbacks.History`` or (this module's) ``History``... |
def save_history_to_csv(history, filepath):
'\n Save a training history into a csv file.\n :param history: a ``History`` callback instance from ``Model`` instance.\n :param filepath: a string filepath.\n '
hist = history.history
hist['epoch'] = history.epoch
df = pd.DataFrame.from_dict(his... |
def reset_keras(per_process_gpu_memory_fraction=1.0):
"\n Reset Keras session and set GPU configuration as well as collect unused memory.\n This is adapted from [jaycangel's post on fastai forum](https://forums.fast.ai/t/how-could-i-release-gpu-memory-of-keras/2023/18).\n Calling this before any training... |
def cuda_release_memory():
"\n Force cuda to release GPU memory by closing it.\n :return cuda: numba's cuda module.\n "
spec = importlib.util.find_spec('numba')
if (spec is None):
raise Exception("numba module cannot be found. Can't function before numba module is installed.")
else:
... |
def moving_window_avg(x, window=5):
'\n Return a moving-window average.\n :param x: a numpy array\n :param window: an integer, number of data points for window size.\n '
return pd.DataFrame(x).rolling(window=window, min_periods=1).mean().values.squeeze()
|
def set_momentum(optimizer, mom_val):
'\n Helper to set momentum of Keras optimizers.\n :param optimizer: Keras optimizer\n :param mom_val: value of momentum.\n '
keys = dir(optimizer)
if ('momentum' in keys):
K.set_value(optimizer.momentum, mom_val)
if ('rho' in keys):
K.s... |
def set_lr(optimizer, lr):
'\n Helper to set learning rate of Keras optimizers.\n :param optimizer: Keras optimizer\n :param lr: value of learning rate.\n '
K.set_value(optimizer.lr, lr)
|
def dot_product(x, kernel):
return tf.tensordot(x, kernel, axes=1)
|
class Attention(Layer):
def __init__(self, W_regularizer=None, b_regularizer=None, W_constraint=None, b_constraint=None, bias=True, return_attention=False, **kwargs):
'\n Keras Layer that implements an Attention mechanism for temporal data.\n Supports Masking.\n Follows the work of R... |
class LayerNormalization(Layer):
'\n Implementation of Layer Normalization (https://arxiv.org/abs/1607.06450).\n "Unlike batch normalization, layer normalization performs exactly\n the same computation at training and test times."\n '
def __init__(self, axis=(- 1), **kwargs):
self.axis = ... |
class FocalLoss(tf.keras.losses.Loss):
def __init__(self, gamma=2.0, alpha=4.0, name='focal_loss', reduction='auto'):
'Focal loss for multi-classification\n FL(p_t)=-alpha(1-p_t)^{gamma}ln(p_t)\n Notice: y_pred is probability after softmax\n gradient is d(Fl)/d(p_t) not d(Fl)/d(x) as... |
class LDAMLoss(tf.keras.losses.Loss):
def __init__(self, cls_num_list, max_m=0.5, weight=None, s=30, reduction=tf.keras.loses.Reduction.AUTO, name='LDAM'):
super().__init__(reduction=reduction, name=name)
m_list = (1.0 / np.sqrt(np.sqrt(cls_num_list)))
m_list *= max_m(m_list.max())
... |
class Lookahead(tf.keras.optimizers.Optimizer):
'This class allows to extend optimizers with the lookahead mechanism.\n The mechanism is proposed by Michael R. Zhang et.al in the paper\n [Lookahead Optimizer: k steps forward, 1 step back]\n (https://arxiv.org/abs/1907.08610v1). The optimizer iteratively ... |
class NovoGrad(tf.keras.optimizers.Optimizer):
'The NovoGrad Optimizer was first proposed in [Stochastic Gradient\n Methods with Layerwise Adaptvie Moments for training of Deep\n Networks](https://arxiv.org/pdf/1905.11286.pdf)\n NovoGrad is a first-order SGD-based algorithm, which computes second\n mo... |
def Ranger(sync_period=6, slow_step_size=0.5, learning_rate=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-07, weight_decay=0.0, amsgrad=False, sma_threshold=5.0, total_steps=0, warmup_proportion=0.1, min_lr=0.0, name='Ranger'):
'\n function returning a tf.keras.optimizers.Optimizer object\n returned o... |
class RectifiedAdam(tf.keras.optimizers.Optimizer):
'Variant of the Adam optimizer whose adaptive learning rate is rectified\n so as to have a consistent variance.\n It implements the Rectified Adam (a.k.a. RAdam) proposed by\n Liyuan Liu et al. in [On The Variance Of The Adaptive Learning Rate\n And ... |
class rec_optimizer(Optimizer):
def __init__(self, layers=2, nodes=20):
pass
|
def _solve(a, b, c):
'Return solution of a quadratic minimization.\n The optimization equation is:\n f(a, b, c) = argmin_w{1/2 * a * w^2 + b * w + c * |w|}\n we get optimal solution w*:\n w* = -(b - sign(b)*c)/a if |b| > c else w* = 0\n REQUIRES: Dimensionality of a and b must be same\n ... |
class Yogi(tf.keras.optimizers.Optimizer):
'Optimizer that implements the Yogi algorithm in Keras.\n See Algorithm 2 of\n https://papers.nips.cc/paper/8186-adaptive-methods-for-nonconvex-optimization.pdf.\n '
@typechecked
def __init__(self, learning_rate: Union[(FloatTensorLike, Callable)]=0.01,... |
def get_flops():
run_meta = tf.RunMetadata()
opts = tf.profiler.ProfileOptionBuilder.float_operation()
flops = tf.profiler.profile(graph=K.get_session().graph, run_meta=run_meta, cmd='op', options=opts)
return flops.total_float_ops
|
def attention_simple(inputs, timesteps):
input_dim = int(inputs.shape[(- 1)])
a = Permute((2, 1), name='transpose')(inputs)
a = Dense(timesteps, activation='softmax', name='attention_probs')(a)
a_probs = Permute((2, 1), name='attention_vec')(a)
output_attention_mul = Multiply(name='focused_attenti... |
def dense_model(timesteps, n_class, n_features, classifier_architecture, dropout):
inputs = Input((timesteps, n_features))
x = BatchNormalization(axis=1, momentum=0.99)(inputs)
x = Dense(128, activation=Mish())(x)
x = LayerNormalization()(x)
(x, a) = attention_simple(x, timesteps)
for (d, dr) ... |
class ContactGenerator(Sequence):
def __init__(self, pdb_id_list, features_path, distmap_path, dim, pad_size, batch_size, expected_n_channels):
self.pdb_id_list = pdb_id_list
self.features_path = features_path
self.dim = dim
self.pad_size = pad_size
self.distmap_path = dis... |
class BinnedDistGenerator(Sequence):
def __init__(self, pdb_id_list, features_path, distmap_path, bins, dim, pad_size, batch_size, expected_n_channels):
self.pdb_id_list = pdb_id_list
self.features_path = features_path
self.dim = dim
self.pad_size = pad_size
self.distmap_p... |
class DistGenerator(Sequence):
def __init__(self, pdb_id_list, features_path, distmap_path, dim, pad_size, batch_size, expected_n_channels, label_engineering=None):
self.pdb_id_list = pdb_id_list
self.features_path = features_path
self.distmap_path = distmap_path
self.dim = dim
... |
def inv_log_cosh(y_true, y_pred):
y_pred = ops.convert_to_tensor(y_pred)
y_true = math_ops.cast(y_true, y_pred.dtype)
def _logcosh(x):
return ((x + nn.softplus(((- 2.0) * x))) - math_ops.log(2.0))
return K.mean(_logcosh(((100.0 / (y_pred + epsilon)) - (100.0 / (y_true + epsilon)))), axis=(- 1... |
def basic_fcn(L, num_blocks, width, expected_n_channels):
input_shape = (L, L, expected_n_channels)
img_input = layers.Input(shape=input_shape)
x = img_input
for i in range(num_blocks):
x = layers.Conv2D(width, (3, 3), padding='same')(x)
x = layers.BatchNormalization()(x)
x = l... |
def deepcon_rdd(L, num_blocks, width, expected_n_channels):
print('')
print('Model params:')
print('L', L)
print('num_blocks', num_blocks)
print('width', width)
print('expected_n_channels', expected_n_channels)
print('')
dropout_value = 0.3
my_input = Input(shape=(L, L, expected_n_... |
def deepcon_rdd_distances(L, num_blocks, width, expected_n_channels):
print('')
print('Model params:')
print('L', L)
print('num_blocks', num_blocks)
print('width', width)
print('expected_n_channels', expected_n_channels)
print('')
dropout_value = 0.3
my_input = Input(shape=(L, L, e... |
def deepcon_rdd_binned(L, num_blocks, width, bins, expected_n_channels):
print('')
print('Model params:')
print('L', L)
print('num_blocks', num_blocks)
print('width', width)
print('expected_n_channels', expected_n_channels)
print('')
dropout_value = 0.3
my_input = Input(shape=(L, L... |
def load_satellite_data(path):
train_file = os.path.join(path, 'satellite_train.npy')
test_file = os.path.join(path, 'satellite_test.npy')
(all_train_data, all_train_labels) = (np.load(train_file, allow_pickle=True)[()]['data'], np.load(train_file, allow_pickle=True)[()]['label'])
(test_data, test_lab... |
class NeuralNet(nn.Module):
def __init__(self, input_size, hidden_size_1, hidden_size_2, num_classes):
super(NeuralNet, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size_1)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size_1, hidden_size_2)
self.fc3 = nn.L... |
def train(X, Y, X_validation, Y_validation, kernels, num_features, num_classes, minibatch_size=256, max_epochs=100, patience=2, tranche_size=(2 ** 11), cache_size=(2 ** 14)):
def init(layer):
if isinstance(layer, nn.Linear):
nn.init.constant_(layer.weight.data, 0)
nn.init.constant... |
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.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.