content
stringlengths
200
198k
repo
stringlengths
4
186
path
stringclasses
1 value
license
stringclasses
101 values
size
int64
200
198k
sha
stringlengths
40
40
lang
stringclasses
1 value
ext
stringclasses
1 value
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import math from math import log import torch import torch.nn.functional as F from fairseq import metrics, utils from fairseq.criterions impo...
fairseq/criterions/glat_loss.py
MIT
8,533
3a30bad0dc4620b8de0688670c92df89de5e428c
Python
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 11 16:34:10 2019 @author: lingkaikong """ from __future__ import print_function import torch import torch.nn as nn import torch.optim as optim import torch.backends.cudnn as cudnn import os import argparse import models import data_loader import t...
SVHN/initializartion/2/resnet_bayesian_svhn.py
Apache-2.0
5,997
651b6c87fc1aea2eb399ca53007db57737872066
Python
py
#!/usr/bin/env python3 # Copyright (c) 2020-2022, NVIDIA CORPORATION. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted # provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice...
samples/mlp_learning_an_image_pytorch.py
BSD-3-Clause
7,972
3a30d890f3cde74ceff5a92c6771810915a6ad0f
Python
py
import os, json import numpy as np import networkx as nx from tqdm import trange import torch import torch.utils from torch.nn import Linear from torch_scatter import scatter_mean from torch_geometric.nn import MessagePassing from torch_geometric.data import DataLoader from torch_geometric.utils import degree from tor...
models/LEGS.py
MIT
8,513
b2c20653edbbf73e282995211eda440bca39aecb
Python
py
# -*- coding: utf-8 -*- """ Model definition functions and weight loading. """ from __future__ import print_function, division, unicode_literals from os.path import exists import torch import torch.nn as nn from torch.autograd import Variable from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence, ...
metric/torchMoji/torchmoji/model_def.py
MIT
14,042
d7eec96367ec675b34168c651aa49ec610be1cff
Python
py
# Author: Vincent Zhang # Mail: zhyx12@gmail.com # ---------------------------------------------- import torch from collections.abc import Sequence from mmcv.runner import get_dist_info from mmcv.parallel import MMDistributedDataParallel import numpy as np import random import torch.distributed as dist from mmcv.utils ...
fastda/utils/basic_utils.py
MIT
6,695
340f8469ae39a9337d9895d140cab4be1408bf83
Python
py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from itertools import count from typing import Tuple, Union class StandardScaler: def __init__(self) -> None: self.mu = None self.std = None def fit(self, data: torch.Tensor) -> None: self.mu = torc...
callbacks/dynamics/stochastic.py
MIT
11,642
b299abc48f834964a7f0e9db082b0b082462dea7
Python
py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import numpy as np import time import os from six.moves import cPickle import opts3 as opts import models from dataloader3 import * from dataloaderraw import * import eval_utils import argparse im...
eval.py
MIT
2,650
7006c1624a4fbc3fbf539246fac41bd7d1eb221d
Python
py
# Copyright (c) 2019 Western Digital Corporation or its affiliates. import logging import torch import torch.nn as nn import torch.nn.functional as F # from ..registry import NECKS from ..builder import NECKS # from mmdet.models.utils import ConvLayer from mmcv.cnn import xavier_init from mmcv.runner import load_c...
mmdet/models/necks/yolo_neck.py
Apache-2.0
6,570
7c4fd4ceebe0444a5e7e74ce4de375a735617fe5
Python
py
from functools import partial from typing import Callable, Any, List, Optional import torch import torch.nn as nn from torch import Tensor from ..transforms._presets import ImageClassification from ..utils import _log_api_usage_once from ._api import WeightsEnum, Weights from ._meta import _IMAGENET_CATEGORIES from ....
torchvision/models/shufflenetv2.py
BSD-3-Clause
14,320
3a314c867ca3268672e0b9291690f43fc1ec588f
Python
py
# Display transformed images from torchvision import models, transforms, datasets import torch from PIL import Image import json import numpy as np import os import csv import matplotlib.pyplot as plt from tqdm import tqdm import scipy.misc # Transform for input images transform = transforms.Compose([ transforms.R...
disp_transformed_im.py
MIT
1,797
3a31505174482f8f3a68e72cbb8b84d2e274545d
Python
py
import torch # torch.autograd.set_detect_anomaly(True) import torch.nn as nn import torch.nn.functional as F import numpy as np import cv2 from plyfile import PlyData, PlyElement import sys # Misc img2mse = lambda x, y : torch.mean((x - y) ** 2) mse2psnr = lambda x : -10. * torch.log(x) / torch.log(torch.Tensor([10.]...
run_nerf_helpers.py
MIT
15,033
3a3158ed147df88fb1cf05ca11f79db4ca370a1e
Python
py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def hidden_init(layer): fan_in = layer.weight.data.size()[0] lim = 1. / np.sqrt(fan_in) return (-lim, lim) class Actor(nn.Module): """Actor (Policy) Model.""" def __init__(self, state_size, action_size, seed, f...
p2_continuous-control/model.py
MIT
2,869
3a3164076016f3c78b45ee10b97545d09ec32f6d
Python
py
# -*- coding: utf-8 -*- import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from data import voc as cfg from ..box_utils import match, match_offset, match_four_corners, match_only_four_corners, log_sum_exp from ..box_utils import decode, decode_four_corners, decode_fou...
layers/modules/multibox_loss.py
MIT
46,547
3a3173309e1d480c23012e00a4ca72b8d6b493cf
Python
py
# File under the MIT license, see https://github.com/adefossez/julius/LICENSE for details. # Author: adefossez, 2020 import random import unittest import torch as th from julius import LowPassFilter, LowPassFilters, lowpass_filter, resample_frac from julius.core import pure_tone def delta(a, b, ref, fraction=0.9):...
tests/test_lowpass.py
MIT
3,226
65496520257aa9d474c780777f54dd854a68997d
Python
py
import glob import os from shutil import copyfile import subprocess import numpy as np import torch newpath = '/run/media/rice/DATA/devector_data/' speakers = set([""]) # if os.path.isfile(newpath): # print("yes") # else: # os.mkdir(newpath) """ data_thchs30 """ def getdata(path,speakers): length = len(pa...
data.py
BSD-3-Clause
2,292
5f43c5b4f5980868c29b4c9fb5f2480a63812dbf
Python
py
import torch import torch.nn as nn import detectron2.lib.ops as ops def get_conv_op(conv="Conv2d", **kwargs): if len(conv) == 0: return None conv_op = { "Conv2d": nn.Conv2d, # "Conv2dWS": ops.Conv2dWS, # "DeformConv": ops.DeformConvPack, # "MDeformConv": ops.ModulatedD...
detectron2/lib/layers/wrappers.py
Apache-2.0
3,174
3a31da44d0d135adb56dee7b917c5ad07d02f8ad
Python
py
"""Testing recognition module.""" import pytest import torch from gpssm.models.components.recognition_model import OutputRecognition, \ ZeroRecognition, NNRecognition, ConvRecognition, LSTMRecognition @pytest.fixture(params=[OutputRecognition, ZeroRecognition, NNRecognition, ConvRecognitio...
gpssm/models/components/test/test_recognition.py
MIT
1,215
3a31e0dd452a8d85f5fdb18bb1f7e4610e30573c
Python
py
import torch MAX_RESAMPLE = 10000 class Lipo: def __init__(self, k, d, a, b): assert b > a self.k = k self.d = d self.a = a self.b = b def scale(self, X): "Assumes X is a matrix of values in [0, 1]." return X * (self.b-self.a) +self.a def sample(s...
src/src/globaloptim/Lipo.py
MIT
1,173
f97b4d13e976da6ac1abb7135cd89a7c9caac506
Python
py
import torch import torch.nn as nn from torchvision import models, datasets, transforms from torch.nn import functional as F def get_backbone(name, pretrained=True, replace_stride_with_dilation=[False, False, False]): """ Loading backbone, defining names for skip-connections and encoder output. """ # TODO: ...
backboned_unet/unet.py
MIT
10,491
3a3247c4da0f4241dfd88f38a926e40c644d029d
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import logging import numpy as np from typing import Dict import torch from torch import nn from detectron2.layers import ShapeSpec from detectron2.structures import Boxes, Instances, pairwise_iou from detectron2.utils.events import get_event_stora...
detectron2/modeling/roi_heads/roi_heads.py
Apache-2.0
31,041
7c9ab4dca764ef4d16cd8e6d2506a60ca7ab3ed6
Python
py
# https://github.com/anandsaha/pytorch.cyclic.learning.rate import numpy as np from torch.optim.optimizer import Optimizer class CyclicLR(object): """Sets the learning rate of each parameter group according to cyclical learning rate policy (CLR). The policy cycles the learning rate between two boundaries ...
attributes_classify/CyclicLR.py
MIT
6,735
3a3271554082f8d1a5d3dc1338e8bfb14c6dcbfa
Python
py
import numpy as np import torch import copy import sys sys.path.append('../') from utils.manip import clip_image_values def unravel_index(index, shape): out = [] for dim in reversed(shape): out.append(index % dim) index = index // dim return tuple(reversed(out)) def linear_solver(x_0, nor...
fool/linear_solver.py
Apache-2.0
1,526
45e72de4ba4d1d97cc51cbe4444202a44fbc4f8f
Python
py
import torch import torch.nn as nn from torch.nn import init import functools from torch.optim import lr_scheduler ############################################################################### # Helper Functions ############################################################################### def get_norm_layer(norm_...
models/networks.py
BSD-3-Clause
31,699
ffaa9247eb5333455cabb1ed7c7f0ab862761840
Python
py
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. import glob import os import shutil from os import path from setuptools import find_packages, setup from typing import List import torch from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension torch_ver = [int(x) for x in to...
setup.py
Apache-2.0
7,808
e64eb42144b9b2a81e890221972c56d84ff35f1c
Python
py
"""Common blur operations. Blur may be caused by unstable camera sensor, dirty lens, relative motion between the camera and the subject, insufficient illumination, out of focus settings, imaging while zooming, subject behind a frosted glass window, or shallow depth of field. The Blur group includes: 1) GaussianBlu...
straug/blur.py
Apache-2.0
6,255
347682daea727acdca784dec891f7e840a4ebec6
Python
py
# Copyright The PyTorch Lightning team. # # 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
flash/core/classification.py
Apache-2.0
5,556
5fb983983ca730645bc3a01e5b85a8dd04678c22
Python
py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2021 The TARTRL Authors. # # 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 copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unle...
dfd/runners/test.py
Apache-2.0
2,327
12f20444bde199bddb2af6bf13eb7005d73c564c
Python
py
import os import torch from Utils.Helpers import * from experiments import * # Experiments params: python_env_path = '$HOME/anaconda3/envs/thesis_env/bin/python3' exps = [exp_0, exp_1, exp_2, exp_3, exp_4, exp_5, exp_6, exp_7, exp_8] # Run experiments: working_dir = Path('') if not Path('experiments').exists(): P...
run_experiments.py
MIT
852
d77fd25496896af27185d10d6c0de8f8a909d692
Python
py
from torch import nn from omegaconf import DictConfig from models.edge_conv import DynamicEdgeConv, DynamicEdgeConv_DGM, DynamicEdgeConvMINE class EdgeNet(nn.Module): """EdgeNet""" def __init__(self, cfg: DictConfig): super().__init__() self.cfg = cfg dynamic_edge_type = { ...
models/EdgeNet.py
MIT
1,645
3a32fd880f7b06110191fbcdf40ebfb6c8e3ff17
Python
py
import torch import gdgrid import transforms import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches from datetime import datetime np.random.seed(1) def random_draw(dataset): now = datetime.now().time().strftime("%H_%M") num2label = {1:'badge', 2:'offground', 3:'ground', 4:'sa...
data/tst_draw.py
MIT
1,768
7040d6afe533d978f53ca804a77768eed0596dbf
Python
py
from typing import List, Tuple import numpy as np import torch from ..builder import BBOX_ASSIGNERS from .base_assigner import BaseAssigner from .assign_result import AssignResult @BBOX_ASSIGNERS.register_module() class PointKptAssigner(BaseAssigner): """Assign a corresponding gt bbox or background to each point...
code/core/bbox/assigners/point_kpt_assigner.py
MIT
4,773
52b619caae92987a2e64c3a189f10d8da2c5d27d
Python
py
# Copyright 2021 Google LLC # # 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
corenet/debug_helpers.py
Apache-2.0
2,504
3a3313f52df18c6d960d7bf7d41eddc6abb3b254
Python
py
import torch import torch.nn as nn class BNConvt(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride, padding, bias=False, eps=1e-5, momentum=0.1, conv_first=True, relu=False): super(BNConvt, self).__init__() if conv_first: self.main...
models/BNConvt.py
BSD-3-Clause
1,923
03f044658d60579a48068ce9abea9d7c46bb3a4b
Python
py
from SAC_Networks import Actor_Critic,ReplayBuffer from copy import deepcopy import numpy as np import torch from torch.optim import Adam import gym import timeit import itertools def sac(): polyak_avg=0.995 lr=1e-3 alpha=0.2 gamma=0.99 #(env.observation_space) #print(env.act...
SAC/SAC_CORE.py
CC0-1.0
2,846
3a3337260083d3908038dbd955196785027983c9
Python
py
# -*- coding: utf-8 -*- """ Created on Fri Feb 8 22:10:13 2019 @author: Yuntian Chen """ import numpy as np from .grid_configuration import config import torch.utils.data import torch import pandas as pd from scipy import signal # hyper parameters use_forcast_weather = 1 # whether to use the forecast d...
src/tgdlf/grid_data_v2.py
MIT
18,488
10bd625c15ac9a79189ffe2af32af1bf884b05f4
Python
py
import torch import copy import sys import time import pickle import numpy as np import warnings from scipy.interpolate import Rbf from collections import OrderedDict from constants import * def update_progress(index, length, **kwargs): ''' display progress Input: `index`: (i...
functions.py
MIT
44,039
f9aaae456e4d822f52f88add625f58b4c2da82c4
Python
py
import torch from optparse import OptionParser import rdkit from rdkit.Chem import Descriptors from rdkit.Chem import MolFromSmiles, MolToSmiles from rdkit.Chem import rdmolops from . import sascorer import numpy as np from jtnn.jtnn import * lg = rdkit.RDLogger.logger() lg.setLevel(rdkit.RDLogger.CRITICAL) pars...
jtnn/bo/gen_latent.py
MIT
2,906
ff5b5dda06167c2b17ef6e43931a664e9a94f5cd
Python
py
# Copyright (C) 2021 Maxime Robeyns <maximerobeyns@gmail.com> # # 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
bdrl/agents/dqn_agent.py
Apache-2.0
5,730
5e526542b91eae6ccd3aa8be17d60fb5ebc60608
Python
py
import torch import torch.nn as nn from utils.debug_tools import save_image_stack, clear_debug_image class SmoothModel(nn.Module): def __init__(self, base_model, mean=0, std=0.5, sample_size=20): super(SmoothModel, self).__init__() self.base_model = base_model self.mean = mean sel...
custom_models/smooth_model.py
MIT
3,198
341c8041c00846a071d26aacdc187aaaee593567
Python
py
# -*- encoding:utf-8 -*- """ The optimizer is identical with huggingface's implementation. See https://github.com/huggingface/pytorch-pretrained-BERT """ import math import torch from torch.optim import Adam from torch.optim import Optimizer from torch.nn.utils import clip_grad_norm_ def warmup_cosine(x, ...
uer/utils/optimizers.py
Apache-2.0
6,427
3a33eede57d42c4495ea542a2f6275c4bd2a9cf6
Python
py
# flake8: noqa # @TODO: code formatting issue for 20.07 release from typing import Dict, List, TYPE_CHECKING import wandb from catalyst.core.callback import ( Callback, CallbackNode, CallbackOrder, CallbackScope, ) from catalyst.utils.misc import split_dict_to_subdicts if TYPE_CHECKING: from cata...
catalyst/contrib/callbacks/wandb_logger.py
Apache-2.0
6,437
3a34013831cf05add5caf024b9814fdca74c83bb
Python
py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np BATCH_SIZE = 8 LR = 0.01 EPSILON = 0.95 GAMMA = 0.99 TARGET_REPLACE_ITER = 100 # After how much time you refresh target network # MEMORY_CAPACITY = 20 # The size of experience replay buffer # N_ACTIONS = 2 # # N_STATES = len(X_train...
DQN_a_index.py
MIT
2,916
f9f7c12dbde7c6fc13bc5da183e4cb530f94618d
Python
py
import os import glob import json import pandas as pd import numpy as np import csv import torch import time from torch.autograd import Variable from PIL import Image import cv2 from torch.nn import functional as F from opts import parse_opts_online from model import generate_model from mean import get_...
online_test_video_depth.py
MIT
16,070
3a340ee0dd8ed64a1c87487c18ff89aa161a9648
Python
py
import numpy as np import torch import torch.nn as nn from skimage import measure from pytorch3dunet.augment.transforms import LabelToAffinities, StandardLabelToBoundary from pytorch3dunet.unet3d.losses import GeneralizedDiceLoss, WeightedCrossEntropyLoss, \ DiceLoss, WeightedSmoothL1Loss, _MaskingLossWrapper, Ski...
tests/test_criterion.py
MIT
6,821
5f358dacdf23f86d4626e9bccd87e5f1faff22fe
Python
py
''' AUTHORS: NORSTRÖM, ARVID 19940206-3193, HISELIUS, LEO 9402214192 ''' import torch import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D actor = torch.load('models/neural-network-3-actor.pt') critic = torch.load('models/neural-network-3-critic.pt') ys = np.linspace(0,1....
Assignment 3/problem 3/Q_plot.py
MIT
1,194
3a3441aba3352eaceb2e1f0575dcc3e842e18cc1
Python
py
import math from typing import List, Tuple import torch import torch.nn as nn import torch.nn.functional as F from kornia.filters import filter2d, gaussian_blur2d __all__ = [ "PyrDown", "PyrUp", "ScalePyramid", "pyrdown", "pyrup", "build_pyramid" ] def _get_pyramid_gaussian_kernel() -> torc...
kornia/geometry/transform/pyramid.py
ECL-2.0,Apache-2.0
12,317
3a345372247f6dd1560958cb751774b6db379f29
Python
py
import torch import torch.nn as nn from torchvision.ops import nms import numpy as np class DecodeBox(): def __init__(self, anchors, num_classes, input_shape, anchors_mask = [[6,7,8], [3,4,5], [0,1,2]]): super(DecodeBox, self).__init__() self.anchors = anchors self.num_class...
utils/utils_bbox.py
MIT
14,778
28e963a7431a0e0eee094ecc0b809416ec1a69a9
Python
py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
tests/python/frontend/onnx/test_forward.py
Apache-2.0
156,780
fdb8d205a244aada5e886f4312c1983bd0b550c8
Python
py
from collections import OrderedDict from turtle import width from matplotlib.pyplot import axis import torch import torch.nn as nn from .asff import ASFF from .rfb import BasicRFB as RFB from nets.CSPdarknet import darknet53 def conv2d(filter_in, filter_out, kernel_size, stride=1): pad = (kernel_size - 1) // 2...
nets/yolo.py
MIT
9,313
3a3475fb12fc7639c2e64108bc8907a3eeb18e04
Python
py
# encoding: utf-8 import operator import torch # isort:skip import torch.fx.experimental.fx_acc.acc_utils as acc_utils import torch.nn as nn from torch.fx.experimental.fx_acc.acc_normalizer import ( register_acc_op, register_acc_op_mapping, register_custom_acc_mapper_fn, ) from torch.fx.passes.shape_prop ...
torch/fx/experimental/fx_acc/acc_ops.py
Intel
43,973
fcd60c7d83944b4a57c4f295c41c7216dc2e88a2
Python
py
from typing import Optional, Iterable import torch import torch.nn as nn from rex.modules.dropout import SharedDropout class FFN(nn.Module): """ Multi-layer feed-forward neural networks Args: input_dim: input dimension output_dim: output dimension mid_dims: middle dimensions, if...
rex/modules/ffn.py
MIT
4,219
03c2bba8e0857e13595973b1b9ba546e857c62cb
Python
py
# %%-- Imports # General import numpy as np import pandas as pd pd.options.mode.chained_assignment = None # default='warn' import datetime import time import imageio import matplotlib.pyplot as plt from PIL import Image # Machine learning import torch from torch.autograd import Variable from torch.utils.data im...
LumiGAN/gcompute.py
MIT
24,624
3a349d98a857e107bc7dacbcd9b71c7304c67c4a
Python
py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from collections import Counter def calculate_prior( num_classes, img_max=None, prior=None, prior_txt=None, reverse=False ): if prior_txt: labels = [] with open(prior_txt) as f: for line in f: ...
IMU/loss/BalancedCE.py
MIT
2,030
1097922b1bcf4ea5a0ebb3761f13b1696bedd187
Python
py
import torch from .search_cells import NAS201SearchCell as SearchCell from .search_model import TinyNetwork as TinyNetwork from .genotypes import Structure class TinyNetworkDartsProj(TinyNetwork): def __init__(self, C, N, max_nodes, num_classes, criterion, search_space, args, affine=False, track_...
nasbench201/search_model_darts_proj.py
Apache-2.0
2,736
03a18264f5e1880520510486d185eb4776bf7227
Python
py
from concurrent.futures import ThreadPoolExecutor, as_completed import torch import torch.nn.functional as F try: import matplotlib.pyplot as plt except ImportError: pass from .box_ops import box_iou def factor_getter(n, base): base = base * 0.8 ** (n // 6) i = n % 6 if i < 3: f = [0, 0,...
pytorch_mask_rcnn/test.py
MIT
7,096
4215e018c5339e58437d219121a9f3df1be036bb
Python
py
# Copyright (c) OpenMMLab. All rights reserved. import platform import random import warnings from copy import deepcopy from functools import partial import numpy as np import torch from mmcv.parallel import collate from mmcv.runner import get_dist_info from mmcv.utils import TORCH_VERSION, Registry, build_from_cfg, d...
mmgen/datasets/builder.py
Apache-2.0
5,066
701909950c5ae976f81fa4a5ae2005d32c692f6a
Python
py
#!/usr/bin/env python # encoding: utf-8 # The MIT License (MIT) # Copyright (c) 2018-2020 CNRS # 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, including without limita...
pyannote/audio/embedding/approaches/triplet_loss.py
MIT
11,817
5ed73f8e3a8fa537bae4df3d4ceb0319673478e3
Python
py
import torch def padding_mask(lens): """Mask out the blank (padding) values Args: lens: (bs,) Return: mask: (bs, 1, max_len) """ bs, max_len = len(lens), max(lens) mask = torch.zeros(bs, 1, max_len) for i, l in enumerate(lens): mask[i, :, :l] = 1 mask = mask > 0...
torchnmt/networks/utils.py
MIT
611
3a353e1aeb787c60720c9e07200605adf07bd2a1
Python
py
import sys, os import pytest import torch import torchxrayvision as xrv sys.path.insert(0, "../torchxrayvision/") def test_model_basic(): model = xrv.models.DenseNet() def test_model_pretrained(): model = xrv.models.DenseNet(weights="densenet121-res224-all") model = xrv.models.DenseNet(weights="dens...
tests/test_models.py
Apache-2.0
2,196
5e61657b508238288a7ea7247094006726b2cce6
Python
py
import argparse import torch import torch.nn as nn parser = argparse.ArgumentParser() parser.add_argument('--max_epoch', type=int, default=30) parser.add_argument('--dataset', default='prep-amazon') # prep-amazon or fdu-mtl parser.add_argument('--prep_amazon_file', default='../data/prep-amazon/amazon.pkl') parser.add...
code/options.py
MIT
5,459
3a35861a684bf04028e7e0bb94c5bc47cf194ac0
Python
py
# Copyright The PyTorch Lightning team. # # 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
pytorch_lightning/plugins/precision/deepspeed_precision.py
Apache-2.0
3,444
ff33ccc690ef2fba85dea37a4f69a5adc4462297
Python
py
""" v.e.s. Local Learner for the FPC training. Its execution is synchronized with lo_train MIT License Copyright (c) 2020 Cesar A. Gomez 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...
ll_train.py
MIT
8,563
107068da47fe5ce8037ce69d03ccdc427fd14e83
Python
py
""" utils.py """ import ast, re import numpy as np import os, sys, multiprocessing, logging from collections import defaultdict import nltk import spacy import lemminflect import torch from transformers import GPT2Tokenizer, XLNetTokenizer, TransfoXLTokenizer, OpenAIGPTTokenizer from transformers import GPT2LMHeadMod...
src/utils.py
MIT
4,462
3a35b7f453e276a67571a68a3d53af99e94e2788
Python
py
import torch import torch.nn as nn def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation) def conv1x1(in_p...
imagenet/my_models/doublenorm.py
BSD-3-Clause
13,320
5f15658acc8218609e2a9af7d288925f423b0633
Python
py
# coding: utf-8 # DISTRIBUTION STATEMENT A. Approved for public release: distribution unlimited. # # This material is based upon work supported by the Assistant Secretary of Defense for Research and # Engineering under Air Force Contract No. FA8721-05-C-0002 and/or FA8702-15-D-0001. Any opinions, # findings, conclusio...
models/models.py
MIT
10,886
d71d26ee9cb91367a4b0b4ebf984f87d889642a2
Python
py
import IPython from torch import nn as nn import nasws.cnn.utils from nasws.cnn.policy.darts_policy import utils as darts_utils from .train_search_procedure import _summarize_shared_train def fairnas_train_model_v1(train_queue, valid_queue, model, criterion, optimizer, lr, args, architect, to...
nasws/cnn/procedures/fairnas_procedure.py
MIT
5,438
3a35ed822bf3001bc54ccd94707419db86df8bb9
Python
py
""" Script to print CPU/GPU latency of GeneralGenotypeModel's blocks """ import argparse import os import sys import yaml import torch from aw_nas.common import get_search_space from aw_nas.final.general_model import GeneralGenotypeModel from aw_nas.utils.elapse_utils import analyze_elapses def profiling(config, d...
scripts/hardware/latency.py
MIT
2,155
3a35f9b2af0c0d61dd26121a4274fca01fc68e06
Python
py
#!/usr/bin/env python3 import math import warnings import gpytorch import torch from .. import settings from ..functions._inv_matmul import InvMatmul from ..functions._inv_quad_log_det import InvQuadLogDet from ..functions._matmul import Matmul from ..functions._root_decomposition import RootDecomposition from ..uti...
gpytorch/lazy/lazy_tensor.py
MIT
57,504
f9aed6b0ba905de320d7870c49447c734b4d3e3f
Python
py
# coding=utf-8 # Copyright 2021 Intel Corporation. All rights reserved. # code taken from commit: 35b4582486fe096a5c669b6ca35a3d5c6a1ec56b # https://github.com/microsoft/DeepSpeedExamples/tree/master/bing_bert # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in comp...
pretraining/dataset/distributed_pretraining_dataset.py
Apache-2.0
9,964
b2fee13f8b556fd5786930a2981453d73634fab7
Python
py
import torch import torch.nn as nn from torch.nn import init import functools from torch.optim import lr_scheduler from collections import namedtuple from models import TransGAN_im2im from models import ViT_8_8 ############################################################################### # Helper Functions #######...
models/networks.py
BSD-3-Clause
28,990
e62191ba806852a16ff9d6d2e4f78e75d53fc866
Python
py
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and affiliates. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import argparse import os from typing import List from torch import distributed as dist...
torchrec_dlrm/data/dlrm_dataloader.py
MIT
4,051
03e88d9b1fb97d6f1de60149f4bb86b15b0b7f37
Python
py
# Copyright The PyTorch Lightning team. # # 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 copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
torchmetrics/classification/matthews_corrcoef.py
Apache-2.0
3,713
a95a33807085240444fc1ec22a43049846bc2a25
Python
py
import torch import numpy as np from .convert import to_var def normal_logpdf(x, mean, var): """ Args: x: (Variable, FloatTensor) [batch_size, dim] mean: (Variable, FloatTensor) [batch_size, dim] or [batch_size] or [1] var: (Variable, FloatTensor) [batch_size, dim]: positive value ...
model/utils/probability.py
MIT
890
3a36e5e704dafab393f21729b44ce67dfdb86780
Python
py
import datetime import logging import math import random import sys import time import psutil import skopt import torch import torch.nn as nn start = time.time() process = psutil.Process() random.seed(0) logger = logging.getLogger() logger.addHandler( logging.FileHandler(datetime.datetime.now().strftime("logs/%...
expr_1hidden.py
MIT
6,219
b2d91d72bee02ab2c156443541c7a59af757a80a
Python
py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import logging import re import torch from torch.utils.data import TensorDataset, DataLoader, SequentialSampler from torch.utils.data.distributed import DistributedSampler from pyt...
examples/attention_visualization.py
Apache-2.0
14,013
3a3724c95a094da96f11ae852ac9bb9aba0dc2f0
Python
py
import numpy as np from scipy.sparse import issparse from torch.utils.data import Dataset class MultiYDataset(Dataset): """A dataset that group each item in X with its labels for t tasks from Y Args: X: an n-dim iterable of inputs Y: a t-length list of n-dim iterables corresponding to labels ...
metal/multitask/utils.py
Apache-2.0
1,768
3a373b1e8b8a2f0cefc6b068c8611970a8af6154
Python
py
import torch class WindowLoss(torch.nn.Module): def __init__(self, metric, window_size=32, stride=16, batch_reduction='mean'): super(WindowLoss, self).__init__() self.window_size = window_size self.stride = stride self.metric = metric # self.metric.batch_reduction = 'mean' ...
losses/composite_losses/window_loss.py
MIT
1,015
e98acf6da8d9604fcd0fff9ba4601aef5dc95ac8
Python
py
import torch import numpy as np import math import mmcv from transforms3d.euler import euler2mat from core.utils.pose_utils import euler2mat_torch def aug_poses_normal(poses, std_rot=15, std_trans=[0.01, 0.01, 0.05], max_rot=45, min_z=0.1): """ Args: poses (Tensor): [n,3,4] std_rot: deg, rando...
core/utils/pose_aug.py
Apache-2.0
3,398
3a374e36863764546af414eed08c680d2c5b7032
Python
py
import torch from ..util import barit class BaseTrainer(object): """Generic Base trainer object to inherit functionality from.""" def __init__(self): self.training = True self.device = 'cpu' self._models = {} self._optimizers = {} self._losses = {} self.epoch = 1...
dlt/train/basetrainer.py
BSD-3-Clause-Clear
3,420
e9085af4726f48c7262b29ace780073703797bb1
Python
py
import argparse import os import time import numpy as np import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from models.CNN.CNN import ResNet20, train_ResNet, test_ResNet, calculate_intermediate_output from utils_cifar import load_cifar_2 def main(args): torch...
models/CNN/train.py
MIT
3,589
1084477316b3c0ab32f67d82e8d2710d80e63fda
Python
py
# -*- coding: utf-8 -*- """ Created on Wed Jan 29 18:38:40 2020 @author: Arthur TODO list balance the weights when mixing data sets """ import torch from torch.utils.data import Dataset, DataLoader, ConcatDataset, Subset import numpy as np import os.path import matplotlib.pyplot as plt # import mlflow # from sklearn....
data/datasets.py
MIT
32,673
12bc0f9752dc99f8299fa50e6b7c4b41736ab090
Python
py
import argparse import logging import os import random from pathlib import Path from typing import Any, Dict import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.utilities import rank_zero_info, rank_zero_only from transformers import ( AdamW, AutoConfig, AutoModel, Au...
examples/lightning_base.py
Apache-2.0
12,378
6b04f94328f0ff3b6122369aa192f9b4233749ad
Python
py
import numpy import argparse import os.path as osp import random import nni import torch from torch_geometric.utils import dropout_adj, degree, to_undirected from simple_param.sp import SimpleParam from pGRACE.model import Encoder, GRACE from pGRACE.functional import drop_feature, drop_edge_weighted, \ degree_dro...
train.py
MIT
6,922
7c5be9bc14ca7b9cc6abf82ad18874f771ba3991
Python
py
from typing import Dict, List, Optional, Tuple, Union from typing_extensions import TypedDict import numpy as np import torch from torch.tensor import Tensor from tqdm import tqdm from transformers import PreTrainedTokenizer from neuro_comma.augmentation import AUGMENTATIONS from neuro_comma.pretrained import TOKEN_I...
src/neuro_comma/dataset.py
MIT
9,546
5f1e62cc47587406b4741d3d7cd5a2aad0b6e1ab
Python
py
#!/usr/bin/env python from __future__ import print_function from itertools import count import torch import torch.autograd import torch.nn.functional as F from torch.autograd import Variable POLY_DEGREE = 4 W_target = torch.randn(POLY_DEGREE, 1) * 5 b_target = torch.randn(1) * 5 def make_features(x): """Builds ...
regression/main.py
BSD-3-Clause
1,690
42766b075b4c6232c1a3d8c4c96d17000b84415d
Python
py
import torch import torch.nn as nn from flask_login import UserMixin class NeuralNet(nn.Module): def __init__(self, input_size, hidden_size, num_classes): super(NeuralNet, self).__init__() self.l1 = nn.Linear(input_size, hidden_size) self.l2 = nn.Linear(hidden_size, hidden_size) ...
model.py
MIT
584
3a37d0c7626ce2acbed054d4241d0da1d08c4c84
Python
py
import gc import glob import hashlib import itertools import json import os import re import subprocess import time from os.path import join as pjoin import torch from multiprocess import Pool from pytorch_pretrained_bert import BertTokenizer from others.logging import logger from others.utils import clean from prepr...
samples/summarize-bot/BertSum/src/prepro/data_builder.py
MIT
13,213
03c83a3fc20bddcc263d8e8989c592078b0132b6
Python
py
#copy of j25 import numpy as np from collections import namedtuple from functools import partial from PIL import Image import data_transforms import data_iterators import pathfinder import utils import app import torch import torchvision import torch.optim as optim import torch.nn as nn import torch.nn.functional...
configs/f97-3_pt.py
MIT
12,376
fdf499656776cf66f488d690eec012c87da4c4be
Python
py
#!/usr/bin/env python # coding=utf-8 # Copyright The HuggingFace Team and The HuggingFace Inc. team. 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 copy of the License at # # http://www.ap...
examples/multiple-choice/run_swag.py
Apache-2.0
16,231
28b2605f0ca785733c0f6a18ac8d73c6c309e3ad
Python
py
#import libraries import matplotlib.pyplot as plt import torch from torchvision import datasets, transforms, models from torch import nn, optim import torch.nn.functional as F from collections import OrderedDict from PIL import Image import numpy as np import seaborn as sb import json import argparse # Define command...
train.py
MIT
7,972
3a37feb635877a45c4051e6e26639327f35c270e
Python
py
import torch import torch.nn as nn import torch.optim as optim class PPO: def __init__( self, agent, clip_param, ppo_epoch, num_mini_batch, value_coef, entropy_coef, lr=None, eps=None, max_grad_norm=None, use_clipped_value_los...
rl/ppo.py
MIT
4,264
4b344ab3dd09f714c0895a1066b8ce4e80126d15
Python
py
import torch from torch2trt_dynamic.torch2trt_dynamic import (get_arg, tensorrt_converter, trt_) from .plugins import create_delta2bbox_custom_plugin @tensorrt_converter( 'mmdet2trt.core.bbox.coder.delta_xywh_bbox_coder.delta2bbox_custom_func') def convert_delta2b...
mmdet2trt/converters/delta2bbox_custom.py
Apache-2.0
1,943
5f65982437cc8f321b10f40a19490345dd30d1d4
Python
py
import warnings import torch.nn as nn import torch.utils.checkpoint as cp from mmcv.cnn import build_conv_layer, build_norm_layer, build_plugin_layer, build_activation_layer from mmcv.runner import BaseModule from torch.nn.modules.batchnorm import _BatchNorm from ..builder import BACKBONES from ..utils import ResLaye...
mmdet/models/backbones/actnn_resnet.py
Apache-2.0
24,191
3a383fd25b9cd5a27d2a8c17a51aedabab462af2
Python
py
# Copyright (c) 2018-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch import sys def uniform_multinomial(batchsize, num_action, use_cuda=True): ''' Sam...
src_py/rlpytorch/sampler/sample_methods.py
BSD-3-Clause
5,118
5fa61e1ad96f29108eca595c7239641f8708feda
Python
py
import torch import torch.nn as nn import torch.nn.functional as F def get_attention(preds, temp): """ preds: Bs*C*W*H """ N, C, H, W = preds.shape value = torch.abs(preds) # Bs*W*H fea_map = value.mean(axis=1, keepdim=True) print("fea_map = ", fea_map.shape) S_attention = ( H * W ...
code_test.py
Apache-2.0
1,258
3a386d9626fece53f92bebb1cc670e2c71128b98
Python
py
import torch import math import torch.nn as nn import torch.nn.functional as F from torch.nn import Linear, Conv1d from torch_geometric.nn import GCNConv, RGCNConv, global_sort_pool, global_add_pool from torch_geometric.utils import dropout_adj from util_functions import * import pdb import time class GNN(torch.nn.Mo...
models.py
MIT
12,053
3a387ff26a191e315d4eab2e8239c3f174863b1b
Python
py
import os import math import argparse import random import logging import torch import torch.distributed as dist import torch.multiprocessing as mp from data.data_sampler import DistIterSampler import options.options as option from utils import util from data import create_dataloader, create_dataset from models impor...
codes/train.py
Apache-2.0
16,488
e96c561b171e5d750f76000048bdaa1abff538e0
Python
py
import torch from utils.common_utils import * import numpy as np import os from networks.skip import skip from networks.fcn import * from torch.optim.lr_scheduler import MultiStepLR from SSIM import SSIM import cv2 from copy import deepcopy from math import sqrt INPUT = 'noise' #input type pad = 'reflection' impath = ...
deblurring/gradient_prior.py
MIT
6,463
b2f046b0dc515a50af0c657bed41c227892ce0ca
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Wrappers around on some nn functions, mainly to support empty tensors. Ideally, add support directly in PyTorch to empty tensors in those functions. These can be removed once https://github.com/pytorch/pytorch/issues/12013 is implemented """ ...
detectron2/layers/wrappers.py
Apache-2.0
5,936
b2eeca4bf7d5869cf880ccaea62cc76f22b16a77
Python
py