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 |
|---|---|---|---|---|---|---|
mmdeploy | mmdeploy-master/mmdeploy/pytorch/functions/flatten.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmdeploy.core import FUNCTION_REWRITER
from mmdeploy.utils import Backend
@FUNCTION_REWRITER.register_rewriter(
func_name='torch.Tensor.flatten', backend=Backend.COREML.value)
@FUNCTION_REWRITER.register_rewriter(
func_name='torch.flatten', ba... | 723 | 31.909091 | 73 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/functions/linear.py | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Optional, Union
import torch
from mmdeploy.core import FUNCTION_REWRITER
class GemmOp(torch.autograd.Function):
"""Create onnx::Gemm op."""
@staticmethod
def forward(ctx, input, weight, bias=None):
out = input @ weight.transpose... | 2,069 | 27.75 | 77 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/functions/multi_head_attention_forward.py | # Copyright (c) OpenMMLab. All rights reserved.
import math
from typing import Optional, Tuple
import torch
from torch import Tensor
from mmdeploy.core import FUNCTION_REWRITER
from mmdeploy.utils.constants import Backend
class ScaledDotProductAttentionTRT(torch.autograd.Function):
"""Caller of scale dot produc... | 1,613 | 26.827586 | 73 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/functions/repeat.py | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Sequence, Union
import torch
from mmdeploy.core import FUNCTION_REWRITER
@FUNCTION_REWRITER.register_rewriter(
func_name='torch.Tensor.repeat', backend='tensorrt')
def tensor__repeat__tensorrt(ctx, input: torch.Tensor,
... | 752 | 30.375 | 78 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/functions/size.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmdeploy.core import FUNCTION_REWRITER
@FUNCTION_REWRITER.register_rewriter(
func_name='torch.Tensor.size', backend='ncnn')
def tensor__size__ncnn(ctx, self, *args):
"""Rewrite `size` for ncnn backend.
ONNX Shape node is not supported in ... | 1,049 | 24 | 74 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/functions/group_norm.py | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Union
import torch
from mmdeploy.core import FUNCTION_REWRITER
@FUNCTION_REWRITER.register_rewriter(
func_name='torch.nn.functional.group_norm', backend='ncnn')
def group_norm__ncnn(
ctx,
input: torch.Tensor,
num_groups: int,
wei... | 1,659 | 33.583333 | 74 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/functions/masked_fill.py | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Union
import torch
from torch.types import Number
from mmdeploy.core import FUNCTION_REWRITER
from mmdeploy.utils.constants import Backend
@FUNCTION_REWRITER.register_rewriter(
func_name='torch.masked_fill', backend=Backend.ONNXRUNTIME.value)
@F... | 916 | 34.269231 | 78 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/functions/normalize.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmdeploy.core import FUNCTION_REWRITER
@FUNCTION_REWRITER.register_rewriter(
func_name='torch.nn.functional.normalize', backend='ncnn')
def normalize__ncnn(ctx,
input: torch.Tensor,
p: int = 2,
... | 1,323 | 30.52381 | 71 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/functions/interpolate.py | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Optional, Tuple, Union
import torch
from torch.autograd import Function
from mmdeploy.core import FUNCTION_REWRITER
from mmdeploy.utils import Backend, get_root_logger
@FUNCTION_REWRITER.register_rewriter(
func_name='torch.nn.functional.interpol... | 5,158 | 35.85 | 79 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/ops/adaptive_pool.py | # Copyright (c) OpenMMLab. All rights reserved.
from mmdeploy.core import SYMBOLIC_REWRITER
@SYMBOLIC_REWRITER.register_symbolic(
'adaptive_avg_pool2d', is_pytorch=True, backend='ncnn')
def adaptive_avg_pool2d__ncnn(ctx, g, x, output_size):
"""Register ncnn symbolic function for `adaptive_avg_pool2d`.
A... | 580 | 31.277778 | 66 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/ops/squeeze.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch.onnx.symbolic_helper as sym_help
from mmdeploy.core import SYMBOLIC_REWRITER
@SYMBOLIC_REWRITER.register_symbolic('squeeze', is_pytorch=True)
def squeeze__default(ctx, g, self, dim=None):
"""Register default symbolic function for `squeeze`.
squeez... | 677 | 29.818182 | 77 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/ops/grid_sampler.py | # Copyright (c) OpenMMLab. All rights reserved.
from torch.onnx.symbolic_helper import parse_args
from mmdeploy.core import SYMBOLIC_REWRITER
from mmdeploy.utils import Backend, get_backend
@parse_args('v', 'v', 'i', 'i', 'i')
def grid_sampler(g,
input,
grid,
interp... | 1,873 | 28.746032 | 79 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/ops/lstm.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Modified from:
# https://github.com/pytorch/pytorch/blob/9ade03959392e5a90b74261012de1d806cab2253/torch/onnx/symbolic_opset9.py
import warnings
import torch
import torch.onnx.symbolic_helper as sym_help
from torch.onnx.symbolic_helper import _uni... | 8,929 | 37.826087 | 112 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/ops/roll.py | # Copyright (c) OpenMMLab. All rights reserved.
# modified from
# https://github.com/pytorch/pytorch/blob/master/torch/onnx/symbolic_opset9.py
import sys
from torch.onnx.symbolic_helper import _slice_helper, parse_args
from mmdeploy.core import SYMBOLIC_REWRITER
@parse_args('v', 'is', 'is')
def roll(g, self, shifts... | 1,038 | 29.558824 | 79 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/ops/instance_norm.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Modified from:
# https://github.com/pytorch/pytorch/blob/9ade03959392e5a90b74261012de1d806cab2253/torch/onnx/symbolic_opset9.py
import torch
from torch.onnx.symbolic_helper import (_get_tensor_dim_size, _get_tensor_rank,
... | 2,891 | 38.081081 | 112 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/ops/gelu.py | # Copyright (c) OpenMMLab. All rights reserved.
from torch.onnx import symbolic_helper
from mmdeploy.core import SYMBOLIC_REWRITER
from mmdeploy.utils import Backend
@symbolic_helper.parse_args('v')
def gelu__ncnn_pt111(g, self):
"""gelu for torch<=1.12."""
return g.op('mmdeploy::Gelu', self)
@SYMBOLIC_REW... | 545 | 27.736842 | 56 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/ops/hardsigmoid.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# Modified from:
# https://github.com/pytorch/pytorch/blob/9ade03959392e5a90b74261012de1d806cab2253/torch/onnx/symbolic_opset9.py
from mmdeploy.core import SYMBOLIC_REWRITER
@SYMBOLIC_REWRITER.register_symbolic(
'hardsigmoid', is_pytorch=True,... | 533 | 40.076923 | 112 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/ops/linear.py | # Copyright (c) OpenMMLab. All rights reserved.
# Modified from:
# https://github.com/pytorch/pytorch/blob/9ade03959392e5a90b74261012de1d806cab2253/torch/onnx/symbolic_opset9.py
from torch.onnx.symbolic_helper import parse_args
from mmdeploy.core import SYMBOLIC_REWRITER
from mmdeploy.utils import Backend
@parse_arg... | 1,314 | 28.222222 | 112 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/ops/layer_norm.py | # Copyright (c) OpenMMLab. All rights reserved.
# Modified from:
# https://github.com/pytorch/pytorch/blob/9ade03959392e5a90b74261012de1d806cab2253/torch/onnx/symbolic_opset9.py
import torch
from torch.onnx.symbolic_helper import parse_args
from mmdeploy.core import SYMBOLIC_REWRITER
from mmdeploy.utils import Backend... | 3,355 | 35.879121 | 112 | py |
mmdeploy | mmdeploy-master/mmdeploy/pytorch/ops/pad.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.onnx.symbolic_helper as sym_help
from packaging.version import parse as version_parse
from mmdeploy.core import FUNCTION_REWRITER
# modified from
# https://github.com/pytorch/pytorch/blob/65a37923f9b14c7c9e80535d771ef9e4e92d0502/torch/onnx/sym... | 3,232 | 40.448718 | 113 | py |
mmdeploy | mmdeploy-master/mmdeploy/mmcv/cnn/hsigmoid.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmdeploy.core import FUNCTION_REWRITER
from mmdeploy.utils import Backend
class hsigmoid(torch.autograd.Function):
"""Rewrite this op because the param 'lower' and 'upper' in ncnn are fixed
while 'min_value' and 'max_value' are configurable i... | 1,214 | 33.714286 | 78 | py |
mmdeploy | mmdeploy-master/mmdeploy/mmcv/cnn/context_block.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmdeploy.core import FUNCTION_REWRITER
@FUNCTION_REWRITER.register_rewriter(
func_name='mmcv.cnn.bricks.context_block.ContextBlock.spatial_pool', )
def context_block_spatial_pool(ctx, self, x):
"""change the axis index in used in unsqueeze:
... | 1,162 | 29.605263 | 74 | py |
mmdeploy | mmdeploy-master/mmdeploy/mmcv/cnn/hswish.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmdeploy.core import FUNCTION_REWRITER
from mmdeploy.utils import Backend
class hswish(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
return torch.nn.functional.hardswish(x)
@staticmethod
def symbolic(g, x):
... | 635 | 21.714286 | 73 | py |
mmdeploy | mmdeploy-master/mmdeploy/mmcv/cnn/transformer.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from torch import Tensor
from mmdeploy.core import FUNCTION_REWRITER
from mmdeploy.utils import Backend
class MultiHeadAttentionop(torch.autograd.Function):
"""Create onnx::MultiHeadAttention op."""
@staticmethod
def forward(ctx, q: Tensor, k... | 5,643 | 37.394558 | 78 | py |
mmdeploy | mmdeploy-master/mmdeploy/mmcv/ops/nms.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from torch import Tensor
from torch.onnx import symbolic_helper as sym_help
class ONNXNMSop(torch.autograd.Function):
"""Create onnx::NonMaxSuppression op.
NMS in mmcv only supports one class with no batch info. This class assists
in exporting ... | 7,048 | 38.601124 | 79 | py |
mmdeploy | mmdeploy-master/mmdeploy/mmcv/ops/roi_align.py | # Copyright (c) OpenMMLab. All rights reserved.
from typing import List
import torch
from torch import Tensor
from mmdeploy.core import SYMBOLIC_REWRITER
from mmdeploy.utils import Backend, get_backend, get_ir_config
# Here using mmcv.ops.roi_align.__self__ to find
# mmcv.ops.roi_align.RoIAlignFunction, because RoI... | 4,217 | 37.697248 | 78 | py |
mmdeploy | mmdeploy-master/mmdeploy/mmcv/ops/point_sample.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn.functional as F
from mmdeploy.core import FUNCTION_REWRITER
@FUNCTION_REWRITER.register_rewriter(
func_name='mmcv.ops.point_sample', backend='default')
def point_sample__default(ctx, input, points, align_corners=False, **kwargs):
"""A wrapper ar... | 2,546 | 35.913043 | 78 | py |
mmdeploy | mmdeploy-master/mmdeploy/mmcv/ops/nms_rotated.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from torch import Tensor
class ONNXNMSRotatedOp(torch.autograd.Function):
"""Create onnx::NMSRotated op."""
@staticmethod
def forward(ctx, boxes: Tensor, scores: Tensor, iou_threshold: float,
score_threshold: float) -> Tensor:
... | 9,201 | 38.663793 | 77 | py |
mmdeploy | mmdeploy-master/mmdeploy/mmcv/ops/modulated_deform_conv.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmdeploy.core import FUNCTION_REWRITER, SYMBOLIC_REWRITER
from mmdeploy.utils import IR
@FUNCTION_REWRITER.register_rewriter(
'mmcv.ops.modulated_deform_conv.modulated_deform_conv2d',
ir=IR.TORCHSCRIPT)
def modulated_deform_conv__torchscript(c... | 1,932 | 38.44898 | 78 | py |
mmdeploy | mmdeploy-master/mmdeploy/mmcv/ops/roi_align_rotated.py | # Copyright (c) OpenMMLab. All rights reserved.
from typing import List
from torch import Tensor
from mmdeploy.core import SYMBOLIC_REWRITER
# Here using mmcv.ops.roi_align_rotated.__self__ to find
# mmcv.ops.roi_align.RoIAlignRotatedFunction, because RoIAlignRotatedFunction
# is not visible in mmcv.
@SYMBOLIC_REWR... | 2,084 | 39.096154 | 77 | py |
human_motion_manifold | human_motion_manifold-master/h36m_dataset.py | import os
from torch.utils.data import Dataset
import torch
import glob
import numpy as np
MOTION_EXTENSIONS = [
'.bvh', '.npy', '.npz'
]
class H36MDataset(Dataset):
def __init__(self, phase, config, specific_motion=None):
super(H36MDataset, self).__init__()
assert phase in ['train', 'valid',... | 5,205 | 37.850746 | 87 | py |
human_motion_manifold | human_motion_manifold-master/visualization.py |
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, writers
import matplotlib.patheffects as pe
from mpl_toolkits.mplot3d import Axes3D, axes3d
import numpy as np
import torch
import sys
import h5py
import os
from skeleton_h36m import skeleton_H36M
import argparse
def render_animation(data... | 5,138 | 38.229008 | 123 | py |
human_motion_manifold | human_motion_manifold-master/mocap_dataset.py | import numpy as np
import torch
from utils import qeuler_np, qfix, qexp_np
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class MocapDataset:
def __init__(self, path, skeleton, fps):
self._data = self._load(path)
self._fps = fps
self._use_gpu = False
self._sk... | 8,673 | 42.808081 | 141 | py |
human_motion_manifold | human_motion_manifold-master/reconstruction.py | import torch
import argparse
import os
import sys
from skeleton_h36m import skeleton_H36M
from trainer import Trainer
from h36m_dataset import H36MDataset
from torch.utils.data import DataLoader
from utils import get_config, save_motions, set_seed, ensure_dirs, ensure_dir, cycle
def initialize_path(args, config, save=... | 2,306 | 33.432836 | 104 | py |
human_motion_manifold | human_motion_manifold-master/random_sample.py | import torch
import argparse
import os
import sys
from skeleton_h36m import skeleton_H36M
from trainer import Trainer
from h36m_dataset import H36MDataset
from utils import get_config, save_motions, set_seed, ensure_dirs, ensure_dir
def initialize_path(args, config, save=True):
config['main_dir'] = os.path.join('.... | 1,711 | 30.703704 | 87 | py |
human_motion_manifold | human_motion_manifold-master/utils.py | import numpy as np
import torch
import torch.nn.init as init
from torch.optim import lr_scheduler
import h5py
import os
import math
import yaml
import shutil
import random
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
#############################################################################... | 28,678 | 36.148964 | 121 | py |
human_motion_manifold | human_motion_manifold-master/model.py | from torch import nn
from torch.autograd import Variable
import torch
import torch.nn.functional as F
import numpy as np
##################################################################################
# Generator
##################################################################################
class MotionGen(nn.M... | 14,185 | 37.237197 | 110 | py |
human_motion_manifold | human_motion_manifold-master/skeleton.py | import torch
import numpy as np
from utils import qmul_np, qmul, qrot, expmap2rotmat_tensor, quat2rotmat
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class Skeleton:
def __init__(self, offsets, parents, joints_left=None, joints_right=None):
assert len(offsets) == len(parents)
... | 9,713 | 44.820755 | 182 | py |
human_motion_manifold | human_motion_manifold-master/train.py | import torch
import argparse
import os
import sys
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from torch.utils.data import DataLoader
from skeleton_h36m import skeleton_H36M
from trainer import Trainer
from h36m_dataset import H36MDataset
from utils import get_config, set_seed, initialize_pa... | 4,346 | 38.162162 | 99 | py |
human_motion_manifold | human_motion_manifold-master/trainer.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import os
import h5py
import numpy as np
from model import MotionGen, MotionDis, Gaussian_P_Z
from utils import unNormalizeData_tensor_batch, get_model_list, \
get_scheduler, lerp, slerp, prepare_next_batch, expma... | 19,665 | 43.392777 | 129 | py |
SGD_exit_time | SGD_exit_time-main/exit_time/utility.py | #!/usr/bin/env python
# coding: utf-8
# -------------------------------------------------------------------
import datetime
def report(rank, *args):
if rank == 0:
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')+' '+' '.join(map(str,args)).replace('\n',''), flush=True)
# --------------------... | 4,672 | 35.795276 | 128 | py |
SGD_exit_time | SGD_exit_time-main/exit_time/exit_time.py | from utility import *
import argparse
args = argparse.ArgumentParser()
args.add_argument('--setup', default='', type=str)
args.add_argument('--sanity_check', action='store_true')
dataset = None
#
import torch
import copy
def get_exit_time(config, lr, sharpness, batch_size, r):
model = get_model(config, sharpness)
... | 11,100 | 41.370229 | 104 | py |
SGD_exit_time | SGD_exit_time-main/exit_time/model_zoo.py | import copy
import torch
class Base(torch.nn.Module):
def __init__(self):
super(Base, self).__init__()
def get_param(self):
state = copy.deepcopy(self.state_dict())
for k in state:
state[k] = state[k].cpu().detach().numpy()
return state
def set_param(self, param... | 917 | 31.785714 | 93 | py |
SGD_exit_time | SGD_exit_time-main/exit_time/dataset.py | from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import torch
class CIFAR2(Dataset):
def __init__(self, root, train, transform=None):
"""
Args:
csv_file (string): Path to the csv file with annotations.
root_dir (string): Directory wit... | 3,112 | 39.428571 | 92 | py |
SGD_exit_time | SGD_exit_time-main/exit_time/CIFAR10_model_zoo.py | #!/usr/bin/env python
# coding: utf-8
# -------------------------------------------------------------------
import copy
import torch
class BaseNNs(torch.nn.Module):
def __init__(self, dropout_ratio):
super(BaseNNs, self).__init__()
self.Dropout = torch.nn.Dropout(p=dropout_ratio)
self.Dro... | 2,375 | 33.941176 | 69 | py |
SGD_exit_time | SGD_exit_time-main/exit_time/AVILA2_model_zoo.py | import torch
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
dtype = torch.float
# -------------------------------------------------------------------
import copy
class BaseNNs(torch.nn.Module):
def __init__(self, k):
super(BaseNNs, self).__init__()
def get_param(self):
... | 3,240 | 32.412371 | 122 | py |
SGD_exit_time | SGD_exit_time-main/exit_time/sharpness/Minimum.py | #!/usr/bin/env python
# coding: utf-8
# -------------------------------------------------------------------
import datetime
def report(*args):
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+' '+' '.join(map(str,args)).replace('\n',''))
# ---------------------------------------------------------------... | 4,679 | 36.741935 | 109 | py |
SGD_exit_time | SGD_exit_time-main/exit_time/sharpness/tools/Hessian_trace.py | #!/usr/bin/env python
# coding: utf-8
# -------------------------------------------------------------------
import datetime
def report(*args):
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+' '+' '.join(map(str,args)).replace('\n',''))
# ---------------------------------------------------------------... | 2,076 | 33.04918 | 109 | py |
SGD_exit_time | SGD_exit_time-main/exit_time/sharpness/tools/Hessian_diag.py | #!/usr/bin/env python
# coding: utf-8
# -------------------------------------------------------------------
import datetime
def report(*args):
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+' '+' '.join(map(str,args)).replace('\n',''))
# ---------------------------------------------------------------... | 2,255 | 34.809524 | 109 | py |
SGD_exit_time | SGD_exit_time-main/exit_time/sharpness/tools/gradient_per_example.py | #!/usr/bin/env python
# coding: utf-8
# ref
# - https://github.com/cybertronai/autograd-hacks
# - https://github.com/jusjusjus/autograd-hacks
import torch
def _is_support_layer(layer):
return layer.__class__.__name__ in {'Linear', 'Conv2d'}
def _get_layer_type(layer):
return layer.__class__.__name__
# -----------... | 2,771 | 30.146067 | 104 | py |
SGD_exit_time | SGD_exit_time-main/fluctuation/final.py | #!/usr/bin/env python
# coding: utf-8
"""
import torch
torch.set_num_threads(7)
torch.set_num_interop_threads(7)
torch.backends.cudnn.benchmark = True
#"""
from utility import *
# ------------------------------------------------------
import argparse
import datetime
def get_config():
args = argparse.ArgumentParser... | 2,603 | 30.373494 | 106 | py |
SGD_exit_time | SGD_exit_time-main/fluctuation/MNIST_model_zoo.py | #!/usr/bin/env python
# coding: utf-8
# -------------------------------------------------------------------
import copy
import torch
class BaseNNs(torch.nn.Module):
def __init__(self, dropout_ratio):
super(BaseNNs, self).__init__()
self.Dropout = torch.nn.Dropout(p=dropout_ratio)
def get_param... | 3,741 | 47.597403 | 105 | py |
SGD_exit_time | SGD_exit_time-main/fluctuation/utility.py | #!/usr/bin/env python
# coding: utf-8
# -------------------------------------------------------------------
import datetime
def report(*args):
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')+' '+' '.join(map(str,args)).replace('\n',''))
# ------------------------------------------------------------... | 3,989 | 38.9 | 112 | py |
SGD_exit_time | SGD_exit_time-main/fluctuation/dataset.py | from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import torch
class CIFAR2(Dataset):
"""Face Landmarks dataset."""
def __init__(self, root, train, transform=None):
"""
Args:
csv_file (string): Path to the csv file with annotations.
... | 1,029 | 33.333333 | 76 | py |
SGD_exit_time | SGD_exit_time-main/fluctuation/CIFAR2_model_zoo.py | #!/usr/bin/env python
# coding: utf-8
# -------------------------------------------------------------------
import copy
import torch
class BaseNNs(torch.nn.Module):
def __init__(self, dropout_ratio):
super(BaseNNs, self).__init__()
self.Dropout = torch.nn.Dropout(p=dropout_ratio)
self.Dro... | 6,176 | 49.219512 | 109 | py |
SGD_exit_time | SGD_exit_time-main/fluctuation/CIFAR10_model_zoo.py | #!/usr/bin/env python
# coding: utf-8
# -------------------------------------------------------------------
import copy
import torch
class BaseNNs(torch.nn.Module):
def __init__(self, dropout_ratio):
super(BaseNNs, self).__init__()
self.Dropout = torch.nn.Dropout(p=dropout_ratio)
self.Dro... | 6,177 | 49.227642 | 109 | py |
SGD_exit_time | SGD_exit_time-main/fluctuation/draw.py | #!/usr/bin/env python
# coding: utf-8
"""
import torch
torch.set_num_threads(7)
torch.set_num_interop_threads(7)
torch.backends.cudnn.benchmark = True
#"""
from utility import *
# ------------------------------------------------------
import argparse
args = argparse.ArgumentParser()
args.add_argument('--config_fn', d... | 3,475 | 29.491228 | 102 | py |
SGD_exit_time | SGD_exit_time-main/fluctuation/dump_trails.py | #!/usr/bin/env python
# coding: utf-8
"""
import torch
torch.set_num_threads(7)
torch.set_num_interop_threads(7)
torch.backends.cudnn.benchmark = True
#"""
from utility import *
# ------------------------------------------------------
import argparse
args = argparse.ArgumentParser()
args.add_argument('--config_fn', de... | 5,540 | 33.203704 | 106 | py |
SGD_exit_time | SGD_exit_time-main/fluctuation/train.py | #!/usr/bin/env python
# coding: utf-8
itr = 0
from utility import *
# ------------------------------------------------------
import argparse
args = argparse.ArgumentParser()
args.add_argument('--config_fn', default='', type=str)
# -------------------------------------------------------------------
import torch
import... | 3,539 | 31.477064 | 101 | py |
SGD_exit_time | SGD_exit_time-main/fluctuation/sharpness/Minimum.py | #!/usr/bin/env python
# coding: utf-8
# -------------------------------------------------------------------
import datetime
def report(*args):
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+' '+' '.join(map(str,args)).replace('\n',''))
# ---------------------------------------------------------------... | 4,679 | 36.741935 | 109 | py |
SGD_exit_time | SGD_exit_time-main/fluctuation/sharpness/tools/Hessian_trace.py | #!/usr/bin/env python
# coding: utf-8
# -------------------------------------------------------------------
import datetime
def report(*args):
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+' '+' '.join(map(str,args)).replace('\n',''))
# ---------------------------------------------------------------... | 2,076 | 33.04918 | 109 | py |
SGD_exit_time | SGD_exit_time-main/fluctuation/sharpness/tools/Hessian_diag.py | #!/usr/bin/env python
# coding: utf-8
# -------------------------------------------------------------------
import datetime
def report(*args):
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+' '+' '.join(map(str,args)).replace('\n',''))
# ---------------------------------------------------------------... | 2,255 | 34.809524 | 109 | py |
SGD_exit_time | SGD_exit_time-main/fluctuation/sharpness/tools/gradient_per_example.py | #!/usr/bin/env python
# coding: utf-8
# ref
# - https://github.com/cybertronai/autograd-hacks
# - https://github.com/jusjusjus/autograd-hacks
import torch
def _is_support_layer(layer):
return layer.__class__.__name__ in {'Linear', 'Conv2d'}
def _get_layer_type(layer):
return layer.__class__.__name__
# -----------... | 2,771 | 30.146067 | 104 | py |
feature-dropout | feature-dropout-main/src/objectives/simclr.py | import math
import torch
import numpy as np
from src.utils.utils import l2_normalize
import torch
class SimCLRObjective(torch.nn.Module):
def __init__(self, outputs1, outputs2, t, push_only=False):
super().__init__()
self.outputs1 = l2_normalize(outputs1, dim=1)
self.outputs2 = l2_normal... | 958 | 33.25 | 95 | py |
feature-dropout | feature-dropout-main/src/objectives/adversarial.py | import math
import torch
import numpy as np
from src.utils.utils import l2_normalize
from src.objectives.simclr import SimCLRObjective
from src.objectives.infonce import NoiseConstrastiveEstimation
class AdversarialSimCLRLoss(object):
def __init__(
self,
embs1,
embs2,
t=0.07,
... | 2,450 | 28.890244 | 94 | py |
feature-dropout | feature-dropout-main/src/objectives/memory_bank.py | import torch
import numpy as np
from src.utils.utils import l2_normalize
class MemoryBank(torch.nn.Module):
"""For efficiently computing the background vectors."""
def __init__(self, size, dim, dtype=float):
super().__init__()
self.size = size
self.dim = dim
self.register_buf... | 3,156 | 34.875 | 107 | py |
feature-dropout | feature-dropout-main/src/objectives/infonce.py | import math
import torch
import numpy as np
from src.utils.utils import l2_normalize
class NoiseConstrastiveEstimation(object):
def __init__(self, indices, outputs, memory_bank, k=4096, t=0.07, m=0.5, **kwargs):
self.k, self.t, self.m = k, t, m
self.indices = indices.detach()
self.outpu... | 1,319 | 33.736842 | 87 | py |
feature-dropout | feature-dropout-main/src/models/resnet_small.py | '''A version of ResNet for smaller input sizes.'''
import torch
import torch.nn as nn
import torch.nn.functional as F
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, kerne... | 4,486 | 33.251908 | 102 | py |
feature-dropout | feature-dropout-main/src/models/viewmaker.py | '''Core architecture and functionality of the viewmaker network.
Adapted from the transformer_net.py example below, using methods proposed in Johnson et al. 2016
Link:
https://github.com/pytorch/examples/blob/0c1654d6913f77f09c0505fb284d977d89c17c1a/fast_neural_style/neural_style/transformer_net.py
'''
import torch
i... | 8,994 | 41.03271 | 131 | py |
feature-dropout | feature-dropout-main/src/models/resnet.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
import torch.utils.model_zoo as model_zoo
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106c... | 7,345 | 29.995781 | 82 | py |
feature-dropout | feature-dropout-main/src/models/mlp.py | import torch.nn as nn
class MLP(nn.Module):
def __init__(self, input_dim=2048, hidden_size=4096, output_dim=256):
super().__init__()
self.output_dim = output_dim
self.input_dim = input_dim
self.model = nn.Sequential(
nn.Linear(input_dim, hidden_size, bias=False),
... | 521 | 25.1 | 73 | py |
feature-dropout | feature-dropout-main/src/models/transfer.py | import torch
import torch.nn as nn
class LogisticRegression(nn.Module):
def __init__(self, num_inputs, num_outputs):
super().__init__()
self.num_inputs = num_inputs
self.num_outputs = num_outputs
self.linear = nn.Linear(num_inputs, num_outputs)
def forward(self, x):
r... | 341 | 21.8 | 56 | py |
feature-dropout | feature-dropout-main/src/datasets/audio_mnist.py | import os
import torch
import random
import librosa
import torchaudio
import numpy as np
from glob import glob
import nlpaug.flow as naf
import nlpaug.augmenter.audio as naa
import nlpaug.augmenter.spectrogram as nas
from torchvision.transforms import Normalize
from torch.utils.data import Dataset
from nlpaug.augmente... | 9,815 | 35.088235 | 170 | py |
feature-dropout | feature-dropout-main/src/datasets/datasets.py | import torch
import random
from torchvision import transforms
from PIL import ImageFilter, Image
from src.datasets.cifar10 import CIFAR10, CIFAR10Corners, CIFAR10Shapes, CIFAR10Digits, CIFAR10Letters
from src.datasets.data_statistics import get_data_mean_and_stdev
DATASET = {
'cifar10': CIFAR10,
'cifar10shap... | 6,307 | 33.097297 | 102 | py |
feature-dropout | feature-dropout-main/src/datasets/cifar10.py | import os
import copy
import getpass
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import random
import string
import math
import torch
import torch.utils.data as data
from torchvision import transforms, datasets
from src.datasets.root_paths import DATA_ROOTS
from torchvision.datasets import MNIST
cl... | 11,805 | 33.023055 | 119 | py |
feature-dropout | feature-dropout-main/src/systems/image_systems.py | import os
import random
import dotmap
import numpy as np
from dotmap import DotMap
from collections import OrderedDict
from sklearn.metrics import f1_score
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision
from src.datasets import datasets
fr... | 32,189 | 41.299606 | 161 | py |
feature-dropout | feature-dropout-main/src/systems/audio_systems.py | """
Try some simple SimCLR inspired audio adaptations. Audio augmentations
include cropping, noise, pitch, and speed. We should fit this on Librispeech.
"""
import os
import math
import random
import librosa
import numpy as np
from dotmap import DotMap
from itertools import chain
from sklearn.metrics import f1_score
f... | 42,677 | 40.155256 | 110 | py |
feature-dropout | feature-dropout-main/src/utils/callbacks.py | import math
from pytorch_lightning import Callback
class MoCoLRScheduler(Callback):
def __init__(self,
initial_lr=0.03,
use_cosine_scheduler=False,
schedule=(120, 160),
max_epochs=200):
super().__init__()
self.lr = initial_lr
... | 957 | 29.903226 | 74 | py |
feature-dropout | feature-dropout-main/src/utils/setup.py | import os
import sys
import torch
import logging
import getpass
import numpy as np
from pprint import pprint
from dotmap import DotMap
from logging import Formatter
from time import strftime, localtime, time
from logging.handlers import RotatingFileHandler
from src.utils.utils import load_json, save_json
DEFAULT_EXP_... | 4,379 | 33.21875 | 107 | py |
feature-dropout | feature-dropout-main/src/utils/utils.py | import os
import json
import shutil
import torch
import numpy as np
from collections import Counter, OrderedDict
from dotmap import DotMap
from matplotlib import pyplot as plt
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def ... | 2,333 | 24.369565 | 80 | py |
feature-dropout | feature-dropout-main/scripts/run_image.py | import os
from copy import deepcopy
from src.systems import image_systems
from src.utils.utils import load_json
from src.utils.setup import process_config
from src.utils.callbacks import MoCoLRScheduler
import random, torch, numpy
import pytorch_lightning as pl
import wandb
torch.backends.cudnn.benchmark = True
SYST... | 3,559 | 33.230769 | 91 | py |
feature-dropout | feature-dropout-main/scripts/run_audio.py | import os
import wandb
from copy import deepcopy
from src.systems import audio_systems
from src.utils.utils import load_json
from src.utils.setup import process_config
import random, torch, numpy
import pytorch_lightning as pl
SYSTEM = {
'PretrainExpertInstDiscSystem': audio_systems.PretrainExpertInstDiscSystem,
... | 3,921 | 34.017857 | 91 | py |
moco-v3 | moco-v3-main/main_lincls.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import builtins
import math
import os
import random
import shutil
import time
import ... | 20,441 | 37.937143 | 119 | py |
moco-v3 | moco-v3-main/vits.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import math
import torch
import torch.nn as nn
from functools import partial, reduce
from operator import mul
from timm.mod... | 5,847 | 39.895105 | 120 | py |
moco-v3 | moco-v3-main/convert_to_deit.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import os
import torch
if __name__ == '__main__':
parser = argparse.ArgumentPar... | 1,458 | 35.475 | 96 | py |
moco-v3 | moco-v3-main/main_moco.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import builtins
import math
import os
import random
import shutil
import time
import ... | 17,948 | 39.886105 | 121 | py |
moco-v3 | moco-v3-main/transfer/oxford_flowers_dataset.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import print_function
from PIL import Image
from typing import Any, Callable, Optional, Tuple
import numpy ... | 1,964 | 27.897059 | 72 | py |
moco-v3 | moco-v3-main/transfer/datasets.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import json
import os
from torchvision import datasets, transforms
from torchvision.datasets.folder import ImageFolder, def... | 3,032 | 39.44 | 106 | py |
moco-v3 | moco-v3-main/transfer/oxford_pets_dataset.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from PIL import Image
from typing import Any, Callable, Optional, Tuple
import numpy as np
import os
import os.path
import ... | 1,960 | 27.838235 | 80 | py |
moco-v3 | moco-v3-main/moco/builder.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
class MoCo(nn.Module):
"""
Build a MoCo model with a base encoder, a momentum e... | 4,926 | 34.702899 | 114 | py |
moco-v3 | moco-v3-main/moco/loader.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from PIL import Image, ImageFilter, ImageOps
import math
import random
import torchvision.transforms.functional as tf
clas... | 1,182 | 27.166667 | 82 | py |
moco-v3 | moco-v3-main/moco/optimizer.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
class LARS(torch.optim.Optimizer):
"""
LARS optimizer, no rate scaling or weight decay for parameters... | 1,639 | 36.272727 | 113 | py |
Relative_Human | Relative_Human-master/RH_evaluation/evaluation.py | import os, sys
import os.path as osp
import numpy as np
import cv2
import torch
from .matching import match_2d_greedy
Relative_Human_dir = '/home/yusun/data_drive/dataset/Relative_human'
results_path = '/home/yusun/data_drive/evaluation_results/Relative_results/zip_files/CRMH_RH_results.npz'
relative_age_types = ['... | 13,517 | 48.881919 | 204 | py |
Relative_Human | Relative_Human-master/RH_evaluation/eval_SMAP_RH_results.py | import torch
import numpy as np
import os
import json
from itertools import product
# /path/to/SMAP_RH_results.npz
results_path = '/home/yusun/data_drive/evaluation_results/Relative_results/zip_files/SMAP_RH_results.npz'
# /path/to/Relative_human
RH_dir = '/home/yusun/data_drive/dataset/Relative_human'
def l2_error(j... | 20,213 | 41.826271 | 206 | py |
Relative_Human | Relative_Human-master/RH_evaluation/eval_3DMPPE_RH_results.py | import torch
import numpy as np
import os
# /path/to/SMAP_RH_results.npz
results_path = '/home/yusun/data_drive/evaluation_results/Relative_results/zip_files/3DMPPE_RH_results.npz'
# /path/to/Relative_human
RH_dir = '/home/yusun/data_drive/dataset/Relative_human'
relative_depth_types = ['eq', 'cd', 'fd']
relative_age... | 6,154 | 50.291667 | 202 | py |
S2-transformer-HSI | S2-transformer-HSI-main/test.py |
import os
import time
import torch
import scipy
import datetime
import argparse
from utils_spectral import *
from network_backbone_channelattn import SpaSpe_Attn_Net
parser = argparse.ArgumentParser()
# GPU setting #################################################
parser.add_argument('--device', default='0,1', hel... | 7,036 | 43.257862 | 263 | py |
S2-transformer-HSI | S2-transformer-HSI-main/network.py |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
... | 60,705 | 42.392423 | 135 | py |
S2-transformer-HSI | S2-transformer-HSI-main/utils.py |
import os
import math
import torch
import logging
import numpy as np
import scipy.io as sio
from ssim_torch import ssim
patch_size = 256
def generate_masks(mask_path, batch_size):
mask = sio.loadmat(mask_path + '/mask.mat')
mask = mask['mask']
mask3d = np.tile(mask[:,:,np.newaxis],(1,1,28))
mask3d ... | 6,120 | 32.266304 | 130 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/load_dse_checkpoint_example.py | import argparse
import torch
import examples.run_classifier_dataset_utils as classifier_utils
from factories.dse_model_factory import DSEModelFactory
from pytorch_pretrained_bert import BertTokenizer
def load_model(params, processor):
label_list = processor.get_labels()
return DSEModelFactory.create_model(p... | 4,831 | 52.688889 | 150 | py |
Distilled-Sentence-Embedding | Distilled-Sentence-Embedding-master/finetune_bert.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a cop... | 27,254 | 47.844086 | 150 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.