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 |
|---|---|---|---|---|---|---|
DataFree | DataFree-main/datafree/models/score_sde/op/fused_act.py | import os
import torch
from torch import nn
from torch.nn import functional as F
from torch.autograd import Function
from torch.utils.cpp_extension import load
module_path = os.path.dirname(__file__)
# print('****1')
fused = load(
"fused",
sources=[
os.path.join(module_path, "fused_bias_act.cpp"),
... | 2,724 | 26.25 | 83 | py |
DataFree | DataFree-main/datafree/models/classifiers/shufflenetv2.py | '''ShuffleNetV2 in PyTorch.
https://github.com/HobbitLong/RepDistiller/blob/34557d2728/models/ShuffleNetv2.py
See the paper "ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class ShuffleBlock(nn.Module)... | 6,616 | 34.196809 | 107 | py |
DataFree | DataFree-main/datafree/models/classifiers/resnet_in.py | # ResNet for ImageNet (224x224)
import torch
import torch.nn as nn
from torchvision.models.utils import load_state_dict_from_url
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
'wide_resnet50_2', 'wide_resnet101_2']
mod... | 14,306 | 40.469565 | 107 | py |
DataFree | DataFree-main/datafree/models/classifiers/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,647 | 35.3125 | 103 | py |
DataFree | DataFree-main/datafree/models/classifiers/mobilenetv2.py | from torch import nn
from torch import Tensor
from torchvision.models.utils import load_state_dict_from_url
from typing import Callable, Any, Optional, List
__all__ = ['MobileNetV2', 'mobilenet_v2']
model_urls = {
'mobilenet_v2': 'https://download.pytorch.org/models/mobilenet_v2-b0353104.pth',
}
def _make_div... | 7,798 | 35.962085 | 116 | py |
DataFree | DataFree-main/datafree/models/classifiers/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,711 | 29.371041 | 98 | py |
DataFree | DataFree-main/datafree/models/classifiers/wresnet.py | '''https://github.com/polo5/ZeroShotKnowledgeTransfer/blob/master/models/wresnet.py
'''
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
Original Author: Wei Yang
"""
__all__ = ['wrn']
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, dropout_rate... | 4,728 | 38.408333 | 118 | py |
DataFree | DataFree-main/datafree/models/classifiers/lenet.py | # https://github.com/huawei-noah/Data-Efficient-Model-Compression
import torch.nn as nn
class LeNet5(nn.Module):
def __init__(self, nc=1, num_classes=10):
super(LeNet5, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 6, kernel_size=(5, 5)),
nn.ReLU(inplace=True... | 1,909 | 32.508772 | 65 | py |
DataFree | DataFree-main/datafree/models/classifiers/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,296 | 30.80303 | 116 | py |
DataFree | DataFree-main/datafree/models/jem/sampling.py |
import torch as t
import numpy as np
from torch.nn.modules.loss import _Loss
from math import sqrt
import torchvision as tv
class Hamiltonian(_Loss):
def __init__(self, layer, reg_cof=1e-4):
super(Hamiltonian, self).__init__()
self.layer = layer
self.reg_cof = 0
def forward(self, x,... | 5,530 | 32.11976 | 113 | py |
DataFree | DataFree-main/datafree/metrics/stream_metrics.py | from __future__ import division
import torch
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):
""" Overridden by subclasses """
raise NotImplementedE... | 1,426 | 24.945455 | 58 | py |
DataFree | DataFree-main/datafree/metrics/confusion_matrix.py | from .stream_metrics import Metric
import torch
from typing import Callable
class ConfusionMatrix(Metric):
def __init__(self, num_classes, ignore_idx=None):
super(ConfusionMatrix, self).__init__()
self._num_classes = num_classes
self._ignore_idx = ignore_idx
self.reset()
... | 1,806 | 34.431373 | 121 | py |
DataFree | DataFree-main/datafree/metrics/accuracy.py | import numpy as np
import torch
from .stream_metrics import Metric
from typing import Callable
__all__=['Accuracy', 'TopkAccuracy']
class Accuracy(Metric):
def __init__(self):
self.reset()
@torch.no_grad()
def update(self, outputs, targets):
outputs = outputs.max(1)[1]
if len(targ... | 1,339 | 28.777778 | 84 | py |
DataFree | DataFree-main/datafree/metrics/kl_metric.py | import numpy as np
import torch
from .stream_metrics import Metric
from typing import Callable
from scipy.spatial import distance
__all__=['ProbLoyalty']
class ProbLoyalty(Metric):
def __init__(self):
self.reset()
@torch.no_grad()
def update(self, outputs, targets):
outputs = torch.softma... | 1,522 | 29.46 | 84 | py |
DataFree | DataFree-main/datafree/metrics/running_average.py | import numpy as np
import torch
from .stream_metrics import Metric
__all__=['Accuracy', 'TopkAccuracy']
class RunningLoss(Metric):
def __init__(self, loss_fn, is_batch_average=False):
self.reset()
self.loss_fn = loss_fn
self.is_batch_average = is_batch_average
@torch.no_grad()
def... | 683 | 25.307692 | 60 | py |
DataFree | DataFree-main/datafree/datasets/nyu.py | # Modified from https://github.com/VainF/nyuv2-python-toolkit
import os
import torch
import torch.utils.data as data
from PIL import Image
from scipy.io import loadmat
import numpy as np
import glob
from torchvision import transforms
from torchvision.datasets import VisionDataset
import random
from .utils import color... | 3,454 | 39.647059 | 144 | py |
DataFree | DataFree-main/datafree/utils/_utils.py | import torch
from torch.utils.data import ConcatDataset, Dataset
import numpy as np
from PIL import Image
import os, random, math
from copy import deepcopy
from contextlib import contextmanager
import torch.nn.functional as F
import torch.distributed as dist
def estimate_gradient_objective(victim_model, clone_model, ... | 16,618 | 34.209746 | 217 | py |
DataFree | DataFree-main/datafree/utils/inception.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
try:
from torchvision.models.utils import load_state_dict_from_url
except ImportError:
from torch.utils.model_zoo import load_url as load_state_dict_from_url
# Inception weights ported to Pytorch from
# http://download.tenso... | 12,186 | 36.847826 | 140 | py |
DataFree | DataFree-main/datafree/utils/sync_transforms/functional.py | # A synchronized version modified from https://github.com/pytorch/vision
from __future__ import division
import torch
import sys
import math
from PIL import Image, ImageOps, ImageEnhance, __version__ as PILLOW_VERSION
try:
import accimage
except ImportError:
accimage = None
import numpy as np
import numbers
imp... | 29,959 | 36.217391 | 116 | py |
DataFree | DataFree-main/datafree/utils/sync_transforms/transforms.py | # A synchronized version modified from https://github.com/pytorch/vision
from __future__ import division
import torch
import math
import sys
import random
from PIL import Image
try:
import accimage
except ImportError:
accimage = None
import numpy as np
import numbers
import types
import collections
import warni... | 56,390 | 37.231186 | 119 | py |
biva-pytorch | biva-pytorch-master/example.py | import torch
from torch.distributions import Bernoulli
from biva import DenseNormal, ConvNormal
from biva import VAE, LVAE, BIVA
# build a 2 layers VAE for binary images
# define the stochastic layers
z = [
{'N': 8, 'kernel': 5, 'block': ConvNormal}, # z1
{'N': 16, 'block': DenseNormal} # z2
]
# define th... | 1,084 | 30.911765 | 100 | py |
biva-pytorch | biva-pytorch-master/setup.py | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name='biva-pytorch',
version='0.1.4',
author="Valentin Lievin",
author_email="valentin.lievin@gmail.com",
description="Official PyTorch BIVA implementation (BIVA: A Very Deep Hierarchy of Latent... | 861 | 27.733333 | 129 | py |
biva-pytorch | biva-pytorch-master/run_deepvae.py | import argparse
import json
import logging
import os
import pickle
import numpy as np
import torch
from biva.datasets import get_binmnist_datasets, get_cifar10_datasets
from biva.evaluation import VariationalInference
from biva.model import DeepVae, get_deep_vae_mnist, get_deep_vae_cifar, VaeStage, LvaeStage, BivaStag... | 8,795 | 38.981818 | 120 | py |
biva-pytorch | biva-pytorch-master/load_deepvae.py | import argparse
import math
import os
import matplotlib
import matplotlib.pyplot as plt
import torch
from biva.utils.restore import restore_session
from booster.utils import logging_sep
from torch.utils.data import DataLoader
from torchvision.utils import make_grid
def build_and_save_grid(data, logdir, filename, N=1... | 2,210 | 30.140845 | 118 | py |
biva-pytorch | biva-pytorch-master/biva/evaluation/vi.py | import math
from functools import partial
from typing import *
import numpy as np
import torch
from booster import Diagnostic
from torch import Tensor, nn
from .freebits import FreeBits
from ..utils import batch_reduce, log_sum_exp, detach_to_device
class VariationalInference(object):
def __init__(self, likelih... | 5,873 | 35.03681 | 180 | py |
biva-pytorch | biva-pytorch-master/biva/evaluation/freebits.py | import numpy as np
import torch
class FreeBits():
"""
free bits: https://arxiv.org/abs/1606.04934
Assumes a each of the dimension to be one group
"""
def __init__(self, min_KL: float):
self.min_KL = min_KL
def __call__(self, kls: torch.Tensor) -> torch.Tensor:
"""
App... | 1,077 | 32.6875 | 96 | py |
biva-pytorch | biva-pytorch-master/biva/datasets/cifar10.py | import os
import pickle as pkl
import tarfile
from urllib.request import urlretrieve
import numpy as np
import torch
from torch.utils.data import Dataset
def quantisize(images, levels):
return (np.digitize(images, np.arange(levels) / levels) - 1).astype('i')
def load_cifar(root, levels=256, with_y=False):
d... | 3,113 | 37.925 | 112 | py |
biva-pytorch | biva-pytorch-master/biva/datasets/binmnist.py | import os
import pickle as pkl
from urllib.request import urlretrieve
import numpy as np
import torch
from torch.utils.data import Dataset
def load_mnist_binarized(root):
datapath = os.path.join(root, 'bin-mnist')
if not os.path.exists(datapath):
os.makedirs(datapath)
dataset = os.path.join(datap... | 2,088 | 33.816667 | 124 | py |
biva-pytorch | biva-pytorch-master/biva/layers/block.py | from typing import *
from .convolution import *
from .linear import *
class GatedResNet(nn.Module):
def __init__(self, input_shape: Tuple, dim: Tuple, aux_shape: Optional[Tuple] = None, weightnorm: bool = True,
act: nn.Module = nn.ReLU,
transposed: bool = False, dropout: Optiona... | 5,909 | 33.561404 | 115 | py |
biva-pytorch | biva-pytorch-master/biva/layers/convolution.py | import warnings
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
def getSAMEPadding(tensor_shape, conv):
"""
return the padding to apply to a given convolution such as it reproduces the 'SAME' behavior from Tensorflow
This works as well for pooling layers.
args:
... | 15,024 | 44.807927 | 133 | py |
biva-pytorch | biva-pytorch-master/biva/layers/linear.py | import numpy as np
import torch
from torch import nn
class NormedLinear(nn.Module):
"""
Linear layer with normalization
"""
def __init__(self, in_features, out_features, dim=-1, weightnorm=True):
super(NormedLinear, self).__init__()
"""
args:
in_features (in): numb... | 5,913 | 33.383721 | 114 | py |
biva-pytorch | biva-pytorch-master/biva/utils/discretized_mixture_logits.py | import numpy as np
import torch
import torch.nn.functional as F
from torch.autograd import Variable
from torch.distributions import Distribution
class DiscretizedMixtureLogitsDistribution(Distribution):
def __init__(self, nr_mix, logits):
self.logits = logits
self.nr_mix = nr_mix
def log_prob... | 10,680 | 40.886275 | 164 | py |
biva-pytorch | biva-pytorch-master/biva/utils/logging.py | import math
import os
import matplotlib.image
import numpy as np
import torch
from torchvision.utils import make_grid
def save_img(img, path):
def _scale(img):
img *= 255
return img.astype(np.uint8)
img = _scale(img)
matplotlib.image.imsave(path, img)
def summary2logger(logger, summar... | 2,017 | 27.828571 | 93 | py |
biva-pytorch | biva-pytorch-master/biva/utils/utils.py | from typing import *
import torch
from torch.optim.lr_scheduler import _LRScheduler
def shp_cat(shps: List[Tuple[int]], dim: int):
"""concatenate tensor shapes"""
out = list(shps[0])
out[dim] = sum(list(s)[dim] for s in shps)
return tuple(out)
def detach_to_device(x, device):
"""detach, clone a... | 2,184 | 31.61194 | 91 | py |
biva-pytorch | biva-pytorch-master/biva/utils/restore.py | import json
import os
import pickle
from booster.utils import available_device
from torch.distributions import Bernoulli
from .discretized_mixture_logits import DiscretizedMixtureLogits
from .logging import load_model
from ..datasets import get_binmnist_datasets, get_cifar10_datasets
from ..evaluation import Variatio... | 1,970 | 31.311475 | 109 | py |
biva-pytorch | biva-pytorch-master/biva/utils/ops.py | from time import time
import torch
def append_ellapsed_time(func):
def wrapper(*args, **kwargs):
start_time = time()
diagnostics = func(*args, **kwargs)
diagnostics['info']['elapsed-time'] = time() - start_time
return diagnostics
return wrapper
@append_ellapsed_time
def tra... | 833 | 19.85 | 76 | py |
biva-pytorch | biva-pytorch-master/biva/model/stochastic.py | from typing import *
import torch
from torch import nn, Tensor
from torch.distributions import Normal
from ..layers import PaddedNormedConv, NormedDense
from ..utils import batch_reduce
class StochasticLayer(nn.Module):
"""
An abstract class of a VAE stochastic layer.
"""
def __init__(self, data: D... | 7,544 | 30.970339 | 128 | py |
biva-pytorch | biva-pytorch-master/biva/model/utils.py | from collections import defaultdict
from typing import *
import torch
class DataCollector(defaultdict):
def __init__(self):
super().__init__(list)
def extend(self, data: Dict[str, List[Optional[torch.Tensor]]]) -> None:
"""Append new data item"""
for key, d in data.items():
... | 574 | 24 | 76 | py |
biva-pytorch | biva-pytorch-master/biva/model/deepvae.py | from typing import *
import torch
from torch import nn
from .architectures import get_deep_vae_mnist
from .stage import VaeStage, LvaeStage, BivaStage
from .utils import DataCollector
from ..layers import PaddedNormedConv
class DeepVae(nn.Module):
"""
A Deep Hierarchical VAE.
The model is a stack of N s... | 7,574 | 36.132353 | 123 | py |
biva-pytorch | biva-pytorch-master/biva/model/stage.py | from copy import copy
from typing import *
import torch
from torch import nn, Tensor
from .stochastic import StochasticLayer
from .utils import DataCollector
from ..layers import GatedResNet, AsFeatureMap
from ..utils import shp_cat
def StochasticBlock(data: Dict, *args, **kwargs):
"""Construct the stochastic b... | 35,209 | 39.564516 | 126 | py |
deeplake | deeplake-master/benchmarks/benchmark_iterate_hub_local_pytorch.py | import torchvision
from torchvision import transforms
import torch
import os
from hub import Dataset
class HubAdapter(torch.utils.data.Dataset):
def __init__(self, ds):
self.ds = ds
def __len__(self):
return len(self.ds)
@property
def shape(self):
return (len(self), None, No... | 1,481 | 23.7 | 75 | py |
deeplake | deeplake-master/benchmarks/benchmark_iterate_hub_pytorch.py | import torch
from hub import Dataset
def benchmark_iterate_hub_pytorch_setup(
dataset_name, batch_size, prefetch_factor, num_workers=1
):
dset = Dataset(dataset_name, cache=False, storage_cache=False, mode="r")
loader = torch.utils.data.DataLoader(
dset.to_pytorch(),
batch_size=batch_siz... | 531 | 20.28 | 76 | py |
deeplake | deeplake-master/examples/eurosat.py | import hub
import torch
def main():
ds = hub.Dataset("eurosat/eurosat-rgb")
# 26000 samples in dataset, accessing values
print(ds["image"][10].numpy())
print(
ds["label", 15].numpy()
) # alternate way to access, by specifying both key and sample number at once
print(ds["filename", 20... | 1,466 | 26.679245 | 82 | py |
deeplake | deeplake-master/examples/train_tensorflow.py | """Basic example of training tensorflow model on hub.Dataset
"""
import tensorflow as tf
import hub
from hub.training.model import Model
def to_model_fit(item):
x = item["image"]
y = item["label"]
return (x, y)
def example_to_tensorflow():
ds = hub.Dataset("activeloop/fashion_mnist_train")
tds... | 953 | 21.186047 | 77 | py |
deeplake | deeplake-master/examples/load_pytorch.py | import torch
from hub import Dataset, schema
def main():
# Create dataset
ds = Dataset(
"davitb/pytorch_example",
shape=(640,),
mode="w",
schema={
"image": schema.Tensor((512, 512), dtype="float"),
"label": schema.Tensor((512, 512), dtype="float"),
... | 722 | 19.657143 | 68 | py |
deeplake | deeplake-master/examples/load_tf.py | from hub import Dataset, schema
def main():
# Create dataset
ds = Dataset(
"./data/example/pytorch",
shape=(64,),
schema={
"image": schema.Tensor((512, 512), dtype="float"),
"label": schema.Tensor((512, 512), dtype="float"),
},
)
# tansform into... | 513 | 19.56 | 62 | py |
deeplake | deeplake-master/examples/train_pytorch.py | """Basic example of training pytorch model on hub.Dataset
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import hub
from hub.training.model import Model
def example_to_pytorch():
ds = hub.Dataset("activeloop/fashion_mnist_train")
torch_ds = ds.to_pytorch(output_type=list)
torch_da... | 1,684 | 25.328125 | 73 | py |
deeplake | deeplake-master/examples/old/load_pytorch.py | import torch
import hub
# Load data
ds = hub.load("mnist/mnist")
# Transform into pytorch
ds = ds.to_pytorch()
ds = torch.utils.data.DataLoader(
ds, batch_size=8, num_workers=8, collate_fn=ds.collate_fn
)
# Iterate over the data
for batch in ds:
print(batch["data"], batch["labels"])
| 297 | 15.555556 | 61 | py |
deeplake | deeplake-master/examples/old/3D Object Dataset/upload.py | """
Dataset Download Source: http://cvgl.stanford.edu/data2/3Ddataset.zip
Dataset format: Images(.bmp file)
Dataset Features: bicycle, car, cellphone, head, iron, monitor, mouse, shoe, stapler, toaster
Folder Structure:
3Ddataset
-bicycle
-bicycle_1
- Various Images in .bmp format
-bicycle_2
-bicyc... | 3,051 | 29.217822 | 109 | py |
deeplake | deeplake-master/examples/old/fashion-mnist/train_tf_fit.py | from hub import dataset
import tensorflow as tf
def create_CNN():
model = tf.keras.Sequential()
model.add(
tf.keras.layers.Conv2D(
filters=64,
kernel_size=2,
padding="same",
activation="relu",
input_shape=(28, 28, 1),
)
)
mode... | 1,952 | 26.125 | 87 | py |
deeplake | deeplake-master/examples/old/fashion-mnist/train_tf_gradient_tape.py | from hub import dataset
import tensorflow as tf
from tensorflow.keras.losses import SparseCategoricalCrossentropy
from tensorflow.keras.optimizers import Adam
import numpy as np
def create_CNN():
model = tf.keras.Sequential()
model.add(
tf.keras.layers.Conv2D(
filters=64,
kerne... | 3,521 | 31.611111 | 101 | py |
deeplake | deeplake-master/examples/old/fashion-mnist/train_pytorch.py | from hub import dataset
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class CNN(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv2_... | 3,631 | 29.521008 | 101 | py |
deeplake | deeplake-master/test/benchmark_new/basic_train.py | import time
import io
import torch
import hub
from hub.schema import Tensor
from hub.store.store import get_fs_and_path
import numpy as np
from PIL import Image
from pathlib import Path
import os
import tensorflow as tf
from torch import nn, optim
import torchvision.models as models
def set_parameter_requires_grad(m... | 9,713 | 30.745098 | 86 | py |
deeplake | deeplake-master/test/benchmark_new/basic_datasets.py | import time
import io
import torch
import hub
from hub.schema import Tensor
from hub.store.store import get_fs_and_path
from helper import report
import numpy as np
from PIL import Image
from pathlib import Path
import os
import tensorflow as tf
class PytorchDataset(torch.utils.data.Dataset):
"Characterizes a dat... | 5,582 | 29.016129 | 86 | py |
deeplake | deeplake-master/hub/utils.py | """
License:
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""
import time
from collections import abc
from math import gcd
from numpy.lib.arraysetops import isin
from h... | 4,332 | 17.83913 | 108 | py |
deeplake | deeplake-master/hub/training/model.py | """
License:
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""
import os
import sys
from typing import Union, Dict
import json
import tempfile
import io
from hub.store.st... | 5,563 | 34.896774 | 108 | py |
deeplake | deeplake-master/hub/training/tests/test_model.py | """
License:
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""
import numpy as np
import pytest
from hub.utils import pytorch_loaded, tensorflow_loaded
from hub.training.m... | 2,269 | 30.971831 | 108 | py |
deeplake | deeplake-master/hub/api/datasetview.py | """
License:
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""
from typing import Iterable
from hub.api.tensorview import TensorView
import collections.abc as abc
from hub.... | 15,550 | 37.022005 | 139 | py |
deeplake | deeplake-master/hub/api/dataset.py | """
License:
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""
import warnings
from hub.api.versioning import VersionNode
import os
import posixpath
import collections.abc ... | 41,453 | 36.514932 | 156 | py |
deeplake | deeplake-master/hub/api/integrations.py | """
License:
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""
import sys
import numpy as np
import json
from itertools import chain
from collections import defaultdict
im... | 32,585 | 34.496732 | 136 | py |
deeplake | deeplake-master/hub/api/tests/test_converters.py | """
License:
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""
import hub.api.tests.test_converters
from hub.schema.features import Tensor
import numpy as np
import shutil... | 21,100 | 32.924437 | 108 | py |
deeplake | deeplake-master/hub/collections/dataset/core.py | """
License:
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""
from collections import abc
from configparser import ConfigParser
import json
import os
from typing import D... | 29,981 | 34.231492 | 147 | py |
deeplake | deeplake-master/hub/collections/tests/test_collections.py | """
License:
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""
import numpy as np
import pytest
from hub.collections import dataset, tensor
from hub.utils import (
gcp... | 13,059 | 35.077348 | 108 | py |
deeplake | deeplake-master/hub/tests/test_utils.py | """
License:
This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
"""
from hub.utils import *
from hub.utils import _flatten, _tuple_product
def test_flatten_array():
expec... | 1,790 | 19.352273 | 108 | py |
sigGCN | sigGCN-main/siggcn.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 22 14:00:37 2020
@author: tianyu
"""
import sys, os
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
import torch.utils.data as Data
import torch.optim as optim
import argparse
import time
im... | 5,559 | 37.344828 | 169 | py |
sigGCN | sigGCN-main/train.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 23 18:30:20 2021
@author: tianyu
"""
import time
import pandas as pd
import torch
#from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim
from sklearn import metrics
import numpy as np
... | 7,479 | 32.846154 | 134 | py |
sigGCN | sigGCN-main/lib/utilsdata.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 21 12:00:37 2019
@author: tianyu
"""
import numpy as np
import pandas as pd
import scipy.sparse as sp
import torch
from sklearn.preprocessing import Normalizer
import math
from torch.autograd import Variable
import torch.nn.functional as F
import t... | 8,922 | 34.268775 | 140 | py |
sigGCN | sigGCN-main/lib/layermodel.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 13 21:15:43 2020
@author: tianyu
"""
import torch
#from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
import numpy as np
import sys
sys.path.insert(0, 'lib/')
if torch.cuda.is_available():
print('cuda ava... | 8,536 | 30.043636 | 106 | py |
LWSIS | LWSIS-main/setup.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import glob
import os
from setuptools import find_packages, setup
import torch
from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension
torch_ver = [int(x) for x in torch.__version__.split(".")[:2]]
assert... | 2,755 | 28.956522 | 100 | py |
LWSIS | LWSIS-main/tools/visualize_data.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import numpy as np
import os
from itertools import chain
import cv2
import tqdm
from PIL import Image
from detectron2.data import DatasetCatalog, MetadataCatalog, build_detection_train_loader
from detectron2.da... | 3,843 | 37.059406 | 96 | py |
LWSIS | LWSIS-main/tools/rename_blendmask.py | import argparse
from collections import OrderedDict
import torch
def get_parser():
parser = argparse.ArgumentParser(description="FCOS Detectron2 Converter")
parser.add_argument(
"--model",
default="weights/blendmask/person/R_50_1x.pth",
metavar="FILE",
help="path to model weig... | 1,086 | 24.880952 | 77 | py |
LWSIS | LWSIS-main/tools/train_net_nuscenes.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Detection Training Script.
This scripts reads a given config file and runs the training or evaluation.
It is an entry point that is made to train standard models in detectron2.
In order to let one script support training of many models,
this s... | 9,499 | 35.821705 | 124 | py |
LWSIS | LWSIS-main/tools/remove_optim_from_ckpt.py | import argparse
import torch
def get_parser():
parser = argparse.ArgumentParser(description="Keep only model in ckpt")
parser.add_argument(
"--path",
default="output/person/blendmask/R_50_1x/",
help="path to model weights",
)
parser.add_argument(
"--name",
defa... | 589 | 21.692308 | 75 | py |
LWSIS | LWSIS-main/tools/convert_fcos_weight.py | import argparse
from collections import OrderedDict
import torch
def get_parser():
parser = argparse.ArgumentParser(description="FCOS Detectron2 Converter")
parser.add_argument(
"--model",
default="weights/fcos_R_50_1x_official.pth",
metavar="FILE",
help="path to model weights... | 2,104 | 32.412698 | 77 | py |
LWSIS | LWSIS-main/tools/train_net.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Detection Training Script.
This scripts reads a given config file and runs the training or evaluation.
It is an entry point that is made to train standard models in detectron2.
In order to let one script support training of many models,
this s... | 8,426 | 35.167382 | 105 | py |
LWSIS | LWSIS-main/tools/train_net_waymo.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Detection Training Script.
This scripts reads a given config file and runs the training or evaluation.
It is an entry point that is made to train standard models in detectron2.
In order to let one script support training of many models,
this s... | 9,978 | 36.799242 | 124 | py |
LWSIS | LWSIS-main/adet/evaluation/text_evaluation.py | import contextlib
import copy
import io
import itertools
import json
import logging
import numpy as np
import os
import re
import torch
from collections import OrderedDict
from fvcore.common.file_io import PathManager
from pycocotools.coco import COCO
from detectron2.utils import comm
from detectron2.data import Metad... | 10,225 | 34.140893 | 394 | py |
LWSIS | LWSIS-main/adet/layers/conv_with_kaiming_uniform.py | from torch import nn
from detectron2.layers import Conv2d
from .deform_conv import DFConv2d
from detectron2.layers.batch_norm import get_norm
def conv_with_kaiming_uniform(
norm=None, activation=None,
use_deformable=False, use_sep=False):
def make_conv(
in_channels, out_channels, kernel_s... | 1,652 | 30.188679 | 68 | py |
LWSIS | LWSIS-main/adet/layers/deform_conv.py | import torch
from torch import nn
from detectron2.layers import Conv2d
class _NewEmptyTensorOp(torch.autograd.Function):
@staticmethod
def forward(ctx, x, new_shape):
ctx.shape = x.shape
return x.new_empty(new_shape)
@staticmethod
def backward(ctx, grad):
shape = ctx.shape
... | 3,992 | 32 | 104 | py |
LWSIS | LWSIS-main/adet/layers/iou_loss.py | import torch
from torch import nn
class IOULoss(nn.Module):
"""
Intersetion Over Union (IoU) loss which supports three
different IoU computations:
* IoU
* Linear IoU
* gIoU
"""
def __init__(self, loc_loss_type='iou'):
super(IOULoss, self).__init__()
self.loc_loss_type ... | 832 | 24.242424 | 58 | py |
LWSIS | LWSIS-main/adet/layers/bezier_align.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from adet import _C
class _BezierAlign(Function):
@staticmethod
def forward(ctx, inp... | 3,390 | 33.602041 | 96 | py |
LWSIS | LWSIS-main/adet/layers/gcn.py | # coding:utf-8
import torch.nn as nn
import torch.nn.functional as F
class Conv2D(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, padding='same',
stride=1, dilation=1, groups=1):
super(Conv2D, self).__init__()
assert type(kernel_size) in [int, tuple], "Allo... | 2,530 | 32.746667 | 120 | py |
LWSIS | LWSIS-main/adet/layers/def_roi_align.py | import torch
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from adet import _C
class _DefROIAlign(Function):
@staticmethod
def forward(ctx, input, roi, offsets, output_size, spatial_scale, sampling_rat... | 3,444 | 32.77451 | 106 | py |
LWSIS | LWSIS-main/adet/layers/naive_group_norm.py | import torch
from torch.nn import Module, Parameter
from torch.nn import init
class NaiveGroupNorm(Module):
r"""NaiveGroupNorm implements Group Normalization with the high-level matrix operations in PyTorch.
It is a temporary solution to export GN by ONNX before the official GN can be exported by ONNX.
Th... | 2,981 | 38.76 | 103 | py |
LWSIS | LWSIS-main/adet/utils/comm.py | import torch
import torch.nn.functional as F
import torch.distributed as dist
from detectron2.utils.comm import get_world_size
def reduce_sum(tensor):
world_size = get_world_size()
if world_size < 2:
return tensor
tensor = tensor.clone()
dist.all_reduce(tensor, op=dist.ReduceOp.SUM)
retur... | 2,880 | 26.701923 | 68 | py |
LWSIS | LWSIS-main/adet/data/dataset_mapper.py | import copy
import logging
import os.path as osp
import numpy as np
import torch
from fvcore.common.file_io import PathManager
from PIL import Image
from pycocotools import mask as maskUtils
from detectron2.data import detection_utils as utils
from detectron2.data import transforms as T
from detectron2.data.dataset_m... | 8,053 | 36.460465 | 97 | py |
LWSIS | LWSIS-main/adet/data/detection_utils.py | import logging
import numpy as np
import torch
from detectron2.data import transforms as T
from detectron2.data.detection_utils import \
annotations_to_instances as d2_anno_to_inst
from detectron2.data.detection_utils import \
transform_instance_annotations as d2_transform_inst_anno
def transform_instance_a... | 2,993 | 27.514286 | 87 | py |
LWSIS | LWSIS-main/adet/data/dataset_mapper_nuscenes2.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import logging
import numpy as np
from typing import List, Union
import torch
import os
import detectron2.data.detection_utils as utils
from detectron2.data.dataset_mapper import DatasetMapper
import detectron2.data.transforms as T
from ... | 11,949 | 44.961538 | 134 | py |
LWSIS | LWSIS-main/adet/data/detection_utils_nuscenes.py | # -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import numpy as np
import torch
# fmt: off
from detectron2.data.detection_utils import \
annotations_to_instances as base_annotations_to_instances
from detectron2.data.detection_utils import \
transform_instance_ann... | 9,769 | 39.539419 | 124 | py |
LWSIS | LWSIS-main/adet/data/dataset_mapper_nuscenes.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import logging
import numpy as np
from typing import List, Union
import torch
import detectron2.data.detection_utils as utils
from detectron2.data.dataset_mapper import DatasetMapper
import detectron2.data.transforms as T
from detectron... | 8,673 | 43.71134 | 124 | py |
LWSIS | LWSIS-main/adet/modeling/poolers.py | import sys
import torch
from torch import nn
from detectron2.layers import cat
from detectron2.modeling.poolers import (
ROIPooler, convert_boxes_to_pooler_format, assign_boxes_to_levels
)
from adet.layers import BezierAlign
from adet.structures import Beziers
__all__ = ["TopPooler"]
def _box_max_size(boxes):
... | 5,976 | 35.445122 | 97 | py |
LWSIS | LWSIS-main/adet/modeling/__init__.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from .fcos import FCOS
from .blendmask import BlendMask
from .backbone import build_fcos_resnet_fpn_backbone
from .one_stage_detector import OneStageDetector, OneStageRCNN
from .roi_heads.text_head import TextHead
from .batext import BAText
from .ME... | 519 | 36.142857 | 86 | py |
LWSIS | LWSIS-main/adet/modeling/one_stage_detector.py | import logging
from torch import nn
from detectron2.modeling.meta_arch.build import META_ARCH_REGISTRY
from detectron2.modeling import ProposalNetwork, GeneralizedRCNN
from detectron2.utils.events import get_event_storage
from detectron2.utils.logger import log_first_n
from detectron2.modeling.postprocessing import de... | 7,387 | 38.297872 | 100 | py |
LWSIS | LWSIS-main/adet/modeling/backbone/dla.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# this file is from https://github.com/ucbdrive/dla/blob/master/dla.py.
import math
from os.path import join
import torch
from torch import nn
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
import fvcore.nn.weight_init as weight_init
from dete... | 15,702 | 34.527149 | 95 | py |
LWSIS | LWSIS-main/adet/modeling/backbone/bifpn.py | import torch
import torch.nn.functional as F
from torch import nn
from detectron2.layers import Conv2d, ShapeSpec, get_norm
from detectron2.modeling.backbone import Backbone, build_resnet_backbone
from detectron2.modeling import BACKBONE_REGISTRY
from .mobilenet import build_mnv2_backbone
__all__ = []
def swish(x)... | 15,363 | 37.603015 | 108 | py |
LWSIS | LWSIS-main/adet/modeling/backbone/lpf.py | import torch
import torch.nn.parallel
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
class Downsample(nn.Module):
def __init__(self, pad_type='reflect', filt_size=3, stride=2, channels=None, pad_off=0):
super(Downsample, self).__init__()
self.filt_size = filt_size
... | 4,208 | 35.6 | 143 | py |
LWSIS | LWSIS-main/adet/modeling/backbone/vovnet.py | # Copyright (c) Youngwan Lee (ETRI) All Rights Reserved.
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
import fvcore.nn.weight_init as weight_init
from detectron2.modeling.backbone import Backbone
from detectron2.modeling.backbone.build import BACKBONE_REGISTRY
... | 11,685 | 29.997347 | 105 | py |
LWSIS | LWSIS-main/adet/modeling/backbone/fpn.py | from torch import nn
import torch.nn.functional as F
import fvcore.nn.weight_init as weight_init
from detectron2.modeling.backbone import FPN, build_resnet_backbone
from detectron2.layers import ShapeSpec
from detectron2.modeling.backbone.build import BACKBONE_REGISTRY
from .resnet_lpf import build_resnet_lpf_backbon... | 2,850 | 31.033708 | 86 | py |
LWSIS | LWSIS-main/adet/modeling/backbone/mobilenet.py | # taken from https://github.com/tonylins/pytorch-mobilenet-v2/
# Published by Ji Lin, tonylins
# licensed under the Apache License, Version 2.0, January 2004
from torch import nn
from torch.nn import BatchNorm2d
#from detectron2.layers.batch_norm import NaiveSyncBatchNorm as BatchNorm2d
from detectron2.layers import ... | 5,386 | 33.532051 | 97 | py |
LWSIS | LWSIS-main/adet/modeling/backbone/resnet_lpf.py | # This code is built from the PyTorch examples repository: https://github.com/pytorch/vision/tree/master/torchvision/models.
# Copyright (c) 2017 Torch Contributors.
# The Pytorch examples are available under the BSD 3-Clause License.
#
# =================================================================================... | 12,203 | 40.794521 | 136 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.