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 |
|---|---|---|---|---|---|---|---|
#Classes for basic encoder/decoder stuff
import torch
import torch.nn as nn
import numpy as np
import math
#from torch.autograd import Variable
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from utils import variable
class EncDecBase(nn.Module):
def __ini... | S2S/EncDec.py | MIT | 10,823 | 3a5a2a7672087be3698500300087a4b8de310bed | Python | py | |
import torch
from pynvrtc.compiler import Program
from torch.autograd import Function
from collections import namedtuple
from cupy.cuda import function
SRU_CODE = """
extern "C" {
__forceinline__ __device__ float sigmoidf(float x)
{
return 1.f / (1.f + expf(-x));
}
__forceinline__ __device__ f... | oldsru/cuda_functional.py | MIT | 22,989 | 28c5f9a000724505ddc0cdfad9959b869b1f7e9e | Python | py | |
from collections import UserDict
import copy
import math
from typing import Callable, Optional, Union, Dict
import warnings
import torch
from torch import nn
import torch.distributed as dist
import torch.nn.functional as F
from transformers.generation_beam_search import BeamSearchScorer
from transformers.generation_s... | experiments/explainx/search_engine/contrastive_captioner.py | MIT | 21,732 | a927d164274df481e22a49421944e1005e58b014 | Python | py | |
from itertools import chain
import torch
from torch_sparse import SparseTensor
from scipy.sparse.csgraph import minimum_spanning_tree
from torch_geometric.utils import to_undirected
try:
import rdkit.Chem as Chem
except ImportError:
Chem = None
def tree_decomposition(mol, return_vocab=False):
r"""The t... | torch_geometric/utils/tree_decomposition.py | MIT | 4,808 | 3a5a59d5e236c732154c639de458861f941f4ff0 | Python | py | |
# Copyright (C) 2020 THL A29 Limited, a Tencent company.
# 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 appl... | benchmark/benchmark_helper.py | BSD-3-Clause | 5,195 | 45f4412065dec6210ac750fafb36e988c9184c58 | Python | py | |
from __future__ import print_function
import sys
import os
import pickle
import argparse
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
import numpy as np
from torch.autograd import Variable
#from data import VOCroot,COCOroot
#from data import Annota... | test.py | MIT | 8,083 | 3a5a824f47c903a7903f60ac85be5781539da93a | Python | py | |
import torch
import torch.nn as nn
import numpy as np
from torch.distributions import Categorical
import gym
from tqdm import tqdm
from procgen import ProcgenGym3Env
def test_procgen(agent, env, n_steps, update_step):
rewards = []
firsts = []
_, prev_state, prev_first = env.observe()
for step in tqdm(range(n_s... | mtpm/utils/test_loop.py | Apache-2.0 | 1,459 | df97944f73ba8e1b2993a56c235cb7f3f3cf90bf | Python | py | |
import copy
from typing import Any, Callable, Dict, List, Optional, Set, Union
import numpy as np
import torch
from toolz import compose_left, pipe
from torch.utils.data import Dataset
from tqdm import tqdm
from slp.data.transforms import ToTensor
class MMDataset(Dataset):
def __init__(
self,
da... | slp/data/multimodal.py | MIT | 3,377 | 52fdabbb099a9324a08a7b04f4ecd4708e367507 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import Conv2d, ConvModule, build_upsample_layer, constant_init, xavier_init
from mmcv.ops.carafe import CARAFEPack
from mmcv.runner import BaseModule, ModuleList, auto_fp16, force_fp32
from torch.nn.modules.utils import ... | mmdet/models/roi_heads/mask_heads/fcn_mask_head_ntm.py | Apache-2.0 | 14,801 | 24e2b3844e77a95dfff9939654873c7f8b78a7b2 | Python | py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import math
import logging
import numpy as np
from os.path import join
import torch
from torch import nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from dcn_v2 import ... | src/lib/models/networks/pose_dla_dcn.py | MIT | 18,034 | 45c270841b22734df2f31cddba924e75856739d3 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
import io
import numpy as np
import os
import re
import tempfile
import unittest
from typing import Callable
import torch
import torch.onnx.symbolic_helper as sym_help
from packaging import version
from torch._C import ListType
from torch.onnx import register_custom_op... | detectron2/utils/testing.py | Apache-2.0 | 18,538 | 3a5b367f8d962176fbde2e76112481755e0c6102 | Python | py | |
import os
from skimage import io, transform
import torch
import torchvision
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms#, utils
# import torch.optim as optim
import numpy as np
from PIL imp... | u2net_test.py | Apache-2.0 | 3,659 | 3460b562c2b96063553383c9646509779d2acdb8 | Python | py | |
import torch
import torch.nn as nn
from torch.autograd import Variable as V
import cv2
import numpy as np
class MyFrame():
def __init__(self, net, loss, lr=2e-4, evalmode = False):
self.net = net().cuda()
self.net = torch.nn.DataParallel(self.net, device_ids=range(torch.cuda.device_count()))
... | framework.py | MIT | 2,663 | 3a5b6f762f4f68dcd21dac4119e33392969d32be | Python | py | |
from typing import Optional, Union
import warnings
import torch
from torch_geometric.typing import InputNodes
from torch_geometric.data import Data, HeteroData, Dataset
from torch_geometric.loader.dataloader import DataLoader
from torch_geometric.loader.neighbor_loader import (NeighborSampler,
... | torch_geometric/data/lightning_datamodule.py | MIT | 13,267 | 3a5b943d1de1da2e3dfc5522a70ecc5fee96567e | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import torch.nn as nn
import torch
def weight_init(m):
if isinstance(m, nn.Linear):
nn.init.kaiming_normal(m.weight)
class Linear(nn.Module):
def __init__(self, linear_size, p_d... | src/model.py | MIT | 2,932 | 3a5b99297ae5a1d41b4fa6d08444a96689e2d047 | Python | py | |
import math
from typing import List, Dict
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from detectron2.layers import ShapeSpec
from detectron2.modeling.proposal_generator.build import PROPOSAL_GENERATOR_REGISTRY
from adet.layers import DFConv2d, IOULoss, NaiveGroupNorm, GC... | adet/modeling/MEInst/MEInst.py | BSD-2-Clause | 13,344 | 1ec074ac03c3cfd0542b00ee0feddf115fd2ca40 | Python | py | |
from mmdet.datasets import DATASETS
from torch.utils.data import Dataset
import os
import json
from mmdet3d.datasets.pipelines import Compose
import numpy as np
import copy
@DATASETS.register_module()
class NuscDepthDataset(Dataset):
CLASSES=2
def __init__(self, data_path='data/nuscenes/depth_maps/train/detpt... | plugin/depth_lidar_supervision/dataset.py | Apache-2.0 | 3,165 | dfe08b53a5510f3caa8e677339a00ab1f814357e | Python | py | |
# Copyright 2020 - 2021 MONAI Consortium
# 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 wri... | monai/transforms/utility/dictionary.py | Apache-2.0 | 60,066 | 3a5be20e8b9a3a1e33deda238aef203994d5424a | Python | py | |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a cop... | src/modeling.py | Apache-2.0 | 60,136 | 3a5becfb8dffbd79934290e5a8c7c1ec6157e5f6 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import copy
import itertools
import numpy as np
from typing import Any, Iterator, List, Union
import pycocotools.mask as mask_utils
import torch
from detectron2.layers.roi_align import ROIAlign
from .boxes import Boxes
def polygon_area(x, y):
... | detectron2/structures/masks.py | Apache-2.0 | 15,900 | 7ca272476e6c571b0030eee4e8bdb21165651898 | Python | py | |
import itertools, os, time, shutil
import numpy as np
from sklearn.preprocessing import MinMaxScaler
from scipy.spatial import distance
import nibabel as nib
import SimpleITK as sitk
from skimage.transform import resize
import matplotlib.pyplot as plt
import torch
import torch.utils.data as Data
from torchvision imp... | Code/Functions.py | MIT | 12,492 | 7c33805737db7f9939a624141f35cf6c04b950ca | Python | py | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
from pathlib import Path
from typing import Optional, cast
import numpy as np
import gym
import torch
import torch.nn as nn
from gym.spaces import Discrete
from tianshou.data import Batch, to_torch
from tianshou.policy import PPOPolicy, BasePoli... | qlib/rl/order_execution/policy.py | MIT | 4,758 | f95a53c75884d2701519565300518f3ce5fb6f12 | Python | py | |
import glob
import sys
import time
from random import shuffle
from threading import Thread
import queue
import json
import torch
sys.path.append("..")
import params
from .vocab import PAD_TOKEN, UNKNOWN_TOKEN, DECODING_START, DECODING_END
class Batch(object):
def __init__(self, examples, vocab, struct_dist, dev... | data_apis/UbuntuChatCorpus.py | MIT | 13,839 | 5f8dfb29cbc3fd07cba051381567227d1a857343 | Python | py | |
from model import Seq2seq
import os
from data_utils import START_TOKEN, END_ID, get_loader, UNK_ID, outputids2words
import torch
import torch.nn.functional as F
import config
import pickle
class Hypothesis(object):
def __init__(self, tokens, log_probs, state, context=None):
self.tokens = tokens
se... | inference.py | MIT | 7,547 | 4b7ce9d0fa64d0f225b851203473b213913d5a98 | Python | py | |
"""
An agent for the IDSGameEnv that implements the DQN algorithm.
"""
from typing import Union
import numpy as np
import time
import tqdm
import torch
from torch.utils.tensorboard import SummaryWriter
from gym_idsgame.envs.rendering.video.idsgame_monitor import IdsGameMonitor
from gym_idsgame.agents.training_agents.q_... | gym_idsgame/agents/training_agents/q_learning/dqn/dqn.py | MIT | 47,417 | 3a5c15a29225a63fc84eb131fbbbb35239f47236 | Python | py | |
from .slakh_dataset import SlakhDataset
import torch
from pathlib import Path
def load_datasets(parser, args):
"""Loads the specified dataset from commandline arguments
Returns:
train_dataset, validation_dataset
"""
args = parser.parse_args()
dataset_kwargs = {
"root": Path(args.... | code/local/dataloader.py | MIT | 1,932 | 70056c69cd3cca8b2fc7b3ae024211d4f4fec960 | Python | py | |
# _*_ coding=utf-8 _*_
import math
import torch
import torch.nn as nn
import numpy as np
from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.lr_scheduler import ReduceLROnPlateau
class GradualWarmupScheduler(_LRScheduler):
""" Gradually warm-up(increasing) learning rate in optimizer.
Proposed ... | transformer/module.py | Apache-2.0 | 11,995 | 4b3997ddbce7e5270d173f5c8fc32a48e9832739 | Python | py | |
#!/usr/bin/env python3
import os
from cnns import matplotlib_backend
import argparse
import torch
import torch.optim as optim
import torch.nn as nn
import torchvision.datasets as dst
import torchvision.transforms as tfs
from cnns.nnlib.pytorch_architecture.vgg import VGG as vgg
from cnns.nnlib.pytorch_architecture.vgg_... | cnns/nnlib/pytorch_architecture/vgg_train.py | Apache-2.0 | 10,966 | f999158339d5a3f0b1fd124d6da8542bcf722e1e | Python | py | |
import argparse
import concurrent.futures as fut
import cv2
import gc
import os
import sys
import time
from argparse import Namespace
from functools import partial
from typing import Dict, List, Callable, Optional, Tuple
import numpy as np
import pandas as pd
from nvidia.dali.plugin.pytorch import DALIGenericIterator
... | src/prepare_data.py | Apache-2.0 | 11,466 | 3a5c2e99c545ac10dbd71b9d8e46cdb729445695 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from torch import nn
from torch.nn import functional as F
from ..box_head.roi_box_feature_extractors import ResNet50Conv5ROIFeatureExtractor
from maskrcnn_benchmark.modeling import registry
from maskrcnn_benchmark.modeling.poolers import Pooler
fr... | maskrcnn_benchmark/modeling/roi_heads/mask_head/roi_mask_feature_extractors.py | MIT | 2,571 | b2be8aa77c4e9a7b604bb63cb602e14214558149 | Python | py | |
r"""Train routines.
This module contains various functions, which are aimed to structure the
training procedure of the Conditional Channel Gated Networks.
"""
import torch
import torch.nn.functional as F
from tqdm.auto import tqdm
from config import cfg
from src.data import prepare_dataset, get_loaders, set_task, get... | src/train_utils.py | MIT | 8,095 | 4579959aafcb21a83c28e5753848b1510ac421b0 | Python | py | |
import torch
import numpy as np
import argparse
from environment import Env
from Network import Tracknet
from torch.nn import functional as F
import os
import shutil
import Dataset
from utils import get_transform
from PIL import Image
from torch.utils.data import DataLoader
from torchvision.transforms import transforms... | pytorch/train.py | Apache-2.0 | 6,656 | 7cf5f16f0e9b05c2e6beb4ed4aa3b12de29505ec | Python | py | |
import os
import torch
import numpy as np
from torch.nn import functional as F
from im2mesh.common import compute_iou
from torch import distributions as dist
from im2mesh.training import BaseTrainer
import time
class Trainer(BaseTrainer):
''' Trainer class for OFlow Model.
Args:
model (nn.Module): OFl... | im2mesh/lpdc/training.py | MIT | 14,072 | 7c427d75429b7fdda41ece5a8a68ca5e5d5bd18f | Python | py | |
from __future__ import absolute_import, division, print_function
import torch
from torch.autograd import Variable
from pyro.distributions.distribution import Distribution
from pyro.distributions.util import copy_docs_from, get_probs_and_logits, torch_eye, torch_multinomial, torch_zeros_like
@copy_docs_from(Distribu... | pyro/distributions/one_hot_categorical.py | MIT | 6,197 | 24ccda2f674b7f8a4deaabb28e1e04cd57f16d34 | Python | py | |
import torch
from torch import Tensor
from torch import nn
from typing import Union, Tuple, List, Iterable, Dict
import os
import json
import logging
import numpy as np
from .tokenizer import WhitespaceTokenizer
logger = logging.getLogger(__name__)
class BoW(nn.Module):
"""Implements a Bag-of-Words... | sentence_transformers/models/BoW.py | Apache-2.0 | 3,288 | 3a5c6c7278734850da70d690def6346958182fc5 | Python | py | |
import torch
from torch import nn
from torch import optim
from torch.nn import functional as F
from torch.utils.data import TensorDataset, DataLoader
from torch import optim
import numpy as np
from learner import Learner
from copy import deepcopy
class Meta(nn.Module):
"""
Meta Learne... | meta.py | MIT | 10,621 | 3a5c76a0eeeb075530fbeaf55a325bbbdc40b9e0 | Python | py | |
import os
import time
from datetime import datetime
from enum import Enum
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from matplotlib import gridspec
from src.coders.conv imp... | src/learners.py | MIT | 33,970 | 3a5c78f493ea4f6148dc861c1ecec65e10d24b2f | Python | py | |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a cop... | layoutlmv3/layoutlmft/models/layoutlmv3/modeling_layoutlmv3.py | MIT | 68,737 | 3a5ca131aa29d025bec61c92c127f126069f0cf8 | Python | py | |
import gym
import torch
import numpy as np
import torchvision.transforms as T
from gym.spaces import Box
class SkipFrame(gym.Wrapper):
def __init__(self, env, skip):
"""Return only every `skip`-th frame"""
super().__init__(env)
self._skip = skip
def step(self, action):
"""Repe... | examples/wrappers.py | MIT | 2,019 | 7c8ab583dddf42bd313f05d47ce4e179cc647256 | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# Please DO NOT import gym in here. We might have installation without gym depending on
# this module for typing
from abc import ABC, abstractmethod
from dataclasses import asdict, dataclass, field, fields
from typing impor... | reagent/gym/types.py | BSD-3-Clause | 3,865 | 3a5ccee8e97868f7907778b75064d7a288d502ef | Python | py | |
from typing import Optional, Dict, Any
import torch
from torch import nn
from dpu_utils.ptutils import BaseComponent
class LuongAttention(BaseComponent):
"""
A Luong-style attention that also includes the inner product of targets-lookup
"""
def __init__(self, name: str, hyperparameters: ... | mlcomponents/seqdecoding/luongattention.py | MIT | 3,647 | 3a5cdb51b2bd405f0928300a9a7b23d4305107ad | Python | py | |
import json
import numpy as np
import os
import os.path as osp
from pytorch_lightning import LightningDataModule, LightningModule, Trainer
from pytorch_lightning.accelerators import Accelerator
from pytorch_lightning.callbacks.base import Callback
from pytorch_lightning.loggers.wandb import WandbLogger
from ray import ... | src/kosmoss/hyperopt/runtune.py | MIT | 4,654 | 3a5ceb01122b253a6c15c0ace6225adcbbe71501 | Python | py | |
import os
import visdom
import torchvision.transforms as trans
import _init_paths
import torch
import xml.etree.ElementTree as ET
import numpy as np
import scipy.sparse
import scipy.io as sio
import pickle
import subprocess
import uuid
from datasets.factory import get_imdb
import cv2
vis = visdom.Visdom(server='http:/... | visdom_trial.py | MIT | 2,005 | 3a5d2f0b0e5f31d3287b9a965415b28205699e62 | Python | py | |
from lib import utils
from lib import unet
from lib import datahandler
import os.path
import sys
import torch
from torch.autograd import Variable
from torch.utils.data import TensorDataset, DataLoader
from sklearn.model_selection import train_test_split
import numpy as np
import torchvision
import h5py
# GPU ID to use... | ssd_liverdet/utils/DEPRECATED/train_liverseg_unet.py | MIT | 7,967 | 3a5d3ec0d5cd72a2d360e7072b1357faeac6a6b6 | Python | py | |
from pathlib import Path
from typing import Any, List, Literal, Optional, Tuple, Union
import albumentations
import pytorch_lightning as pl
import torch.utils
from omegaconf import DictConfig
from ..custom_types import AnyPath, Batch, CroppingRectangle
from .maskrcnn_dataloader import MaskRCNNDataLoader
from .maskrcn... | paddle/data/maskrcnn_datamodule.py | MIT | 8,481 | 1e1355a3545c94435d0a9e616f161a4b0639bfea | Python | py | |
import os
import time
import csv
import numpy as np
import torch
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
cudnn.benchmark = True
import models
from metrics import AverageMeter, Result
import utils
args = utils.parse_command()
print(args)
os.environ["CUDA_VISIBLE_DEVICES"] = ar... | main.py | MIT | 4,790 | f95c78a0f13960fb6404f6dfc2fdccc487d33458 | 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.
from typing import Dict, Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from ncc.utils import utils
from torch i... | Birnn_Transformer/ncc/modules/learned_positional_embedding.py | MIT | 2,458 | 3a5d813fdef5ed38f1beb0779b5b27b044756153 | Python | py | |
import torch
class GPUReplayBuffer:
"""
This class implements a GPU-ready replay buffer
"""
def __init__(self, state_shape, action_shape, size=int(1e6)):
self.state_shape = state_shape
self.action_shape = action_shape
self.buffer_size = size
self.state_buffer = torch.zeros(0, *state_shape)
... | torchrl/storage/gpu_replay_buffer.py | Apache-2.0 | 2,672 | b27450a3d1ffc5985fe6fa904b5d24e9a485609b | Python | py | |
# -*- coding: utf-8 -*-
"""
@Time : 2022/3/1 3:37 下午
@Author : hcai
@Email : hua.cai@unidt.com
"""
import os
from tqdm import tqdm
import numpy as np
import torch
from torch.utils.data import Dataset
from torch.nn.utils import rnn
from collections import Counter
import matplotlib.pyplot as plt
from matplotlib.... | unlp/supervised/nlg/gutils/gpt_data.py | MIT | 4,910 | 28c21f4bf04ee5222f50cc496463ce4514b01092 | Python | py | |
import os
import random
import numpy as np
import torch
import pandas as pd
from scipy.sparse import coo_matrix
# initialize the weighs of the network for Convolutional layers and batchnorm layers
class AverageValueMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
... | auxiliary/utils.py | MIT | 11,466 | 5f38164bfbb22ea8e7c3083e50492255faa48d7c | Python | py | |
import torch
from torch import nn
from catalyst.utils import outer_init
class TemporalLastPooling(nn.Module):
"""@TODO: Docs. Contribution is welcome."""
def forward(
self, x: torch.Tensor, mask: torch.Tensor = None
) -> torch.Tensor:
"""Forward call."""
x_out = x[:, -1:, :]
... | catalyst/contrib/nn/modules/lama.py | Apache-2.0 | 6,202 | dfa7fc175cfaf6e70fd8503d04705e969d07ccf5 | 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 argparse
import math
from collections.abc import Iterable
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.mo... | examples/speech_recognition/models/vggtransformer.py | MIT | 37,045 | 3a5db5bb16558f75a0d785de1351aa48e90a2ee3 | Python | py | |
import math
import random
from collections import deque
import airsim
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from PIL import Image
from setuptools import glob
from env import DroneEnv
from torch.utils.tensorboard import SummaryWriter
i... | agent.py | MIT | 14,021 | b283ff05e9db8681f5a30bad06812bcaf2268e94 | Python | py | |
""" Trainer class basic with SGD optimizer """
import copy
import tqdm
import numpy as np
import torch
import torch.optim as optim
from torch.utils.data import DataLoader
from ..datasets import collate
from ..functions import (loss_functions, available_score_functions, compute_metrics_dataset)
from ..utils import (m... | dosed/trainers/base.py | MIT | 13,805 | 4233180aec81e4aeb45730738f436d99e9ffe2ae | Python | py | |
import numpy as np
import torch
class compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, pointcloud):
for t in self.transforms:
pointcloud = t(pointcloud)
return pointcloud
def __repr__(self):
format_string = self... | pointnet2/transforms_3d.py | Unlicense | 3,723 | 3a5df84f50447971dfd355b78fc010f72790508c | Python | py | |
import torch.nn as nn
from mmcv.utils import Registry, build_from_cfg
TRANSFORMER = Registry('Transformer')
LINEAR_LAYERS = Registry('linear layers')
def build_transformer(cfg, default_args=None):
"""Builder for Transformer."""
return build_from_cfg(cfg, TRANSFORMER, default_args)
LINEAR_LAYERS.register_mo... | downstream/tinypersons/mmdet/models/utils/builder.py | MIT | 1,487 | fdcff090f9253dfbcb0ad5c290a0028abad5f35c | Python | py | |
import logging
from typing import Dict, List
import numpy as np
import torch
from numpy import ndarray
from sentence_transformers import SentenceTransformer, models
from melior_transformers.config.global_args import global_args
from melior_transformers.encoding.constants import MODEL_CLASSES
logger = logging.getLogg... | melior_transformers/encoding/encoding_model.py | Apache-2.0 | 3,910 | 1e57a3b1f5bc69858ee77a65eb9d305c058566c9 | Python | py | |
#!/usr/bin/env python3
import sys
import os
import argparse
import json
import random
import shutil
import torch
from torch import cuda
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def log_bernoulli_loss(pred, y, min_eps=1e-5, max_eps=1.-1e-5, average=True):
prob = torch.clamp(pred.vie... | utils.py | MIT | 1,453 | 3a5e2eca27e48f7a4de8ff8ccccc0c8970eeb6bd | Python | py | |
"""
A trainer class.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from model.gcn import GCNClassifier
from utils import constant, torch_utils
from loss import SoftNLL
torch.set_printoptions(edgeitems=100)
class Trainer(object):
def... | model/trainer.py | Apache-2.0 | 4,861 | 3a5e34fd245e62fc760095a700b7a274aff6565b | 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 ... | vega/trainer/callbacks/model_tuner.py | MIT | 2,150 | 1ea0c0ead65e97a17d3525110b5f96217a831d45 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
import datetime
import logging
import time
import collections
import torch
import torch.distributed as dist
from fcos_core.utils.comm import get_world_size, is_pytorch_1_1_0_or_later
from fcos_core.utils.metric_logger import MetricLogger
... | fcos_core/engine/trainer.py | BSD-2-Clause | 7,719 | 3a5e55b1e24de1da2cbfbbf3d6da2bc5c8f7c3bf | Python | py | |
# encoding: utf-8
# type: ignore[]
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.p... | torch/fx/experimental/fx_acc/acc_ops.py | Intel | 36,755 | 7c9520660ef772fe164e5619ac1a201e1b0d143b | Python | py | |
# Copyright (c) 2017-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. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
import torch
import torch.o... | parlai/agents/drqa/model.py | BSD-3-Clause | 6,383 | 3a5e7ff53f5b08bb6baf1813a48a4ba0f28e40d4 | Python | py | |
'''
source:
https://github.com/yoonholee/pytorch-vae/blob/master/data_loader/stoch_mnist.py
Quantitative results on dynamically binarized MNIST
| Method | NLL (this repo) | NLL ([IWAE paper](https://arxiv.org/abs/1509.00519)) | NLL ([MIWAE paper](https://arxiv.org/abs/1802.04537)) | comments |
| ------------- ... | utils/stoch_mnist.py | MIT | 1,659 | 3a5e86dff6e892f3085d10d8fa8a2d0e863a82bb | Python | py | |
import pytest
import torch as th
import crypten
from syft.frameworks.crypten import utils
class ExampleNet(th.nn.Module):
def __init__(self):
super(ExampleNet, self).__init__()
self.fc = th.nn.Linear(28 * 28, 2)
def forward(self, x):
out = self.fc(x)
return out
@pytest.mark.... | test/crypten/test_utils.py | Apache-2.0 | 3,258 | 4b6897181e459c964735d057c37a4830c4132755 | Python | py | |
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
import torch
from torch_mlir_torchscript.e2e_test.framework import TestUtils
from torch_mlir_torchscript.e2e_test.reg... | frontends/pytorch/e2e_testing/torchscript/basic.py | Apache-2.0 | 4,829 | dfe7e08ad8dbe5d3a3ba70658b58da057154944d | 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.
import unittest
import torch
from torch import nn
from torchmultimodal.modules.encoders.embedding_encoder impo... | test/modules/encoders/test_embedding_encoder.py | BSD-3-Clause | 2,326 | 3a5ef033c6a1bb398fe7d6fb5a5f024089edbd9d | Python | py | |
"""
This module calls the module that implements adversarial lipschitz regularization.
"""
import logging
from art.defences.trainer.trainer import Trainer
from art.defences.trainer.adversarial_trainer import AdversarialTrainer
from art.attacks.evasion.projected_gradient_descent import ProjectedGradientDescent
logger... | armory/art_experimental/defences/adversarial_lipschitz_regularization.py | MIT | 3,202 | 3a5ef6762aab882f6051bd797cedfbf0e13c589d | Python | py | |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Developed by Shangchen Zhou <shangchenzhou@gmail.com>
import os
import sys
import torch.backends.cudnn
import torch.utils.data
import utils.data_loaders
import utils.data_transforms
import utils.network_utils as net_utils
import models
from models.IGNN import IGNN
# fro... | core/build.py | MIT | 5,567 | 7c4fca321051b18e77ac547e497739f502e1029d | Python | py | |
import numpy as np
import torch
import typing
import nptyping
import dataclasses
from torch.utils.data import Dataset, DataLoader
from torch import Tensor
from torch.utils.tensorboard import SummaryWriter
from sklearn.metrics.pairwise import euclidean_distances
import pickle
import os
from logging import getLogger, Str... | two_sample/interfaces/ard_kernel_torch.py | BSD-3-Clause | 21,534 | 70196e5258e82dddb584496e4ba5e798342b106c | Python | py | |
import copy
import pickle
import numpy as np
from skimage import io
from ...ops.roiaware_pool3d import roiaware_pool3d_utils
from ...utils import box_utils, calibration_kitti, common_utils, object3d_kitti
from ..dataset import DatasetTemplate
class ArgoverseDatasetLidarAugmentedKitti(DatasetTemplate):
def __ini... | pcdet/datasets/kitti/argoverse_dataset_lidar_augmented_kitti_format.py | Apache-2.0 | 19,373 | 5ea80eb4592d4b5b8810a48304f47b2792dfb2d0 | Python | py | |
import cv2
import math
import numpy as np
import os
import torch
from torchvision.utils import make_grid
def img2tensor(imgs, bgr2rgb=True, float32=True):
"""Numpy array to tensor.
Args:
imgs (list[ndarray] | ndarray): Input images.
bgr2rgb (bool): Whether to change bgr to rgb.
float3... | basicsr/utils/img_util.py | Apache-2.0,MIT | 6,195 | 3a5f1da0911d9b12f9c6164df6c6e14e3c1aef88 | Python | py | |
import os
import logging
import bunyan
import torch
import numpy as np
from sklearn.metrics import pairwise_distances
def setup_logger(log_path, log_level, rank=None, append=False):
if rank is None:
log_file = 'main.log'
logger_id = 'Main'
else:
log_file = 'rank_%s.log' % rank
... | src/common/util.py | MIT | 2,752 | 28bb5a1df3b41caabe9ade007a0410a608b33423 | Python | py | |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a cop... | examples/run_squad.py | Apache-2.0 | 28,724 | d72d67b87dcbc3575ce002ce4b01ddd4e69456f1 | Python | py | |
import pandas as pd
from tqdm import tqdm
import json
import torch
from nltk.corpus import stopwords
from transformers import GPT2LMHeadModel
from model.ConditionalLM import ConditionalLM
from util.utils import load_args, compute_logProb, init_tokenizer
from util.CLMDataset import CLMDataset
from torch.utils.data impor... | GOT4OOD/locating_module.py | Apache-2.0 | 6,932 | a93e8f6ab9839daff2a2e1f5e2f1994ab29a4768 | Python | py | |
#!/usr/bin/env python3
# encoding: utf-8
# Copyright 2017 Johns Hopkins University (Shinji Watanabe)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Training/decoding definition for the speech recognition task."""
import copy
import json
import logging
import math
import os
import sys
import matplotl... | espnet/asr/pytorch_backend/asr.py | Apache-2.0 | 52,582 | 52b117fad10fcfb49983685e02279bcbc73e0515 | Python | py | |
import os
import torch
from torch.nn.utils.rnn import pad_sequence
import numpy as np
import kaldi_io
# Select kaldi,
if 'KALDI_ROOT' in os.environ:
print(os.environ['KALDI_ROOT'])
if not 'KALDI_ROOT' in os.environ:
# Default! To change run python with 'export KALDI_ROOT=/some_dir python'
print("no KALDI_... | pytorch/dataset.py | Apache-2.0 | 5,270 | 3a5f5d371d24d2f6d5b5a446342849c99722eb0d | Python | py | |
# Copyright (c) 2021 ralabo.jp
# This software is released under the MIT License.
# see https://opensource.org/licenses/mit-license.php
# ====================================================
import os
import sys
import numpy as np
import json
import torch
from sklearn import metrics
from model.model_provi... | _01_test.py | MIT | 5,954 | 3a5f92c96bf374d243553b745066fa7a0327030c | Python | py | |
from collections import defaultdict
import torch
from torch import nn, optim
class AveragedModel:
def __init__(self, model, optimizer):
self.model = model
self.optimizer = optimizer
self.current_parameters = {}
def __enter__(self):
"""Assign average value to self.model param... | averaging_manager.py | MIT | 2,480 | 3a5f9855e5b780b850ebf4445a905fd5bc648d9e | Python | py | |
# ! /usr/bin/python
# 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
#
# Unle... | nemo/collections/asr/losses/ctc.py | Apache-2.0 | 4,340 | dfd70100386a665cacce1f06c8f4e31b7af0e670 | Python | py | |
""" Full assembly of the parts to form the complete network """
import torch.nn.functional as F
from .unet_parts import *
class UNet_2(nn.Module):
def __init__(self, n_channels, n_classes, bilinear=True):
super(UNet_2, self).__init__()
self.n_channels = n_channels
self.n_classes = n_clas... | model/unet_2/unet_model.py | MIT | 1,183 | 45a35b72df98b519fe83196a70b116d78524e185 | Python | py | |
import torch
from torch.autograd import Variable
# import models
import torch.nn.functional as F
from tqdm import tqdm
import statistics
import torchvision.utils as vutils
from train_funcs_brdf import get_labels_dict_brdf
def get_labels_dict_light(data_batch, opt, list_from_brdf=None, return_input_batch_as_list=True)... | train/train_funcs_light.py | MIT | 7,187 | dfc136d39b979603d57ce938ab52277f13b84ad2 | Python | py | |
import json
import numpy
import logging
import sys
import os
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from model.yolo import Darknet
from utils.utils import *
from utils.datasets import *
from data.dataset import Dataset, TestDataset
from utils import array_tool as at
from... | Test_DataSet.py | Apache-2.0 | 3,591 | 3453a5d4de5deeb063d0e3d40048e99c1739ff18 | Python | py | |
import argparse
import math
import os
import sys
import time
import gin
import numpy as np
import torch
import torch.utils.data
import torch.nn.functional as F
from torch import nn, optim
from torch.utils.data.dataloader import DataLoader
import utils_pytorch as pyu
from pytorch import feature_extracto... | pytorch/train_extractor.py | MIT | 9,497 | b22beb39a5035ed183ee588a014effe8f1c554da | Python | py | |
import pytest
import tests.base.utils as tutils
from pytorch_lightning import Callback
from pytorch_lightning import Trainer, LightningModule
from pytorch_lightning.callbacks import EarlyStopping, LearningRateLogger, ModelCheckpoint
from pytorch_lightning.loggers import TensorBoardLogger
from tests.base import EvalMod... | tests/callbacks/test_callbacks.py | Apache-2.0 | 13,273 | 52c03ada3bd62e84cbb21f24244e5b9304b3aa43 | Python | py | |
#!/usr/bin/env python3
"""Recipe for multi-task learning, using seq2seq and enhancement objectives.
To run this recipe, do the following:
> python train.py hparams/{config file} --data_folder /path/to/noisy-vctk
There's three provided files for three stages of training:
> python train.py hparams/pretrain_perceptual.y... | recipes/Voicebank/MTL/ASR_enhance/train.py | Apache-2.0 | 19,885 | 3a601d3b799cd7881535d021a41a00863efe88f7 | Python | py | |
import torch
from data import device
import numpy as np
class BiLSTM(torch.nn.Module):
def __init__(self, input_dim, hidden_dim, num_layers=1):
super().__init__()
self.lstm = torch.nn.LSTM(input_dim, hidden_dim, num_layers, batch_first=True, bidirectional=True)
def forward(self, x... | ChineseReverseDictionary/code/model.py | MIT | 7,864 | 3a60220ceba67b5924cead53693529d4f312ce27 | Python | py | |
import torch.nn as nn
from losses.svm import SmoothSVM
from losses.lml_loss import LMLLoss
from losses.ml import MLLoss
from losses.entr import EntrLoss
def get_loss(xp, args):
if args.loss == "svm":
print("Using SVM loss")
loss = SmoothSVM(n_classes=args.num_classes, k=args.topk, tau=args.tau, alp... | smooth-topk/src/losses/main.py | MIT | 977 | e9a79e532b3c7f2c38069ccce4d509da34244b54 | 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/optimizer.py | Apache-2.0 | 3,388 | 3a6046325fd8a0ebe3df0fd5fc31ca576546da50 | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os
import os.path as osp
import time
import mmcv
import torch
from mmcv import Config, DictAction
from mmcv.cnn import fuse_conv_bn
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import (get_dist_info, init_dis... | tools/test.py | Apache-2.0 | 7,930 | 3a605615f06f433a6aeb87b71bfc3f0ee4f2d60f | Python | py | |
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch
import torch.nn.functional as F
import numpy as np
import random
from simulator.nlu_model.nlu_config import Config
config = Config()
def cuda_(var):
return var.cuda() if config.use_gpu else var
def init_gru(gru):
gru.reset_par... | simulator/nlu_model/model.py | Apache-2.0 | 12,201 | 3a605b40bfb8e1e422f7e4a0ed7516bbfe22aa15 | Python | py | |
import torch
import rlkit.torch.pytorch_util as ptu
import numpy as np
from rlkit.data_management.normalizer import Normalizer, FixedNormalizer
class TorchNormalizer(Normalizer):
"""
Update with np array, but de/normalize pytorch Tensors.
"""
def normalize(self, v, clip_range=None):
if not se... | rlkit/torch/data_management/normalizer.py | MIT | 2,270 | 3479e59c5d0f1a161cf96eab6aef43e88ced1aee | Python | py | |
import datetime
import logging
import time
from collections import OrderedDict
from contextlib import contextmanager
import torch
from tkdet.utils.comm import get_world_size
from tkdet.utils.comm import is_main_process
from tkdet.utils.logger import log_every_n_seconds
__all__ = [
"DatasetEvaluator",
"Datase... | tkdet/evaluation/evaluator.py | MIT | 3,963 | 3a609fc80f978a7e0ac2911a1b44510dc17df795 | Python | py | |
import os
from pathlib import Path
import PIL.Image as Image
import pandas as pd
import torch
from modun.download_utils import download_zip_from_url
from modun.file_io import json2dict
from torch.utils.data import Dataset
from mmvae_hub import log
from mmvae_hub.utils.setup.flags_utils import get_config_path
from mmv... | mmvae_hub/celeba/CelebADataset.py | MIT | 3,450 | 3a60a94be84043c37e95b442f74eb9ea1b896c23 | Python | py | |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from collections import OrderedDict
import pytest
import torch
import funsor.torch.distributions as dist
import funsor.ops as ops
from funsor.cnf import Contraction
from funsor.domains import Bint, Reals
from funsor.gaussian import G... | test/examples/test_sensor_fusion.py | Apache-2.0 | 4,188 | 3a60aa6b0b3e3b9130148802f053187a820495cf | Python | py | |
# -*- coding: utf-8 -*-
# @Time : 2020/11/4 16:04
# @Email : 986798607@qq.com
# @Software: PyCharm
# @License: BSD 3-Clause
import numbers
from typing import Union, List, Tuple
import math
import torch
import torch.nn.functional as F
from torch import Tensor, Size
from torch import multiply
from torch import nn... | cams/nnn.py | BSD-3-Clause | 8,665 | 3a60af28377eec2e2bc4f3e0c4343a9c0c0c8f18 | Python | py | |
#!/usr/bin/env python3
# This file is covered by the LICENSE file in the root of this project.
import torch
class iouEval:
def __init__(self, n_classes, device, ignore=None):
self.n_classes = n_classes
self.device = device
# if ignore is larger than n_classes, consider no ignoreIndex
self.ignore =... | train/tasks/segmentation/modules/ioueval.py | MIT | 2,741 | 3a60c1ae302ae26e1e8e24cbb17eafa872878a11 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from .box_head.box_head import build_roi_box_head
from .mask_head.mask_head import build_roi_mask_head
from .keypoint_head.keypoint_head import build_roi_keypoint_head
class CombinedROIHeads(torch.nn.ModuleDict):
"""
Combine... | fcos_core/modeling/roi_heads/roi_heads.py | BSD-2-Clause | 4,280 | 3a60d4dfe92bb83c37f26bdf4123b2b09bd3c329 | Python | py | |
"""
@author: Zongyi Li
This file is the Fourier Neural Operator for 1D problem such as the (time-independent) Burgers equation discussed in Section 5.1 in the [paper](https://arxiv.org/pdf/2010.08895.pdf).
"""
import logging
import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as ... | experiments/27_test_oversampling/train_models.py | MIT | 15,944 | 10fbde004ee28800c0a821621169b602e2d984fb | Python | py | |
from os import path as osp
import numpy as np
from typing import List, Text
import torch
import pdb
from config_utils import dict2config
# from genotypes import Structure as CellStructure
from search_model_prdarts_nasnet import NASNetworkPRDARTS
def change_key(key, value):
def func(m):
if hasattr(m, key):
... | PRDARTS_search/models.py | MIT | 1,510 | 3a613a367ca84019451b64c3c359e06e12f62734 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.