repo
stringlengths
1
99
file
stringlengths
13
215
code
stringlengths
12
59.2M
file_length
int64
12
59.2M
avg_line_length
float64
3.82
1.48M
max_line_length
int64
12
2.51M
extension_type
stringclasses
1 value
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/models/graph/dgcnn.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ https://github.com/WangYueFt/dgcnn/blob/master/pytorch/model.py @Author: Yue Wang @Contact: yuewangx@mit.edu @File: model.py @Time: 2018/10/13 6:35 PM """ import torch import torch.nn as nn import torch.nn.functional as F def knn(x, k): inner = -2*torch.matmul(x....
5,442
36.537931
181
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/models/cifar/inceptionv4.py
# -*- coding: UTF-8 -*- """ inceptionv4 in pytorch [1] Christian Szegedy, Sergey Ioffe, Vincent Vanhoucke, Alex Alemi Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning https://arxiv.org/abs/1602.07261 """ import torch import torch.nn as nn class BasicConv2d(nn.Module): def...
18,161
32.202925
109
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/models/cifar/swin.py
import torch from torch import nn, einsum import numpy as np from einops import rearrange, repeat class CyclicShift(nn.Module): def __init__(self, displacement): super().__init__() self.displacement = displacement def forward(self, x): return torch.roll(x, shifts=(self.displacement, s...
10,305
41.941667
118
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/models/cifar/resnet.py
# ResNet for CIFAR (32x32) # 2019.07.24-Changed output of forward function # Huawei Technologies Co., Ltd. <foss@huawei.com> # taken from https://github.com/huawei-noah/Data-Efficient-Model-Compression/blob/master/DAFL/resnet.py # for comparison with DAFL import torch import torch.nn as nn import torch.nn.functional ...
4,252
35.663793
103
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/models/cifar/mobilenetv2.py
"""mobilenetv2 in pytorch [1] Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen MobileNetV2: Inverted Residuals and Linear Bottlenecks https://arxiv.org/abs/1801.04381 """ import torch import torch.nn as nn import torch.nn.functional as F class LinearBottleNeck(nn.Module): de...
2,857
28.163265
109
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/models/cifar/vgg.py
"""https://github.com/HobbitLong/RepDistiller/blob/master/models/vgg.py """ import torch.nn as nn import torch.nn.functional as F import math __all__ = [ 'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn', 'vgg19_bn', 'vgg19', ] model_urls = { 'vgg11': 'https://download.pytorch.org/mod...
6,706
29.348416
98
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/models/cifar/preactresnet.py
"""preactresnet in pytorch [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun Identity Mappings in Deep Residual Networks https://arxiv.org/abs/1603.05027 """ import torch import torch.nn as nn import torch.nn.functional as F class PreActBasic(nn.Module): expansion = 1 def __init__(self, in_channe...
4,077
30.859375
111
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/models/cifar/densenet.py
"""dense net in pytorch [1] Gao Huang, Zhuang Liu, Laurens van der Maaten, Kilian Q. Weinberger. Densely Connected Convolutional Networks https://arxiv.org/abs/1608.06993v5 """ import torch import torch.nn as nn #"""Bottleneck layers. Although each layer only produces k #output feature-maps, it typically has...
5,231
41.193548
147
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/models/cifar/googlenet.py
"""google net in pytorch [1] Christian Szegedy, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed, Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, Andrew Rabinovich. Going Deeper with Convolutions https://arxiv.org/abs/1409.4842v1 """ import torch import torch.nn as nn class Inception(nn.Module): ...
4,526
32.533333
94
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/models/cifar/vit.py
import torch from torch import nn from einops import rearrange, repeat from einops.layers.torch import Rearrange # helpers def pair(t): return t if isinstance(t, tuple) else (t, t) # classes class PreNorm(nn.Module): def __init__(self, dim, fn): super().__init__() self.norm = nn.LayerNorm(...
4,362
32.305344
166
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/models/cifar/resnext.py
"""resnext in pytorch [1] Saining Xie, Ross Girshick, Piotr Dollár, Zhuowen Tu, Kaiming He. Aggregated Residual Transformations for Deep Neural Networks https://arxiv.org/abs/1611.05431 """ import math import torch import torch.nn as nn import torch.nn.functional as F #only implements ResNext bottleneck c #...
4,302
33.98374
99
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/models/cifar/senet.py
""" The script is adapted from torchvision.models.ResNet """ import torch.nn as nn __all__ = ['se_resnet20', 'se_resnet32', 'se_resnet44', 'se_resnet56', 'se_resnet110', 'se_resnet164', 'resnet20', 'resnet32', 'resnet44', 'resnet56', 'resnet110', 'resnet164'] model_urls = { 'se_resnet18': None, 's...
8,792
26.392523
114
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/models/cifar/nasnet.py
"""nasnet in pytorch [1] Barret Zoph, Vijay Vasudevan, Jonathon Shlens, Quoc V. Le Learning Transferable Architectures for Scalable Image Recognition https://arxiv.org/abs/1707.07012 """ import torch import torch.nn as nn class SeperableConv2d(nn.Module): def __init__(self, input_channels, output_channel...
9,626
28.990654
125
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/models/cifar/xception.py
"""xception in pytorch [1] François Chollet Xception: Deep Learning with Depthwise Separable Convolutions https://arxiv.org/abs/1610.02357 """ import torch import torch.nn as nn class SeperableConv2d(nn.Module): #***Figure 4. An “extreme” version of our Inception module, #with one spatial convolutio...
6,142
26.547085
82
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/models/cifar/resnet_tiny.py
# Tiny ResNet for CIFAR (32x32) from __future__ import absolute_import '''Resnet for cifar dataset. https://github.com/HobbitLong/RepDistiller/blob/master/models/resnet.py Ported form https://github.com/facebook/fb.resnet.torch and https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py (c) YANG, W...
6,215
30.876923
116
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/models/cifar/inceptionv3.py
import os from collections import namedtuple import torch import torch.nn as nn import torch.nn.functional as F __all__ = ["Inception3", "inception_v3"] _InceptionOuputs = namedtuple("InceptionOuputs", ["logits", "aux_logits"]) def inception_v3(num_classes, pretrained=False, progress=True, device="cpu", **kwargs)...
13,148
38.368263
102
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/utils/utils.py
from contextlib import contextmanager import logging import os, sys from termcolor import colored import copy import numpy as np import torch class MagnitudeRecover(): def __init__(self, model, reg=1e-3): self.rec = {} self.reg = reg self.cnt = 0 with torch.no_grad(): fo...
3,306
32.40404
91
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/utils/evaluator.py
from tqdm import tqdm import torch.nn.functional as F import torch from . import metrics class Evaluator(object): def __init__(self, metric, dataloader): self.dataloader = dataloader self.metric = metric def eval(self, model, device=None, progress=False): self.metric.reset() w...
1,370
36.054054
97
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/utils/metrics.py
import numpy as np import torch from typing import Callable __all__=['Accuracy', 'TopkAccuracy'] from abc import ABC, abstractmethod from typing import Callable, Union, Any, Mapping, Sequence import numbers import numpy as np class Metric(ABC): @abstractmethod def update(self, pred, target): """ Over...
3,186
27.455357
84
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/utils/datasets/modelnet40.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ https://github.com/WangYueFt/dgcnn/blob/master/pytorch/data.py @Author: Yue Wang @Contact: yuewangx@mit.edu @File: data.py @Time: 2018/10/13 6:21 PM """ import os import sys import glob import h5py import numpy as np from torch.utils.data import Dataset def downloa...
2,734
29.388889
110
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/utils/imagenet_utils/sampler.py
import math import torch import torch.distributed as dist class RASampler(torch.utils.data.Sampler): """Sampler that restricts data loading to a subset of the dataset for distributed, with repeated augmentation. It ensures that different each augmented version of a sample will be visible to a differe...
2,393
38.245902
103
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/utils/imagenet_utils/presets.py
import torch from torchvision.transforms import autoaugment, transforms from torchvision.transforms.functional import InterpolationMode class ClassificationPresetTrain: def __init__( self, *, crop_size, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), interpol...
2,502
34.253521
106
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/utils/imagenet_utils/utils.py
import copy import datetime import errno import hashlib import os import time from collections import defaultdict, deque, OrderedDict from typing import List, Optional, Tuple import torch import torch.distributed as dist class SmoothedValue: """Track a series of values and provide access to smoothed values over ...
15,753
33.472648
120
py
Torch-Pruning
Torch-Pruning-master/benchmarks/engine/utils/imagenet_utils/transforms.py
import math from typing import Tuple import torch from torch import Tensor from torchvision.transforms import functional as F class RandomMixup(torch.nn.Module): """Randomly apply Mixup to the provided batch and targets. The class implements the data augmentations as described in the paper `"mixup: Beyon...
6,774
36.849162
108
py
Torch-Pruning
Torch-Pruning-master/tests/test_score_normalization.py
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch from torchvision.models import resnet18 as entry import torch_pruning as tp from torch import nn import torch.nn.functional as F def test_pruner(): # Global metrics example_inputs = torch.randn(1, 3...
1,923
32.754386
120
py
Torch-Pruning
Torch-Pruning-master/tests/test_unwrapped_parameters.py
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch from torchvision.models import convnext_base as entry import torch_pruning as tp model = entry() print(model) # Global metrics example_inputs = torch.randn(1, 3, 224, 224) imp = tp.importance.MagnitudeImportance...
1,634
28.196429
112
py
Torch-Pruning
Torch-Pruning-master/tests/test_customized_layer.py
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch import torch.nn as nn import torch.nn.functional as F import torch_pruning as tp from typing import Sequence ############ # Customize your layer # class CustomizedLayer(nn.Module): def __init__(self, in_dim)...
3,179
31.783505
108
py
Torch-Pruning
Torch-Pruning-master/tests/test_single_channel_output.py
import torch from torch import nn import torch.nn.functional as F import torch_pruning as tp class TestModel(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 16, 3, stride=1, padding=1) self.bn1 = nn.BatchNorm2d(16) self.conv2 = nn.Conv2d(16, 64, 2, strid...
982
29.71875
84
py
Torch-Pruning
Torch-Pruning-master/tests/test_concat.py
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch import torch_pruning as tp import torch.nn as nn class Net(nn.Module): def __init__(self, in_dim): super().__init__() self.block1 = nn.Sequential( nn.Conv2d(in_dim, in_dim, 1), ...
2,401
28.654321
116
py
Torch-Pruning
Torch-Pruning-master/tests/test_pruner.py
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch from torchvision.models import resnet18 as entry import torch_pruning as tp from torch import nn import torch.nn.functional as F def test_pruner(): model = entry() print(model) # Global metrics e...
4,324
32.527132
125
py
Torch-Pruning
Torch-Pruning-master/tests/test_taylor_importance.py
import torch from torchvision.models import resnet18 import torch_pruning as tp def test_taylor(): model = resnet18(pretrained=True) # Importance criteria example_inputs = torch.randn(1, 3, 224, 224) imp = tp.importance.TaylorImportance() ignored_layers = [] for m in model.modules(): ...
1,379
33.5
116
py
Torch-Pruning
Torch-Pruning-master/tests/test_split.py
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch import torch_pruning as tp import torch.nn as nn class Net(nn.Module): def __init__(self, in_dim): super().__init__() self.block1 = nn.Sequential( nn.Conv2d(in_dim, in_di...
2,595
28.5
116
py
Torch-Pruning
Torch-Pruning-master/tests/test_load.py
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch from torchvision.models import resnet18 as entry import torch_pruning as tp def test_pruner(): model = entry() print(model) # Global metrics example_inputs = torch.randn(1, 3, 224, 224) imp =...
1,961
31.163934
116
py
Torch-Pruning
Torch-Pruning-master/tests/test_interactive_pruner.py
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch from torchvision.models import resnet18 as entry import torch_pruning as tp def test_interactive_pruner(): model = entry() print(model) # Global metrics example_inputs = torch.randn(1, 3, 224, 22...
1,715
30.2
116
py
Torch-Pruning
Torch-Pruning-master/tests/test_reshape.py
import torch import torch.nn as nn import torch.nn.functional as F import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch_pruning as tp class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.Linear = nn.Linear(in_features=512, ...
2,073
32.451613
116
py
Torch-Pruning
Torch-Pruning-master/tests/test_fully_connected_layers.py
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch import torch.nn as nn import torch.nn.functional as F import torch_pruning as tp class FullyConnectedNet(nn.Module): """https://github.com/VainF/Torch-Pruning/issues/21""" def __init__(self, input_size, ...
1,304
28
99
py
Torch-Pruning
Torch-Pruning-master/tests/test_dependency_graph.py
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch from torchvision.models import resnet18 import torch_pruning as tp def test_depgraph(): model = resnet18().eval() # 1. build dependency graph for resnet18 DG = tp.DependencyGraph() DG.build_depen...
1,231
28.333333
102
py
Torch-Pruning
Torch-Pruning-master/tests/test_importance.py
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch from torchvision.models import resnet18 import torch_pruning as tp model = resnet18() # Global metrics def test_imp(): DG = tp.DependencyGraph() example_inputs = torch.randn(1,3,224,224) DG.build_depe...
1,693
35.042553
101
py
Torch-Pruning
Torch-Pruning-master/tests/test_dependency_lenet.py
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch import torch.nn as nn import torch_pruning as tp class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv1 = nn.Conv2d(1, 6, 5) self.relu1 = nn.ReLU() ...
1,749
29.172414
99
py
Torch-Pruning
Torch-Pruning-master/tests/graph_drawing.py
import torch import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch_pruning as tp from torchvision.models import densenet121, resnet18, googlenet, vgg16_bn import torch.nn as nn from torchvision.models.vision_transformer import VisionTransformer, vit_b_16 import matplo...
1,502
33.953488
136
py
Torch-Pruning
Torch-Pruning-master/tests/test_pruning_fn.py
from torchvision.models import alexnet import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch_pruning as tp def test_pruning_fn(): model = alexnet() print("Before pruning: ") print(model.features[:4]) print(model.features[0].weight.shape) print(mo...
681
28.652174
77
py
Torch-Pruning
Torch-Pruning-master/tests/test_concat_split.py
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch import torch_pruning as tp import torch.nn as nn class Net(nn.Module): def __init__(self, in_dim): super().__init__() self.block1 = nn.Sequential( nn.Conv2d(in_dim, in_dim, 1), ...
2,666
30.376471
116
py
Torch-Pruning
Torch-Pruning-master/tests/test_serialization.py
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch from torchvision.models import vit_b_16 as entry import torch_pruning as tp from torchvision.models.vision_transformer import VisionTransformer def test_serialization(): model = entry().eval() customized...
1,819
30.929825
120
py
Torch-Pruning
Torch-Pruning-master/tests/test_backward.py
import os, sys import torchvision sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))) # torchvision==0.13.1 ########################################### # Prunable Models ############################################ try: from torchvision.models.vision_tra...
8,079
34.130435
136
py
Torch-Pruning
Torch-Pruning-master/tests/test_multiple_inputs_and_outputs.py
import sys, os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import torch import torch.nn as nn import torch.nn.functional as F import torch_pruning as tp class FullyConnectedNet(nn.Module): """https://github.com/VainF/Torch-Pruning/issues/21""" def __init__(self, input_size...
1,468
28.979592
100
py
Torch-Pruning
Torch-Pruning-master/torch_pruning/dependency.py
import typing import warnings from numbers import Number from collections import namedtuple import torch import torch.nn as nn from .pruner import function from . import _helpers, utils, ops __all__ = ["Dependency", "Group", "DependencyGraph"] class Node(object): """ Nodes of DepGraph """ def __init__...
42,920
40.309913
284
py
Torch-Pruning
Torch-Pruning-master/torch_pruning/_helpers.py
import torch.nn as nn import numpy as np import torch from operator import add from numbers import Number def is_scalar(x): if isinstance(x, torch.Tensor): return len(x.shape) == 0 elif isinstance(x, Number): return True elif isinstance(x, (list, tuple)): return False return Fa...
3,356
26.072581
74
py
Torch-Pruning
Torch-Pruning-master/torch_pruning/importance.py
import abc import torch import torch.nn as nn import typing from .pruner import function from ._helpers import _FlattenIndexMapping from . import ops import math class Importance(abc.ABC): """ estimate the importance of a Pruning Group, and return an 1-D per-channel importance score. """ @abc.abstractcla...
19,716
41.863043
119
py
Torch-Pruning
Torch-Pruning-master/torch_pruning/ops.py
import torch.nn as nn from enum import IntEnum class DummyMHA(nn.Module): def __init__(self): super(DummyMHA, self).__init__() class _CustomizedOp(nn.Module): def __init__(self, op_class): self.op_cls = op_class def __repr__(self): return "CustomizedOp({})".format(str(self.op_cl...
6,864
27.367769
76
py
Torch-Pruning
Torch-Pruning-master/torch_pruning/serialization.py
import torch from torch.serialization import DEFAULT_PROTOCOL import pickle load = torch.load save = torch.save def state_dict(model: torch.nn.Module): full_state_dict = {} attributions = {} for name, module in model.named_modules(): # state dicts full_state_dict[name] = module.__dict__.co...
1,461
36.487179
113
py
Torch-Pruning
Torch-Pruning-master/torch_pruning/pruner/function.py
import torch import torch.nn as nn from .. import ops from copy import deepcopy from functools import reduce from operator import mul from abc import ABC, abstractclassmethod, abstractmethod, abstractstaticmethod from typing import Callable, Sequence, Tuple, Dict __all__=[ 'BasePruningFunc', 'PrunerBox', ...
20,280
39.562
197
py
Torch-Pruning
Torch-Pruning-master/torch_pruning/pruner/algorithms/batchnorm_scale_pruner.py
from numbers import Number from typing import Callable from .metapruner import MetaPruner from .scheduler import linear_scheduler import torch import torch.nn as nn class BNScalePruner(MetaPruner): def __init__( self, model, example_inputs, importance, reg=1e-5, iter...
1,647
32.632653
131
py
Torch-Pruning
Torch-Pruning-master/torch_pruning/pruner/algorithms/metapruner.py
import torch import torch.nn as nn import typing from .scheduler import linear_scheduler from ..import function from ... import ops, dependency class MetaPruner: """ Meta Pruner for structural pruning. Args: model (nn.Module): A to-be-pruned model example_inputs (torch.Te...
11,945
40.769231
126
py
Torch-Pruning
Torch-Pruning-master/torch_pruning/pruner/algorithms/group_norm_pruner.py
import torch import math from .metapruner import MetaPruner from .scheduler import linear_scheduler from .. import function from ..._helpers import _FlattenIndexMapping class GroupNormPruner(MetaPruner): def __init__( self, model, example_inputs, importance, reg=1e-4, ...
8,060
43.783333
189
py
Torch-Pruning
Torch-Pruning-master/torch_pruning/utils/utils.py
from ..ops import TORCH_CONV, TORCH_BATCHNORM, TORCH_PRELU, TORCH_LINEAR from ..ops import module2type import torch from .op_counter import count_ops_and_params import torch.nn as nn @torch.no_grad() def count_params(module): return sum([p.numel() for p in module.parameters()]) def flatten_as_list(obj): if is...
5,557
42.76378
152
py
Torch-Pruning
Torch-Pruning-master/torch_pruning/utils/op_counter.py
''' This opcounter is adapted from https://github.com/sovrasov/flops-counter.pytorch Copyright (C) 2021 Sovrasov V. - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license. * You should have received a copy of the MIT license with * this file. If not visit https://...
15,847
31.879668
89
py
invertinggradients
invertinggradients-master/rec_mult.py
"""Run reconstruction in a terminal prompt. Optional arguments can be found in inversefed/options.py This CLI can recover the baseline experiments. """ import torch import torchvision import numpy as np import inversefed torch.backends.cudnn.benchmark = inversefed.consts.BENCHMARK from collections import defaultdi...
14,673
44.571429
153
py
invertinggradients
invertinggradients-master/reconstruct_image.py
"""Run reconstruction in a terminal prompt. Optional arguments can be found in inversefed/options.py """ import torch import torchvision import numpy as np from PIL import Image import inversefed from collections import defaultdict import datetime import time import os torch.backends.cudnn.benchmark = inversefed....
10,859
38.347826
130
py
invertinggradients
invertinggradients-master/inversefed/reconstruction_algorithms.py
"""Mechanisms for image reconstruction from parameter gradients.""" import torch from collections import defaultdict, OrderedDict from inversefed.nn import MetaMonkey from .metrics import total_variation as TV from .metrics import InceptionScore from .medianfilt import MedianPool2d from copy import deepcopy import ti...
18,066
44.97201
131
py
invertinggradients
invertinggradients-master/inversefed/utils.py
"""Various utilities.""" import os import csv import torch import random import numpy as np import socket import datetime def system_startup(args=None, defs=None): """Print useful system information.""" # Choose GPU device and print status information: device = torch.device('cuda:0') if torch.cuda.is_a...
2,420
33.098592
107
py
invertinggradients
invertinggradients-master/inversefed/metrics.py
"""This is code based on https://sudomake.ai/inception-score-explained/.""" import torch import torchvision from collections import defaultdict class InceptionScore(torch.nn.Module): """Class that manages and returns the inception score of images.""" def __init__(self, batch_size=32, setup=dict(device=torch....
3,866
35.140187
107
py
invertinggradients
invertinggradients-master/inversefed/medianfilt.py
"""This is code for median pooling from https://gist.github.com/rwightman. https://gist.github.com/rwightman/f2d3849281624be7c0f11c85c87c1598 """ import torch.nn as nn import torch.nn.functional as F from torch.nn.modules.utils import _pair, _quadruple class MedianPool2d(nn.Module): """Median pool (usable as med...
2,025
35.836364
87
py
invertinggradients
invertinggradients-master/inversefed/nn/modules.py
"""For monkey-patching into meta-learning frameworks.""" import torch import torch.nn.functional as F from collections import OrderedDict from functools import partial import warnings from ..consts import BENCHMARK torch.backends.cudnn.benchmark = BENCHMARK DEBUG = False # Emit warning messages when patching. Use th...
4,125
40.676768
120
py
invertinggradients
invertinggradients-master/inversefed/nn/densenet.py
"""DenseNet in PyTorch.""" """Adaptation we did with ******.""" import math import torch import torch.nn as nn import torch.nn.functional as F class _Bottleneck(nn.Module): def __init__(self, in_planes, growth_rate): super().__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.conv1 = nn....
3,305
34.548387
98
py
invertinggradients
invertinggradients-master/inversefed/nn/revnet_utils.py
"""https://github.com/jhjacobsen/pytorch-i-revnet/blob/master/models/model_utils.py. Code for "i-RevNet: Deep Invertible Networks" https://openreview.net/pdf?id=HJsjkMb0Z ICLR, 2018 (c) Joern-Henrik Jacobsen, 2018 """ """ MIT License Copyright (c) 2018 Jörn Jacobsen Permission is hereby granted, free of charge, t...
4,614
33.699248
135
py
invertinggradients
invertinggradients-master/inversefed/nn/revnet.py
"""https://github.com/jhjacobsen/pytorch-i-revnet/blob/master/models/iRevNet.py. Code for "i-RevNet: Deep Invertible Networks" https://openreview.net/pdf?id=HJsjkMb0Z ICLR, 2018 (c) Joern-Henrik Jacobsen, 2018 """ """ MIT License Copyright (c) 2018 Jörn Jacobsen Permission is hereby granted, free of charge, to an...
7,362
37.150259
80
py
invertinggradients
invertinggradients-master/inversefed/nn/models.py
"""Define basic models and translate some torchvision stuff.""" """Stuff from https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py.""" import torch import torchvision import torch.nn as nn from torchvision.models.resnet import Bottleneck from .revnet import iRevNet from .densenet import _DenseNet...
15,319
44.868263
132
py
invertinggradients
invertinggradients-master/inversefed/training/scheduler.py
"""This file is part of https://github.com/ildoonet/pytorch-gradual-warmup-lr. MIT License Copyright (c) 2019 Ildoo Kim Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, inclu...
4,218
42.947917
143
py
invertinggradients
invertinggradients-master/inversefed/training/training_routine.py
"""Implement the .train function.""" import torch import numpy as np from collections import defaultdict from .scheduler import GradualWarmupScheduler from ..consts import BENCHMARK, NON_BLOCKING torch.backends.cudnn.benchmark = BENCHMARK def train(model, loss_fn, trainloader, validloader, defs, setup=dict(dtype=t...
4,586
35.696
117
py
invertinggradients
invertinggradients-master/inversefed/data/loss.py
"""Define various loss functions and bundle them with appropriate metrics.""" import torch import numpy as np class Loss: """Abstract class, containing necessary methods. Abstract class to collect information about the 'higher-level' loss function, used to train an energy-based model containing the eval...
3,507
29.504348
117
py
invertinggradients
invertinggradients-master/inversefed/data/data.py
"""This is data.py from pytorch-examples. Refer to https://github.com/pytorch/examples/blob/master/super_resolution/data.py. """ from os.path import exists, join, basename from os import makedirs, remove from six.moves import urllib import tarfile from torchvision.transforms import Compose, CenterCrop, ToTensor, Resi...
3,694
37.092784
116
py
invertinggradients
invertinggradients-master/inversefed/data/data_processing.py
"""Repeatable code parts concerning data loading.""" import torch import torchvision import torchvision.transforms as transforms import os from ..consts import * from .data import _build_bsds_sr, _build_bsds_dn from .loss import Classification, PSNR def construct_dataloaders(dataset, defs, data_path='~/data', sh...
8,575
39.838095
126
py
invertinggradients
invertinggradients-master/inversefed/data/datasets.py
"""This is dataset.py from pytorch-examples. Refer to https://github.com/pytorch/examples/blob/master/super_resolution/dataset.py. """ import torch import torch.utils.data as data from os import listdir from os.path import join from PIL import Image def _is_image_file(filename): return any(filename.endswith(ex...
1,881
28.873016
119
py
Set_Functions_for_Time_Series
Set_Functions_for_Time_Series-master/seft/callbacks.py
"""Module containing Keras callbacks.""" import time from itertools import chain import numpy as np import tensorflow as tf import tensorflow_datasets as tfds import tensorboard.plugins.hparams.api as hp from tensorflow.keras.callbacks import TensorBoard class FailsafeTensorBoard(TensorBoard): """Failsafe versi...
6,605
33.40625
79
py
Set_Functions_for_Time_Series
Set_Functions_for_Time_Series-master/seft/training_utils.py
"""Utility functions for training and evaluation.""" import math import random from collections.abc import Sequence import tensorflow as tf import tensorflow_datasets as tfds import medical_ts_datasets import seft.models from tensorflow.data.experimental import AUTOTUNE import tensorboard.plugins.hparams.api as hp fr...
8,761
32.570881
78
py
Set_Functions_for_Time_Series
Set_Functions_for_Time_Series-master/seft/training_routine.py
"""Training routine for models.""" from os.path import join import json from itertools import chain import numpy as np import tensorflow as tf from typing import Callable from tensorflow.keras.callbacks import ( CSVLogger, EarlyStopping, ModelCheckpoint, ReduceLROnPlateau, TensorBoard) from .callbacks import ( ...
12,606
36.298817
88
py
Set_Functions_for_Time_Series
Set_Functions_for_Time_Series-master/seft/cli/fit_model.py
"""Fit a model in SeFT using a tensorflow dataset.""" import os import logging import seft.cli.silence_warnings # import tensorflow as tf # tf.enable_eager_execution() # tf.config.experimental_run_functions_eagerly(True) import tensorboard.plugins.hparams.api as hp import seft.models from seft.training_routine impor...
4,834
30.396104
79
py
Set_Functions_for_Time_Series
Set_Functions_for_Time_Series-master/seft/models/set_utils.py
import inspect from itertools import chain import numpy as np import tensorflow as tf from tensorflow.keras.layers import Dense, Dropout class PaddedToSegments(tf.keras.layers.Layer): """Convert a padded tensor with mask to a stacked tensor with segments.""" def compute_output_shape(self, input_shape): ...
11,322
32.699405
103
py
Set_Functions_for_Time_Series
Set_Functions_for_Time_Series-master/seft/models/deep_set_attention.py
from collections.abc import Sequence from itertools import chain import numpy as np import tensorflow as tf from tensorflow.keras.layers import Dense from tensorflow.python.framework.smart_cond import smart_cond from .set_utils import ( build_dense_dropout_model, PaddedToSegments, SegmentAggregation, cumulati...
23,841
36.665087
107
py
Set_Functions_for_Time_Series
Set_Functions_for_Time_Series-master/seft/models/gru_simple.py
"""GRU_simple. RECURRENT NEURAL NETWORKS FOR MULTIVARIATE TIME SERIES WITH MISSING VALUES, Che et al., 2016 """ from collections.abc import Sequence import tensorflow as tf from .delta_t_utils import get_delta_t class GRUSimpleModel(tf.keras.Model): def __init__(self, output_activation, output_dims, n_units, ...
3,269
33.0625
76
py
Set_Functions_for_Time_Series
Set_Functions_for_Time_Series-master/seft/models/utils.py
"""Module containing utility functions specific to implementing models.""" import logging import tensorflow as tf K = tf.keras.backend def build_and_compute_output_shape(layer, input_shape): layer.build(input_shape) return layer.compute_output_shape(input_shape) class ResNetBlock(tf.keras.layers.Layer): ...
6,479
33.468085
79
py
Set_Functions_for_Time_Series
Set_Functions_for_Time_Series-master/seft/models/gru_d.py
"""Implementation of GRU-D model. The below implementation is based on and adapted from https://github.com/PeterChe1990/GRU-D Which is published unter the MIT licence. """ from collections.abc import Sequence from collections import namedtuple import tensorflow as tf from tensorflow.keras import backend as K from ten...
23,399
39.554593
86
py
Set_Functions_for_Time_Series
Set_Functions_for_Time_Series-master/seft/models/transformer.py
"""Module with implementation of Transformer architecture.""" from collections.abc import Sequence import tensorflow as tf import numpy as np import keras_transformer from .set_utils import PaddedToSegments, SegmentAggregation class PositionalEncoding(tf.keras.layers.Layer): def __init__(self, max_time=20000, n_...
8,048
35.586364
86
py
Set_Functions_for_Time_Series
Set_Functions_for_Time_Series-master/seft/models/interpolation_prediction.py
"""Interpolation-Prediction Networks.""" from collections.abc import Sequence import numpy as np import tensorflow as tf K = tf.keras.backend class single_channel_interp(tf.keras.layers.Layer): def __init__(self, **kwargs): self.reconstruction = False super(single_channel_interp, self).__init__(...
14,598
38.671196
84
py
Set_Functions_for_Time_Series
Set_Functions_for_Time_Series-master/seft/models/phased_lstm.py
"""Phased LSTM implementation based on the version in tensorflow contrib. See: https://github.com/tensorflow/tensorflow/blob/r1.15/tensorflow/contrib/rnn/python/ops/rnn_cell.py#L1915-L2064 Due to restructurings in tensorflow some adaptions were required. This implementation does not use global naming of variables and...
10,675
36.724382
114
py
MDD-StochasticSolvers
MDD-StochasticSolvers-main/setup.py
import os from setuptools import setup, find_packages def src(pth): return os.path.join(os.path.dirname(__file__), pth) # Project description descr = """ StochasticMDD """ # Setup setup( name='stochmdd', description=descr, long_description=open(src('README.md')).read(), long_descr...
887
28.6
83
py
MDD-StochasticSolvers
MDD-StochasticSolvers-main/stochmdd/stochmdd.py
import time import numpy as np import torch import torch.nn as nn import pylops_gpu from math import ceil from torch.utils.data import TensorDataset, DataLoader from pylops.waveeqprocessing.mdd import MDC as MDClops class MDC(nn.Module): r"""Multi-dimensional convolution Wrap PyLops :py:func:`pylops.waveeqp...
19,896
37.634951
187
py
MDD-StochasticSolvers
MDD-StochasticSolvers-main/stochmdd/stochmdd_numpy.py
import numpy as np import time from .mdc import MDC from .solver_numpy import * def MDDminibatch(nt, nr, dt, dr, Gfft, d, optimizer, n_epochs, batch_size, shuffle=True, shuffleonce=False, twosided=True, mtrue=None, ivstrue=None, enormabsscaling=False, seed=None, sche...
12,597
34.789773
156
py
MultiEchoAI
MultiEchoAI-main/models.py
# -*- coding: utf-8 -*- """ Created on Sun Apr 25 15:25:31 2021 @author: degerli """ from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Convolution1D from tensorflow.keras.layers import MaxPooling1D from tensorflow.keras.layers import Flatten, Input from tensorflow.keras.layers impor...
5,193
39.263566
174
py
glide-text2im
glide-text2im-main/setup.py
from setuptools import setup setup( name="glide-text2im", packages=[ "glide_text2im", "glide_text2im.clip", "glide_text2im.tokenizer", ], package_data={ "glide_text2im.tokenizer": [ "bpe_simple_vocab_16e6.txt.gz", "encoder.json.gz", "v...
610
18.709677
46
py
glide-text2im
glide-text2im-main/glide_text2im/download.py
import os from functools import lru_cache from typing import Dict, Optional import requests import torch as th from filelock import FileLock from tqdm.auto import tqdm MODEL_PATHS = { "base": "https://openaipublic.blob.core.windows.net/diffusion/dec-2021/base.pt", "upsample": "https://openaipublic.blob.core.w...
2,609
35.25
108
py
glide-text2im
glide-text2im-main/glide_text2im/text2im_model.py
import torch as th import torch.nn as nn import torch.nn.functional as F from .nn import timestep_embedding from .unet import UNetModel from .xf import LayerNorm, Transformer, convert_module_to_f16 class Text2ImUNet(UNetModel): """ A UNetModel that conditions on text with an encoding transformer. Expect...
7,803
32.350427
127
py
glide-text2im
glide-text2im-main/glide_text2im/nn.py
""" Various utilities for neural networks. """ import math import torch as th import torch.nn as nn import torch.nn.functional as F class GroupNorm32(nn.GroupNorm): def __init__(self, num_groups, num_channels, swish, eps=1e-5): super().__init__(num_groups=num_groups, num_channels=num_channels, eps=eps) ...
2,859
25.981132
85
py
glide-text2im
glide-text2im-main/glide_text2im/fp16_util.py
""" Helpers to inference with 16-bit precision. """ import torch.nn as nn def convert_module_to_f16(l): """ Convert primitive modules to float16. """ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): l.weight.data = l.weight.data.half() if l.bias is not None: l.bias.dat...
646
23.884615
74
py
glide-text2im
glide-text2im-main/glide_text2im/unet.py
import math from abc import abstractmethod import torch as th import torch.nn as nn import torch.nn.functional as F from .fp16_util import convert_module_to_f16, convert_module_to_f32 from .nn import avg_pool_nd, conv_nd, linear, normalization, timestep_embedding, zero_module class TimestepBlock(nn.Module): """...
23,009
35.179245
124
py
glide-text2im
glide-text2im-main/glide_text2im/gaussian_diffusion.py
""" Simplified from https://github.com/openai/guided-diffusion/blob/main/guided_diffusion/gaussian_diffusion.py. """ import math import numpy as np import torch as th def _warmup_beta(beta_start, beta_end, num_diffusion_timesteps, warmup_frac): betas = beta_end * np.ones(num_diffusion_timesteps, dtype=np.float6...
23,741
36.096875
129
py
glide-text2im
glide-text2im-main/glide_text2im/respace.py
""" Utilities for changing sampling schedules of a trained model. Simplified from: https://github.com/openai/guided-diffusion/blob/main/guided_diffusion/respace.py """ import numpy as np import torch as th from .gaussian_diffusion import GaussianDiffusion def space_timesteps(num_timesteps, section_counts): """...
4,879
40.355932
99
py
glide-text2im
glide-text2im-main/glide_text2im/xf.py
""" Transformer implementation adapted from CLIP ViT: https://github.com/openai/CLIP/blob/4c0275784d6d9da97ca1f47eaaee31de1867da91/clip/model.py """ import math import torch as th import torch.nn as nn def convert_module_to_f16(l): """ Convert primitive modules to float16. """ if isinstance(l, (nn.L...
3,382
24.824427
90
py
glide-text2im
glide-text2im-main/glide_text2im/clip/model_creation.py
import os from functools import lru_cache from typing import Any, Callable, Dict, List, Optional, Tuple import attr import numpy as np import torch import torch.nn as nn import yaml from glide_text2im.tokenizer.simple_tokenizer import SimpleTokenizer from .encoders import ImageEncoder, TextEncoder @lru_cache() def ...
3,859
31.711864
92
py
glide-text2im
glide-text2im-main/glide_text2im/clip/utils.py
import math from typing import Callable, Optional import attr import torch import torch.nn as nn import torch.nn.functional as F FilterFn = Callable[[torch.Tensor], torch.Tensor] class ZeroKeyBiasGrad(torch.autograd.Function): @staticmethod def forward(ctx, x): return x @staticmethod def ba...
3,354
33.234694
100
py