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
import torch import numpy as np import pandas as pd def load_data(file_path, len_train, len_val): df = pd.read_csv(file_path, header=None).values.astype(float) train = df[: len_train] val = df[len_train: len_train + len_val] test = df[len_train + len_val:] return train, val, test def data_trans...
examples/pytorch/stgcn_wave/load_data.py
Apache-2.0
842
3a53409f54fab58339e880076dc2d244f73b4dda
Python
py
import logging from logging.handlers import RotatingFileHandler import pandas as pd import torch import torch.nn.functional as F import torchmetrics from datasets import Dataset from pytorch_lightning import LightningModule from transformers import GPT2Config, GPT2DoubleHeadsModel, GPT2Tokenizer from .basic_model imp...
kirby/qa_model.py
Apache-2.0
9,686
701aa31db08f0dc560cdeecc6c22cebd8e093b7d
Python
py
# Copyright 2019 Shigeki Karita # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Transformer speech recognition model (pytorch).""" from argparse import Namespace from distutils.util import strtobool from itertools import groupby import logging import math import numpy import torch from espnet.nets.as...
espnet/nets/pytorch_backend/e2e_asr_transformer_recons.py
Apache-2.0
31,557
3a53a344b92b75db9092590525a40c84740e91d6
Python
py
import os import random import cv2 import numpy as np import torch import torchvision.datasets as datasets import tqdm from dg_util.python_utils import drawing from dg_util.python_utils import pytorch_util as pt_util from dg_util.python_utils.persistent_dataloader import PersistentDataLoader from sklearn.decomposition...
visualizations/view_nearest_neighbors.py
Apache-2.0
6,770
a95a39e7f516df07ec51fd5e3d0992ab9654e961
Python
py
# -*- coding: utf-8 -*- """ Created on Mon Mar 29 10:52:58 2021 @author: Mohammed Amine """ import pickle import numpy as np import os import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import matplotlib import torch #import region_labels def extract_weights_single(dataset, v...
extract_results.py
MIT
19,664
3a53b339b5947564ede02388a26be20545954a6f
Python
py
""" 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 itertools import json import os import re import torch import torchaudio import torchvision def log_normalize(x): x.add_(1e-6).l...
datasets/audioset.py
MIT
6,104
03ed5799803b2bb56efda7312c40c549c74788b3
Python
py
#encoding:utf-8 import random import numpy as np import glob import os import itertools import time import sys import re import pyopenjtalk import torch import torch.nn as nn import torch.optim as optim import torch.utils.data as data import torchvision from torchvision import models,transforms import torchvision.uti...
vits_text_to_speech.py
MIT
3,330
3a53d053f222e12d7eaf4144db17fafa2e62cfdc
Python
py
# 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. from typing import Tuple import torch import torch.nn.functional as F class LinearWithRepeat(torch.nn.Linear...
projects/nerf/nerf/linear_with_repeat.py
BSD-3-Clause
1,496
3a53db5643fa77101ab11d09cd5abb73d14b6898
Python
py
import torch.nn as nn import torch.nn.functional as F import sys # stop python from writing so much bytecode #sys.dont_write_bytecode = True # ----------------------------------------- # custom modules # ----------------------------------------- from lib.rpn_util import * class RPN_3D_loss(nn.Module): def __in...
lib/loss/rpn_3d.py
MIT
67,261
3a53e1d6ff27ef96c964cdb18f1165ab3319b0c0
Python
py
import os import torch import cv2 import numpy as np from easydict import EasyDict from torch.utils.data import DataLoader from tensorboardX import SummaryWriter from tqdm import tqdm import time from haco.DIDrive_core.policy import LBCBirdviewPolicy from haco.DIDrive_core.data import LBCBirdViewDataset from haco.DIDr...
haco/DIDrive_core/demo/lbc/lbc_birdview_train.py
Apache-2.0
5,092
3a53ff64477a5f72f1f9134968cfce260a145718
Python
py
# Written by Seonwoo Min, Seoul National University (mswzeus@gmail.com) """ Utility functions """ import os import sys import math import random import numpy as np from datetime import datetime from sklearn.metrics import auc, roc_auc_score from scipy.stats import pearsonr, spearmanr, t import torch import torch.nn ...
plus/utils.py
MIT
5,494
3a540a58f6e33fadeffee5f00a22845f9644c6fb
Python
py
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import torch.nn as nn import numpy as np import torch.nn.functional as F from models.networks.base_network import BaseNetwork from models.networks.normalization import get_nonspade_norm_layer class ConvEncoder(BaseNetwork): """ Same archite...
Face_Enhancement/models/networks/encoder.py
MIT
1,914
3a540e06cf584cb7ad932e498a219f52171c9a81
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import os import torch from PIL import Image, ImageFile from torchvision import transforms import torchvision.datasets.folder from torch.utils.data import TensorDataset, Subset from torchvision.datasets import MNIST, ImageFolder from torchvision.tr...
domainbed/datasets.py
MIT
12,652
3a54145da4ae502c82cbe2e8252699057b7400f9
Python
py
""" Utilities for working with the local dataset cache. This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp Copyright by the AllenNLP authors. """ import copy import gzip import json import lzma import os import re import shutil import sys import tarfile import tempfile import time im...
src/datasets/utils/file_utils.py
Apache-2.0
26,747
1e5cf1c70785867216750f84efea6b3a049eea4e
Python
py
from numpy import random from numpy.core.numeric import full import torch import numpy as np import os import scipy.ndimage import torchvision.transforms as transforms import torch.nn.functional as F from PIL import Image import random from torch._C import dtype, set_flush_denormal # from detectron2.structures.masks i...
COTR/datasets/tracking_datasets.py
Apache-2.0
93,775
454f7cdc5862a7a3416b5256258ba3bead5b4599
Python
py
from tqdm import tqdm import numpy as np import matplotlib.pyplot as plt import torch from utilities import * from VoxelGrid import * import os import argparse parser = argparse.ArgumentParser(description='Compute a movie from a model.') parser.add_argument('-model', default="chair", help='model') args = parser.parse...
make_movie.py
MIT
1,175
dfc4f8c81645e7a51d43efee753f3ee4e642d7df
Python
py
import torch import torch.nn as nn import torch.nn.functional as F import pdb class CrowdCounter(nn.Module): def __init__(self,gpus,model_name): super(CrowdCounter, self).__init__() if model_name == 'AlexNet': from .SCC_Model.AlexNet import AlexNet as net elif m...
models/CC.py
MIT
2,629
3a546196d164e9649583ed24e253efcdb9870db0
Python
py
import copy from abc import ABCMeta, abstractmethod import mmcv import numpy as np from torch.utils.data import Dataset from mmcls.core.evaluation import precision_recall_f1, support from mmcls.models.losses import accuracy from .pipelines import Compose class BaseDataset(Dataset, metaclass=ABCMeta): """Base da...
mmcls/datasets/base_dataset.py
Apache-2.0
6,714
fda3fb7042a67f15b36e1d753af5b16670321300
Python
py
import torch from torch import nn from torch.nn import functional as F class Encoder(nn.Module): """Maps an (x_i, y_i) pair to a representation r_i. Parameters ---------- x_dim : int Dimension of x values. y_dim : int Dimension of y values. h_dim : int Dimension of h...
models.py
MIT
4,653
3a54979f0a57bd8292ab13828f4d2d8e09dce6fa
Python
py
import json import os import sys import torch from pathlib import Path from nni.retiarii.experiment import RetiariiExperiment, RetiariiExeConfig from nni.retiarii.strategies import TPEStrategy, RandomStrategy from nni.retiarii.trainer import PyTorchImageClassificationTrainer from darts_model import CNN if __name__ =...
test/retiarii_test/darts/test.py
MIT
1,300
3a549b76cd7ac83e1d54ba8d753424b09f37bf4d
Python
py
# loaders.py import torch import numpy as np import scipy.io as sio from skimage import io from PIL import Image def loader_skimage(path): return io.imread(path) def loader_image(path): return Image.open(path).convert('RGB') def loader_torch(path): return torch.load(path) def loader_numpy(path): ...
extraction/msu_latentafis/datasets/loaders.py
MIT
396
3a549f58467a74f9a1741f47aee32cc4442303aa
Python
py
r""" This package adds support for CUDA tensor types, that implement the same function as CPU tensors, but they utilize GPUs for computation. It is lazily initialized, so you can always import it, and use :func:`is_available()` to determine if your system supports CUDA. :ref:`cuda-semantics` has more details about wo...
torch/cuda/__init__.py
Intel
27,007
d782c300c332a83a68668ddd6af98cfa8bf5d0dc
Python
py
r"""Functional interface""" from typing import Callable, List, Optional, Tuple import math import warnings import torch from torch import _VF from torch._C import _infer_size, _add_docstr from torch._torch_docs import reproducibility_notes, tf32_notes from .._jit_internal import boolean_dispatch, _overload, Broadcast...
torch/nn/functional.py
Intel
197,724
3a54a8df58538dc5d602334cda8201d0fd36e344
Python
py
from __future__ import print_function, division from collections import OrderedDict import torch import torch.nn as nn from torch.autograd import Variable import torchvision.models as models import numpy as np import numpy.matlib import pickle from lib.torch_util import Softmax1D from lib.conv4d import Conv4d from lib...
lib/model_train/trash/model_pixelCT_mask_both_FB_check_differ.py
MIT
36,198
7cad0609de1b77b3e514b7c5914f3b229396c763
Python
py
from torch import nn from torch.autograd import Function import ocnn class OctreeMaxPoolFunction(Function): @staticmethod def forward(ctx, data_in, octree, depth): data_in = data_in.contiguous() data_out, mask = ocnn.nn.octree_max_pool(data_in, octree, depth) ctx.depth = depth ctx.save_for_backw...
pytorch/ocnn/octree_pool.py
MIT
3,126
3a54d971fab1d5bbfcd88d4ecd81eeeae98bbb16
Python
py
from __future__ import print_function, division, absolute_import import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo import os import sys __all__ = ['InceptionV4', 'inceptionv4'] pretrained_settings = { 'inceptionv4': { 'imagenet': { 'ur...
inception_v4.py
MIT
10,999
10de4ec790880ca7f2822bb06d423aef2764dd4c
Python
py
import unittest from transformers import AutoTokenizer, is_torch_available from transformers.testing_utils import require_torch, slow if is_torch_available(): import torch from transformers import ( DataCollatorForLanguageModeling, DataCollatorForNextSentencePrediction, DataCollatorF...
tests/test_data_collator.py
Apache-2.0
9,294
ff45e87d6ce695175c2298a3b2c1c2ae6b19c084
Python
py
import random import torch import os import numpy as np from rendering import render_path from dataset import load_data from inputs import config_parser from model import create_nerf device = torch.device("cuda" if torch.cuda.is_available() else "cpu") np.random.seed(0) def test(): parser = config_parser() ...
test_nerf.py
MIT
2,564
1ec4706d1f8a23ce752d88d708d7b1c037bdc109
Python
py
from agent import Agent import argparse from collections import deque from env import Environment import numpy as np import torch from model import QNetwork, Small, Large, Dropout import matplotlib matplotlib.use("TkAgg") from matplotlib import pyplot as plt def main(args): if args.examine: examine() ...
main.py
MIT
7,213
f9686dc9ff2b89a0df7aed64052c25f7bda29a89
Python
py
from __future__ import absolute_import, division, print_function from torch.nn import functional as F import argparse #import csv import logging import os import random import sys import json import numpy as np import torch from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, ...
run_xlm.py
MIT
34,111
3a559a7b4d3df48475c8c1c2f827fb1bc7c46c5b
Python
py
import torch.nn.functional as F import torch.nn as nn from torch2trt.torch2trt import * from torch2trt.module_test import add_module_test import collections def has_interpolate_plugin(): try: from torch2trt.plugins import InterpolatePlugin return True except: ...
torch2trt/converters/interpolate.py
MIT
7,562
dfa20d1918c5df125e88527604e183fd71d272e3
Python
py
""" The ConvNeXt architecture is similar to previous convnet but was updated with many of the advances found in recent papers (as of early 2022). Networks are expanded by increasing the numbers of channel (denoted with C) or block (denoted with B). Configurations suggested in the ConvNeXt paper are: ConvNeXt-T: C =...
models/convnext.py
MIT
22,776
7c2a07aaf5d92980a1f2a16e2ea87fb92e8f9a14
Python
py
""" Created by Edward Li at 10/7/20 Using a CNN structure from this paper (https://www.diva-portal.org/smash/get/diva2:1342302/FULLTEXT01.pdf) and Google Deep mind """ import torch.nn.functional as F import torch.nn as nn class DQNCNN(nn.Module): def __init__(self, side_length, outputs, in_channels = 1, features=...
DQN.py
MIT
2,473
3a55adc947f77f29348907d83944b9ab51e3a831
Python
py
#!/usr/bin/env python3 import math import pickle import unittest import torch from gpytorch.kernels import RBFKernel from gpytorch.priors import NormalPrior from gpytorch.test.base_kernel_test_case import BaseKernelTestCase class TestRBFKernel(unittest.TestCase, BaseKernelTestCase): def create_kernel_no_ard(se...
test/kernels/test_rbf_kernel.py
MIT
8,740
3a55c3bef794e8b3182f77af5dd55f21ff19a3eb
Python
py
""" CLIP Model Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI. """ from collections import OrderedDict from dataclasses import dataclass from typing import Tuple, Union, Callable, Optional import numpy as np import torch import torch.nn.functional as F from torch impor...
src/open_clip/model.py
MIT
20,574
3a55f17311c1e13f6eba4ef8a69863a7464cc1dc
Python
py
import torch from torch.utils.data import DataLoader, Dataset import pickle import h5py from random import shuffle from common import Common from config import Config class Dictionaries: def __init__(self, conf): self.config = conf with open(self.config.DICT_PATH, 'rb') as f: self.s...
loader.py
MIT
8,483
ffaadd5b3de17406db275c413770dfaba3274694
Python
py
import torch import numpy as np from copy import deepcopy import torch.nn.functional as F from tianshou.data import Batch from tianshou.policy import DDPGPolicy class SACPolicy(DDPGPolicy): """Implementation of Soft Actor-Critic. arXiv:1812.05905 :param torch.nn.Module actor: the actor network following the...
tianshou/policy/modelfree/sac.py
MIT
5,644
3a55fbafcb5f5b6a957ae773b4157267c27f99ba
Python
py
import glob import math import random import matplotlib.pyplot as plt import numpy as np import torch import torch.distributions as tdist import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision import torchvision.transforms as transforms import torchvision.transforms.functi...
inf.py
MIT
2,211
5e74daeb9deeafa0fc74757e3d7fc9bcbc14df6f
Python
py
# MIT License # # Copyright (c) 2017 Max W. Y. Lam # # 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 limitation the rights # to use, copy, modify, mer...
run.py
MIT
6,875
ff4b21ce954bf05d55c3a7d9edbcb0222a9e6b25
Python
py
import torch from torch import nn import torch.nn.functional as F import models from torch.utils.data import DataLoader import os.path as osp from tqdm import tqdm from torch.autograd import Variable import numpy as np from utils.logger import AverageMeter as meter from data_loader import Visda_Dataset, Office_Dataset...
model_trainer.py
MIT
25,854
457a9cc2ecab393aa0ad701a3fbc15b30b68006b
Python
py
# -*- coding:utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the ...
zeus/networks/pytorch/customs/modnas/arch_space/ops.py
MIT
9,047
34458ac76ceb7763746666f8d5e28094854d2872
Python
py
# YOLOv5 common modules import logging from copy import copy from pathlib import Path, PosixPath import math import numpy as np import pandas as pd import requests import torch import torch.nn as nn from PIL import Image from torch.cuda import amp from .datasets import exif_transpose, letterbox from .general import ...
packages/yolov5/models/common.py
MIT
16,648
3a5668b72cd35f4c8ad959a22604ef6fd371e123
Python
py
import sys, time, random, argparse from copy import deepcopy import torch from pathlib import Path import numpy as np import torch.nn as nn import math import os import torch.nn.init as init import torch.nn.functional as F import warnings warnings.filterwarnings("ignore") lib_dir = (Path(__file__).parent / ".." / ".."...
exps/algos/Block_wise_TANAS.py
MIT
24,534
3a566a598d46ef3bca6de25963ffae888cd1d384
Python
py
from collections import defaultdict, deque import datetime import pickle import time import torch import torch.distributed as dist import errno import os class SmoothedValue(object): """Track a series of values and provide access to smoothed values over a window or the global series average. """ ...
torchvision-object-detection-finetuning-tutorial/utils.py
MIT
9,758
3a566e434c66eada4efbfd3bc119fdc743505a1d
Python
py
import torch import torch.nn as nn from lib.utils import Configure, decoding, detection class MultiDetector(nn.Module): def __init__(self, block, in_planes, kernel_size=(16, 2, 2), num_classes=3, extra_layers=False, phase='train', data_type='normal', policy='first', conf_thresh=0.01): sup...
modules/layers/multi_detector.py
MIT
15,747
45538dbe4f9a9073ebc9889b40b5d2ba96212fd9
Python
py
import librosa import torch from typing import Tuple import numpy as np from espnet.nets.pytorch_backend.nets_utils import make_pad_mask class LogMel(torch.nn.Module): """Convert STFT to fbank feats The arguments is same as librosa.filters.mel Args: fs: number > 0 [scalar] sampling rate of the ...
espnet2/layers/log_mel.py
Apache-2.0
2,756
3a569c6d2a4b057fc8e15f3a503ee3d47dfdefdb
Python
py
import collections from contextlib import contextmanager from dataclasses import dataclass, field from enum import Enum from typing import ( Dict, List, Optional, Union ) import threading import torch import torch.distributed as dist from torch.distributed import rpc from torch.distributed import distr...
torch/distributed/_sharded_tensor/api.py
Intel
33,240
42a7eaf327eaa0c7e3f8a6de7d86cc0067345ad8
Python
py
#! /usr/bin/python3 """ Reference: https://github.com/pytorch/examples/blob/master/mnist/main.py """ from __future__ import print_function import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms from net import LeNe...
train.py
MIT
5,172
1e9365ba1ad28247a19e10b2de9297c3dfac8169
Python
py
import functools import logging import random import re import warnings from concurrent.futures import ProcessPoolExecutor from contextlib import contextmanager from dataclasses import dataclass from decimal import ROUND_HALF_UP from functools import lru_cache, partial from io import BytesIO, IOBase from itertools impo...
lhotse/audio.py
Apache-2.0
73,177
d7da4698a100ee231e17b85d2bd1a2506bf34e4a
Python
py
import glob import os import re import setuptools from pkg_resources import DistributionNotFound, get_distribution from setuptools import dist, find_packages, setup dist.Distribution().fetch_build_eggs(['Cython', 'numpy>=1.11.1']) import numpy # NOQA: E402 # isort:skip from Cython.Build import cythonize # NOQA: E4...
mmcv-full-1.2.0/setup.py
Apache-2.0
8,106
3a56de8aa0bc50ef2e25291283fcf53738617791
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import unittest from collections import Counter import numpy as np import torch from pytorchvideo.data.utils import thwc_to_cthw from pytorchvideo.transforms import ( ApplyTransformToKey, MixUp, Normalize, OpSampler, RandomSho...
tests/test_transforms.py
Apache-2.0
14,848
5f615ceb91178f50bd6476afe9e24dfaf6e0f26f
Python
py
from torch.utils.data import Dataset, DataLoader import os import json import sys import csv import itertools import numpy as np BASE_DIR = os.path.dirname(os.path.abspath(__file__)) UTILS_DIR = os.path.abspath(os.path.join(BASE_DIR, '..', 'utils')) sys.path.append(UTILS_DIR) from data_helper import * from coord_helpe...
src/lin_my/classifier_dataset_torch.py
MIT
11,370
3a570834f83c9f535df334cdcb39e0a8931d2881
Python
py
import torch import torch.nn as nn import numpy as np from collections import OrderedDict from modules.my_modules import MyNetwork, MyModule from modules.operations import ConvLayer, FactorizedIncrease, FactorizedReduce, \ MobileInvertedResidualBlock, MBInvertedConvLayer, Identity, ASPP from modules.mixed_...
models/new_model.py
MIT
14,971
4b3cb2f8d40646d0d38e792313306f8fd92f1ce0
Python
py
# coding=utf-8 # Copyright 2021 Intel 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 required ...
pretraining/optimizers.py
Apache-2.0
2,343
3a57109da508e64f161b6e792e77fa3d5ddba875
Python
py
#!/usr/bin/env python # coding: utf-8 # # This script allows you to run the model on the cluster. # runall.py is not on an actual version right now but runall_onO2.py is # Both scripts will be merged eventually to one. # # Code starts here ####################################################################### # IM...
misc/runallskorch.py
Apache-2.0
12,058
3a572769175ab9a26bd59f85408b6002f9852010
Python
py
import argparse import time import math import numpy as np np.random.seed(331) import torch import torch.nn as nn import tcn import data import model from utils import batchify, get_batch, repackage_hidden parser = argparse.ArgumentParser(description='PyTorch PennTreeBank RNN/LSTM Language Model') parser.add_argument...
finetune_span.py
BSD-3-Clause
13,467
cc14a09ef974053294aa489cce47d26c3667c60c
Python
py
import numpy as np import torch from torch import nn from torchvision.utils import make_grid import visdom class Visualizer(): def __init__(self, name, display_id=1): self.display_id = display_id self.vis = visdom.Visdom(env=name) self.name = name def throw_visdom_connection_error(sel...
utils/visualizer.py
MIT
1,959
3a57449917a814901e97566773f58ab82330cbce
Python
py
# flake8: noqa # There's no way to ignore "F401 '...' imported but unused" warnings in this # module, but to preserve other warnings. So, don't check this module at all. # coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this...
src/transformers/pipelines/__init__.py
Apache-2.0
19,326
24a5b176335a71d8b718f4cbb587d54bae53c04b
Python
py
from __future__ import print_function, division 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 from PIL import Image import glob from sklearn import...
datasets/wavelets/wavelet_dset.py
MIT
2,952
5f323386cd472e99d65e3ab68380b2c842492120
Python
py
""" Taken from https://github.com/TUM-LMF/MTLCC-pytorch/blob/master/src/models/convlstm/convlstm.py authors: TUM-LMF """ import torch.nn as nn from torch.autograd import Variable import torch class ConvLSTMCell(nn.Module): def __init__(self, input_size, input_dim, hidden_dim, kernel_size, bias): """ ...
src/backbones/convlstm.py
MIT
10,503
7c21d36bb4c33d5cdecf78376c8ad4e404bbf09e
Python
py
import logging import os import setproctitle import shutil import subprocess import sys import click import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.multiprocessing as multiprocessing from revolver.data import datasets, datatypes, prepare_loader from revolver.model impo...
train.py
BSD-2-Clause
6,386
45ce9fdc17cc0872b93fa1958deec0248099c067
Python
py
import os import glob import numpy as np import pandas as pd import torch from torch.utils.data import Dataset, DataLoader, random_split from skimage import io, transform class DataHandler(): def __init__(self, dataset, batch_size=64, shuffle=True, validation_prop=0.2, validation_cache=64): self.__val_...
src/data_handle/data_handler.py
MIT
12,896
fcc25483aadb115bbb479863291dd9d7b473ae8f
Python
py
import torch.nn as nn class DeepSurv(nn.Module): def __init__(self, n_features, hidden_size=64): super().__init__() self.survival = nn.Sequential( nn.Linear(n_features, hidden_size), nn.ReLU(), nn.Dropout(0.2), nn.BatchNorm1d(hidden_s...
Models/MFPCA_DeepSurv/DeepSurv.py
MIT
633
3a579845c530fb5c5d0b960be1184bd0e446d7bc
Python
py
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @File : main.py @Time : 2020/03/09 @Author : jhhuang96 @Mail : hjh096@126.com @Version : 1.0 @Description: """ from comet_ml import Experiment import os os.environ["CUDA_VISIBLE_DEVICES"] = "0" from encoder import Encoder from decoder import De...
main.py
MIT
9,361
a940cf87f847651f323d59050fd850c978e0b9fa
Python
py
# -*- Python -*- # This file is licensed under a pytorch-style license # See frontends/pytorch/LICENSE for license information. import typing import torch import torch_mlir # RUN: %PYTHON %s | npcomp-opt | FileCheck %s mb = torch_mlir.ModuleBuilder() class Submodule(torch.nn.Module): def __init__(self, n): ...
frontends/pytorch/test/module_import/submodules.py
Apache-2.0
1,596
3a57c085defd12a35156ca8aa66901a02bbd4c9d
Python
py
"""Deformable 3D convolution Adapted from https://github.com/oeway/pytorch-deform-conv/ """ import torch import torch.nn as nn import numpy as np from torch.autograd import Variable def flatten(a): return a.contiguous().view(a.nelement()) def repeat(a, repeats, axis=0): assert len(a.size()) == 1 return...
deformable_conv_3d.py
MIT
8,617
f9a29b8779ca57d673408754c9d0d1fd5f015dbe
Python
py
import math import torch import torch.nn as nn 4 from models import register def default_conv(in_channels, out_channels, kernel_size, bias=True): return nn.Conv2d( in_channels, out_channels, kernel_size, padding=(kernel_size // 2), bias=bias) class BasicBlock(nn.Module): def __init__( ...
models/common.py
Apache-2.0
2,833
cc18a6a9e2623949e38eae3c94ef16e0301d1d63
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import random from typing import Tuple import torch from torch import nn from torch.nn import functional as F from detectron2.config import CfgNode from densepose2.structures.mesh import create_mesh from .utils import sample_random_indices cla...
projects/DensePose/densepose/modeling/losses/cycle_shape2shape.py
Apache-2.0
4,667
10fb13dc6901245541ecb8f69344eca9b86f5a9c
Python
py
import torch.nn as nn import torch.nn.functional as F import torch from functools import partial def conv3x3(in_planes, out_planes, stride=1, bias=False): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=bias) def dilat...
src/models/modules/refinenet.py
MIT
13,612
f9a13967862c1365ae821d2f3b967d3f83bd627a
Python
py
from thop import profile import torch import argparse import os import pprint # import pose_resnet import _init_paths from config import cfg from config import update_config import models def parse_args(): parser = argparse.ArgumentParser(description='Train keypoints network') # general parser.add_argument(...
tools/calculate.py
MIT
1,667
425f0cd14831f3480a078ed8ee37469e1578da73
Python
py
#!/usr/bin/env python3 import copy import inspect import itertools import operator from collections import OrderedDict import torch from torch import nn from torch.distributions import Distribution from .constraints import Interval from .lazy import LazyTensor class Module(nn.Module): def __init__(self): ...
gpytorch/module.py
MIT
25,703
3a583798e2ffdaabba7d4a785880c458fc8a7ee7
Python
py
import torch import torch.nn as nn import torch.nn.functional as F from loss.dice_loss import DiceLoss,ShiftDiceLoss from loss.cross_entropy import CrossentropyLoss, TopKLoss, DynamicTopKLoss class BCEPlusDice(nn.Module): """Dice loss, need one hot encode input Args: weight: An array of shape [num_cl...
loss/combine_loss.py
MIT
8,494
24e96985b8161b9a6fc50adf91ffe5f3da556940
Python
py
# -*- coding: utf-8 -*- """ @date: 2020/4/26 下午3:38 @file: squeeze_net.py @author: zj @description: """ import torch.nn as nn from models.squeezenet.basic_conv2d import BasicConv2d from models.squeezenet.fire import Fire class SqueezeNet(nn.Module): def __init__(self, num_classes=1000): super(Squeeze...
py/lib/models/squeezenet/squeeze_net.py
Apache-2.0
1,926
3a587b65901fef5fc45c4b349763133908fe5cf5
Python
py
import io import os import sys import unittest import torch import torch.nn as nn from torch.testing import FileCheck from typing import Any # Make the helper files in test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) from torch.testing....
test/jit/test_class_type.py
Intel
43,672
3a5881f365c168de569192ccc02a9cbbaca86fe3
Python
py
from __future__ import division from tools.model import load_model from config.configs_kf import * from lib.utils.visual import * import torchvision.transforms as st from sklearn.metrics import confusion_matrix import numpy as np # from tqdm import tqdm_notebook as tqdm from tqdm import tqdm from tools.ckpt import ...
MSCG-Net/test_submission.py
MIT
9,111
ff33d0ce6b545371dc987ee3de50f64ddfaf7165
Python
py
import torch import torch.distributed as dist import argparse import collections import datetime import json import os import _jsonnet import attr import random import numpy # These imports are needed for registry.lookup # noinspection PyUnresolvedReferences from ratsql import ast_util # noinspection PyUnresolvedRe...
ratsql/commands/train.py
MIT
15,553
3a589e8fae44c3a44971f37b0d8026ecbca31da2
Python
py
import os import argparse import copy from functools import partial from easydict import EasyDict import torch import torch.nn as nn from tensorboardX import SummaryWriter import numpy as np from carla_env import ImplicitCarlaEnv from models import ImplicitDQN from core.utils.others.tcp_helper import parse_carla_tcp ...
demo/implicit/train_rl.py
Apache-2.0
7,816
3a58a64f0501d41a31f24e6668eaad98de1ba6ca
Python
py
import torch def flipud(tensor): """ Flips a given tensor along the first dimension (up to down) Parameters ---------- tensor a tensor at least two-dimensional Returns ------- Tensor the flipped tensor """ return torch.flip(tensor, dims=[0])
ACME/utility/flipud.py
MIT
303
3a58ae95d719e650ef8251214e5592bff3f6c967
Python
py
import os import math import json import logging import torch import torch.optim as optim from tensorboardX import SummaryWriter from ..utils.util import ensure_dir class BaseTrainer: """ Base class for all trainers """ def __init__(self, model, loss, metrics, resume, config, train_logger=None): ...
FOTS/base/base_trainer.py
BSD-3-Clause
7,418
6b2ba80cecb4bb3bf407def805dd43d468b8913d
Python
py
# -*- coding: utf-8 -*- """ Created on Sat Oct 27 11:58:26 2018 file_utils @author: GEO """ import os import sys import torch import shutil from datetime import datetime import pandas as pd from matplotlib import pyplot as plt def init_folders(base_output_dir, model_name, resume, logging): output_dir = os.path.j...
utils/file_utils.py
MIT
10,852
3a58cfee04cd808757c8a0372cee0049c1b420b5
Python
py
import numpy as np from typing import NamedTuple, Mapping, Dict from enum import Enum from dataclasses import dataclass import torch import torch.utils.data.dataloader as dataloader from jiant.utils.python.datastructures import ExtendedDataClassMixin, combine_dicts @dataclass class FeaturizationSpec: """Tokeniz...
jiant/tasks/core.py
MIT
7,397
28bd8b051ace8f55c78f0682a6d1c314842a7de7
Python
py
""" Description: This library contains all the class model for building ml architectures Please refer to each of the functions/classes for a full description of what they do. Functions ([first,second] "first bool" notes the implemented functions "second bool" notes the implemented documentation): n...
SP/ml/archs/build.py
MIT
2,388
651acc487827fca4cb44a3f2e4e1321a4f6238cc
Python
py
import pytest import time from itertools import product import numpy as np import torch from ding.rl_utils import ppg_data, ppg_joint_error use_value_clip_args = [True, False] random_weight = torch.rand(4) + 1 weight_args = [None, random_weight] args = [item for item in product(*[use_value_clip_args, weight_args])] ...
ding/rl_utils/tests/test_ppg.py
Apache-2.0
1,712
ffa881662e5f13ff101948279df38a5a3bc9c506
Python
py
# This file is based on the BiaffineDependencyParser implemented in AllenNLP 0.8.4, # which is licensed under the Apache License, Version 2.0. # see https://github.com/allenai/allennlp/blob/030ef755aeeee7d05d119dcfe367f81bb26aed53/allennlp/models/biaffine_dependency_parser.py # # Copyright (c) 2020 Saarland University...
graph_dependency_parser/components/edge_models/DM.py
Apache-2.0
9,892
3a5904c85cfb29f13735ed7a21a1ba6f49c91d04
Python
py
import torch import torch.nn as nn import torch.autograd as autograd import torch.cuda.comm as comm import torch.nn.functional as F from torch.autograd.function import once_differentiable import time import functools #from libs import InPlaceABN, InPlaceABNSync #BatchNorm2d = functools.partial(InPlaceABNSync, activat...
cc_attention/functions.py
MIT
5,093
3a59085e87b260d8f4cdb3bd0870cdb1d884b794
Python
py
# -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ This file contains components with some default boilerplate logic user may need in training / testing. They will not work for everyone, but many users may find them useful. The behavior of functions/classes in this file...
detectron2/engine/defaults.py
Apache-2.0
18,818
3a5913f02a4a2b71339d0a27ca1254a777434a55
Python
py
# coding=utf-8 # Copyright 2018 the HuggingFace Inc. 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...
tests/test_trainer.py
Apache-2.0
37,364
3a5916d19a9423e050c346702933bb3647517a2a
Python
py
""" Copyright 2022 Vanessa Boehm 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, software d...
pytorch_pae/data_loader.py
Apache-2.0
1,863
ff03e5b32be61f7c369110b0ee6295f7cf203780
Python
py
import torch.optim as optim import torch from utils.train_utils import * import logging import math import importlib import datetime import random import munch import yaml import os import sys import argparse from dataset import ShapeNetH5 def train(): logging.info(str(args)) metrics = ['cd_p', 'cd_t', 'emd',...
train.py
MIT
8,621
3a593d8ae8e5f8dd5c879ef4750e874c9e22b130
Python
py
import copy from typing import Optional, Any import torch, pickle from torch import Tensor,nn import torch.nn.functional as F from torch.nn.modules import Module from torch.nn.modules.activation import MultiheadAttention from torch.nn.modules.container import ModuleList from torch.nn.init import xavier_uniform_ from t...
HackTransformer.py
MIT
38,912
d7e062b0bdf874ce53260ae03cf6dbe999bcf708
Python
py
import torch.nn as nn class PairNorm(nn.Module): def __init__(self, mode='PN', scale=1): """ mode: 'None' : No normalization 'PN' : Original version 'PN-SI' : Scale-Individually version 'PN-SCS' : Scale-and-Center-Simultaneously versio...
src/mylib/torch/nn/modules/pair_norm.py
MIT
1,584
3a594b5d8d475e431e1886e8834f5080fc0e706e
Python
py
from __future__ import print_function import torch import torchvision.transforms as transforms import torch.optim as optim import torch.backends.cudnn as cudnn import torch.nn as nn import argparse import os import random import sys import pprint import datetime import dateutil.tz import time import cloudpickle impor...
code/auto-encoder-pokemon/gridsearch.py
MIT
5,980
1e5f54221c0cf6fd9f3f3eef4d073800655dae17
Python
py
# Copyright (c) Facebook, Inc. and its affiliates. # Modified by Bowen Cheng from: https://github.com/facebookresearch/detr/blob/master/models/detr.py import fvcore.nn.weight_init as weight_init import torch from torch import nn from torch.nn import functional as F from detectron2.config import configurable from detec...
backend/MaskFormer/mask_former/modeling/transformer/transformer_predictor.py
MIT
6,381
45d04451444dc5532d60dd7a6b6072ba5b87357f
Python
py
import cubes.torch.functional as C import torch def main(): x = torch.ones(1, 40, 5).cuda() x.requires_grad = True t = C.graded_dropout(x, a=10, b=50, training=True).sum() t.backward() print(x.grad) if __name__ == "__main__": main()
examples/graded_dropout.py
MIT
261
3a597f73a915909b2685989e96000ce3feba2806
Python
py
# -*- coding: utf-8 -*- """basic_DDQN.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/107IqlTumlwGkd_ijA3PBnT9VJwoF4nF_ # README based on: https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.html ##Requirements ## DONE - ma...
basic_ddqn.py
MIT
16,402
45b61ef908fc45578fa4cf40541a700710f3fd52
Python
py
# get_objects.py from os import path import numpy as np import pickle import torch from torch.autograd import Variable import cv2 from WP5.KU.Algorithms.frame_analyser import FrameAnalyser from WP5.KU.Algorithms.object_detection.SSD.data import BaseTransform, VOC_CLASSES as LABEL_MAP from WP5.KU.Algorithms.object_detec...
WP5/KU/Algorithms/object_detection/get_objects.py
Apache-2.0
3,253
802f99d9d4c75a54fefb81bef9daacbb6f4381f2
Python
py
import os import glob import numpy as np import albumentations from torch.utils.data import Dataset from taming.data.base import ImagePaths, NumpyPaths, ConcatDatasetWithIndex class ObjectsBase(Dataset): def __init__(self, *args, **kwargs): super().__init__() self.data = None self.keys = ...
taming/data/objects.py
MIT
8,523
45ae3677356da3a1d10e7003aaa4d20b59d3658f
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/integrations/icevision/adapter.py
Apache-2.0
7,470
1e6c7d48a98a657a59a768866b86d766361c9d2a
Python
py
import os import time import torch import torch.nn as nn from torch.autograd import Variable from models import ResNet as resnet_cifar import pandas as pd import argparse import csv from torch.optim.lr_scheduler import MultiStepLR from dataLoader import DataLoader from summaries import TensorboardSummary # parameters...
Old_Codes_For_Exploration/train_js.py
MIT
8,386
5fd1e458f2bbe264d3174d77470398e191a2f19b
Python
py
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT license. from __future__ import division from __future__ import absolute_import from __future__ import print_function import os import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F from la...
examples/pytorch/vision/Face_Detection/models/RPool_Face_C.py
MIT
12,493
4b7dcb89ac44d66b027c20abf005f9390ba18210
Python
py