code
stringlengths
17
6.64M
class LeNet(nn.Module): def __init__(self): super(LeNet, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(((16 * 5) * 5), 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x)...
class Block(nn.Module): 'Depthwise conv + Pointwise conv' def __init__(self, in_planes, out_planes, stride=1): super(Block, self).__init__() self.conv1 = nn.Conv2d(in_planes, in_planes, kernel_size=3, stride=stride, padding=1, groups=in_planes, bias=False) self.bn1 = nn.BatchNorm2d(in...
class MobileNet(nn.Module): cfg = [64, (128, 2), 128, (256, 2), 256, (512, 2), 512, 512, 512, 512, 512, (1024, 2), 1024] def __init__(self, num_classes=10): super(MobileNet, self).__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.Ba...
def test(): net = MobileNet() x = torch.randn(1, 3, 32, 32) y = net(Variable(x)) print(y.size())
class Block(nn.Module): 'expand + depthwise + pointwise' def __init__(self, in_planes, out_planes, expansion, stride): super(Block, self).__init__() self.stride = stride planes = (expansion * in_planes) self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, stride=1, padding...
class MobileNetV2(nn.Module): cfg = [(1, 16, 1, 1), (6, 24, 2, 1), (6, 32, 3, 2), (6, 64, 4, 2), (6, 96, 3, 1), (6, 160, 3, 2), (6, 320, 1, 1)] def __init__(self, num_classes=10): super(MobileNetV2, self).__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1, bias=False)...
def test(): net = MobileNetV2() x = Variable(torch.randn(2, 3, 32, 32)) y = net(x) print(y.size())
class SepConv(nn.Module): 'Separable Convolution.' def __init__(self, in_planes, out_planes, kernel_size, stride): super(SepConv, self).__init__() self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding=((kernel_size - 1) // 2), bias=False, groups=in_planes) self.bn...
class CellA(nn.Module): def __init__(self, in_planes, out_planes, stride=1): super(CellA, self).__init__() self.stride = stride self.sep_conv1 = SepConv(in_planes, out_planes, kernel_size=7, stride=stride) if (stride == 2): self.conv1 = nn.Conv2d(in_planes, out_planes,...
class CellB(nn.Module): def __init__(self, in_planes, out_planes, stride=1): super(CellB, self).__init__() self.stride = stride self.sep_conv1 = SepConv(in_planes, out_planes, kernel_size=7, stride=stride) self.sep_conv2 = SepConv(in_planes, out_planes, kernel_size=3, stride=strid...
class PNASNet(nn.Module): def __init__(self, cell_type, num_cells, num_planes): super(PNASNet, self).__init__() self.in_planes = num_planes self.cell_type = cell_type self.conv1 = nn.Conv2d(3, num_planes, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchN...
def PNASNetA(): return PNASNet(CellA, num_cells=6, num_planes=44)
def PNASNetB(): return PNASNet(CellB, num_cells=6, num_planes=32)
def test(): net = PNASNetB() print(net) x = Variable(torch.randn(1, 3, 32, 32)) y = net(x) print(y)
class PreActBlock(nn.Module): 'Pre-activation version of the BasicBlock.' expansion = 1 def __init__(self, in_planes, planes, stride=1): super(PreActBlock, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride,...
class PreActBottleneck(nn.Module): 'Pre-activation version of the original Bottleneck module.' expansion = 4 def __init__(self, in_planes, planes, stride=1): super(PreActBottleneck, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.conv1 = nn.Conv2d(in_planes, planes, ker...
class PreActResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=10): super(PreActResNet, self).__init__() self.in_planes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) self.layer1 = self._make_layer(block, 64, num_blocks[0], str...
def PreActResNet18(): return PreActResNet(PreActBlock, [2, 2, 2, 2])
def PreActResNet34(): return PreActResNet(PreActBlock, [3, 4, 6, 3])
def PreActResNet50(): return PreActResNet(PreActBottleneck, [3, 4, 6, 3])
def PreActResNet101(): return PreActResNet(PreActBottleneck, [3, 4, 23, 3])
def PreActResNet152(): return PreActResNet(PreActBottleneck, [3, 8, 36, 3])
def test(): net = PreActResNet18() y = net(Variable(torch.randn(1, 3, 32, 32))) print(y.size())
class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2...
class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_planes, planes, stride=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_s...
class ResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=10): super(ResNet, self).__init__() self.in_planes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(64) self.layer1 = self._make_layer(blo...
def ResNet18(num_classes=10): return ResNet(BasicBlock, [2, 2, 2, 2], num_classes=num_classes)
def ResNet34(): return ResNet(BasicBlock, [3, 4, 6, 3])
def ResNet50(): return ResNet(Bottleneck, [3, 4, 6, 3])
def ResNet101(): return ResNet(Bottleneck, [3, 4, 23, 3])
def ResNet152(): return ResNet(Bottleneck, [3, 8, 36, 3])
def test(): net = ResNet18() y = net(Variable(torch.randn(1, 3, 32, 32))) print(y.size())
class Block(nn.Module): 'Grouped convolution block.' expansion = 2 def __init__(self, in_planes, cardinality=32, bottleneck_width=4, stride=1): super(Block, self).__init__() group_width = (cardinality * bottleneck_width) self.conv1 = nn.Conv2d(in_planes, group_width, kernel_size=1...
class ResNeXt(nn.Module): def __init__(self, num_blocks, cardinality, bottleneck_width, num_classes=10): super(ResNeXt, self).__init__() self.cardinality = cardinality self.bottleneck_width = bottleneck_width self.in_planes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=1,...
def ResNeXt29_2x64d(): return ResNeXt(num_blocks=[3, 3, 3], cardinality=2, bottleneck_width=64)
def ResNeXt29_4x64d(): return ResNeXt(num_blocks=[3, 3, 3], cardinality=4, bottleneck_width=64)
def ResNeXt29_8x64d(): return ResNeXt(num_blocks=[3, 3, 3], cardinality=8, bottleneck_width=64)
def ResNeXt29_32x4d(): return ResNeXt(num_blocks=[3, 3, 3], cardinality=32, bottleneck_width=4)
def test_resnext(): net = ResNeXt29_2x64d() x = torch.randn(1, 3, 32, 32) y = net(Variable(x)) print(y.size())
class BasicBlock(nn.Module): def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, ...
class PreActBlock(nn.Module): def __init__(self, in_planes, planes, stride=1): super(PreActBlock, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) ...
class SENet(nn.Module): def __init__(self, block, num_blocks, num_classes=10): super(SENet, self).__init__() self.in_planes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(64) self.layer1 = self._make_layer(block...
def SENet18(): return SENet(PreActBlock, [2, 2, 2, 2])
def test(): net = SENet18() y = net(Variable(torch.randn(1, 3, 32, 32))) print(y.size())
class ShuffleBlock(nn.Module): def __init__(self, groups): super(ShuffleBlock, self).__init__() self.groups = groups def forward(self, x): 'Channel shuffle: [N,C,H,W] -> [N,g,C/g,H,W] -> [N,C/g,g,H,w] -> [N,C,H,W]' (N, C, H, W) = x.size() g = self.groups retur...
class Bottleneck(nn.Module): def __init__(self, in_planes, out_planes, stride, groups): super(Bottleneck, self).__init__() self.stride = stride mid_planes = (out_planes / 4) g = (1 if (in_planes == 24) else groups) self.conv1 = nn.Conv2d(in_planes, mid_planes, kernel_size=...
class ShuffleNet(nn.Module): def __init__(self, cfg): super(ShuffleNet, self).__init__() out_planes = cfg['out_planes'] num_blocks = cfg['num_blocks'] groups = cfg['groups'] self.conv1 = nn.Conv2d(3, 24, kernel_size=1, bias=False) self.bn1 = nn.BatchNorm2d(24) ...
def ShuffleNetG2(): cfg = {'out_planes': [200, 400, 800], 'num_blocks': [4, 8, 4], 'groups': 2} return ShuffleNet(cfg)
def ShuffleNetG3(): cfg = {'out_planes': [240, 480, 960], 'num_blocks': [4, 8, 4], 'groups': 3} return ShuffleNet(cfg)
def test(): net = ShuffleNetG2() x = Variable(torch.randn(1, 3, 32, 32)) y = net(x) print(y)
class VGG(nn.Module): def __init__(self, vgg_name): super(VGG, self).__init__() self.features = self._make_layers(cfg[vgg_name]) self.classifier = nn.Linear(512, 10) def forward(self, x): out = self.features(x) out = out.view(out.size(0), (- 1)) out = self.cla...
def get_process_ros(node_name, doprint=False): node_api = rosnode.get_api_uri(rospy.get_master(), node_name, skip_cache=True)[2] if (not node_api): rospy.logwarn(('could not get api of node %s (%s)' % (node_name, node_api))) return False try: response = ServerProxy(node_api).getPid...
def get_process_name(process_name, doprint=False): processes = [] for proc in psutil.process_iter(): (name, exe, cmdline) = ('', '', []) try: name = proc.name() cmdline = proc.cmdline() exe = proc.exe() except (psutil.AccessDenied, psutil.ZombieProce...
def launch_setup(context): config_path = LaunchConfiguration('config_path').perform(context) if (not config_path): configs_dir = os.path.join(get_package_share_directory('ov_msckf'), 'config') available_configs = os.listdir(configs_dir) config = LaunchConfiguration('config').perform(co...
def generate_launch_description(): opfunc = OpaqueFunction(function=launch_setup) ld = LaunchDescription(launch_args) ld.add_action(opfunc) return ld
def complex_flatten(real, imag): real = tf.keras.layers.Flatten()(real) imag = tf.keras.layers.Flatten()(imag) return (real, imag)
def CReLU(real, imag): real = tf.keras.layers.ReLU()(real) imag = tf.keras.layers.ReLU()(imag) return (real, imag)
def zReLU(real, imag): real = tf.keras.layers.ReLU()(real) imag = tf.keras.layers.ReLU()(imag) real_flag = tf.cast(tf.cast(real, tf.bool), tf.float32) imag_flag = tf.cast(tf.cast(imag, tf.bool), tf.float32) flag = (real_flag * imag_flag) real = tf.math.multiply(real, flag) imag = tf.math.m...
def modReLU(real, imag): norm = tf.abs(tf.complex(real, imag)) bias = tf.Variable(np.zeros([norm.get_shape()[(- 1)]]), trainable=True, dtype=tf.float32) relu = tf.nn.relu((norm + bias)) real = tf.math.multiply(((relu / norm) + 100000.0), real) imag = tf.math.multiply(((relu / norm) + 100000.0), im...
def CLeaky_ReLU(real, imag): real = tf.nn.leaky_relu(real) imag = tf.nn.leaky_relu(imag) return (real, imag)
def complex_tanh(real, imag): real = tf.nn.tanh(real) imag = tf.nn.tanh(imag) return (real, imag)
def complex_softmax(real, imag): magnitude = tf.abs(tf.complex(real, imag)) magnitude = tf.keras.layers.Softmax()(magnitude) return magnitude
def get_planetoid_dataset(name, normalize_features=False, transform=None, split='public'): path = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', name) if (split == 'complete'): dataset = Planetoid(path, name) dataset[0].train_mask.fill_(False) dataset[0].train_mask[:(datas...
class Net_orig(torch.nn.Module): def __init__(self, dataset): super(Net2, self).__init__() self.conv1 = GCNConv(dataset.num_features, args.hidden) self.conv2 = GCNConv(args.hidden, dataset.num_classes) def reset_parameters(self): self.conv1.reset_parameters() self.con...
class CRD(torch.nn.Module): def __init__(self, d_in, d_out, p): super(CRD, self).__init__() self.conv = GCNConv(d_in, d_out, cached=True) self.p = p def reset_parameters(self): self.conv.reset_parameters() def forward(self, x, edge_index, mask=None): x = F.relu(s...
class CLS(torch.nn.Module): def __init__(self, d_in, d_out): super(CLS, self).__init__() self.conv = GCNConv(d_in, d_out, cached=True) def reset_parameters(self): self.conv.reset_parameters() def forward(self, x, edge_index, mask=None): x = self.conv(x, edge_index) ...
class Net(torch.nn.Module): def __init__(self, dataset): super(Net, self).__init__() self.crd = CRD(dataset.num_features, args.hidden, args.dropout) self.cls = CLS(args.hidden, dataset.num_classes) def reset_parameters(self): self.crd.reset_parameters() self.cls.reset...
def run(dataset, model, str_optimizer, str_preconditioner, runs, epochs, lr, weight_decay, early_stopping, logger, momentum, eps, update_freq, gamma, alpha, hyperparam): if (logger is not None): if hyperparam: logger += f'-{hyperparam}{eval(hyperparam)}' path_logger = os.path.join(path...
def train(model, optimizer, data, preconditioner=None, lam=0.0): model.train() optimizer.zero_grad() out = model(data) label = out.max(1)[1] label[data.train_mask] = data.y[data.train_mask] label.requires_grad = False loss = F.nll_loss(out[data.train_mask], label[data.train_mask]) loss...
def evaluate(model, data): model.eval() with torch.no_grad(): logits = model(data) outs = {} for key in ['train', 'val', 'test']: mask = data['{}_mask'.format(key)] loss = F.nll_loss(logits[mask], data.y[mask]).item() pred = logits[mask].max(1)[1] acc = (pred.eq...
class Txt2ImgIterableBaseDataset(IterableDataset): '\n Define an interface to make the IterableDatasets for text2img data chainable\n ' def __init__(self, num_records=0, valid_ids=None, size=256): super().__init__() self.num_records = num_records self.valid_ids = valid_ids ...
def synset2idx(path_to_yaml='data/index_synset.yaml'): with open(path_to_yaml) as f: di2s = yaml.load(f) return dict(((v, k) for (k, v) in di2s.items()))
class ImageNetBase(Dataset): def __init__(self, config=None): self.config = (config or OmegaConf.create()) if (not (type(self.config) == dict)): self.config = OmegaConf.to_container(self.config) self.keep_orig_class_label = self.config.get('keep_orig_class_label', False) ...
class ImageNetTrain(ImageNetBase): NAME = 'ILSVRC2012_train' URL = 'http://www.image-net.org/challenges/LSVRC/2012/' AT_HASH = 'a306397ccf9c2ead27155983c254227c0fd938e2' FILES = ['ILSVRC2012_img_train.tar'] SIZES = [147897477120] def __init__(self, process_images=True, data_root=None, **kwarg...
class ImageNetValidation(ImageNetBase): NAME = 'ILSVRC2012_validation' URL = 'http://www.image-net.org/challenges/LSVRC/2012/' AT_HASH = '5d6d0df7ed81efd49ca99ea4737e0ae5e3a5f2e5' VS_URL = 'https://heibox.uni-heidelberg.de/f/3e0f6e9c624e45f2bd73/?dl=1' FILES = ['ILSVRC2012_img_val.tar', 'validatio...
class ImageNetSR(Dataset): def __init__(self, size=None, degradation=None, downscale_f=4, min_crop_f=0.5, max_crop_f=1.0, random_crop=True): '\n Imagenet Superresolution Dataloader\n Performs following ops in order:\n 1. crops a crop of size s from image either as random or center c...
class ImageNetSRTrain(ImageNetSR): def __init__(self, **kwargs): super().__init__(**kwargs) def get_base(self): with open('data/imagenet_train_hr_indices.p', 'rb') as f: indices = pickle.load(f) dset = ImageNetTrain(process_images=False) return Subset(dset, indice...
class ImageNetSRValidation(ImageNetSR): def __init__(self, **kwargs): super().__init__(**kwargs) def get_base(self): with open('data/imagenet_val_hr_indices.p', 'rb') as f: indices = pickle.load(f) dset = ImageNetValidation(process_images=False) return Subset(dset...
class LambdaWarmUpCosineScheduler(): '\n note: use with a base_lr of 1.0\n ' def __init__(self, warm_up_steps, lr_min, lr_max, lr_start, max_decay_steps, verbosity_interval=0): self.lr_warm_up_steps = warm_up_steps self.lr_start = lr_start self.lr_min = lr_min self.lr_ma...
class LambdaWarmUpCosineScheduler2(): '\n supports repeated iterations, configurable via lists\n note: use with a base_lr of 1.0.\n ' def __init__(self, warm_up_steps, f_min, f_max, f_start, cycle_lengths, verbosity_interval=0): assert (len(warm_up_steps) == len(f_min) == len(f_max) == len(f...
class LambdaLinearScheduler(LambdaWarmUpCosineScheduler2): def schedule(self, n, **kwargs): cycle = self.find_in_interval(n) n = (n - self.cum_cycles[cycle]) if (self.verbosity_interval > 0): if ((n % self.verbosity_interval) == 0): print(f'current step: {n}, r...
class VQModel(pl.LightningModule): def __init__(self, ddconfig, lossconfig, n_embed, embed_dim, ckpt_path=None, ignore_keys=[], image_key='image', colorize_nlabels=None, monitor=None, batch_resize_range=None, scheduler_config=None, lr_g_factor=1.0, remap=None, sane_index_shape=False, use_ema=False): supe...
class VQModelInterface(VQModel): def __init__(self, embed_dim, *args, **kwargs): super().__init__(*args, embed_dim=embed_dim, **kwargs) self.embed_dim = embed_dim def encode(self, x): h = self.encoder(x) h = self.quant_conv(h) return h def decode(self, h, force_n...
class AutoencoderKL(pl.LightningModule): def __init__(self, ddconfig, lossconfig, embed_dim, ckpt_path=None, ignore_keys=[], image_key='image', colorize_nlabels=None, monitor=None): super().__init__() self.image_key = image_key self.encoder = Encoder(**ddconfig) self.decoder = Dec...
class IdentityFirstStage(torch.nn.Module): def __init__(self, *args, vq_interface=False, **kwargs): self.vq_interface = vq_interface super().__init__() def encode(self, x, *args, **kwargs): return x def decode(self, x, *args, **kwargs): return x def quantize(self, x...
class DDIMSampler(object): def __init__(self, model, schedule='linear', **kwargs): super().__init__() self.model = model self.ddpm_num_timesteps = model.num_timesteps self.schedule = schedule def register_buffer(self, name, attr): if (type(attr) == torch.Tensor): ...
class PLMSSampler(object): def __init__(self, model, schedule='linear', **kwargs): super().__init__() self.model = model self.ddpm_num_timesteps = model.num_timesteps self.schedule = schedule def register_buffer(self, name, attr): if (type(attr) == torch.Tensor): ...
def exists(val): return (val is not None)
def uniq(arr): return {el: True for el in arr}.keys()
def default(val, d): if exists(val): return val return (d() if isfunction(d) else d)
def max_neg_value(t): return (- torch.finfo(t.dtype).max)
def init_(tensor): dim = tensor.shape[(- 1)] std = (1 / math.sqrt(dim)) tensor.uniform_((- std), std) return tensor
class GEGLU(nn.Module): def __init__(self, dim_in, dim_out): super().__init__() self.proj = nn.Linear(dim_in, (dim_out * 2)) def forward(self, x): (x, gate) = self.proj(x).chunk(2, dim=(- 1)) return (x * F.gelu(gate))
class FeedForward(nn.Module): def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.0): super().__init__() inner_dim = int((dim * mult)) dim_out = default(dim_out, dim) project_in = (nn.Sequential(nn.Linear(dim, inner_dim), nn.GELU()) if (not glu) else GEGLU(dim, inne...
def zero_module(module): '\n Zero out the parameters of a module and return it.\n ' for p in module.parameters(): p.detach().zero_() return module
def Normalize(in_channels): return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-06, affine=True)
class LinearAttention(nn.Module): def __init__(self, dim, heads=4, dim_head=32): super().__init__() self.heads = heads hidden_dim = (dim_head * heads) self.to_qkv = nn.Conv2d(dim, (hidden_dim * 3), 1, bias=False) self.to_out = nn.Conv2d(hidden_dim, dim, 1) def forward...
class SpatialSelfAttention(nn.Module): def __init__(self, in_channels): super().__init__() self.in_channels = in_channels self.norm = Normalize(in_channels) self.q = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0) self.k = torch.nn.Conv2d(in_c...
class CrossAttention(nn.Module): def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0): super().__init__() inner_dim = (dim_head * heads) context_dim = default(context_dim, query_dim) self.scale = (dim_head ** (- 0.5)) self.heads = heads ...
class BasicTransformerBlock(nn.Module): def __init__(self, dim, n_heads, d_head, dropout=0.0, context_dim=None, gated_ff=True, checkpoint=True): super().__init__() self.attn1 = CrossAttention(query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout) self.ff = FeedForward(dim, dropou...