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
from transformers import RobertaTokenizer
from colbert.modeling.tokenization.utils import _split_into_batches, _sort_by_length
class DocTokenizer():
def __init__(self, doc_maxlen):
self.tok = RobertaTokenizer.from_pretrained('microsoft/codebert-base')
self.doc_maxlen = doc_maxlen
... | colbert/modeling/tokenization/doc_tokenization.py | MIT | 2,261 | 29b387ec9313ace73a712bdb412d87671f8a764a | Python | py | |
from importlib import import_module
from torch.utils.data import DataLoader
class Data:
def __init__(self, args):
self.loader_train = None
if not args.test_only:
module_train = import_module('data.' + args.data_train.lower()) # import df2k模块
trainset = getattr(module_train... | data/__init__.py | MIT | 1,177 | 29b38ccac5f834a21bddc132af53390cdac7b464 | Python | py | |
#!/usr/bin/env python
# coding: utf-8
#
# Author: Kazuto Nakashima
# URL: http://kazuto1011.github.io
# Created: 2018-03-26
from __future__ import absolute_import, print_function
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from .resnet import _ConvB... | libs/models/deeplabv3.py | MIT | 2,961 | 29b393479b5e8ed5ad459083f8795b1d98ee4416 | Python | py | |
'''
This is the main script to run OpenAi's Acrobot-v1 environment
'''
# imports
import argparse
import gym
import torch
import numpy as np
import random
import time
from datetime import datetime
import pickle
import os
from itertools import count
from utils.Schedule import LinearSchedule, ExponentialSchedule
from uti... | acrobot_main.py | MIT | 15,730 | 5f7ec857ee87e161f8832e96a0710d061543539b | Python | py | |
import torch
import pytorch_lightning as pl
from pytorch_lightning import loggers as pl_loggers
from torch.utils.data import DataLoader
from networks.simclr import SimCLR
from networks.nnclr import NNCLR
import networks.resnet as resnet
from data.iNaturalist_dataset import iNaturalistDataset
import click
@click.comm... | train.py | MIT | 3,557 | 29b3a58a7bfe2aa83f00e31d066fe0382fddeff4 | Python | py | |
import torch
import torch.nn as nn
import numpy as np
class Actor(nn.Module):
def __init__(self, state_dim, action_dim, size=256):
super().__init__()
self.state_dim = state_dim
self.action_dim = action_dim
self.l1 = nn.Linear(state_dim, size)
self.l2 = nn.Linear(size, size)... | TD3/net.py | MIT | 1,180 | 1e54c6db35f166a3c7cb4c114c0d99c2decee135 | Python | py | |
# -*- coding:utf-8 -*-
# email:bingchengzhou@foxmail.com
# create: 2021/1/20
import torch
import torchvision.models as models
class VGG16(torch.nn.Module):
def __init__(self):
super(VGG16, self).__init__()
features = models.vgg16(pretrained=True).features
self.relu1_1 = torch.nn.Sequential... | networks/backbone/vgg.py | MIT | 3,368 | b2d5896ef743ce6e64133a489733d414b5bca1e0 | Python | py | |
# -*- encoding:utf-8 -*-
import torch.nn as nn
from uer.layers.layer_norm import LayerNorm
from uer.layers.position_ffn import PositionwiseFeedForward
from uer.layers.multi_headed_attn import MultiHeadedAttention
class TransformerLayer(nn.Module):
"""
Transformer layer mainly consists of two parts:
... | uer/layers/transformer.py | Apache-2.0 | 1,540 | 653ede24a58455f0d6e292ad35ad13fb430119ab | Python | py | |
""" PyTorch Conditionally Parameterized Convolution (CondConv)
Paper: CondConv: Conditionally Parameterized Convolutions for Efficient Inference
(https://arxiv.org/abs/1904.04971)
Hacked together by Ross Wightman
"""
import math
from functools import partial
import numpy as np
import torch
from torch import nn as nn... | models/layers/cond_conv2d.py | MIT | 5,107 | df98f71afa898cd77e2bfdd989c03292076dd75d | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from enum import Enum
import torch
import torch.nn.functional as F
from pytext.config import ConfigBase
from pytext.config.component import Component, ComponentType
from pytext.utils import loss as loss_utils, precision
from... | pytext/loss/loss.py | BSD-3-Clause | 23,372 | 29b3cd9a581407f0102c72233002d5d5119fb00f | Python | py | |
#Common imports
import os
import random
import copy
import numpy as np
import h5py
from PIL import Image
#Pytorch
import torch
import torch.utils.data as data_utils
from torchvision import datasets, transforms
from torchvision import datasets, transforms
#Base Class
from .data_loader import BaseDataLoader
class PACS... | data/pacs_loader_match_eval.py | MIT | 7,152 | 29b3fe672080327577130eab63f8e2f7d8f16c09 | Python | py | |
#!/usr/bin/env python
import time
import torch
import torch.nn as nn
from torchdiffeq import odeint_adjoint as odeint
from sdeint.euler import sdeint_euler
""" Compare the wall clock time, as requested by Reviewer 3. """
class ConcatConv2d(nn.Module):
""" Concat with time and then do the convolution. """
d... | cmp_wall_time.py | MIT | 4,946 | 29b401b22204d7158d483ed06ff719663091eaf0 | Python | py | |
# coding=utf-8
# Copyright (c) 2019, 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... | data_utils/tf_dl.py | Apache-2.0 | 5,443 | 29b4056de833b89076350d71e1f4b32edc22e882 | Python | py | |
import numpy as np
import torch
def ELBO(log_w):
return torch.mean(log_w, dim=-1)
def IWAE(log_w, trick=False):
if not trick:
return torch.logsumexp(log_w, dim=-1) - np.log(log_w.shape[-1]), {}
# notice that using the trick is required for computing the gradient wrt the IWAE measure, but doesn't... | models/_density_estimators.py | MIT | 1,201 | 8012b94ebe20dcba57aa7a65f9a507b061481324 | Python | py | |
# Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditi... | qa/common/gen_qa_models.py | BSD-3-Clause | 70,152 | 5eb10a5137290b1d5da49ae97a5ec41a10109214 | Python | py | |
# coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import logging
import math
from os.path import join as pjoin
import torch
import torch.nn as nn
import numpy as np
from torch.nn import CrossEntropyLoss, Dropout, Softmax, Linear, ... | networks/vision_transformer.py | Apache-2.0 | 3,893 | 29b43eab567895dc7fa2ae39f0766fb84da13d08 | Python | py | |
import torch
from torch.utils import data
from utils import config
# from network.model import Model
from network import dataset
from sklearn.metrics import recall_score
from focal_loss.focal_loss import FocalLoss
def evaluate(model, val_dataloader, criterion):
device = torch.device('cuda:0' if torch.cuda.is_ava... | evaluate.py | Apache-2.0 | 2,173 | 1e4e067730579d191031436a306ed32b82853df8 | Python | py | |
#! -*- coding: utf-8 -*-
"""
@author: Gump
@time: 2019/7/11
"""
import torch
import logging
from tqdm import tqdm
import argparse
import torch.nn as nn
import torch.optim as optim
from models import EncoderInductionRelation
from utils.data_loader import DataLoader
from utils.utils import label2tensor, get_accuracy
p... | train.py | Apache-2.0 | 3,061 | 4b01c0ea16c5e23b192647596b6247f1ed453b09 | Python | py | |
import time
import random
import argparse
from pathlib import Path
import numpy as np
import torch
import torchvision
from torchvision import transforms
from torch.backends import cudnn
from utils.dataloader_util import generate
from utils.train_util import load_model_pytorch, train, test
from nets.resnet_cifar import ... | retraining_model_cifar10_resnet20_multi0+5+9.py | MIT | 6,351 | e9d69523af60b0e220c08f021bc905e1bddf5850 | Python | py | |
"""
Copyright (c) 2019 Imperial College London.
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 torch
def fft2(data):
assert data.size(-1) == 2
data = torch.fft(data, 2, normal... | reconstruction/common/mytorch/fft.py | MIT | 2,840 | 29b49039b08c576d6923248c1a0e95d7c37a6755 | Python | py | |
"""
Utility method to instantiate weight layers
"""
import numpy as np
import torch
from src.env import device, dtype
def random_weight(shape):
"""
Create random Tensors for weights; setting requires_grad=True means that we
want to compute gradients for these Tensors during the backward pass.
We use... | src/defs/weights.py | MIT | 804 | 455bf662ef8a415f099bdd3077b143985dd6618f | Python | py | |
import torch
from torchvision import transforms
from PIL import Image
from modalities.Modality import Modality
from utils import utils
from utils.save_samples import write_samples_img_to_file
class CMNIST(Modality):
def __init__(self, name, enc, dec, class_dim, style_dim, lhood_name):
super().__init__... | modalities/CMNIST.py | MIT | 836 | 45b35381fa6de08fc91a0a60e150b6d222796ecd | Python | py | |
import math
from functools import partial
from collections import defaultdict
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from . import torchvision_models
from .torchvision_models import load_pretrained, inflate_pretrained, modify_resnets
__all__ = [
'Re... | pretorched/models/resnet3D.py | MIT | 11,325 | 29b51cfc4c8131ea06bb221dd9f0c0ef22c04ab4 | Python | py | |
from collections.abc import Sequence, Mapping
from typing import List, Dict, Union, Any
import torch
import treetensor.torch as ttorch
import re
from torch._six import string_classes
import collections.abc as container_abcs
from ding.compatibility import torch_ge_131
int_classes = int
np_str_obj_array_pattern = re.co... | ding/utils/data/collate_fn.py | Apache-2.0 | 10,855 | e9782496c1948f691fd03c522e84b2b729fc6c42 | Python | py | |
# Copyright 2021 TUNiB Inc.
import os
import random
import numpy
import torch
import torch.distributed as dist
from datasets import load_dataset
from torch.optim import Adam
from torch.utils.data import DataLoader
from transformers import GPT2Tokenizer
from oslo.models.gpt_neo.modeling_gpt_neo import (
GPTNeoFor... | tests/gpt_neo/gpt_neo_test_pp_training_with_fusion.py | Apache-2.0 | 7,791 | 29b533420263b4ba1330f1ad25133cf9c05097ea | Python | py | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" rbc_ae_ode.py
Train the Auto-encoder and ODENet together for
the Rayleigh-Bernard-Convection problem
@author: Haijun Yu <hyu@lsec.cc.ac.cn>
"""
# %%
import config as cfgs
import ode_net as ode
import autoencoders as ae
import rbctools as rbc... | RBC1r/rbc_ae_ode.py | Apache-2.0 | 22,729 | 10827718bd0cee8b28f2af9c54a6e767ff3f4795 | Python | py | |
"""Sigmoid Activation Function"""
from torch.nn import Sigmoid as _Sigmoid
from neuralpy.utils import CustomLayer
class Sigmoid(CustomLayer):
"""
Applies a element-wise Sigmoid or Logistic function to the input tensor.
Supported Arguments
name=None: (String) Name of the activation function layer,
... | neuralpy/layers/activation_functions/sigmoid.py | MIT | 1,575 | 29b53d71adc248f3112611432a79525638b553ec | Python | py | |
from torch import nn
from .scaled_softmax import ScaledSoftmax
from .perplexity_entropy import calc_relation_structure
import torch
import torch.nn.functional as F
from . import register_rblock
@register_rblock('RBlockPEEfficient')
class RBlockPEEfficient(nn.Module):
def __init__(self,
in_channel... | relation/rblock_pe_efficient.py | MIT | 6,545 | d76c05b0973d60587fca9dde08cc78e4f2b0feb3 | Python | py | |
# Copyright 2020 Toyota Research Institute. All rights reserved.
import torch
import torch.nn as nn
from packnet_sfm.networks.layers.packnet.layers01 import \
PackLayerConv3d, UnpackLayerConv3d, Conv2D, ResidualBlock, InvDepth
class PackNetSlim01(nn.Module):
"""
PackNet network with 3d convolutions (vers... | packnet_sfm/networks/depth/PackNetSlim01.py | MIT | 6,650 | 29b57616abb667dc71489acb6994386d29d8e515 | Python | py | |
import math
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
__all__ = ["ResNeXt", "resnet50", "resnet101"]
def conv3x3x3(in_planes, out_planes, stride=1):
# 3x3x3 convolution with padding
return nn.Conv3d(
in_planes, out_planes... | evaluation/models/resnext.py | MIT | 5,202 | 29b585e573c77e796120420acbcf672b9e0f8353 | Python | py | |
import numpy as np
import torch
class MinNormSolver:
MAX_ITER = 250
STOP_CRIT = 1e-5
def _min_norm_element_from2(v1v1, v1v2, v2v2):
"""
Analytical solution for min_{c} |cx_1 + (1-c)x_2|_2^2
d is the distance (objective) optimzed
v1v1 = <x1,x1>
v1v2 = <x1,x2>
... | multi_task/min_norm_solvers.py | MIT | 7,675 | ff17f99bcccf298f959c11d877841f87a64a859d | Python | py | |
import abc
from typing import Iterable
import numpy as np
import random
import re
import os
import json
import hashlib
from sqlitedict import SqliteDict
from tqdm import tqdm
import torch
import torch.nn.functional as F
from lm_eval.metrics import mean, weighted_perplexity, weighted_mean, bits_per_byte
from lm_eval im... | lm_eval/base.py | MIT | 36,654 | 29b59241b9662a308bf98d1e4dc355f9d9ddcaff | Python | py | |
import torch.nn.functional as F
import torch.nn as nn
from mmcv.cnn import kaiming_init
from mmcv.cnn import ConvModule, xavier_init
from mmcv.runner import auto_fp16
from mmdet.models.builder import NECKS
import torch
from mmdet.models.necks.TransNeck import TransEncoder, CBAM
from mmdet.models.backbones.swin_transfor... | mmdet/models/necks/new/TransFPN_top_scale_spatial.py | Apache-2.0 | 16,865 | 29b5aa6dbcbbc20b096151a13f536cd1690e8752 | Python | py | |
"""
Script for domain transfer experiments
"""
from torch.optim import Adam
from torch.utils.data import DataLoader
import argparse
from few_shot.models import FewShotClassifier
from few_shot.datasets import OmniglotDataset, MiniImageNet, FashionDataset
from few_shot.models import get_few_shot_encoder
#from experime... | experiments/infer.py | MIT | 8,982 | 03f105ad3a4798b5f59f6f41f847012471d8bd23 | Python | py | |
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import dgl
import torch.nn.functional as F
class PositionwiseFeedForward(nn.Module):
''' A two-feed-forward-layer module '''
def __init__(self, d_in, d_hid, dropout=0.1):
super(PositionwiseFeedForward, self).__init__()
self.w_1 = nn.C... | pykp/modules/gat.py | MIT | 9,936 | e61e6f1e96ccdfcaeb521fd6146c189f828ae3d7 | Python | py | |
# Copyright (c) 2017-present, Facebook, Inc.
#
# 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... | lib/core/rpn_generator.py | MIT | 9,352 | 29b5e294f3d4b2fb3a3fb9ae19893ff383f92be5 | Python | py | |
# -*- coding:utf-8 -*-
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torchvision.transforms as transforms
from data.cifar import CIFAR10, CIFAR100
from data.mnist import MNIST
from model import CNN
import argparse, sys
import numpy as np
import ... | other_methods/coteaching/main.py | MIT | 12,495 | 29b5ea8eb7455b699fa3933184a95466186e4d1b | Python | py | |
import itertools
import sys
import numpy as np
import pytest
import torch
from torch_sparse import SparseTensor
from torch_geometric.data import Data, HeteroData
from torch_geometric.loader import NeighborLoader
from torch_geometric.loader.neighbor_loader import get_input_nodes
from torch_geometric.nn import GraphCon... | test/loader/test_neighbor_loader.py | MIT | 17,147 | fda1687724933683f07155373821114da7d373b5 | Python | py | |
import os
import torchvision.transforms as transforms
from torch.utils.data import Dataset
from PIL import Image
class PokemonDataset(Dataset):
def __init__(self, image_size: int = 256, phase: str = 'train'):
if phase not in ['train', 'val']:
raise ValueError(f'Phase "{phase}" not supported. ... | dataset.py | MIT | 1,758 | f9d77c154a788c908297236f0289a469c3047eec | Python | py | |
#!/usr/bin/env python
# Standard
import os
import sys
import random
import datetime
# Libraries
import numpy as np
import pandas as pd
import seaborn as sns
from collections import Counter
# PyTorch
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torch.autograd import V... | diatom/adversarial_vae_model.py | MIT | 30,203 | fd8dd0e912e56b045c96460f7d726d86abcc11ab | Python | py | |
import isaacgym
import torch
import torch.nn as nn
import torch.nn.functional as F
# Import the skrl components to build the RL system
from skrl.models.torch import GaussianModel, DeterministicModel
from skrl.memories.torch import RandomMemory
from skrl.agents.torch.ppo import PPO, PPO_DEFAULT_CONFIG
from skrl.traine... | docs/source/examples/isaacgym3/ppo_ant.py | MIT | 4,823 | d79f8e7e46cdc59636ead33369d3f9f9a7922f84 | Python | py | |
"""
Classes for all models and loss functions for clustering.
FC --> ReLU --> BN --> Dropout --> FC
"""
import warnings
import numpy as np
# Torch
import torch
import torch.nn as nn
import torch.nn.functional as F
# Local imports
#import utils
#import config
#import lorentz
def sqeuclidean_pdist(x, y=None):
"... | GCN/net/optim_modules.py | MIT | 18,315 | 29b67e41e348a6e358c7960c8664a595ae80e960 | Python | py | |
"""Base class for vision datasets."""
from __future__ import annotations
from pathlib import Path
from typing import Optional, Union
import albumentations as A
from albumentations.pytorch import ToTensorV2
from kit import implements
from kit.torch import TrainingMode
import pytorch_lightning as pl
from typing_extensio... | conduit/data/datamodules/vision/base.py | MIT | 4,410 | 1e24db44df2767928eb184e433a4f23f6a72f6ab | Python | py | |
# coding=utf-8
# Copyright 2018 The OpenAI Team Authors and 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 copy of the License... | src/transformers/models/gpt2/modeling_gpt2.py | Apache-2.0 | 59,550 | 29b69166b5bafe5abcf926a27fe9544b1b37dc0a | Python | py | |
import torch
from fairseq.data import BaseWrapperDataset
from fairseq.data import (data_utils,
TokenBlockDataset, PrependTokenDataset, PadDataset, TruncateDataset,
NumelDataset, NumSamplesDataset, NestedDictionaryDataset,
MaskTokensDataset, AppendTokenDataset, )
from infoxlm.data.mlm_utils import get_mlm_datas... | infoxlm/src-infoxlm/infoxlm/data/offset_dataset.py | MIT | 2,934 | 29b694c0e7a7446908e55e09749fb0d5c3c64845 | Python | py | |
import glob
import math
import os
import random
import shutil
import subprocess
import time
from contextlib import contextmanager
from copy import copy
from pathlib import Path
from sys import platform
import cv2
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
im... | image_retrieval_resnet/utils/general.py | MIT | 56,730 | 1ec16da8253e71748b63b113e294722783860113 | Python | py | |
import numpy as np
import ray
import torch
from gym_ds3.schedulers.models.scarl_model import attention_net
from gym_ds3.envs.utils.helper_envs import get_env, num_pes
from gym_ds3.envs.utils.helper_training import calculate_returns
@ray.remote
class SCARLWorker(object):
def __init__(self, args, _id):
se... | gym_ds3/schedulers/scarl/data_worker_scarl.py | MIT | 3,964 | b279f3c0d9a4dd5750dfba942e9568d516a63292 | Python | py | |
import os
import torch as t
import datetime
import cv2
from utils.config import opt
from model import FasterRCNNVGG16
from trainer import FasterRCNNTrainer
from data.util import read_image
from utils.vis_tool import vis_bbox
from utils import array_tool as at
from utils.image_enhance import Image_Enhance
import matplo... | demo.py | MIT | 3,074 | 12ee8fdc8048a6387e5b1dd4be6837f6c3d5d14a | Python | py | |
from general_resnet50 import ResNet50
from image_folder import ImageFolder
from torch.utils.data import DataLoader
import os
import scipy.io as sio
from sklearn.metrics import accuracy_score
import torch
import numpy as np
from torch.backends import cudnn
import random
import argparse
from utils import get_device
impor... | images_embeddings.py | MIT | 10,818 | 802beea44278e80b0dbe0bdf253c862222033a23 | Python | py | |
import unittest
import torch
import lightly
class TestFromImports(unittest.TestCase):
def test_from_imports(self):
# active learning (commented out don't work)
from lightly.active_learning.config.sampler_config import SamplerConfig
from lightly.active_learning.agents.agent import ActiveL... | tests/imports/test_from_imports.py | MIT | 3,607 | 29b6d8cd358f48949bea94e0b2b870b596988aca | Python | py | |
from pytorch_lightning.callbacks import ModelCheckpoint
class MyCheckpoint(ModelCheckpoint):
def __init__(self, **kwargs):
super(MyCheckpoint, self).__init__(**kwargs)
def on_pretrain_routine_start(self, trainer, pl_module):
super(MyCheckpoint, self).on_pretrain_routine_start(trainer, pl_mod... | utils.py | MIT | 665 | 29b6dc4f2054f6254809dabfb4a318afe60f440a | Python | py | |
'''
model configurations for:
- dropout
- device settings
- parameters to update
- checking label counts within a batch
- normalization values for transformations
'''
import numpy as np
import torch
from torch import nn
import cocpit.config as config
def set_dropout(model, drop_rate=0.1):
""... | cocpit/model_config.py | MIT | 3,110 | d7b24958736c9bc84d12ffea3306345527642089 | Python | py | |
"""
File based off of dgl tutorial on RGCN
Source: https://github.com/dmlc/dgl/tree/master/examples/pytorch/rgcn
"""
import abc
import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl
class RGCN(nn.Module):
def __init__(self, parameter, is_module=True):
super(RGCN, self).__init__()
... | models/rgcn_model.py | MIT | 9,447 | 29b6eeeddef07c2160b5e8cad402fe630b1666a1 | Python | py | |
import os
import re
import glob
import json
import torch
import random
import warnings
import itertools
import torchaudio
import numpy as np
from pathlib import Path
from tqdm import tqdm
from PIL import Image as PILImage
from itertools import cycle, islice, chain
from einops import rearrange, repeat
from collections i... | cvap/data/audiocaps.py | MIT | 9,115 | 29b6fb42cad18e897133cb6aa63e5402d9c39f14 | Python | py | |
r"""Summary objects at the end of training procedures."""
import numpy as np
import pickle
import torch
class TrainingSummary:
def __init__(self,
model_best,
model_final,
epochs,
epoch_best,
losses_train,
losses_test=None,
identifier=None):
self.i... | hypothesis/summary/train.py | BSD-3-Clause | 2,863 | d728d80a2fbda7f4976910b3a04d59f781a387d1 | Python | py | |
from __future__ import print_function, absolute_import, division
import glob
import pickle
import torch
from models_baseline.gcn.graph_utils import adj_mx_from_skeleton
from models_baseline.gcn.sem_gcn import SemGCN
from models_baseline.mlp.linear_model import LinearModel, init_weights
from models_baseline.models_st... | function_baseline/model_pos_preparation.py | MIT | 3,748 | d789a63a8d6191b889c6aee7f91aff3aed5bb161 | Python | py | |
from azureml.core.run import Run
import argparse
import os
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from math import ceil
from random import Random
from torch.multiprocessing import Process
from torch.autograd import Variable
from ... | examples/training/train-using-nfs/pytorch-on-amlarc-with-nfs/scripts/train.py | MIT | 3,763 | b21e7d87e106f3d230cd85bff3f8eb8c75e356d9 | Python | py | |
import moviepy.editor as mp
import numpy as np
import sys
import cv2
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from keras.models import Model, load_model
from keras.layers import *
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection i... | Code/early_fusion.py | MIT | 5,372 | 12bb02fbf6161262ba8aa7c9c33f65b788f16fc9 | Python | py | |
import torch
from torch import nn
import torch.nn.functional as F
class position_pair(nn.Module):
def __init__(self,channel=64, spatial=112):
super(position_pair, self).__init__()
self.conv_1 = nn.Conv2d(channel, 1, kernel_size=1, bias=False)
self.bn_1 = nn.BatchNorm2d(1)
... | Projection.py | Apache-2.0 | 1,158 | e938bd7beddc5aa3fc74a6d60d3c908354f0d787 | Python | py | |
import torch
import encoding
# Get the model
model = encoding.models.get_model('fcn_resnet50_ade', pretrained=True).cuda()
model.eval()
# Prepare the image
url = 'https://github.com/zhanghang1989/image-data/blob/master/' + \
'encoding/segmentation/ade20k/ADE_val_00001142.jpg?raw=true'
filename = 'example.jpg'
i... | finalists/yc14600/PyTorch-Encoding/experiments/segmentation/demo.py | CC-BY-4.0 | 637 | fde8848cab9dcc0266a2c3e5524b473e6becace4 | Python | py | |
# Copyright 2019 Kakao Brain
#
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
from torch.distributed.pipeline.sync.pipeline import _clock_cycles
def test_clock_cycles(... | test/distributed/pipeline/sync/test_pipeline.py | Intel | 850 | 42a3ce8b679888444b84ed83eadb99b3ffa889e2 | Python | py | |
from enum import IntEnum
from collections import namedtuple
from PIL import Image, ImageDraw, ImageFont
import numpy as np
import random
import torch
#from tw_cooking_game_puzzle.role_master_builder import write_clue
class NSEW(IntEnum):
NORTH = 0
SOUTH = 1
EAST = 2
WEST = 3
font = ImageFont.load_d... | pddlgym_textworld/rendering.py | MIT | 35,662 | 1097bbf3ec9cd3f35241013ba2b9714b7fbfca06 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
#!/usr/bin/env python3
import os
import math
import argparse
import torch
from adagrad_with_grad_clip import AdagradWit... | language-modeling/adaptive/adaptive-span/utils.py | MIT | 8,430 | 29b7775660b42d054c0fe23dbb3fb56f617b5dc7 | Python | py | |
from typing import Tuple
import pytorch_lightning as pl
import torch
import torch.nn as nn
from omegaconf import DictConfig
from pytorch_lightning.core import LightningModule
from pytorch_lightning.metrics.functional import accuracy
from torch import optim
from torch.optim.lr_scheduler import ExponentialLR, ReduceLROn... | src/runner/runner.py | MIT | 5,001 | a94ac849a5093a73b45c0bfc206a504deb4d9fbf | Python | py | |
import torch, tqdm
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
import copy
from . import utils as ut
from haven import haven_utils as hu
from skimage.transform import warp, AffineTransform
import numpy as np
import random
from matplotlib import pyplot as plt
from skimage impor... | src/losses.py | Apache-2.0 | 19,815 | a908f9d7bccb0f296969df2aa58e3c0af350c0c7 | Python | py | |
import os
import torch
import random
import cv2
import scipy.io as scio
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
import torch.utils.data as data
from torchvision import transforms
import datasets.transforms as mytransforms
def get_dataset(is_training):
img_path_list = []
... | datasets/data_live1.py | Apache-2.0 | 3,843 | 29b7efef4275a90540ebe3793be25f8c8da053fb | Python | py | |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the 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.
from dataclasses import dataclass,... | examples/wav2vec/unsupervised/tasks/unpaired_audio_text.py | MIT | 15,458 | 1e2dc55c2358910e1b598a03672fcaa514b4e9ee | Python | py | |
import torch.nn as nn
import torch
from .Baseline import InpaintTemplate
class InpaintingBase(InpaintTemplate):
def __init__(self):
super(InpaintingBase, self).__init__()
pth_mean = torch.FloatTensor([0.485, 0.456, 0.406]).unsqueeze(0).unsqueeze(-1).unsqueeze(-1)
pth_std = torch.FloatTen... | arch/inpainting/InpaintingBase.py | Apache-2.0 | 2,687 | 0387026f4de36725126df66b15ff43d932de449e | Python | py | |
# Copyright 2021 RangiLyu.
#
# 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, so... | mmdet3d/models/necks/tan.py | Apache-2.0 | 3,482 | 29b85ce4c021395212a884caaaaf0c2ac1b10eb3 | Python | py | |
#!/usr/bin/python3
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import datetime
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from numpy.random import RandomState
import os
impo... | codes/model.py | MIT | 66,347 | 29b8913f168790a6b370cfeba40979a59f0eab08 | Python | py | |
import numpy as np
import pytest
import torch
from deep_table.nn.encoders import backbone as B
@pytest.mark.parametrize(
"name", ["FTTransformerBackbone", "MLPBackbone", "SAINTBackbone"]
)
def test_embedding(name):
num_features = 2
dim_embed = 16
backbone = getattr(B, name).make(
num_features... | tests/nn/encoders/test_backbone.py | MIT | 506 | d775eb90d476bb07c70bcf9d2c38b7a7b3796b5b | 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... | tests/plugins/environments/test_kubeflow_environment.py | Apache-2.0 | 3,085 | 29b8bba587922e1569397643f6a4ff92c4a614b0 | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import importlib
from typing import Dict, Optional, Sequence
import ncnn
import numpy as np
import torch
from mmdeploy.utils import Backend, get_root_logger
from mmdeploy.utils.timer import TimeCounter
from ..base import BACKEND_WRAPPER, BaseWrapper
@BACKEND_WRAPPER.r... | mmdeploy/backend/ncnn/wrapper.py | Apache-2.0 | 5,038 | 29b8c5113b01fc1e81baf913fea6d41cc81171a8 | Python | py | |
import random
from tqdm import tqdm
import os
from chinese_calendar import is_holiday
import numpy as np
import torch
from common.spatial_func import distance
from common.trajectory import get_tid, Trajectory
from utils.parse_traj import ParseMMTraj
from utils.save_traj import SaveTraj2MM
from utils.utils import crea... | models/datasets.py | MIT | 17,013 | 29b8c7b3bf0c96793620d55a8673414acdd54a61 | Python | py | |
import os # isort: skip
import time
from shutil import copyfile
import torch
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
import segmentation_models_pytorch as smp
from utils import configuration
from utils.dataset import SegmDataset
from utils.build_model import build... | train.py | MIT | 5,806 | 29b8cbd5b2669ac71a05596eb73324ce6649cd7a | Python | py | |
"""
DEep Evidential Doctor - DEED
MNIST experiment
@author: awaash
"""
import torch
import numpy as np
def get_device():
use_cuda = torch.cuda.is_available()
device = torch.device("cuda:0" if use_cuda else "cpu")
return device
def one_hot_embedding(labels, num_classes=30):
y = torch.eye(num_classes)
... | utils.py | MIT | 486 | 24b7584fa1428bd85af2abc4491b691034e38091 | Python | py | |
from __future__ import print_function
import torch
import numpy as np
import torch.utils.data
from torch import nn
from torch.nn import functional as F
from rlkit.pythonplusplus import identity
from torch.autograd import Variable
from rlkit.torch import pytorch_util as ptu
from rlkit.torch.vae.vae_base import compute_b... | rlkit/torch/vae/vq_vae.py | MIT | 25,800 | 29b8dd7bc398859217d268b851e4994b7e031e64 | Python | py | |
from bgflow.utils import as_numpy
import numpy as np
import torch
def test_as_numpy():
assert np.allclose(as_numpy(2.0), np.array(2.0))
assert np.allclose(as_numpy(np.ones(2)), np.ones(2))
assert as_numpy(1) == np.array(1)
def test_tensor_as_numpy(ctx):
out = as_numpy(torch.zeros(2, **ctx))
as... | tests/utils/test_types.py | MIT | 394 | cc21d014841b7be547a840ee82e55cc353536aa9 | Python | py | |
from torch.autograd import grad
from math import sqrt, inf
import torch
from .gradient import GradientPerturb
class IterativeBasePerturbation(GradientPerturb):
"""Base class for iterative (projected) gradient perturbations.
"""
def _initialize(self):
if self._step_size is None:
self._st... | dlt/perturbations/iterative_projected_gradient.py | MIT | 3,361 | 29b8fa011163bcfb79a8834d3d86ce0a5eb08171 | Python | py | |
# Original Code here:
# https://github.com/pytorch/examples/blob/master/mnist/main.py
from __future__ import print_function
import argparse
import os
import torch
import torch.optim as optim
import ray
from ray import tune
from ray.tune.schedulers import ASHAScheduler
from ray.tune.examples.mnist_pytorch import (trai... | python/ray/tune/examples/mnist_pytorch_trainable.py | Apache-2.0 | 2,884 | 345a69877f1d9948d4e75aad0ffcc283aef74517 | Python | py | |
from __future__ import absolute_import, division, print_function
import torch
from torch.distributions import constraints
from torch.nn import Parameter
import pyro
import pyro.distributions as dist
from .likelihood import Likelihood
class Gaussian(Likelihood):
"""
Implementation of Gaussian likelihood, wh... | pyro/contrib/gp/likelihoods/gaussian.py | MIT | 1,712 | 29b926050da088f657e7a5fdbd0c37cdcf80aaf9 | Python | py | |
# helper functions for saving sample data and models
# import data loading libraries
import os
import pdb
import pickle
import argparse
import warnings
warnings.filterwarnings("ignore")
# import torch
import torch
# numpy & scipy imports
import numpy as np
import scipy
import scipy.misc
import imageio
def checkp... | cycle-gan/helpers.py | MIT | 2,808 | 5e36494f3309b366608f9e2a783cfe83ce4e7546 | Python | py | |
"""
This file holds code for a Training guide for PytorchSGD in the documentation.
It ignores yapf because yapf doesn't allow comments right after code blocks,
but we put comments right after code blocks to prevent large white spaces
in the documentation.
"""
# yapf: disable
# __torch_train_example__
import argparse
... | python/ray/util/sgd/torch/examples/train_example.py | Apache-2.0 | 3,167 | 29b9330c1561f52be9ad0458e253dcd29ba6287d | Python | py | |
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
import matplotlib.ticker as ticker
import numpy as np
import torchvision.utils
plt.switch_backend('agg')
import scipy.io as io
def save_samples(save_dir, images, epoch, plot, name, nrow=4, heatmap=True, cmap='jet'):
"""Save samples in g... | 2D/utils/plot_samples.py | MIT | 2,155 | 4b1e3d9f71482207dc962337a5eea42a605d1ce3 | Python | py | |
import argparse
import torch
def get_args():
# Training settings
parser = argparse.ArgumentParser(description='PyTorch DenseNet Training')
parser.add_argument('--epochs', default=300, type=int,
help='number of total epochs to run')
parser.add_argument('-b', '--batch-size', defau... | arguments.py | MIT | 2,469 | 29b9392c8c33063949b05b133561262c67600d4d | Python | py | |
#!/usr/bin/env python
# coding: utf-8
from __future__ import absolute_import, division, print_function
import json
import logging
import math
import os
import random
import warnings
from multiprocessing import cpu_count
from typing import Dict, List
from dataclasses import asdict
import numpy as np
from sklearn.met... | simpletransformers/language_modeling/language_modeling_model.py | Apache-2.0 | 50,891 | 5e6bf6812a66edce18e4eb0194416985de974368 | Python | py | |
import argparse
from collections import OrderedDict
import torch
def convert_conv1(model_key, model_weight, state_dict, converted_names):
if model_key.find('conv1.0') >= 0:
new_key = model_key.replace('conv1.0', 'backbone.conv1.conv')
else:
new_key = model_key.replace('conv1.1', 'backbone.con... | tools/convert_models/shufflenetv2_to_mmcls.py | Apache-2.0 | 4,089 | 29b9503f12e9321e27099f40b08f77ca29bae849 | Python | py | |
import numpy as np
import torch
def loadGloveModel(File):
print("Loading Glove Model")
f = open(File,'r')
gloveModel = {}
for line in f:
splitLines = line.split()
word = splitLines[0]
wordEmbedding = np.array([float(value) for value in splitLines[1:]])
gloveModel[word] =... | visdialch/utils/util.py | BSD-3-Clause | 892 | 29b952129b1e52870b843d66913455c7df30610a | Python | py | |
import sys
import pprint as pp
import os.path as osp
from torchvision.datasets import STL10, CIFAR10
from dassl.utils import mkdir_if_missing
cifar_label2name = {
0: "airplane",
1: "car", # the original name was 'automobile'
2: "bird",
3: "cat",
4: "deer",
5: "dog",
6: "frog", # conflict... | datasets/da/cifar_stl.py | MIT | 2,383 | 52c16aad44e0bd10adc3dbd08c7641905bf21bcb | Python | py | |
from collections import deque
import torch
import torch.nn as nn
from .nnutils import GRU, create_var
MAX_NB = 8
class JTNNEncoder(nn.Module):
def __init__(self, vocab, hidden_size, embedding=None):
super(JTNNEncoder, self).__init__()
self.hidden_size = hidden_size
self.vocab_size = voc... | jtnn/jtnn_enc.py | MIT | 3,651 | d710d10d729c66eb16e2716ac8c4781ebd104a13 | Python | py | |
from typing import Dict, Generator
import torch
from torch.utils.data import DataLoader
def cycle(
dataloader: DataLoader, device: torch.device
) -> Generator[Dict[str, torch.Tensor], None, None]:
r"""
A generator which yields a random batch from dataloader perpetually. This generator is
used in the ... | updown/utils/common.py | MIT | 790 | f9e3e21b7e39ad85bfdf8e3923b314013d433690 | Python | py | |
"""
@Author: Zhengkun Tian
@Email: zhengkun.tian@outlook.com
@Date: 2020-04-23 15:14:28
@LastEditTime: 2020-04-23 15:16:49
@FilePath: \OpenTransformer\otrans\data.py
"""
import os
import torch
import random
import kaldiio as kio
import numpy as np
import torchaudio as ta
from torch.utils.data import Dataset, DataLoader... | otrans/data.py | MIT | 10,002 | 7c2c34ebc945e9823f16994a9930e5979561b1b2 | Python | py | |
"""
File name: plot-pytorch-autograd-graph.py
Author: Ludovic Trottier
Date created: November 8, 2017.
Date last modified: November 8, 2017
Credits: moskomule (https://discuss.pytorch.org/t/print-autograd-graph/692/15)
"""
# DISCLAIMER
# This code was not written by members of the AML project group... | util/plot_autograd.py | MIT | 2,825 | 29b99487a1f80ba3b0981c75385ae3488b324346 | Python | py | |
"""
Evaluate the robust models.
"""
import torch
import torchvision
import torchvision.transforms as transforms
from evaluation_functions import evaluate_all
from strings import Strings
def main():
"""
Evaluate the robust models in both the non-adversarial and
adversarial settings.
"""
string... | run_analysis.py | MIT | 3,321 | 29b9cb235c248c022d982a69f212e73faaccd6eb | Python | py | |
"""
Module containing the ``pytorch_lightning.LightningModule`` implementation of
the of the Dense Flow Prediction Network (DFPN).
"""
import numpy as np
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
import master_thesis as mt
class DFPN(pl.LightningModule):
""... | master_thesis/model_dfpn.py | MIT | 30,704 | 7c6e912ffe1b28b964df3fc51c587a58649effa9 | Python | py | |
import numpy as np
import random
import torch
import torch.nn.functional as F
from torch.nn import init
from torch import nn, autograd
from spcl.utils.faiss_rerank import compute_jaccard_distance_inital_rank,compute_jaccard_distance_inital_rank_index,compute_knn
from collections import defaultdict
class HM(autograd.F... | spcl/models/hm_final.py | MIT | 4,226 | 03bd47406bd6f6aa343a4a1b17ae18467ed6edca | Python | py | |
from __future__ import print_function
import argparse
import os
import random
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchv... | q3/selective_training/selective_training.py | Unlicense | 10,466 | 29b9f734dc400245b5ce26483086ae66444e4b81 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
from typing import Dict, List, Tuple, Union
import torch
from fvcore.nn import giou_loss, smooth_l1_loss
from torch import nn
from torch.nn import functional as F
from class_ids import coco_obj_class_to_id
from class_ids import coco_obj_id_to_cla... | models/rcnn_predictor.py | BSD-2-Clause | 8,500 | 03eaa4ecac874447d58cde0b19015c61bbfae0c5 | Python | py | |
"""Few-Shot_learning Segmentation"""
import numpy as np
import torch
import torch.nn as nn
from nn_common_modules import modules as sm
from data_utils import split_batch
import torch.nn.functional as F
# from squeeze_and_excitation import squeeze_and_excitation as se
class SDnetConditioner(nn.Module):
"""
... | other_experiments/more/few_shot_segmentor_model9.py | MIT | 8,731 | 29ba384be122e695c922145857a985d92f4497c8 | Python | py | |
from setuptools import setup
from torch.utils.cpp_extension import CUDAExtension, BuildExtension
setup(name='nms', packages=['nms'],
package_dir={'':'src'},
ext_modules=[CUDAExtension('nms.details', ['src/nms.cpp', 'src/nms_kernel.cu'])],
cmdclass={'build_ext': BuildExtension})
| setup.py | BSD-3-Clause | 305 | 6b1dc2043910645e44292d57fee41c67aa9e820c | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.