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) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from typing import List, Optional, Tuple
import torch
import theseus as th
class PosePriorError(th.CostFunction):
def __init__(
... | theseus/utils/examples/pose_graph/pose_prior_error.py | MIT | 1,581 | 4267a18fefc6a284e4da02314233d7d35911dd37 | Python | py | |
# flake8: noqa
from typing import Any, Callable, Dict, List, Optional, Tuple
import os
import pickle
import numpy as np
import torch
import torch.utils.data as data
from catalyst.contrib.datasets.functional import _check_integrity, download_and_extract_archive
from catalyst.data.dataset.metric_learning import Metric... | catalyst/contrib/datasets/cifar.py | Apache-2.0 | 13,382 | feecccb501a56d0c7d11e08ae25be9e9feb02565 | Python | py | |
from tqdm import tqdm
import torch
from torch import optim
import os
import wandb
import ipdb
import numpy as np
from utils.utils import load_unk_model, create_loaders, kwargs_perturb_loss, save_image_to_wandb
import glob
from cnn_models.mnist_ensemble_adv_train_models import load_model
def eval(args, attacker, test_l... | eval.py | MIT | 9,519 | 12f4a3d1dce0bdbd6154f8842dda97e69de04696 | Python | py | |
import logging
import glob
from tqdm import tqdm
import numpy as np
import torch
import cv2
from skimage import io
class FaceDetector(object):
"""An abstract class representing a face detector.
Any other face detection implementation must subclass it. All subclasses
must implement ``detect_f... | face_alignment/detection/core.py | BSD-3-Clause | 5,753 | f99c199207de2ad62123403680a30f0c7318ded2 | Python | py | |
# Owner(s): ["oncall: distributed"]
import torch
from torch.distributed._shard import _shard_tensor
import torch.distributed._shard.sharded_tensor as sharded_tensor
import torch.distributed as dist
from torch.distributed._shard.sharding_spec import (
ChunkShardingSpec,
EnumerableShardingSpec,
ShardMetadat... | test/distributed/_shard/sharded_tensor/ops/test_math_ops.py | Intel | 6,660 | feecefceb2df8b525fc5adeb1e6fb4b777a52d15 | Python | py | |
import torch
import numpy as np
import random
from data_generator import DataLoader
from model import KAReader
from util import get_config, cal_accuracy, load_documents
from tensorboardX import SummaryWriter
def f1_and_hits(answers, candidate2prob, eps):
retrieved = []
correct = 0
best_ans, max_prob = -... | train.py | MIT | 8,632 | 5fc020f59804cd41b4b3fcab35c736977c42906b | Python | py | |
import torch
from torch_sparse import SparseTensor
from torch_geometric.nn import HEATConv
from torch_geometric.testing import is_full_test
def test_heat_conv():
x = torch.randn(4, 8)
edge_index = torch.tensor([[0, 1, 2, 3], [0, 0, 1, 1]])
row, col = edge_index
edge_attr = torch.randn((4, 2))
adj... | test/nn/conv/test_heat_conv.py | MIT | 1,788 | feecf59da801050ee69901579f5b05fc0501537a | Python | py | |
"""
Copyright 2022 Institute of Parallel and Distributed Systems, Shanghai Jiao Tong University
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/LICE... | utility/fastgraph/fastgraph/dataset_loader.py | Apache-2.0 | 5,965 | feecf6a5047693ad6a6573fc9ae6dd37c2172fbc | Python | py | |
# From https://github.com/fuzimaoxinan/Pytorch-Deep-Neural-Networks/
import torch
import torchvision
import torchvision.transforms as transforms
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import math
from tqdm import tqdm
import sys
BATCH_SIZE = 64
class R... | models/RBM.py | Apache-2.0 | 8,089 | 107a25a88eb64ee3024854103127708d690bc21b | Python | py | |
from collections import OrderedDict
from typing import Dict, Any
from tensorboard.compat.proto.config_pb2 import RunMetadata
from tensorboard.compat.proto.graph_pb2 import GraphDef
from tensorboard.compat.proto.step_stats_pb2 import StepStats, DeviceStepStats
from tensorboard.compat.proto.versions_pb2 import VersionDe... | torch/utils/tensorboard/_pytorch_graph.py | Intel | 13,090 | feed2fb09a59dc6847e0710d05457bbad1b35623 | Python | py | |
###################################################################
# Define dataset classes and preprocessing for Pytorch DataLoader #
###################################################################
import pandas as pd
import numpy as np
import torch
from torch.utils.data import Dataset
from copy import deepcopy
... | source_app/class_dataset.py | MIT | 13,379 | fdf5effabee3d58ebc1907db39d816071582ef75 | Python | py | |
# -*- coding: utf-8 -*-
import logging
import os
import tempfile
import xml.etree.ElementTree as ET
from collections import OrderedDict, defaultdict
from functools import lru_cache
import numpy as np
import torch
from detectron2.data import MetadataCatalog
from detectron2.utils import comm
from detectron2.utils.logge... | fsdet/evaluation/powertower_evaluation.py | Apache-2.0 | 11,939 | feed829abb9809b4561d0c4010b6a95b2e43d6c3 | Python | py | |
import os
import cv2
import numpy as np
import _init_paths
from model.test import im_detect
from nets.resnet_v1 import resnetv1
from model.config import cfg
import global_var
import torch
from torch.autograd import Variable
from model.nms_wrapper import nms
import matplotlib.pyplot as plt
import xml.etree.ElementTree a... | tools/save_gt_attention_map_v43.py | MIT | 6,013 | feed8c5653d8ddc723e242cc39559d4b04b386aa | Python | py | |
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
MODEL_URLS = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/models/resnet34-333f7e... | gazenet/models/shared_components/resnet/model.py | MIT | 9,147 | feed92afc2c85f120fcaa133d84f77093b835669 | Python | py | |
import ast
import collections
import collections.abc
import enum
import itertools
import json
import os
import operator
import re
import copy
import random
import asdl
import attr
import pyrsistent
import entmax
import torch
import torch.nn.functional as F
from seq2struct import ast_util
from seq2struct import gramma... | rat-sql-gap/seq2struct/models/nl2code/decoder.py | Apache-2.0 | 61,913 | b2d55bdacb6b1eed083f55b7ff6fb369ec155a8c | Python | py | |
"""
GPT model:
- the initial stem consists of a combination of token encoding and a positional encoding
- the meat of it is a uniform sequence of Transformer blocks
- each Transformer is a sequential combination of a 1-hidden-layer MLP block and a self-attention block
- all blocks feed into a central residual p... | mushr_rhc_ros/src/mingpt/model_naiveCNN.py | BSD-3-Clause | 1,935 | feed9f5575fd0388d6c53fc3596b6dc96bc3bbc5 | Python | py | |
# -*- coding: utf-8 -*-
# @Author: Wenwen Yu
# @Created Time: 7/8/2020 9:21 PM
from typing import *
import logging
import torch
import torch.nn as nn
from torch import Tensor
from .crf import ConditionalRandomField
from PICK.utils.class_utils import keys_vocab_cls, iob_labels_vocab_cls
from PICK.data_utils import do... | PICK/model/decoder.py | MIT | 8,137 | feedbb6d5bcf5831d7847a4f6d5ade6802124722 | Python | py | |
#!/usr/bin/env python3
import torch
from ..distributions import base_distributions
from .likelihood import Likelihood
class SoftmaxLikelihood(Likelihood):
"""
Implements the Softmax (multiclass) likelihood used for GP classification.
"""
def __init__(self, num_features, n_classes, mixing_weights_pri... | gpytorch/likelihoods/softmax_likelihood.py | MIT | 1,314 | e6505353ca327fce9002d9d75cc72b97b0951967 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import torchvision
from PIL import Image
from torch.utils.data import DataLoader
from torchvision.datasets import DatasetFolder
from torchsummary import summary
import utils
from model import CAPTCHA_MODEL
from dataset import CAPTCHA_DATASET
train_path = "../data/... | neural_network/train.py | MIT | 3,513 | 12dcd4d92f2f4dc9f5403c14fb1273585b02e60c | Python | py | |
import hashlib
import itertools
import json
import math
import h5py
import numpy as np
import torch
from np_segments_ops import non_maxima_suppresion
from utils import unique2d_perserve_order
class LoopOverKBase():
"TODO: description"
def __init__(self, dataset, model, h5_1ststage, topk=100,
... | corpus.py | MIT | 6,820 | 7092ef955df1922760c472db3e27e751235e1f17 | Python | py | |
"""
Module for training models with PyTorch.
"""
import time
import torch
def train(model, dataloaders, loss_fn, optimizer, n_epochs, scheduler=None, metric_fns={},
valid_every=1, verbose=True):
"""
Train the model and return the training history.
Parameters
----------
model: PyTo... | src/train/train.py | MIT | 4,741 | 127f3c17504a736afffe7188c43a22c907cd63b0 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import warnings
from typing import Optional, Sequence, Tuple, Union
import hydra
import omegaconf
import torch
import tor... | mbrl/models/basic_ensemble.py | MIT | 11,587 | e6448013f89e7057f05fae7f4d17652db2c887f4 | Python | py | |
# Copyright 2020 Jan Jitse Venselaar.
#
# 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 ... | loaders.py | Apache-2.0 | 2,015 | 4256d064179ba8680a8cf2cc0dfb05a9322cdb26 | Python | py | |
import math
import torch
def huber(t, delta=1):
# calc huber value of input
# delta = manually tuned
huber_tensor = torch.zeros_like(t)
mask = torch.abs(t) <= delta
huber_tensor[mask] = (t[mask] ** 2 / 2.)
huber_tensor[~mask] = (delta * (t[~mask].abs() - (0.5 * delta)))
return huber_tens... | stable_nalu/functional/mnac.py | MIT | 1,589 | feee3114e246f1a98a406fc5542d8aeddda840e5 | Python | py | |
import csv
import os
import numpy as np
import torch
import torch.backends.cudnn
import torch.cuda.amp as amp
import torch.nn as nn
import torch.nn.functional as fun
import torchvision.transforms as transforms
from torch.optim import SGD
from torch.utils.data import DataLoader
from torchvision.datasets import ImageFol... | main.py | Apache-2.0 | 6,016 | e90f43082b2221e4cae4a89fe9efac82886ffd3a | Python | py | |
# coding: utf-8
#############################################
# Consistent Cumulative Logits with ResNet-34
#############################################
# Imports
import os
import time
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
import argparse
import sys
from torch.utils... | model-code/vgg16/cacd-coral.py | MIT | 14,735 | feee4a4a03a3839c595f19baafe63cd65f66ab5d | Python | py | |
import numpy as np
import pytest
import torch
from rfvision.core import BboxOverlaps2D, bbox_overlaps
def test_bbox_overlaps_2d(eps=1e-7):
def _construct_bbox(num_bbox=None):
img_h = int(np.random.randint(3, 1000))
img_w = int(np.random.randint(3, 1000))
if num_bbox is None:
... | tests/test_metrics/test_box_overlap.py | Apache-2.0 | 4,233 | a9659931e18231c01b17cf89fa1840bf2ff88e78 | Python | py | |
import warnings
import numpy as np
import torch
from schnetpack import Properties
class Metric:
r"""
Base class for all metrics.
Metrics measure the performance during the training and evaluation.
Args:
target (str): name of target property
model_output (int, str): index or key, in... | src/schnetpack/train/metrics.py | MIT | 19,420 | 421a4f9baa245cd11d0c880ae9d34e6f89b1ab02 | Python | py | |
import torch
import torch.nn as nn
from torch.utils.model_zoo import load_url as load_state_dict_from_url
from pdb import set_trace as st
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnext50_32x4d', 'resnext101_32x8d',
'wide_resnet50_2', 'wide_resnet101_2'... | CV_adv/model/fe_resnet.py | MIT | 16,657 | feeea4578c3cec2561e8d247ccf4079cfba65e3d | Python | py | |
import warnings
from collections import namedtuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.jit.annotations import Optional, Tuple
from torch import Tensor
from .utils import load_state_dict_from_url
__all__ = ['GoogLeNet', 'googlenet', "GoogLeNetOutputs", "_GoogLeNetOutputs"]
mod... | torchvision/models/googlenet.py | BSD-3-Clause | 10,608 | 4b1cb280035b5adb17b0e6cc93bb57b44f168a01 | Python | py | |
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision.utils import save_image
from .model import Generator, Discriminator, weights_init_normal
from dataset import AnimeFaceLabel
from utils import Status, add_args, save_args
from nnutils import sample_nnoise, get_device
from nnutils.loss imp... | implementations/pixelshuffle/utils.py | MIT | 3,454 | fda04abf574c949983808d893ad28bad276d3a75 | Python | py | |
"""Training algorithms for local representations.
Algorithms implemented as classes since there are a variety of slight variations.
"""
import numpy as np
import torch
from fire import Fire
from itertools import product
from matplotlib import pyplot as plt
from pathlib import Path
from random import sample
from torc... | causal_rl/train.py | MIT | 7,590 | 34510b66df74e858a9bee448ceb8b06d5b5fb442 | Python | py | |
from src.features.pixelwise_loss import PixelwiseLoss
import imgaug.augmenters as iaa
from torch.utils.data import DataLoader
from torchvision.transforms import Compose
import torch.nn as nn
import torch
from src.models.autoencoders import MaskedMSELoss
from src import DATA_PATH
from src.data import TrainValTestSplitte... | src/features/pixelwise_loss/loss_heatmap.py | MIT | 3,120 | 3426e1295b9db2023b089cc989e01fc936c472b1 | Python | py | |
import torch.nn as nn
from fairseq import utils
class LearnedPositionalEmbedding(nn.Embedding):
"""
This module learns positional embeddings up to a fixed maximum size.
Padding ids are ignored by either offsetting based on padding_idx
or by setting padding_idx to None and ensuring that the a... | end-2-end/ProphetNet/prophetnet/learned_positional_embedding.py | MIT | 1,945 | d7f7583d87b2e40e5429345db8e60a6def5d4cfb | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import random
import torch
import torchvision
from torchvision.transforms import functional as F
class Compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, image, target,proposals=None... | openpose/data/transforms/transforms.py | MIT | 2,916 | 1281e4bdbe5493e5f62ce9b72a3fe9c744a612ef | Python | py | |
"""
IMPORTING LIBS
"""
import dgl
import numpy as np
import os
import socket
import time
import random
import glob
import argparse, json
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoade... | main_molecules_graph_regression.py | MIT | 17,812 | e9a29d1b9409138e902aa4efd8899d63e96573c6 | Python | py | |
import torch
from mmdet.core import bbox2roi
from ..builder import HEADS, build_head
from .standard_roi_head import StandardRoIHead
@HEADS.register_module()
class MaskScoringRoIHead(StandardRoIHead):
"""Mask Scoring RoIHead for Mask Scoring RCNN.
https://arxiv.org/abs/1903.00241
"""
def __init__(se... | mmdet/models/roi_heads/mask_scoring_roi_head.py | Apache-2.0 | 3,882 | a90804a5f911a151e7794a6f4a67dd2f74365801 | Python | py | |
import torch
import torch.nn as nn
class AsymmetricLoss(nn.Module):
def __init__(self, gamma_neg=4, gamma_pos=1, clip=0.05, eps=1e-8, disable_torch_grad_focal_loss=False):
super(AsymmetricLoss, self).__init__()
self.gamma_neg = gamma_neg
self.gamma_pos = gamma_pos
self.clip = clip... | src/loss_functions/losses.py | MIT | 5,124 | 5f298723a2a350ec9a4a235e690ebbe0480257bf | Python | py | |
import os
import read_data
from torch.utils.data import DataLoader, Dataset
import torchvision.transforms as transforms
import torch.nn as nn
import torch
import numpy as np
import time
import pandas as pd
import torchvision.models as models
import torch.nn.functional as F
import FGSM
def L_Infinity_Los... | Attack ML Models/run_attack.py | MIT | 2,849 | 8019c1a012f7add62fa35458e7bb45b4c262f26f | Python | py | |
from __future__ import division
import os
import sys
import torch
import torch.nn as nn
import numpy as np
from shutil import copyfile
from pkg.networks import Text2Mel, SuperRes
from pkg.data import BatchMaker, load_data
from pkg.hyper import Hyper
from pkg.utils import PrettyBar, plot_spectrum, plot_attention, plot_... | pkg/train.py | MIT | 11,859 | 1ecd3e9fe57065120c9a40ef78b653d4de6a014d | Python | py | |
from random import shuffle
import numpy as np
import torch
import torch.nn as nn
import math
import torch.nn.functional as F
from PIL import Image
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torch.utils.data.dataset import Dataset
from matplotlib.colors import rgb_to_hsv, ... | utils/dataloader.py | MIT | 4,805 | feefcfcc9a67da637e9f6e6b69f8b34e8e6fa841 | Python | py | |
import copy
import json
import os
from pathlib import Path
import pickle
import shutil
import time
import re
import fire
import numpy as np
import torch
from google.protobuf import text_format
import second.data.kitti_common as kitti
import torchplus
from second.builder import target_assigner_builder, voxel_builder
f... | second/pytorch/train.py | MIT | 26,207 | fce846bd8df3709f391a5f1e6efa7336e63f8834 | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
from common.modules.classifier import Classifier as ClassifierBase
from typing import Optional
logger = logging.getLogger(__name__)
class GradientReversalLayer(torch.autograd.Function):
... | dalib/adaptation/multi_source/mdan.py | MIT | 7,399 | feefdba70ba182a4f168e57fd39c3bb9203f701d | Python | py | |
#################################################
### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ###
#################################################
# file to edit: dev_nb/12_text.ipynb
from exp.nb_11a import *
def read_file(fn):
with open(fn, 'r', encoding = 'utf8') as f: return f.read()
class TextList(ItemLi... | nbs/dl2/exp/nb_12.py | Apache-2.0 | 9,228 | feefe5761a120b201933e02fd82cc08ff7e2ba84 | Python | py | |
import torch
import torch.nn as nn
from torch.nn import functional as F
# from transformers import BertModel, BertTokenizer
from transformers import AutoConfig
from transformers import AutoModelWithLMHead
from src.utils import load_embedding
import logging
logger = logging.getLogger()
class BertTagger(nn.Module):
... | src/model.py | MIT | 10,235 | feeff7582a390b769e3dc319bc3df61f965777e8 | Python | py | |
import sys
home_dir = '/home/jbang36/eva_jaeho'
sys.path.append(home_dir)
## Need to load the modules
from loaders.uadetrac_loader import UADetracLoader
from logger import Logger
import os
import itertools
import time
import torch
from torch.optim.lr_scheduler import MultiStepLR
from eva_storage.baselines.indexing.... | eva_storage/baselines/indexing/external/ssd/custom_code/evaluate_ssd_uad.py | Apache-2.0 | 11,521 | 5e910675982b70f3bd787abfe99688e1fd7c6ceb | Python | py | |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 21 14:31:34 2018
@author: nsde
"""
#%%
import torch
#%%
def mymin(a, b):
return torch.where(a < b, a, torch.round(b))
#%%
def findcellidx(ndim, p, nc):
if ndim==1: return findcellidx1D(p, *nc)
elif ndim==2: return findcellidx2D(p, *nc)
elif ndim==3: r... | libcpab/pytorch/findcellidx.py | MIT | 4,996 | 1e8c6c8c8170e0a39ac9c6fda40bee74513ea51d | Python | py | |
import torch
from torch.utils.data import DataLoader
from torch.autograd import Variable
from torch import nn
import torch.optim as optim
import os
import json
import argparse
from dataloader import CocoDataset
import pretrainedmodels
from pretrainedmodels import utils
C, H, W = 3, 224, 224
class MILModel(nn.Module... | finetune_cnn.py | MIT | 6,101 | fef010409bcb1357451576cbddbf3a73ea754ce4 | Python | py | |
"""
Example showing how to wrap the iGibson class using ray for rllib.
Multiple environments are only supported on Linux. If issues arise, please ensure torch/numpy
are installed *without* MKL support.
This example requires ray to be installed with rllib support, and pytorch to be installed:
`pip install torch "ra... | ray/lidar_only.py | MIT | 9,122 | 107966e8c9c1f94ce6d249999d510c3e0412fd1a | Python | py | |
import torch
import copy
import logging
import os
import random
import mdtraj as md
import networkx as nx
import numpy as np
import parmed as pm
import torchani
from ase import Atom, Atoms
from pdbfixer import PDBFixer
from rdkit import Chem, Geometry
from rdkit.Chem import AllChem, rdFMCS
from scipy.special import lo... | neutromeratio/tautomers.py | MIT | 32,146 | a90d22f6a6e98edb76a713b0c52fc0eec0301598 | Python | py | |
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# 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... | examples/prostate/pt/learners/supervised_learner.py | Apache-2.0 | 15,723 | 3479cebb289af8afa9cc39361eb1da50320b55ca | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import colorsys
import logging
import math
import numpy as np
from enum import Enum, unique
import cv2
import matplotlib as mpl
import matplotlib.colors as mplc
import matplotlib.figure as mplfigure
import pycocotools.mask as mask_util
import torch
... | detectron2/utils/visualizer.py | MIT | 45,052 | 12f2652c389c529aa10df8f0ffc4a8a9c2a1c3c8 | Python | py | |
# coding: utf-8
import numpy as np
import torch
import os
import pickle
from PIL import Image, ImageOps, ImageEnhance
from argparse import ArgumentParser
from torch.optim import SGD, Adam
from torch.autograd import Variable
from torch.utils.data import DataLoader, Dataset
from torchvision.transforms import Normaliz... | train/tool.py | Unlicense | 7,406 | fef0826663ddc10dfea739393e2688b73f8c3059 | Python | py | |
'''
PointGroup
Written by Li Jiang
'''
import torch
import torch.nn as nn
import spconv
from spconv.modules import SparseModule
import functools
from collections import OrderedDict
import sys
sys.path.append('../../')
from lib.pointgroup_ops.functions import pointgroup_ops
from util import utils
class ResidualBlock(... | model/pointgroup/pointgroup.py | Apache-2.0 | 22,203 | f979821a86acde9e8aa64a4986393174db629aca | Python | py | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.networks.base_network import BaseNetwork
from models.networks.normalization import get_nonspade_norm_layer
from models.networks.architecture import ResnetBlock... | Face_Enhancement/models/networks/generator.py | MIT | 8,576 | d722ea3cb11e4b4e87de37b0fc9d0cf5921917f4 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from distributions import Categorical, DiagGaussian
from utils import orthogonal
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1 or classname.find('Linear') != -1:
orthogonal(m.weight.data)
... | model.py | MIT | 7,326 | 458e2f626f630c0ed9624c88568ad7a029710a99 | Python | py | |
from typing import Tuple
import torch
import torch.nn as nn
import kornia
from kornia.filters.kernels import get_box_kernel2d
from kornia.filters.kernels import normalize_kernel2d
class BoxBlur(nn.Module):
r"""Blurs an image using the box filter.
The function smooths an image using the kernel:
.. math... | kornia/filters/blur.py | ECL-2.0,Apache-2.0 | 2,528 | fef0c20814a3f039cf8c4d5ad50cdf9baddd25de | Python | py | |
import math
import torch
import logging
import traceback
import numpy as np
from torch import nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from torch.nn import MarginRankingLoss
from ..transformers import BertPreTrainedModel, BertModel
# from transformers import BertPreTrainedModel, Bert... | bertkpe/networks/Bert2Rank.py | MIT | 10,593 | a9739d8d37ecd07f34631e3486dba45586b037d9 | Python | py | |
'''Module to generate the spherical mnist data set'''
import sys; sys.path.append("../../meshcnn")
import gzip
import pickle
import numpy as np
import argparse
from torchvision import datasets
from projection_helper import img2ERP, erp2sphere
from tqdm import tqdm
def main():
parser = argparse.ArgumentParser()
... | experiments/exp1_sphere_mnist/prepare_data.py | MIT | 4,632 | b2b56eaa8cb9d6f6b232d8ccb4618b3555ed4b93 | Python | py | |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.13.5
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# %% [ma... | Assignments/A08-Overfitting/OverfittingFashionMNIST.py | MIT | 6,986 | 2496cab2cb17b6cb9fca2f57e103b3fb212935b7 | Python | py | |
import torch.nn as nn
class LandmarkHead(nn.Module):
def __init__(self, inchannels=512, num_anchors=3):
super().__init__()
self.conv1x1 = nn.Conv2d(inchannels, num_anchors*10, kernel_size=(1,1), stride=1, padding=0)
def forward(self,x):
out = self.conv1x1(x)
out = out.permute(... | hawkdet/models/head/landmark.py | Apache-2.0 | 391 | fef11d9eed5646e5c02ec5a1f36662573c6308f9 | Python | py | |
'''Encode object boxes and labels.'''
import math
import torch
from torchcv.utils import meshgrid
from torchcv.utils.box import box_iou, box_nms, change_box_order
class BoxCoder:
def __init__(self):
self.anchor_areas = [32*32., 64*64., 128*128., 256*256., 512*512.] # p3 -> p7
self.aspect_ratios ... | torchcv/models/retinanet/box_coder.py | MIT | 4,928 | 7ccae8e8ce96df06fbf19bf75d9fa895c6a769de | Python | py | |
import random
from typing import List
# from collections import namedtuple
import numpy as np
import torch
from torch import nn
import config
from utils import utils, datautils
class ModelSample:
def __init__(self, mention_id, mention_str, mstr_token_seq, context_token_seq, mention_token_idx):
self.ment... | modelexp/exputils.py | MIT | 6,145 | 28b5393fad70db020132480a11c6449fb513b03a | Python | py | |
import torch
from torch import nn
import torch.nn.functional as F
from hw_asr.base import BaseModel
class Block(nn.Module):
def __init__(self, n_subblocks, p, in_ch, out_ch, kernel_size, stride=1, dilation=1):
super().__init__()
padding = (kernel_size - 1)//2
if stride == 1 and dilation ==... | hw_asr/model/jasper_model.py | MIT | 4,152 | fef12dcacc0ee1d49fffc428502fc0d84e279f96 | Python | py | |
import torch
import torch.nn.functional as F
from .gradcam import GradCAM
class GradCAMPP(GradCAM):
"""Calculate GradCAM++ salinecy map.
Args:
input: Input image with shape of (1, 3, H, W)
class_idx: Class index for calculating GradCAM.
If not specified, the class index that make... | S9/gradcam/gradcam_pp.py | Apache-2.0 | 1,920 | fef135805979ea40e77ff082c3df05ea5bb139ab | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from a2c_ppo_acktr.utils import AddBias, init
"""
Modify standard PyTorch distributions so they are compatible with this code.
"""
#
# Standardize distribution interfaces
#
# Categorical
class FixedCategorical(torch.dis... | a2c_ppo_acktr/distributions.py | MIT | 2,920 | 5e4c14ea696bac5c4ca7664eba4d39219c51388d | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import List
from utils import timer
from data.config import cfg
try:
from torch2trt import torch2trt
from torch2trt.torch2trt import TRTModule
use_torch2trt = True
except:
use_torch2trt = False
use_jit = False if use_torch... | layers/warp_utils.py | MIT | 2,137 | fef1441f1f36865af5ee2185a67d9320648b5f84 | Python | py | |
from collections import defaultdict
import numbers
import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
from numba import njit
import torch
from fsdtw import GFSDTWLayer as CppGFSDTWLayer
import torch.nn as nn
from torch.autograd import Function
def reduce_by_half(x):
return ... | modules/gsfdtw_module.py | MIT | 2,654 | 28dcb9ede29862c137d3cc12379a9cf75f5ab055 | Python | py | |
import torch
import torch.nn.functional as F
import torch_scatter
class graph_conv(torch.nn.Module):
def __init__(self, embedding_size, hidden_dim, hidden_dim2, dropout):
super(graph_conv, self).__init__()
self.l1 = torch.nn.Linear(2 * embedding_size, hidden_dim, bias=False)
... | model.py | MIT | 1,535 | 7c73bc4f84bff89d624538580323c8fa5dc78e5e | Python | py | |
# -*- coding: utf-8 -*-
"""
@author:XuMing(xuming624@qq.com), Abtion(abtion@outlook.com), okcd00(okcd00@qq.com)
@description:
"""
import sys
import torch
import operator
from transformers import BertTokenizer
sys.path.append('../..')
from pycorrector.macbert.macbert4csc import MacBert4Csc
from pycorrector.macbert.so... | pycorrector/macbert/infer.py | Apache-2.0 | 5,809 | fef15aecd279cfd6ca3dbe93e1b51ef0c119727e | Python | py | |
# pylint: disable=missing-function-docstring
from torch import jit
from pycave.bayes.gmm import GaussianMixtureModel, GaussianMixtureModelConfig
def test_compile():
config = GaussianMixtureModelConfig(num_components=2, num_features=3, covariance_type="full")
model = GaussianMixtureModel(config)
jit.script... | tests/bayes/gmm/test_gmm_model.py | MIT | 328 | fef15fbf814feaaa136c5f62cff0509040acaa28 | Python | py | |
import torch
import torch.nn as nn
import models
from utils import TensorboardWriter
import os
import re
class Solver(object):
def __init__(self, config, train_data_loader, eval_data_loader, vocab, is_train=True, model=None):
self.config = config
self.epoch_i = 0
self.train_data_loader = t... | NCM/solvers/solver.py | MIT | 3,633 | 52bea431ab46e5cd45e2ea534b799a382a40a182 | Python | py | |
import torch
import torch.nn as nn
from .py_utils import TopPool, BottomPool, LeftPool, RightPool
from .py_utils.utils import convolution, corner_pool, residual
from .py_utils.losses import CornerNet_Loss
from .py_utils.modules import hg_module, hg, hg_net
class fire_module(nn.Module):
def __init__(self, inp_dim... | core/models/CornerNet_Squeeze.py | BSD-3-Clause | 4,695 | fef1beab0b0d61f129b560be11e261e4b51b4d48 | Python | py | |
#!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Detectron2 training script with a plain training loop.
This script reads a given config file and runs the training or evaluation.
It is an entry point that is able to train standard models in detectron2.
In order to let o... | object_detection/detectron2/ewc/fix/plain_train_net.py | Apache-2.0 | 3,506 | 5eba7f4f795f9a387b5b978f80ebbd0b3d2a19dc | Python | py | |
import torch
import warnings
__all__ = ["psd_logdet", "psd_inverse", "add_diagonal"]
def psd_inverse(x=None, chol=None):
"""
Returns the inverse of positive definite matrix x.
:param x: Positive definite matrix, shape (*, D, D).
:param chol: Cholesky factor of s, shape (*, D, D).
:return: Inverse... | pvi/utils/psd_utils.py | MIT | 3,686 | fef1e5f264d135cd1f8b236fb28d7478804827eb | Python | py | |
# Implement perplexity
# Implement cosine distance(semantic similarity rewards)
# Move rouge rewards here
# Lexical complexity award.
from datasets import load_metric, load_dataset
import nltk
from nltk.corpus import stopwords
import nltk
import numpy as np
import torch
from lexical_score import LexicalScore
import tex... | scoring.py | Apache-2.0 | 4,015 | ff021f6dcedb287e78413cff6781e805730db7a0 | Python | py | |
import os
from collections import Counter
from copy import deepcopy
from shutil import copyfile
import torch
import torch.nn as nn
from models.networks import model_val, cem2normal
import logging
logger = logging.getLogger('base')
class nullcast():
#nullcontext:
#https://github.com/python/cpython/commit/07... | codes/models/base_model.py | Apache-2.0 | 28,010 | fef1f0d6b5bdfd8c757edc05873875b6144fec44 | Python | py | |
# coding=utf-8
# Copyright (c) 2020, 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | megatron/p2p_communication.py | MIT | 12,313 | fef206c1ff3582d7faae7ae67ae29dce93ba86c2 | Python | py | |
import argparse
import os
import sys
import time
import cv2
import numpy as np
import torch
from torch.autograd import Variable
from torch.optim import Adam
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision import transforms
from imutils.video import FPS, WebcamVideoStream
impo... | fast_neural_style/neural_style/neural_style.py | BSD-3-Clause | 12,622 | fef2137581163cc68b20398b5f6daa6708f14f09 | Python | py | |
import chika
import torch
from torch.nn import functional as F
from torchvision.models import resnet50
from homura import distributed_ready_main, enable_accimage, get_num_nodes, is_distributed, lr_scheduler, optim, \
reporters
from homura.trainers import SupervisedTrainer
from homura.vision.data import DATASET_REG... | examples/imagenet.py | Apache-2.0 | 2,420 | b2423382fa61374b4b026705e17adc268b6556b6 | Python | py | |
import torch
from .base_reducer import BaseReducer
from .mean_reducer import MeanReducer
class MultipleReducers(BaseReducer):
def __init__(self, reducers, default_reducer=None, **kwargs):
super().__init__(**kwargs)
self.reducers = torch.nn.ModuleDict(reducers)
self.default_reducer = (
... | src/pytorch_metric_learning/reducers/multiple_reducers.py | MIT | 1,214 | b2d986c490d050e07c64ae80555c8efc889d7c94 | Python | py | |
from __future__ import print_function
import sys
import os
import shutil
from six.moves import range
import pprint
from tqdm import tqdm
from tensorboardX import SummaryWriter
import torch.backends.cudnn as cudnn
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.optim as optim
from t... | code/trainer.py | Apache-2.0 | 10,325 | e65df9fa5c6a101cb8e5e50324e93a83e78d0f6b | Python | py | |
import os
from agent import Agent
from config import Config
import random
from replay_buffer import ReplayBuffer
import torch
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
print(torch.__version__)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(torch.cuda.is_available())
clas... | maddpg_agent.py | MIT | 2,622 | fef27ea325d9831f3594022c1d7454fa17048ffd | Python | py | |
import abc
import neptune
import datetime
from hyperdash import Experiment
import time
from millify import millify
import numpy as np
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn.metrics import f1_score, precision_recall_fscore_support
# fro... | src/utils/trainer.py | MIT | 21,184 | fef2ad7e87793c9937373701fd4f85de86748829 | Python | py | |
import random
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
class CaptionGenerator(nn.Module):
def __init__(self, decoder, max_caption_len, vocab):
super(CaptionGenerator, self).__init__()
self.decoder = decoder
self.max_caption_len = max_captio... | models/caption_generator.py | MIT | 7,523 | 5e37d3d8067491e23a6ec0e4da9f1a7193a9825e | Python | py | |
import os
from typing import Tuple
import torchaudio
from torch.utils.data import Dataset
from torch import Tensor
from torchaudio.datasets.utils import (
download_url,
extract_archive,
walk_files
)
FOLDER_IN_ARCHIVE = "SpeechCommands"
URL = "speech_commands_v0.02"
HASH_DIVIDER = "_nohash_"
EXCEPT_FOLDER ... | torchaudio/datasets/speechcommands.py | BSD-2-Clause | 3,538 | 7c56a846b9eca1ee69cb1bc3fb19ee4c43001d69 | Python | py | |
# Copyright (c) 2019, salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: MIT
# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/MIT
import torch
import torch.nn as nn
class Normalizer(nn.Module):
def __init__(self, input_size, epsilon=0.01, zero_... | base/modules/normalization.py | MIT | 3,726 | 346e284bfb8f62230b203ca262a97fb86564c565 | Python | py | |
# Copyright 2021 The HuggingFace 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | src/accelerate/notebook_launcher.py | Apache-2.0 | 5,849 | fef2f0c08f83b004359f7d2e6ef62ffd6946f11e | Python | py | |
'''VGG for CIFAR10. FC layers are removed.
(c) YANG, Wei
'''
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import math
__all__ = [
'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
'vgg19_bn', 'vgg19',
]
model_urls = {
'vgg11': 'https://download.pytorch.org/models/... | cifar/weight-level/models/cifar/vgg.py | MIT | 4,223 | 80296914d9f0b0bf6ecaa6194d0a770319332b4c | Python | py | |
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law... | test/test_npu/test_network_ops/test_size.py | BSD-3-Clause | 1,560 | fef31a6c8687ca96b076ba47d8ffce59910357f4 | Python | py | |
from glob import glob
import os
import hydra
import torch
from omegaconf import DictConfig
from pytorch_lightning import LightningDataModule, LightningModule
from tqdm import tqdm
from myria3d.utils import utils
from myria3d.models.interpolation import Interpolator
log = utils.get_logger(__name__)
torch.set_grad_ena... | myria3d/predict.py | BSD-3-Clause | 3,805 | fef31d3c1c0626ff6040a970e78ad87e05a8cf1e | Python | py | |
# Copyright (c) 2019,20-21 NVIDIA CORPORATION & AFFILIATES.
# 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.apache.org/licenses/LICENSE-2.0
#
# Unles... | kaolin/io/off.py | ECL-2.0,Apache-2.0 | 3,210 | fef323e4dfbfcc7918930716f172978b44b41218 | Python | py | |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import torch
import os
from pyro.infer import Trace_ELBO
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
class Trace_ELBO_Wrapper(Trace_ELBO):
def loss(self, model, guide, *args, **kwargs):
... | src/misc/utils.py | MIT | 11,474 | 45d4c669d849b040e3ba9062ae3c8f48477c50e7 | Python | py | |
import os
import torch
import pandas as pd
from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import random
from PIL import Image
import torchvision.transforms.functional as F
import math
import ... | data/seg_transform.py | MIT | 3,753 | fef34fab3720f44b07abe20b2fcd1fd2acb3c9ca | Python | py | |
import warnings
import torch
from ..domain import Domain, BoundaryDomain
from ...spaces import Points
from .sampler_helper import (_boundary_grid_with_n, _inside_grid_with_n,
_inside_random_with_n, _boundary_random_with_n)
class IntersectionDomain(Domain):
"""Implements the logical ... | src/torchphysics/problem/domains/domainoperations/intersection.py | Apache-2.0 | 7,778 | 5e19a9d07fe3559245e5386ccb43def1766cff33 | Python | py | |
# Copyright 2016-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 torch
import torch.nn as nn
import sparseconvnet as scn
from data import get_iterators
# two-dimensional SparseConv... | examples/Assamese_handwriting/VGGplus.py | BSD-3-Clause | 1,504 | 5e2267c747202d8f6e83edde72010d77cf7ff89a | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from collections import OrderedDict
import os
from tempfile import TemporaryDirectory
import unittest
import torch
from torch import nn
from fcos_core.utils.model_serialization import load_state_dict
from fcos_core.utils.checkpoint import Checkpo... | tests/checkpoint.py | BSD-2-Clause | 4,627 | b27987ba105187d95e6a0188351949e2d978d7b6 | Python | py | |
# -*- coding: utf-8 -*-
# @Author : DevinYang(pistonyang@gmail.com)
__all__ = ['SwitchNorm2d', 'SwitchNorm3d', 'EvoNormB0', 'EvoNormS0']
import torch
from torch import nn
from . import functional as F
class _SwitchNorm(nn.Module):
"""
Avoid to feed 1xCxHxW and NxCx1x1 data to this.
"""
_version = 2
... | torchtoolbox/nn/norm.py | BSD-3-Clause | 3,854 | 7012255ce711fe1659a496daf25f8e8fe8b883d9 | Python | py | |
#!/usr/bin/env python
import torch.utils.data
import numpy as np
import scipy.fftpack
import h5py
import pathlib
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
import deepinpy.utils.complex as cp
from deepinpy.utils.utils import fftmod, fftshift, fft2uc, ifft2uc
'''
Simulates data an... | deepinpy/forwards/mcmri/dataset.py | MIT | 6,234 | 8052cc3eb1bb373bc8bbcff33f9e65e0baada484 | Python | py | |
import os
import numpy as np
import albumentations
from torch.utils.data import Dataset
from taming.data.base import ImagePaths, NumpyPaths, ConcatDatasetWithIndex
class FacesBase(Dataset):
def __init__(self, *args, **kwargs):
super().__init__()
self.data = None
self.keys = None
def ... | Bot/taming_transformers/taming/data/faceshq.py | MIT | 4,630 | fef3818f02ecc81de0038de20222ccf43ee17f30 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.