content stringlengths 200 198k | repo stringlengths 4 186 | path stringclasses 1
value | license stringclasses 101
values | size int64 200 198k | sha stringlengths 40 40 | lang stringclasses 1
value | ext stringclasses 1
value |
|---|---|---|---|---|---|---|---|
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
import torch.distributed as dist
import maskrcnn_benchmark.utils.comm as comm
from torch.autograd.function import Function
class FrozenBatchNorm2d(nn.Module):
"""
BatchNorm2d where the batch sta... | maskrcnn_benchmark/layers/batch_norm.py | MIT | 5,041 | 3a2a83dadfa3aa52b3f854017a9fd71655c2a7c3 | Python | py | |
import argparse
import os
import numpy as np
from tqdm import tqdm
import torch.backends.cudnn as cudnn
# from mypath import Path
from common import config
from data import make_data_loader, make_target_data_loader
from model.sync_batchnorm.replicate import patch_replication_callback
from model.deeplab import *
from ut... | configs/visualize_demo/train.py | MIT | 12,408 | 5f64ea881267ecd6dd0d302080d10498e578f186 | Python | py | |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import re
from typing import Optional
from torch import nn
from .transformer import Transformer
class SentenceEncoder(nn.Module):
"""
This is a TorchScriptable implementation of RoBERTa from fairseq
for the pu... | pytext/models/representations/transformer/sentence_encoder.py | BSD-3-Clause | 3,805 | e9acad67fc4672fb122002b36fd252886c24f3e6 | Python | py | |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
from abc import ABC
from torch import Tensor
class BaseHook(ABC):
"""This class allows users to add desired actions in specific time points
during training or evaluation.
:param priority: Priority in the printing, hooks with small priority will be printed... | colossalai/trainer/hooks/_base_hook.py | Apache-2.0 | 3,074 | 03c3614813b4e050ed37192c7e7cbd8334d7a640 | Python | py | |
import torch
import scipy.misc as misc
class TensorType:
def __str__(self):
return self.__class__.__name__
def getSample(self, sample):
raise NotImplementedError
class ANY(TensorType):
pass
class IMAGE(TensorType):
def image_loader(self, path):
return misc.imread(path)/255.
... | deepleaps/dataloader/TensorTypes.py | MIT | 686 | 3a2aa4cc09c3d38f574c23162af13c9861971122 | Python | py | |
import os
import numpy as np
import pandas as pd
from itertools import count
import torch
import torch.optim as optim
import torch.nn.functional as F
from agent import Agent
from dqn import DQN
from penv import PatientEnvManager
from qvalues import QValues
from replay_mem import ReplayMemory
from strategy import Epsil... | src/main.py | Apache-2.0 | 2,523 | 7cc6cf8526945ed05c21ac51178c11848451b244 | Python | py | |
import logging
import os
import sys
from contextlib import nullcontext
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
from transformers import AutoConfig, AutoTokenizer
from transformers import (
HfArgumentParser,
set_seed,
)
from dense.arguments import ModelArguments, DataArgumen... | examples/run.py | Apache-2.0 | 5,347 | 801f1d294e8be6e302bad7590c250c148a8ced30 | Python | py | |
# -*- coding: utf-8 -*-
import math
import os
import pickle
import torch
import random
import wandb
import pandas as pd
import numpy as np
import torch.nn as nn
import matplotlib.pyplot as plt
from timeit import default_timer as timer
from torch.utils.benchmark import timer
from sklearn.utils import shuffle
class G... | GEFcom2014/models/GAN/utils_gan_wasserstein.py | BSD-2-Clause | 16,865 | f9631fcd087cab5d4a129e54467656777938db0c | Python | py | |
import torch
import torch.nn as nn
import torch.optim as torch_optim
import src.loss as custom_loss
import src.distilled.distilled_network as distilled_network
from src import utils
import src.utils_dir.pytorch as torch_utils
class Model(distilled_network.DistilledNet):
def __init__(self,
layer_s... | src/distilled/gauss_logits.py | MIT | 4,009 | fdb5f42406d609a402399105ec9a056d70006533 | Python | py | |
# MIT License
# code by Soohwan Kim @sooftware
import wandb
import time
import os
import torch
import logging
import pandas as pd
import nltk
from tqdm import tqdm
logger = logging.getLogger(__name__)
class MachineTranslationTrainer:
def __init__(
self,
model,
train_loader,
... | machine_translation/trainer.py | MIT | 5,757 | 12fbf5f5b7487923c58e0498a27d2be3c101594b | 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 math
from typing import Any, Dict, List, Optional, Tuple
import torch
import torch.nn as nn
from fairseq import utils
from fairseq.mod... | fairseq/models/transformer.py | MIT | 48,144 | 12ed20fe2df513dcd51e7065408fa13c69171f8b | Python | py | |
import numpy as np
import cv2
import torch
from .basic_dataset import BasicDataset
from PIL import Image
TOWNS = ['Town01', 'Town02', 'Town03', 'Town04', 'Town05', 'Town06', 'Town07', 'Town10HD']
class BEVDataset(BasicDataset):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
... | lav/utils/datasets/bev_dataset.py | Apache-2.0 | 4,253 | 3a2aeae15ef1ddcc7c2156fcfce8b33bddde9ff8 | Python | py | |
import torch
from torchvision import transforms
from dataset import NYUDataset
from custom_transforms import *
import plot_utils
import model_utils
from nn_model import Net
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
#%matplotlib inline
import torch.nn.functional as F
import torc... | error.py | MIT | 2,312 | 8033c425a5c986f8de2c7e15b50807910c3ad4b3 | Python | py | |
#!python3
"""preparing the dataset for pytorch"""
import h5py
import torch
import bisect
import numpy as np
from explore import print_keys
from torch.utils.data import Dataset, DataLoader
def normalize_data(x):
x_max = np.max(x, axis=0)
x_min = np.min(x, axis=0)
x_denom = (x_max - x_min)
x_denom[x... | src/pytorch/torchdata.py | MIT | 3,276 | 3a2b0bf01177592fcc37dc78c6a7cb69e59ff89a | Python | py | |
# flake8: noqa
# __reproducible_start__
import numpy as np
from ray import tune
def train(config):
# Set seed for trainable random result.
# If you remove this line, you will get different results
# each time you run the trial, even if the configuration
# is the same.
np.random.seed(config["seed"... | doc/source/tune/doc_code/faq.py | Apache-2.0 | 6,555 | 3a2b0c4e3e7eb004bfceb0fb47fa3e21a5587954 | Python | py | |
# pylint: disable=no-member
import torch
from models import AutoEncoder
PATH_TO_EMBEDDER = 'neural/checkpoints/ae-512-224x224-loss-0.024.pth'
def init_model(path_to_checkpoint=PATH_TO_EMBEDDER):
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
net = AutoEncoder(
latent_dim=512... | api/neural/utils.py | MIT | 714 | 3a2b18d668aafd47448bce21f0e223cfc9ce80d2 | Python | py | |
import os
import os.path
import shutil
import torch
from torch.autograd import Variable
from torch.utils.data import DataLoader
def get_data_loader(dataset, batch_size, cuda=False):
return DataLoader(
dataset, batch_size=batch_size, shuffle=True,
**({'num_workers': 1, 'pin_memory': True} if cuda e... | utils.py | MIT | 2,518 | a994d3de4b16c8450ed1134d2893ff45b449e82b | Python | py | |
import torch, torch.nn as nn
class CompositorModel(nn.Module):
def __init__(self, state_model, goal_model):
super(CompositorModel, self).__init__()
self.state_model = state_model
self.goal_model = goal_model
def forward(self, state, objects, instructions):
state_embe... | spatial_reasoning/models/compositor_model.py | MIT | 921 | 3a2b311ce216b131f9911d346a7b75f9b539bc96 | Python | py | |
import torch
from torchvision import transforms
import cv2
import numpy as np
import types
from numpy import random
def intersect(box_a, box_b):
max_xy = np.minimum(box_a[:, 2:], box_b[2:])
min_xy = np.maximum(box_a[:, :2], box_b[:2])
inter = np.clip((max_xy - min_xy), a_min=0, a_max=np.inf)
return in... | utils/augmentations.py | MIT | 13,450 | 3a2b322edab209c8cb59f839c5bdc74e9d368b17 | Python | py | |
import torch
from facenet_pytorch.models.mtcnn import MTCNN, fixed_image_standardization
from facenet_pytorch.models.utils.detect_face import get_size, crop_resize
class AlteredMTCNN(MTCNN):
def forward_return_results(self, img):
"""Run MTCNN face detection on a PIL image or numpy array. This method perfo... | Logic/ProperLogic/models_modules/altered_mtcnn.py | MIT | 3,989 | cc100e31bfe2a54c62d7548087bdcef8a78a0dce | Python | py | |
import torch
from torch import nn
from deepvoice3_pytorch import MultiSpeakerTTSModel, AttentionSeq2Seq
def deepvoice3(n_vocab, embed_dim=256, mel_dim=80, linear_dim=513, r=4,
downsample_step=1,
n_speakers=1, speaker_embed_dim=16, padding_idx=0,
dropout=(1 - 0.95), kernel... | deepvoice3_pytorch/builder.py | MIT | 10,209 | 7033fd269b44a30f0816164bf81e2857cc7af7a8 | Python | py | |
import os
import cv2
import numpy as np
from tqdm import tqdm
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import time
#Neural Network
# 2 conv layer with batch norm , 3 linear layer
# Adam optimizer and MSELoss , one hot vector - labe... | test_model1.py | MIT | 3,538 | fd6dc3195acd7dd7b446d657720b6b20428f8a93 | Python | py | |
### Copyright (C) 2017 NVIDIA Corporation. All rights reserved.
### Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
import torch
import torch.nn as nn
from torch.nn import init
import functools
from torch.autograd import Variable
import numpy as np
impo... | models/networks.py | MIT | 54,072 | 28e8024e16ea02359403067a8d4a946b69f4ada0 | Python | py | |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
import numpy as np
import torch
import torchvision
__all__ = [
"filter_box",
"postprocess",
"bboxes_iou",
"matrix_iou",
"adjust_box_anns",
"xyxy2xywh",
"xyxy2cxcywh",
]
def filter_bo... | yolox/utils/boxes.py | Apache-2.0 | 4,216 | 45fde61cb0f15aaabe4672e30a092c4d927e468b | Python | py | |
import os
import glob
import numpy as np
import cv2
import torch
from torch.utils.data import Dataset
from active_nerf.utils.pybullet_visualization_utils import visualize_camera_frame, visualize_extrinsics
from scipy.spatial.transform import Slerp, Rotation
# NeRF dataset
import json
# ref: https://github.com/NVla... | nerf/provider.py | MIT | 10,018 | 3a2b6bd86ea6e68e8f2a3c5f3dd3a344ebd7fb1e | Python | py | |
# pylint: disable=missing-docstring,missing-module-docstring,not-callable
from itertools import count
import argparse
import gym
from gym import spaces
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.distributions import Categorical
class P... | junk/gym_policy/policy.py | MIT | 4,161 | 3a2b6d492c3ea80a11c09c0cc7324dc44b13f150 | Python | py | |
import json
import logging
import os
from functools import partial
from multiprocessing import Pool, cpu_count
import numpy as np
from tqdm import tqdm
# from ...file_utils import is_tf_available, is_torch_available
# from ...tokenization_bert import whitespace_tokenize
# from .utils import DataProcessor
from transf... | src/squad_update.py | MIT | 28,036 | 706d1e48a3db981765f0650990d37e2450a82a0f | Python | py | |
from torch.nn import functional as F
def compute_tensor_iu(seg, gt):
seg = seg.squeeze(1)
gt = gt.squeeze(1)
intersection = (seg & gt).float().sum()
union = (seg | gt).float().sum()
return intersection, union
def compute_tensor_iou(seg, gt):
seg = seg.squeeze(1)
gt = gt.squeeze(1)
... | util/util.py | MIT | 1,124 | 70181702ac6fd1d08835db9af2f9482874d03eac | Python | py | |
import torch.optim as optim
from graphgym.register import register_optimizer, register_scheduler
from graphgym.config import cfg
def optimizer_example(params):
if cfg.optim.optimizer == 'adagrad':
optimizer = optim.Adagrad(params, lr=cfg.optim.base_lr,
weight_decay=cfg.... | graphgym/contrib/optimizer/example.py | MIT | 635 | 1ec32af9b33a26dc36e65d86caaf859bf5122646 | Python | py | |
import torch
import itertools
from util.image_pool import ImagePool
from .base_model import BaseModel
from data import aux_dataset
from . import networks
class AttnCycleGANModel(BaseModel):
@staticmethod
def modify_commandline_options(parser, is_train=True):
parser.set_defaults(no_dropout=True) # def... | models/attn_cycle_gan_model.py | MIT | 13,751 | fcc2b36d9ede55bd36a6840e37fa2991e5af6c78 | Python | py | |
import glob
import os
import time
import torch
from PIL import Image
from vizer.draw import draw_boxes
from ssd.config import cfg
from ssd.data.datasets import COCODataset, VOCDataset
import argparse
import numpy as np
from ssd.data.transforms import build_transforms
from ssd.modeling.detector import build_detection... | demo.py | MIT | 4,195 | 24723a9320a95e0f23cece21df6381cc148134b0 | Python | py | |
import pytest
import torch
from bgflow.distribution import NormalDistribution
from bgflow.nn.flow.dynamics import TimeIndependentDynamics
from bgflow.nn.flow.estimator import HutchinsonEstimator
from bgflow.nn import DenseNet
from bgflow.utils import brute_force_jacobian_trace
@pytest.mark.parametrize("dim", [1, 2])
... | tests/nn/flow/estimators/test_hutchinson_estimator.py | MIT | 1,952 | 3a2bb9ca91e2174f094e335efce8e4c1708cf249 | 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_util
import torch
from detectron2.layers.roi_align import ROIAlign
from .boxes import Boxes
def polygon_ar... | detectron2/structures/masks.py | Apache-2.0 | 16,389 | 3a2bc1854437b34237e10f0daef486a4e705ada7 | Python | py | |
import os
import random
from os import listdir
from os.path import join
from PIL import Image
from torch.utils.data.dataset import Dataset
from torchvision.transforms import Compose, RandomCrop, ToTensor, ToPILImage, CenterCrop, Resize
def is_image_file(filename):
return any(filename.endswith(extension) for exte... | data_utils.py | MIT | 4,128 | 3a2be2214273809f17621bb5af55037462417953 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
import math
import torch.utils.checkpoint as checkpoint
from performer_pytorch import SelfAttention
USE_CHECKPOINT=False
# for gradient checkpointing
def create_custom_forward(module, **kwargs):
def custom_forward(*inputs):
retu... | hallucination/models/trunk_tbm_v01/Transformer.py | MIT | 19,496 | 3a2be3a2e00c433ca53895f7037431c0200d00c3 | Python | py | |
import monai
import torch
import random
class RandCropData:
def __init__(self, roi_size:int):
self.roi_size = roi_size
def random_size(self, img_size):
# left = random.randint(0,img_size[1] - self.roi_size - 1)
# bottom = random.randint(0, img_size[1] - self.roi_size - 1)
left ... | transforms/Transforms.py | MIT | 3,531 | ffb7b4693b24e652518df5ebffca101c1487e84d | Python | py | |
import torch
import torch.optim as optim
import numpy as np
import pandas_datareader as datareader
import datetime as dt
import matplotlib.pyplot as plt
import random
from random import shuffle
from model import StockPricePredictor
x = [random.random() for i in range(10)]
print(x)
shuffle(x)
print(x) | test.py | MIT | 315 | 654275454a7eddf21f787cf6af959778643ab8ff | Python | py | |
'''ResNet in PyTorch.
BasicBlock and Bottleneck module is from the original ResNet paper:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
PreActBlock and PreActBottleneck module is from the later paper:
[2] Kaiming He, Xiangyu Zhang, Shaoqing Ren,... | ood_imagenet/lib/models/resnet.py | Apache-2.0 | 9,672 | 3a2c14d4593ab3206986c3714ad153c3d2cb4f07 | Python | py | |
#!/usr/bin/env python3
"""
Datset and dataloader.
Authors:
LICENCE:
"""
from pathlib import Path
from typing import List, Tuple
import numpy as np
import torchvision.transforms as transforms
from torch import Tensor
from torch.utils.data import DataLoader, Dataset
def crop(img: np.array) -> np.array:
"""Crop ... | datasets.py | MIT | 1,785 | 801e7658e61e604fc91dee916e45dcb05b5cf6c1 | Python | py | |
import numpy as np
from faiss import IndexFlatIP, IndexFlatL2
import pyvista as pv
import os
import time
from torch_geometric.nn import global_mean_pool, global_add_pool, global_max_pool, global_sort_pool
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from .util import get_labels_from... | src/util/visualization.py | MIT | 2,525 | 03c6ee046fb1724216b4215b0c2bf51766ac9dfa | Python | py | |
# coding=utf-8
# Copyright 2021 The Eleuther AI and HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-... | src/transformers/models/gpt_neo/modeling_gpt_neo.py | Apache-2.0 | 38,474 | 3a2c2e22e4d8c6513dc42773b3216b366c8c6fdc | Python | py | |
# coding=utf-8
# Copyright 2019 The Google AI Language Team Authors and 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/LICEN... | src/transformers/models/electra/modeling_electra.py | Apache-2.0 | 59,366 | fcab923cd91832ef39ec859c0c95c77ccfaf18fe | Python | py | |
import torch.nn as nn
from transformers.modeling_bert import BertPreTrainedModel, BertModel
class Model(BertPreTrainedModel):
def __init__(self, config):
super(Model, self).__init__(config)
self.hidden_size = config.hidden_size
self.bert = BertModel(config=config)
self.dropout = n... | model.py | Apache-2.0 | 799 | 3a2c39c38d1dc113f9dc8219ba0eb599fa3386a1 | Python | py | |
# basic libs
import numpy as np
import torch
# pytorch
import torch
from torch.utils.data import Dataset
import albumentations as A
# custom modules
np.random.seed(42)
class Dataset_train(Dataset):
def __init__(self, volumes_list, aug, dataset):
self.volumes_list = volumes_list
... | experiments/segmentation/contrastive_loss_encoder/data_generator.py | BSD-2-Clause | 6,003 | 3a2c595a622ed888fda61e37680b5cc1505ff02e | Python | py | |
import torch
import time
import os
import copy
import logging
import pickle
logger = logging.getLogger('root')
# dirs and files
model_file = '_model.pt'
train_loss_pkl = 'train_loss.pkl'
val_loss_pkl = 'val_loss.pkl'
# criterion_test = torch.nn.MSELoss(reduction='sum')
criterion_test = torch.nn.MSELoss()
def train_... | DEN/modeling.py | BSD-3-Clause | 4,037 | 3a2c7cc2ec5286949c701af69951f2b05c0d9e53 | Python | py | |
import torch
from torch.utils.data import DataLoader
from dataloaders.dataloader_msrvtt_retrieval import MSRVTT_DataLoader
from dataloaders.dataloader_msrvtt_retrieval import MSRVTT_TrainDataLoader
from dataloaders.dataloader_msvd_retrieval import MSVD_DataLoader
from dataloaders.dataloader_lsmdc_retrieval import LSMDC... | dataloaders/data_dataloaders.py | MIT | 8,815 | 3a2c8b009ffab02e246233c5e871403c540ee41a | Python | py | |
"""
MIT License
Copyright (c) 2019 Christopher Beckham
Copyright (c) 2017 Christian Cosgrove
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 ... | networks/model_resnet.py | BSD-3-Clause | 9,126 | ff40147b00394ebdccdbb8a8caaac2706378a8c1 | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Christian Heider Nielsen"
__doc__ = r"""
Gradient-weighted Class Activation Mapping
Created on 14-02-2021
"""
import argparse
import cv2
import numpy
import torch
from draugr.torch_utilities import GuidedBackPropReLUModel
fro... | samples/classification/grad_cam.py | Apache-2.0 | 6,919 | e9839987b9d4914d8ebc0b214e3043ab0f4211fd | Python | py | |
import torch
import os
import time
from pydispatch import dispatcher
from eisen import EISEN_BEST_MODEL_METRIC, EISEN_BEST_MODEL_LOSS
class SaveTorchModel:
"""
This object implements model saving for pytorch models. Once instantiated with a parameter consisting of a string
representing the path of the di... | eisen/utils/artifacts/savemodel.py | MIT | 10,395 | 7c5b64a770af5c607c3d34415d03fd76b946dc97 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import sys
sys.path.append('..')
from copy import deepcopy
def prox_positive(x):
return torch.nn.functional.threshold(x,0,0)
def prox_identity(x):
return x
def prox_soft_threshold(x,lamb):
return torch.sign(x)*torch.nn.functional.threshold(torch.abs... | trim/funcs.py | MIT | 876 | 3a2cd7ad3ab962ad56ec4bead058de2d65070c95 | Python | py | |
import copy
import torch
from typing import cast, Callable, Optional, Tuple
def repeat_layer(l: torch.nn.Module, times: int):
return [l] + [copy.deepcopy(l) for _ in range(times - 1)]
def pad_mask(lengths: torch.Tensor,
max_length: Optional[int] = None,
device='cpu'):
"""lengths i... | slp/modules/util.py | MIT | 1,421 | 52b09f913267c17a2f7f08db455395fb221b56f9 | Python | py | |
import os
import json
import random
import sys
import time
import math
import gflags
import numpy as np
from spinn.util import afs_safe_logger
from spinn.util.data import SimpleProgressBar
from spinn.util.blocks import to_gpu
from spinn.util.misc import Accumulator, EvalReporter
from spinn.util.logging import stats, ... | python/spinn/models/supervised_classifier.py | Apache-2.0 | 15,596 | 3a2cf9cd95480da6427d4e8ef7060dbbfae3c6a7 | Python | py | |
#! /usr/bin/python
# -*- encoding: utf-8 -*-
import torch
import numpy
import random
import pdb
import os
import threading
import time
import math
import glob
import soundfile
from scipy import signal
from scipy.io import wavfile
from torch.utils.data import Dataset, DataLoader
import torch.distributed as dist
# 将num... | DatasetLoader.py | MIT | 9,318 | 3a2d0ed78c15b846279cd16056985e1e67064df3 | Python | py | |
# Copyright (c) 2020 Horizon Robotics and ALF Contributors. 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... | alf/networks/relu_mlp.py | Apache-2.0 | 8,025 | 7cea893c0688e6046a25b8a9fcdc927ab553a3e9 | Python | py | |
# -*-coding:utf-8 -*-
import torch.nn as nn
import torch.nn.functional as F
__all__ = ['se_resnext29_8x64d', 'se_resnext29_16x64d']
class SEModule(nn.Module):
def __init__(self, channels, reduction=16):
super(SEModule, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc_1 = ... | models/senet.py | MIT | 4,665 | 3a2d3b8d54dd184f7c10fb8e283f9c5b162d9e81 | Python | py | |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Donny You (youansheng@gmail.com)
# Pose Net fot Parts Detection.
import torch.nn as nn
import torch.nn.functional as F
import torch
class Pose_CPM(nn.Module):
def __init__(self):
super(Pose_CPM, self).__init__()
# self.out_c = configer.get('... | lib/models/pose_cpm_git.py | MIT | 9,219 | 1e94d744c942dbf25666aed901e2b49885237869 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
from einops import rearrange
from mmcv import ConfigDict
from mmcv.cnn import build_conv_layer, build_norm_layer, kaiming_init
from mmcv.cnn.bricks.transformer import build_transformer_layer_sequence
from mmcv.cnn.utils.weight_init import trunc_normal_
from mmcv.run... | mmaction/models/backbones/timesformer.py | Apache-2.0 | 11,927 | 3a2d54bd6c1ccf68784baf7168aef3efc8f8c327 | Python | py | |
# https://github.com/spro/char-rnn.pytorch
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class CharRNN2(nn.Module):
def __init__(self, hidden_size, model, char_dict, n_layers=2):
assert model in ["gru", "lstm"]
super(CharRNN2, self).__init__()
self.model ... | model.py | MIT | 1,789 | 129443cf9c71543472e792f4f96c4f08d20d110f | Python | py | |
# -*- coding: utf-8 -*-
"""Test the evaluators."""
import dataclasses
import logging
import unittest
from operator import attrgetter
from typing import Any, ClassVar, Dict, Mapping, Optional, Tuple, Type
import numpy
import torch
from pykeen.datasets import Nations
from pykeen.evaluation import Evaluator, MetricRes... | tests/test_evaluators.py | MIT | 23,053 | 52a6fe477ee82dcfdf092e894b67a681899f4d37 | Python | py | |
# Copyright The PyTorch Lightning team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | torchmetrics/functional/classification/roc.py | Apache-2.0 | 5,328 | 3a2d7e556843cf5a1aaa2cfe0b8843cb159371a3 | Python | py | |
#!/usr/bin/env python3
import math
from numbers import Number
import torch
from torch.distributions import constraints
from torch.distributions.utils import broadcast_all
from torch.nn import Module as TModule
from .prior import Prior
from .torch_priors import NormalPrior
class SmoothedBoxPrior(Prior):
r"""A s... | gpytorch/priors/smoothed_box_prior.py | MIT | 2,536 | 3a2d8292ab4854063f4e87bca43c1b36f94e5825 | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from rl.misc.utils import init
"""
Modify standard PyTorch distributions so they are compatible with this code.
"""
#
# Standardize distribution interfaces
#
# Categorical
class FixedCategorical(torch.distributions.Categorical):
def... | rl/misc/distributions.py | MIT | 1,183 | 3a2d8754ca10dc5e169a1972b7025eb37d72d67a | Python | py | |
# Authors: Robin Schirrmeister <robintibor@gmail.com>
#
# License: BSD (3-clause)
import os
import random
import numpy as np
import mne
import h5py
import torch
from sklearn.utils import check_random_state
def set_random_seeds(seed, cuda):
"""Set seeds for python random module numpy.random and torch.
Para... | braindecode/util.py | BSD-3-Clause | 10,182 | 24a9e86a189cd6d3fb127cabedefc52104fcfa27 | Python | py | |
import sys, os, time
import traceback
from tqdm import tqdm
from tqdm.notebook import tqdm as tqdm_notebook
import math
import torch
import numpy as np
#from itertools import imap
from collections import deque, Mapping
from omnibelt import Simple_Child, Proper_Child, get_now, create_dir, save_yaml, load_ya... | omnilearn/util/misc.py | MIT | 4,121 | fd7546f79f5989c901f3206eee661e1585d29045 | Python | py | |
import time
import numpy as np
import torch
from torch import distributed as dist
class timer():
def __init__(self):
self.acc = 0
self.t0 = torch.cuda.Event(enable_timing=True)
self.t1 = torch.cuda.Event(enable_timing=True)
self.tic()
def tic(self):
self.t0.record()
... | src/trainer/common.py | MIT | 1,214 | 45ff6899d1a005a0dda9baf1f77d16a2ae4d7dc8 | Python | py | |
import numpy as np
from scipy import signal
import librosa
import torch
def compute_PSD_matrix(audio, window_size):
#win = librosa.core.stft(audio, center=False)
#z = np.sqrt(8.0/3.) * abs(win / window_size)
window = torch.hann_window(2048)
stft = torch.stft(torch.FloatTensor(audio), n_fft=2048, h... | deepspeech-psy-adversarial/mask.py | MIT | 6,055 | 3a2deb9c43b3018aeeb53c2ca3ecf970a46f762b | Python | py | |
import numpy as np
import scipy.sparse as sp
import torch
from sklearn.model_selection import train_test_split
import torch.sparse as ts
import torch.nn.functional as F
def encode_onehot(labels):
"""Convert label to onehot format.
Parameters
----------
labels : numpy.array
node labels
Ret... | deeprobust/graph/utils.py | MIT | 23,042 | 1e21629764c07137cc65fdcd8deda28b5ad95407 | Python | py | |
import numpy as np
import pytest
import torch
from mmcv.cnn.bricks import ConvModule
from mmdet3d.models.builder import build_head
def test_paconv_decode_head_loss():
if not torch.cuda.is_available():
pytest.skip('test requires GPU and torch+cuda')
paconv_decode_head_cfg = dict(
type='PAConvH... | tests/test_models/test_heads/test_paconv_decode_head.py | Apache-2.0 | 2,970 | 4b152100e277f11cc7b938f95a34e7dff0698464 | Python | py | |
from torch.optim.lr_scheduler import ReduceLROnPlateau
from torch.optim.lr_scheduler import _LRScheduler
# from .lr_scheduler import _LRScheduler
class GradualWarmupScheduler(_LRScheduler):
""" Gradually warm-up(increasing) learning rate in optimizer.
Proposed in 'Accurate, Large Minibatch SGD: Training Ima... | deepclustering/schedulers/warmup_scheduler.py | MIT | 3,009 | 3a2dfbe5715c33b82cd1cb29cd987bbda9b18911 | Python | py | |
""" Starting point of the script is a saving of all singular values and vectors
in alex_save/
We perform the 100-optimization implemented in optim_nn_pca_greedy
"""
import math
import torch
import torchvision
import numpy as np
from lipschitz_utils import *
from max_eigenvalue import k_generic_power_method
from exp... | lipEstimation/experiments/alex.py | MIT | 3,520 | 3a2e025ebb5aabfcd6a1b9f158d3692fa54118a0 | Python | py | |
import numpy as np
import torch
from generator import Generator
from utils import output_value_hook, sliced_transport, image_preprocessing, vgg_normalization
class StyleTransfer(Generator):
"""Style transfer model.
"""
def __init__(self, style_image, content_image, observed_layers, n_bins=128):
... | style_transfer.py | MIT | 2,910 | 7ceb8b264f8a91c2cb0077f4d01fc03105947b4d | Python | py | |
from sentence_transformers import SentenceTransformer, LoggingHandler, InputExample
from sentence_transformers import models, util, evaluation, losses
import logging
import os
import gzip
from datetime import datetime
import torch
from torch.utils.data import DataLoader
#### Just some code to print debug in... | examples/unsupervised_learning/CT_In-Batch_Negatives/train_askubuntu_ct-improved.py | Apache-2.0 | 4,498 | 3a2e1ebcf035d617f959f854583356083b66bc81 | Python | py | |
from __future__ import division
import torch
import torchvision.transforms.functional as F
from torch import Tensor
from torch.jit.annotations import Optional, List, BroadcastingList2, Tuple
def _is_tensor_a_torch_image(input):
return len(input.shape) == 3
def vflip(img):
# type: (Tensor) -> Tensor
"""V... | torchvision/transforms/functional_tensor.py | BSD-3-Clause | 8,169 | f9fb62b76b04a1adcaf0cbe38a3d80f6865e50fc | Python | py | |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2019 Kyoto University (Hirofumi Inaguma)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Gated convolutional encoder."""
from collections import OrderedDict
import logging
import torch.nn as nn
import torch.nn.functional as F
from neural_sp.... | neural_sp/models/seq2seq/encoders/gated_conv.py | Apache-2.0 | 4,777 | 3a2e4dee3c2dcec868c8127ea238fb1aee92b40f | Python | py | |
import torch
import torch.nn as nn
class Lovasz(nn.Module):
"""Lovasz Loss. Cf: https://arxiv.org/abs/1705.08790 """
def __init__(self):
super().__init__()
def forward(self, inputs, targets):
N, C, H, W = inputs.size()
#masks = torch.zeros(N, C, H, W).to(targets.device).scatter_... | sagemaker/model/robosat_pink/robosat_pink/losses/lovasz.py | MIT | 1,093 | 3a2e5d34c5dc53b62eb5e982b97d112647b9116a | Python | py | |
import numpy as np
import itertools
from typing import List, Dict, Any
import torch
# Match heatmap size and text size
def resize_array(array_d, target_size):
# target size is the text length
assert len(array_d.shape) == 1 # 1D-array only (List like)
array_size= array_d.shape[0]
if target_size <= arr... | src/deep_nlp/grad_cam/utils/utils/utils.py | MIT | 1,434 | 420ad96af20f030da19aa53fbb20cf8d74177fc0 | Python | py | |
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from data import config as cfg # ##将原本的coco换成了voc0712
from ..box_utils import match, log_sum_exp
import focal_loss # ##引入了FocalLoss
class MultiBoxLoss(nn.Module):
"""SSD Weighted Loss F... | layers/modules/multibox_loss.py | MIT | 9,680 | 341d06df2241fa1ac2547a23fafcdbe2108ee821 | Python | py | |
#!/usr/bin/env python3
# coding:utf-8
# Copyright (c) Tsinghua university conversational AI group (THU-coai).
# This source code is licensed under the MIT license.
import codecs
import torch
import math
from source.inputters.corpus import KnowledgeCorpus
from source.inputters.dataset import Dataset
from source.models.... | main.py | Apache-2.0 | 10,023 | 5e849cbdf5eec7ceb9009b2169c75bb2d47a46ca | Python | py | |
import time
import numpy as np
import torch
from torch.autograd import Variable
from torch.nn import Parameter
from torch.utils.data.sampler import SubsetRandomSampler
from data_loader import libsvm_dataset
from thrift_ps.ps_service import ParameterServer
from thrift_ps.client import ps_client
from thrift.transport... | examples/lambda/hybrid/linear_hybrid_ga.py | Apache-2.0 | 8,603 | 3a2e96a860ae7806ef1b3f4cc54f7b77af227d25 | Python | py | |
"""
Special LR scheduler for fine-tuning Transformer networks
"""
from overrides import overrides
import torch
import logging
from allennlp.training.learning_rate_schedulers.learning_rate_scheduler import LearningRateScheduler
logger = logging.getLogger(__name__)
@LearningRateScheduler.register("ulmfit_sqrt")
clas... | udify/optimizers/ulmfit_sqrt.py | MIT | 4,218 | 3a2ec57328443f32bca04bee6fc711b215caa3d2 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from ogb.graphproppred.mol_encoder import AtomEncoder
from torch_geometric.nn import (
BatchNorm,
GlobalAttention,
PNAConv,
Set2Set,
global_add_pool,
global_max_pool,
global_mean_pool,
)
class PNANodeEmbedding(nn.Module):
... | modules/pna/pna_module.py | Apache-2.0 | 2,743 | 5fa3235f0b0c0bf334a0a708b7ddda20579c6933 | Python | py | |
##########################################################
# Copyright 2019 Oath Inc.
# Licensed under the terms of the MIT license.
# Please see LICENSE file in the project root for terms.
##########################################################
# This file contains Att2in2, AdaAtt, AdaAttMO, TopDown model
# AdaAtt... | models/RelationTransformerModel.py | MIT | 26,997 | f9a1f06d38be2e3ebb234cdf775ab406a89910d3 | Python | py | |
import os
import sys
import time
from pprint import pprint
import cv2
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import visdom
from PIL import Image
from skimage import io
from skimage.transform import resize
sys.path.append('../')
from config... | inference/inference_fbp.py | MIT | 11,091 | 3a2ed8c17f4fdb415cf48d0af02cca6345f1956b | Python | py | |
import argparse
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.optim
import torch.multiprocessing as mp
import torch.utils.data
import torch.utils.data.distr... | ImageNet/Train.py | MIT | 17,399 | 24ec4386395081e3161cb62cc450b10f9738bce9 | Python | py | |
from typing import Optional, Tuple, Dict, Any, List
import gym
import torch as th
import torch.nn as nn
from torch.distributions import Normal, Categorical, Bernoulli
from gym import spaces
from stable_baselines3.common.preprocessing import get_action_dim
class Distribution(object):
def __init__(self):
s... | stable_baselines3/common/distributions.py | MIT | 26,563 | f9bb16c9c1432d0d2242c19540870b80a272e869 | Python | py | |
from __future__ import division
import os
import numpy as np
#from scipy.ndimage import imread
from imageio import imread
import scipy.io as sio
import torch
import torch.utils.data as data
from datasets import pms_transforms
from . import util
np.random.seed(0)
class DiLiGenT_main(data.Dataset):
def __init__(se... | datasets/DiLiGenT_main.py | MIT | 3,179 | 12c195d7b8a2a938728bd4a6a5d863c4b95d9cfa | Python | py | |
# coding=utf-8
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless r... | Train/bert/src/run_glue_no_trainer.py | MIT | 27,171 | 3a2f4981b2783f8b80c2c009a0bb2621bf8250ba | Python | py | |
import torch
import torch.nn as nn
import torch.utils.data
# from ipdb import set_trace as stop
class ConvBlock(nn.Module):
def __init__(self, inplanes, outplanes, kernel_size=3, stride=1, upsample=False, bn=True, activation=True):
super(ConvBlock, self).__init__()
self.upsample = upsample
... | models/model_x1.py | MIT | 4,686 | fcc49271d00d8fefe09750c7617952b40092ba1c | Python | py | |
import os
import mmap
from glob import glob
import itertools
import numpy as np
import argparse as ap
import concurrent.futures as cf
import time
from queue import Queue as Queue
import torch.cuda.nvtx as nvtx
import copy
from mpi4py import MPI
from mpi4py.util import dtlib
import torch
import io_helpers as ioh
def... | HelmholtzAI/benchmarks/implementations/image-src/data/stage_data_v2_oo.py | Apache-2.0 | 23,736 | 3a2f9894bc91c5b37040774dd92cc42b20b47ae4 | Python | py | |
import numpy as np
import torch
from agent.heuristics.util import get_agent_turn, wrapper, get_days, \
get_recent_byr_offers, get_last_norm
from agent.const import DELTA_SLR, NUM_COMMON_CONS
class HeuristicSlr:
def __init__(self, delta=None):
self.patient = np.isclose(delta, DELTA_SLR[-1])
def __... | agent/heuristics/HeuristicSlr.py | MIT | 1,673 | 28d46bcf140c71d0908792da346aec3de0c21bf7 | Python | py | |
# -*- coding: utf-8 -*-
# opyright 2018 The Google AI Language Team Authors and 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/licen... | src/utils/optimization.py | Apache-2.0 | 7,959 | 3a2fd43434b404e551a0c2403ad0a69ea7e6a877 | Python | py | |
import time
import numpy as np
from skimage.color import rgb2lab, lab2rgb
import matplotlib.pyplot as plt
import torch
class AverageMeter:
def __init__(self):
self.reset()
def reset(self):
self.count, self.avg, self.sum = [0.] * 3
def update(self, val, count=1):
self.count += c... | Image Colorization Tutorial/utils.py | MIT | 2,282 | e92ecc3b9cf912b3225e1f90ad7f21e8bc71f967 | Python | py | |
# -*- coding: utf-8 -*-
"""
Audio Feature Extractions
=========================
``torchaudio`` implements feature extractions commonly used in the audio
domain. They are available in ``torchaudio.functional`` and
``torchaudio.transforms``.
``functional`` implements features as standalone functions.
They are stateless... | examples/tutorials/audio_feature_extractions_tutorial.py | BSD-2-Clause | 13,122 | 5f5091e66b554c3af166b9120329908e39a48f92 | Python | py | |
import argparse
import os
import pprint
import envpool
import numpy as np
import torch
from torch.utils.tensorboard import SummaryWriter
from tianshou.data import Collector, VectorReplayBuffer
from tianshou.policy import PSRLPolicy
from tianshou.trainer import onpolicy_trainer
from tianshou.utils import LazyLogger, T... | test/modelbased/test_psrl.py | MIT | 4,561 | 3a30230053b19c5ca182c64c7da9caba3908b5a7 | Python | py | |
# coding=utf-8
# Copyright 2020 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 requir... | tests/test_modeling_auto.py | Apache-2.0 | 18,075 | 4575d316adab3d8f0fa9b4025e54457512f2b819 | Python | py | |
import os
import shutil
import time
import csv
import numpy as np
import pandas as pd
import sklearn
import torch
from sklearn.model_selection import train_test_split
from deepoffense.classification import ClassificationModel
from deepoffense.language_modeling.language_modeling_model import LanguageModelingModel
from ... | examples/danish/danish_deepoffense.py | Apache-2.0 | 3,869 | 3a304d357c483a993cb9e64977bf919a0b93c829 | Python | py | |
import torch
import torch.utils.data as data
import numpy as np
import cv2
from PIL import Image
import glob
import os
import random
def populateTrainList(folderPath):
folderList_pre = [x[0] for x in os.walk(folderPath)]
folderList = []
trainList = []
for folder in folderList_pre:
if folder[-3:] == '240':
f... | dataloader.py | MIT | 3,257 | 3a30734957f3dcdb8d8efdd07ad2d01de032a920 | Python | py | |
import torch._C
import contextlib
import ctypes
import sys
import types
import torch.jit
import torch._utils_internal
# Query `hasattr` only once.
_SET_GLOBAL_FLAGS = hasattr(sys, 'getdlopenflags') and hasattr(sys, 'setdlopenflags')
@contextlib.contextmanager
def dl_open_guard():
"""
Context manager to set... | torch/_ops.py | Intel | 4,329 | 3a30862a937a843856cceae178090ba4349a399f | Python | py | |
"""
ONNX module
"""
# Conditional import
try:
from onnxruntime import InferenceSession, SessionOptions
ONNX_RUNTIME = True
except ImportError:
ONNX_RUNTIME = False
import numpy as np
import torch
from transformers import AutoConfig
from transformers.configuration_utils import PretrainedConfig
from trans... | src/python/txtai/models/onnx.py | Apache-2.0 | 2,913 | fdd6c58f0b27c9372fe33999cae16b6ee246bdf6 | Python | py | |
#-*- coding: utf-8 -*-
from __future__ import print_function, division
"""
Pytorch useful tools.
"""
import torch
import os
import errno
import numpy as np
import matplotlib as plt
from sklearn.metrics import average_precision_score
__author__ = 'Pau Riba'
__email__ = 'priba@cvc.uab.cat'
def save_checkpoint(state,... | utils.py | MIT | 6,436 | 3a30a3bd70672359733aaafce55f57f620433823 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.