content stringlengths 200 198k | repo stringlengths 4 186 | path stringclasses 1
value | license stringclasses 101
values | size int64 200 198k | sha stringlengths 40 40 | lang stringclasses 1
value | ext stringclasses 1
value |
|---|---|---|---|---|---|---|---|
import torch
import torch.nn as nn
import os
class Mycnn(nn.Module):
def __init__(self):
super(Mycnn, self).__init__() # 继承__init__功能
# 第一层卷积
self.conv1 = torch.nn.Sequential( # input_size = 25*25*1
torch.nn.Conv2d(in_channels=1, out_channels=12, kernel_size=9, stride=1, padding=4),
torch.nn.ReLU(),
... | rl_trainer/test.py | MIT | 1,480 | 29e36b4d75ead1edc444b7119e77f96778b2021c | Python | py | |
import os
import PIL
from PIL import Image
import torch
from torch.utils.data import Dataset
import numpy as np
class Label(object):
def __init__(self, name, id, trainid, category, catid, hasinstances,
ignoreineval, color):
self.name = name
self.id = id
self.trainid = trai... | src/datasets/cityscapes.py | MIT | 14,963 | 29e382734bc6c50617664a4e49d23bad3024511c | Python | py | |
# sub-parts of the U-Net model
import torch
import torch.nn as nn
import torch.nn.functional as F
class double_conv(nn.Module):
'''(conv => BN => ReLU) * 2'''
def __init__(self, in_ch, out_ch):
super(double_conv, self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(in_ch, out_ch,... | models/backbone/unet/unet_parts.py | Apache-2.0 | 2,490 | b24e375f440e8c6d998548d4d9c8dece636a6efb | Python | py | |
'''
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License.
'''
from torchvision import datasets, transforms
from torch.utils.data.dataset import Dataset
import rasterio as rio
import glob, os
from skimage import io
import numpy as np
import tifffile as tiff
from skimage.transform impo... | data/solar_dataset.py | MIT | 2,035 | d7a0ccbe231f6175b3a92dabc53a5f585db5884d | Python | py | |
import torch
import torch.nn as nn
def tie_weights(src, trg):
assert type(src) == type(trg)
trg.weight = src.weight
trg.bias = src.bias
# for 84 x 84 inputs
OUT_DIM = {2: 39, 4: 35, 6: 31}
# for 64 x 64 inputs
OUT_DIM_64 = {2: 29, 4: 25, 6: 21}
class PixelEncoder(nn.Module):
"""Convolutional encod... | encoder.py | MIT | 3,595 | 7cd07893c6e36acc7e8731c11368a4addbb57860 | Python | py | |
#!/bin/python3
# The MIT License (MIT)
# Copyright © 2021 Yuma Rao
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the “Software”), to deal in the Software without restriction, including without limitation
# the rights to use, copy, ... | neurons/text/template_server/run.py | MIT | 4,192 | 708b67fef4f5a62c4f2e7f31447d93433f4a9622 | Python | py | |
import torch
import os
import sys
import torch.nn as nn
from torch.autograd import Variable
from torchvision import transforms
from PIL import Image
import numpy as np
PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.no... | paper_experiments/utils/resnet_reid_utils.py | MIT | 4,006 | 4b33e333e2218bb4c3c2c971463a2547e714cdcd | Python | py | |
# -*- coding: utf-8 -*-
"""test_ensemble_imagenette.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1GMlNUwMI9KvGZW0CWERa_JHO0E84oPUJ
"""
path_logits_darts = path_logits + "cnn/logits.p"
path_logits1 = path_logits + "cnn_space1/logits.p"
path_log... | darts_imagenette/test_ensemble_imagenette.py | Apache-2.0 | 3,845 | 1e4448570e8e3ef8355a75f128fe0472f01daf75 | Python | py | |
"""This modules creates a sac model in PyTorch."""
from collections import deque
import copy
from dowel import tabular
import numpy as np
import torch
import torch.nn.functional as F
from metarl import log_performance
from metarl.np.algos.off_policy_rl_algorithm import OffPolicyRLAlgorithm
from metarl.torch import di... | src/metarl/torch/algos/sac.py | MIT | 21,729 | 29e39de0c69fec439996f824052324f3b485f715 | Python | py | |
# -*- coding: utf-8 -*-
import torch
from itertools import accumulate
from onmt.constants import SubwordMarker
def make_batch_align_matrix(index_tensor, size=None, normalize=False):
"""
Convert a sparse index_tensor into a batch of alignment matrix,
with row normalize to the sum of 1 if set normalize.
... | onmt/utils/alignment.py | MIT | 6,611 | d775cf920c96546b3d1b7c51a6608ce07d1e191a | 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/loops/test_training_loop_flow_scalar.py | Apache-2.0 | 11,504 | 29e3d3b3a0e5b091f0c8e5fd235752d9d1ecbc59 | Python | py | |
import collections
import csv
import json
import logging
import os.path
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
from torch.nn import CosineEmbeddingLoss
from pytorch_pretrained_bert.modeling import BertModel
from pytorch_pretra... | tatk/dst/sumbt/sumbt.py | Apache-2.0 | 32,404 | d7661c243ef18ccadc3d32a16d8d518b3e5a5587 | Python | py | |
#!/usr/bin/env python
import os, sys, cv2, math
import random, json, logz
import numpy as np
import os.path as osp
from copy import deepcopy
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.tensorboard import Summar... | lib/modules/abstract_trainer.py | MIT,Unlicense | 34,957 | 29e415598be392a6da0191f23ae4131cafe91080 | Python | py | |
import copy
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
from .... import extensions as E
from ...initializer import init_weights_normal
from ...initializer import initialize_from_cfg
from ....utils.bn_helper import setup_bn, rollback_bn, FREEZE
from ..utils import accuracy as A
f... | unn/models/heads/bbox_head/bbox_head.py | Apache-2.0 | 16,755 | 29e4194d243ab7d0f55a9b57c6100c582c3ab9bc | Python | py | |
# https://pytorch.org/tutorials/beginner/nn_tutorial.html
# download MNIST data
from pathlib import Path
import requests
DATA_PATH = Path("data")
PATH = DATA_PATH / "mnist"
PATH.mkdir(parents=True, exist_ok=True)
URL = "https://github.com/pytorch/tutorials/raw/master/_static/"
FILENAME = "mnist.pkl.gz"
if not (PAT... | tutorial-further/about-torch.nn.py | MIT | 3,631 | f9eed5afb4683360518ebad9d517e33bbe3b4810 | Python | py | |
import os
import sys
import math
import argparse
import numpy as np
from tqdm import tqdm
import torch
from torch.multiprocessing import Queue, Process
sys.path.insert(0, '../lib')
sys.path.insert(0, '../model')
from data.CrowdHuman import CrowdHuman
from utils import misc_utils, nms_utils
from evaluate import comput... | tools/test.py | MIT | 6,360 | 29e437895eec0299a0b1bb77a0aa3f4c7524659c | 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 fcos_core.modeling import registry
from fcos_core.modeling.poolers import Pooler
from fcos_cor... | fcos_core/modeling/roi_heads/mask_head/roi_mask_feature_extractors.py | BSD-2-Clause | 2,547 | 29e46a8da83549d75e550d995ba83dafcbb0d9a8 | Python | py | |
import re
import spacy
from torchtext.data import Field, BucketIterator
from torchtext.datasets import IWSLT
def load_dataset(batch_size):
spacy_de = spacy.load('de')
spacy_en = spacy.load('en')
url = re.compile('(<url>.*</url>)')
def tokenize_de(text):
return [tok.text for tok in spacy_de.to... | utils.py | MIT | 1,084 | 1061e8f6ac0c191c5179a9ba963a97c51c466731 | Python | py | |
'''
@author Tian Shi
Please contact tshi@vt.edu
'''
import sys
import time
import numpy as np
import torch
from torch.autograd import Variable
def word_copy(args, beam_seq, beam_attn_, src_msk,
src_arr, batch_size, id2vocab, ext_id2oov):
'''
This is a meta-algorithm that can combine with
... | LeafNATS/modules/decoding/word_copy.py | MIT | 1,606 | 5f2fa7e0015866a39a154df04a0744c3c2d9bc55 | Python | py | |
#!/usr/bin/env python3
# encoding: utf-8
import os
import cv2
import argparse
import numpy as np
import torch
import torch.multiprocessing as mp
import torch.nn.functional as F
from config import config
from utils.pyt_utils import ensure_dir, link_file, load_model, parse_devices
from utils.visualize import print_iou,... | model/cpn/cvpr/ade.cpn.R50_v1c.score_map/visualize_attention.py | MIT | 9,677 | 29e49f7d9514b1672a04fdcae5b2af9354d4ca6d | Python | py | |
# This example demonstrates the behavior of the broadcast primitive.
#
# It requires 6 workers to run.
#
# Run with, e.g.,
# > mpirun -np 6 python ex_broadcast.py
import numpy as np
import torch
from mpi4py import MPI
import distdl.utilities.slicing as slicing
from distdl.backends.mpi.partition import MPIPartitio... | examples/primitives/ex_broadcast.py | BSD-2-Clause | 3,286 | 1e3be4ba50d8af7c48f12b7706d2f40150ecefe6 | Python | py | |
from __future__ import print_function
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class ASRModel(nn.Module):
def __init__(self, input_features=80, num_classes=128):
super(ASRModel, self).__init__()
# Conv1d(in_channels, out_channels, kernel_size, stride)
... | models/wav2letter.py | MIT | 1,625 | 4b6564e8b34025e73606e43d753bd80f83bd2fcb | Python | py | |
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from .adc import _adc
from .dac import _quantize_dac
from .w2g import w2g
from .crossbarlayer import CrossbarLayer
quantize_input = _quantize_dac.apply
# quantize_weight = _quantize_dac.apply
adc = _adc.apply
class crxb_Conv2d(nn.Conv2d... | model/torx/layer.py | Apache-2.0 | 16,660 | e915aa245a1b64264c5132eb5b65268cd0c115f8 | Python | py | |
import os
import pytest
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.utils.data.distributed import DistributedSampler
from torch.utils.data.sampler import RandomSampler, WeightedRandomSampler
import ignite.distributed as idist
from ignite.distribute... | tests/ignite/distributed/test_auto.py | BSD-3-Clause | 8,362 | 29e4f87111832fe279c4d505cb2a4374503010bb | Python | py | |
from typing import List, Optional
import torch
from fedrec.utilities import registry
from torch.optim import Optimizer
from torch.tensor import Tensor
class _RequiredParameter(object):
"""Singleton class representing a required parameter for an Optimizer."""
def __repr__(self):
return "<required param... | fedrec/optimization/corrected_sgd.py | Apache-2.0 | 5,978 | 29e5161f9c5ad85e68a07fce1d4b6d2b063b7437 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, DeepGraphInfomax
class Encoder_DGI(nn.Module):
def __init__(self, nfeat, nhid):
super(Encoder_DGI, self).__init__()
self.hidden_ch = nhid
self.conv = GCNConv(nfeat, self.hidden_ch)
... | models/infomax.py | MIT | 1,534 | 12d6a445e5f983302b92cc70e8a63c714626740c | Python | py | |
# coding=utf-8
# Copyright 2018 Salesforce and HuggingFace Inc. team.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | tests/test_modeling_ctrl.py | Apache-2.0 | 7,716 | 29e5554f4044a73bd65b7e871fa5c5c5bc1ecfd2 | Python | py | |
from __future__ import division
import numpy as np
import torch
import torch.nn as nn
from mmcv.cnn import normal_init
from mmdet.core import (AnchorGenerator, anchor_target, delta2bbox, force_fp32,
multi_apply, multiclass_nms)
from ..builder import build_loss
from ..registry import ... | mmdet/models/anchor_heads/anchor_head.py | Apache-2.0 | 14,144 | 4226fdcfb25e6f35f71dd8ab45ffed43abad0e02 | Python | py | |
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Download utils
"""
import os
import platform
import subprocess
import time
import urllib
from pathlib import Path
from zipfile import ZipFile
import requests
import torch
def gsutil_getsize(url=''):
# gs://bucket/file size https://cloud.google.com/storage/docs/gsu... | src/qcar_perception/src/utils/downloads.py | MIT | 6,289 | d7b87cb2cadd22fcdfaafc7fd56fc29e14d9a538 | Python | py | |
import torch
import torch.utils.data as data
from PIL import Image
import os
import functools
import json
import copy
import math
from utils import load_value_file
def pil_loader(path):
# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
with open(path, 'rb') as ... | datasets/activitynet.py | MIT | 10,930 | e967343550b637bf968ae44cbb8d168532bb4ec0 | Python | py | |
import argparse
import gin
import time
import torch
from tqdm import tqdm
import numpy as np
from torch.functional import F
from selfstudy import session, paths
from selfstudy.util import helper
from sklearn.linear_model import LogisticRegression, LinearRegression
def get_and_save_feats(exp_id=None, dense=False, i... | misc/save_network_output.py | BSD-3-Clause | 6,796 | 7cff93dfd1e5449cb1c942c21f6384a72e9d9488 | Python | py | |
import torch
import time
import math
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.multiprocessing as mp
from torch.nn import Module, Parameter
from .quant_utils import *
class QuantLinear(Module):
"""
Class to quantize weights of given linear layer
... | utils/quantization_utils/quant_modules.py | MIT | 33,730 | fcbdd679003edd6a6cb94583d76f1ceb173c8ab2 | Python | py | |
from torch import nn as nn
class BaseWrapper(nn.Module):
def __init__(self, model, **kkwargs):
super().__init__()
self.model = model
def make_blackbox(self, **kwargs) -> "Callable":
"""Implement this in subclass
Return a forward function
"""
raise NotImplem... | detex/models/base.py | BSD-3-Clause | 330 | 1eb9f83718330877400a6eef4e8ea45a34fd5e63 | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
from mmcv.cnn import (ConvModule, caffe2_xavier_init, constant_init, is_norm,
normal_init)
from torch.nn import BatchNorm2d
from ..builder import NECKS
class Bottleneck(nn.Module):
"""Bottleneck block for DilatedEncoder used in `YOLOF.
<... | mmdet/models/necks/dilated_encoder.py | Apache-2.0 | 3,273 | 29e5b9cbdc6d974dd0557bca051ab4d6e2b6d299 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import os
from lib.layers import *
class FSSDLite(nn.Module):
# FSSD ; Feature Fsuion single shot multibox detector for embeded system
def __init__(self, base, extras, head, features, feature_l... | lib/modeling/ssds/fssd_lite.py | MIT | 7,221 | 29e5bb70fa76e0401089be84090983a6165205d8 | Python | py | |
import argparse
import torch
from tqdm import tqdm
from transformers import GPT2TokenizerFast
from nlp import load_dataset
from modeling import GPT2Wrapper
from self_debiasing import DEBIASING_PREFIXES, DEBIASING_KEYWORDS
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--o... | perplexity.py | Apache-2.0 | 4,282 | 29e5c451d73196e49339a04c990b8c935d55e492 | Python | py | |
"""
Created on 13-June-2020
@author Jibesh Patra
"""
from typing import Dict, List
import torch
class AblationTransformer:
def __init__(self, features_to_ablate=None) -> None:
if features_to_ablate is None:
# Example: ['type'] OR ['type', 'value']
features_to_ablate = []
... | src/nn/dataset_utils/data_transformers/AblationTransformer.py | MIT | 940 | 1e84cf7273d8a82672d8d8d2a26a9c7430916208 | Python | py | |
#!/usr/bin/env python3
import unittest
try:
from packaging.version import Version as LV
except ImportError:
from distutils.version import LooseVersion as LV
print('WARNING: using distutils version check, not packaging!')
import os
nvidia = False # if running within NVIDIA container
nvidia_skip = False
m... | tests/pytorch.py | MIT | 9,647 | dfda6f4aa99ed4b27841ade53831f7a2274099b1 | Python | py | |
# import things
import sys
import argparse
import torch
import json
from torch import nn
from torch import optim
from torchvision import datasets, transforms, models
from torch import tensor
import torch.nn.functional as F
from predict_utils import *
parser = argparse.ArgumentParser()
parser.add_argument('image', ac... | predict.py | MIT | 1,306 | fda81c2783e7e41d0eb205869f0adffdbfee8ed4 | Python | py | |
'''
Code Adopted from https://github.com/Tramac/mobilenetv3-segmentation/blob/master/core/model/segmentation.py
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from isegm.model.modeling.efficientnet.backbone import efficientnet_b0
class LRASPP(nn.Module):
"""Lite R-ASPP"""
def __init_... | isegm/model/modeling/efficientnet/segmentator.py | Apache-2.0 | 2,479 | 52c10abf7d4cc88351a27e64544bae48ade3e359 | Python | py | |
import argparse
import pickle
import torch
from model.BBCluster import CustomSentenceTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from experiments.treccar_run import prepare_cluster_data2
from tqdm.autonotebook import trange
from sklearn.cluster import AgglomerativeClustering
from sklearn.met... | experiments/treccar_eval.py | MIT | 8,532 | 12ab7002342aa3ef1a5ef2ea42eaf4fb1887aed8 | Python | py | |
# cython: language_level=3
import logging
import os
import sys
from collections import deque
from pickle import Pickler, Unpickler
from random import shuffle
from puyo.Duel import *
from multiprocessing import Process, Queue, Manager
import multiprocessing as mp
from puyo.PuyoGame import PuyoGame as Game
from puyo.kera... | Coach.py | MIT | 12,410 | 80426d10927d2bf474571fc1e9de0e60d22da472 | Python | py | |
from typing import Tuple
import torch
import torch.nn as nn
from omegaconf import DictConfig
from torchsummary import summary as torch_summary
from src.data.pascal_voc import VOC2012
from src.model.detection_loss import yolo_loss, yolotensor_to_xyxyabs
from src.model.utils import (
BinarizedConvBlock,
Binariz... | src/model/xnor_yolo.py | MIT | 4,200 | 42065204d5612456d37ff841f58e9f8d1a388a14 | Python | py | |
import os
import pandas as pd
import torch
from transforms import transforms
from utils.autoaugment import ImageNetPolicy
# pretrained model checkpoints
pretrained_model = {'resnet50' : './models/pretrained/resnet50-19c8e357.pth',}
# transforms dict
def load_data_transformers(resize_reso=512, crop_reso=448, swap_num... | config.py | Apache-2.0 | 4,791 | 10a2db42adbdb70c40b6a145ecc96e3af51b1867 | Python | py | |
#!/usr/bin/env python
import sys, os
import termios
import contextlib
import threading
from queue import Queue
import torch
import torch.nn as nn
from collections import OrderedDict
# TODO: conditional actions ?
class InteractiveNeuralTrainer(threading.Thread):
def __init__(self, logger=None):
threading.... | inntt.py | MIT | 7,058 | 1293fbaa00b89ff7c182b84ae9c44564437d4b23 | Python | py | |
import logging
from typing import Dict, List, Iterable, Tuple, Any, Optional
from overrides import overrides
from pytorch_pretrained_bert.tokenization import BertTokenizer
from allennlp.common.file_utils import cached_path
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.da... | srl_model_attention_linear.py | MIT | 29,261 | 7c931a8ae00365128c7848cf99aa87561c8833b4 | Python | py | |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: Deformable ConvNets v2: More Deformable, Better Results
# Modified by: RainbowSecret(yuyua@microsoft.com)
# Select Seg Model for img segmentation.
import pdb
import torch
import torch.nn as nn
import torch.utils.checkpoint as cp
from collections import OrderedDict... | lib/models/backbones/resnet/dcn_resnet_models.py | MIT | 14,323 | 29e6ae8a61cd40b12c444296f1092f870871f313 | Python | py | |
from collections import defaultdict
import logging
import numpy as np
from torch import is_tensor
class Logger:
def __init__(self, console_logger):
self.console_logger = console_logger
self.use_tb = False
self.use_sacred = False
self.use_hdf = False
self.stats = defaultdic... | src/utils/logging.py | Apache-2.0 | 2,429 | 03e3757fac3c360fbed936fd90f182ade6a12d99 | Python | py | |
# encoding:utf-8
from __future__ import print_function
import torch
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
from torchvision import transforms as T
# from warpctc_pytorch import CTCLoss
import os
import train_code.utils as utils
import train_code.my_dataset as my_dataset
... | crnn/train_code/model_train_new.py | MIT | 12,299 | f9ca59f25f20df340e10618c9f6d021b23b22fd8 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import warnings
from typing import List, Optional, Tuple, Union
import torch
import torch.nn as nn
from ..compositing import alpha_composite, norm_weighted_sum
# A compositor should take as input 3D points and some corresponding information.
#... | pytorch3d/renderer/points/compositor.py | BSD-3-Clause | 4,100 | 650f0a3a07e4dffbf67a48c2f6261628078abe7b | Python | py | |
import unittest
import cpp_extension # noqa: F401
import torch
class TestConsumeOp(unittest.TestCase):
def test_jit_consume_op(self):
iters = 6
def foo(x):
for i in range(iters):
result = torch.ops.operator_benchmark._consume(torch.sum(x))
return result
... | benchmarks/operator_benchmark/pt_extension/cpp_extension_test.py | Intel | 1,166 | 4b8f5d7fb7bc20336e8b888704f046b794f7013b | Python | py | |
from collections import OrderedDict
import torch
import torch.nn as nn
from torch.optim import lr_scheduler
from torch.optim import Adam
from models.select_network import define_G, define_D
from models.model_base import ModelBase
from models.loss import GANLoss, PerceptualLoss
from models.loss_ssim import SSIMLoss
c... | models/model_gan.py | MIT | 15,673 | 6b1c8c416a4c0374046b1c666833295cf8172b6c | Python | py | |
import numpy as np
import os
import random
from scipy import io as sio
import sys
import torch
from torch.utils import data
from PIL import Image, ImageOps
import pandas as pd
class FDST(data.Dataset):
def __init__(self, data_path, mode, main_transform=None, img_transform=None, gt_transform=None):
self.im... | datasets/FDST/FDST.py | MIT | 1,861 | 29e6f9196b90375a4b8fd11b569839a88d75b4a4 | 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/retrieval/average_precision.py | Apache-2.0 | 2,171 | 29e6ff6914c9871bc788f5d5f3953ea12e26680b | Python | py | |
# %%
import os
import torch
import torchvision
import torch.nn as nn
import numpy as np
import pickle
import torchvision.transforms as transforms
import torchvision.transforms.functional as TF
import torchvision.models as models
import matplotlib.pyplot as plt
# from tensorboardX import SummaryWriter
# from torchviz i... | test2.py | MIT | 8,265 | e632d363c0220c4fee99d17309e5e6424a9bf8e8 | Python | py | |
import torch
import numpy as np
import random
from torch._six import nan
from itertools import permutations
from torch.testing._internal.common_utils import \
(TestCase, run_tests, make_tensor, slowTest)
from torch.testing._internal.common_device_type import \
(instantiate_device_type_tests, dtypes, onlyOnCPU... | test/test_sort_and_select.py | Intel | 37,400 | 29e714116a82ede7383208e5cd99a301964f414b | Python | py | |
"""Losses for categorical data."""
import torch
from .base import Metric
from nitorch.core.utils import isin
from nitorch.core.py import make_list, flatten
from nitorch.core import py, utils, math
def _pad_zero(x, implicit=False):
"""Add a zero-channels if the input has an implicit background class"""
if not... | nitorch/nn/metrics/cat.py | MIT | 10,448 | fce5c44f0a80aabae5a850ef4a5880384fd96c39 | Python | py | |
#!/usr/bin/env python3
# This file is covered by the LICENSE file in the root of this project.
from open3d import *
import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torchvision.transforms as transforms
import imp
import yaml
import time
from PIL import Image
imp... | MaskGenerator/demo_user.py | Apache-2.0 | 8,459 | 24c35fd4c6109d9c081b1ffe113b282c5695bc78 | Python | py | |
# The MIT License
# Copyright 2019 Innodata Labs and Mike Kroutikov
#
# PyTorch port of
# https://github.com/google-research/bert/modeling.py
#
# Original code copyright follows:
#
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use... | tbert/optimization.py | Apache-2.0,MIT | 1,257 | a9068bdb637e896f99ffaebcf0d921d641bc6885 | Python | py | |
import os
import pdb
import argparse
import numpy as np
import torch
PEND_ORIG = 'orig'
# PEND_NEW = 'splat'
PEND_IND_ORI = 'indpts_orig'
PEND_ATT = 'indpts'
PEND_ATT_FAIL = 'indpts_f'
PEND_ATT2D = '2dimg'
PEND_PRED = 'pred'
parser = argparse.ArgumentParser(
description='test shape net show image')
parser.add_a... | data_analysis/sum-ind_cal_farthest_dist.py | MIT | 6,958 | 29e71e1090565a55308149a95efaddeee5d4b075 | Python | py | |
import torch
import torch.nn as nn
class Emotic(nn.Module):
''' Emotic Model'''
def __init__(self, num_context_features, num_body_features):
super(Emotic,self).__init__()
self.num_context_features = num_context_features
self.num_body_features = num_body_features
self.fc1 = nn.Linear((self.num_con... | midterm/emotic.py | MIT | 1,019 | 29e730f02b8b7486067506dffee27a4c399950e3 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
from tqdm import tqdm
# Let's solve:
# -laplacian(u) = sin(2 * pi * x) + sin(2 * pi * y)
# On the domain x=[0, 1], y=[0, 1], with Dirichlet zero boundary conditions everywhere.
# Device
run_on_gpu = True
if run_on_gpu:
assert torch.cuda.is_available(), "No CUD... | steady_2D_heat_equation_simplifying.py | MIT | 4,621 | d7312e15f5e311c30c3f67d03a94eb1f228258e4 | Python | py | |
import torch
import torch.nn as nn
from torch.autograd import Variable
from dpp_nets.my_torch.linalg import custom_decomp, custom_inverse
from dpp_nets.my_torch.DPP import DPP, AllInOne
from dpp_nets.my_torch.utilities import compute_baseline
from itertools import accumulate
class KernelFixed(nn.Module):
def __i... | dpp_nets/layers/layers_ubuntu.py | MIT | 24,184 | 29e762985508b6d250789823963397389bdcea96 | 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 logging
import numpy as np
import torch
import torch.nn as nn
import math
from fairseq.data import FairseqDataset, data_utils
from an... | models/hierarchical_bias/hf_dataset.py | MIT | 18,226 | fcc6a682c63e42140d67a19b0a994c21d4828f90 | Python | py | |
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | nemo/collections/nlp/models/question_answering/qa_model.py | Apache-2.0 | 18,255 | 652074eaa66e2a366d3b5f67819f3fb703c48ede | Python | py | |
import sys
import os
import torch
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import pickle
from itertools import zip_longest
from data import POSdata, TorchData
from models import SequenceTagger
from train import accuracy, pred... | tag.py | Apache-2.0 | 5,350 | dffd2022c28bef690bb693e1f44007ca46901de1 | Python | py | |
from openselfsup.utils import build_from_cfg
import torch
from PIL import Image
from torchvision.transforms import Compose, RandomCrop
import torchvision.transforms.functional as TF
from .registry import DATASETS, PIPELINES
from .base import BaseDataset
def image_to_patches(img):
"""Crop split_per_side x split_... | openselfsup/datasets/relative_loc.py | Apache-2.0 | 2,327 | 109373f8d85dfa4a8a521f20a4c56dadd76839b1 | Python | py | |
# This file contains our re-implementation of Deep Relative Attributes (ACCV 2016) paper.
import torch
import torch.nn as nn
from torch import Tensor
from coco_tasks.graph_networks import ExtractorResNet
__all__ = ["Ranker", "BinaryCrossEntropy", "Clip"]
class Clip(nn.Module):
def __init__(self, epsilon: float... | src/coco_tasks/ranker_networks.py | MIT | 2,237 | 29e7c4e91b8a691dabb3ef7b797a671e68576a4f | Python | py | |
import math
from copy import deepcopy
from typing import Dict, Optional, Tuple
import torch
import torch.nn.functional as F
from overrides import overrides
from torch import nn
from torch.autograd import Variable
from allennlp.modules.layer_norm import LayerNorm
from allennlp.nn import util as nn_util
from allennlp_... | allennlp_models/generation/modules/decoder_nets/stacked_self_attention.py | Apache-2.0 | 6,683 | 29e7d8cbeacfe04a55005b6c88fee75de266429a | Python | py | |
# Copyright 2020 kurosawa. 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 applicable law or agr... | nne/convert/onnx.py | Apache-2.0 | 3,590 | 29e7f1360a4502c75c9e2809e739396a088ca114 | Python | py | |
from ruamel.yaml import YAML, dump, RoundTripDumper
from raisimGymTorch.env.bin import rsg_ouzel
from raisimGymTorch.env.RaisimGymVecEnv import RaisimGymVecEnv as VecEnv
import raisimGymTorch.algo.ppo.module as ppo_module
import os
import math
import time
import torch
import argparse
import numpy as np
# configuratio... | raisimGymTorch/raisimGymTorch/env/envs/rsg_ouzel/scripts/model_export.py | Apache-2.0 | 2,929 | 29e7f2ae7a53a2ac3937604145d5a78332d9af59 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from celeba_dataset import CelebADataset
from model import Net
# Checking of there is a GPU available
print("CUDA Available: ",torch.cuda.is_available())
use_cuda = torch.cuda.is_available()
device... | src/train.py | MIT | 1,502 | 29e7f5dbc56ba6cdb04817c33f49cd5dec06b63d | Python | py | |
import datetime
import json
import os
import sys
import tempfile
import warnings
from collections import defaultdict
from typing import Any, Dict, List, Optional, Sequence, TextIO, Tuple, Union
import numpy as np
import pandas
import torch as th
from matplotlib import pyplot as plt
try:
from torch.utils.tensorboa... | stable_baselines3/common/logger.py | MIT | 21,454 | 1295e5be954628eee111eee21ccf01cfdda8ef64 | Python | py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
from torch import nn
try:
from .DCNv2.dcn_v2 import DCN
except:
print('import DCN failed')
DCN = None
BN_MOMENTUM = 0.1
def fill_fc_weights(layers):
for m in layers.modules():
... | src/lib/model/networks/base_model.py | MIT | 4,882 | d73151eec3910e778c57e6ccd9b4a27d05570d63 | Python | py | |
from typing import Optional
import sys
from overrides import overrides
import torch
from allennlp.common.checks import ConfigurationError
from allennlp.training.metrics.metric import Metric
@Metric.register("unigram_recall")
class UnigramRecall(Metric):
"""
Unigram top-K recall. This does not take word ord... | allennlp/training/metrics/unigram_recall.py | Apache-2.0 | 3,151 | 29e8489a46c59c38168af3a1c5a392d7c3e0313f | Python | py | |
import os
import numpy as np
import argparse
from aist_plusplus.loader import AISTDataset
from aist_plusplus.features.kinetic import extract_kinetic_features
from aist_plusplus.features.manual import extract_manual_features
from smplx import SMPL
import torch
import multiprocessing
import functools
parser = argpars... | tools/extract_aist_features.py | Apache-2.0 | 2,329 | 29e8a9f11bedfa17ad958b128f32f149b5d9c130 | Python | py | |
# Initial code from https://github.com/kimiyoung/transformer-xl
import argparse
import time
import math
import os
import torch
from data_utils import get_lm_corpus
from utils.exp_utils import get_logger
parser = argparse.ArgumentParser(
description='PyTorch Transformer Language Model')
parser.add_argument('--da... | src/eval.py | MIT | 5,513 | 347d0b6dbb6599c6b3fb1ce5291cb36d5a5bdba3 | Python | py | |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch.utils.data
from .COCODataset import CocoDataset as coco
from .COCOKeypoints import CocoKeypoints as coco_kpt
from .PanopticDataset import PanopticDataset as cmu_kpt
from .PanopticDataset import Re... | src/data/build.py | MIT,Unlicense | 4,139 | b257382bb3d616497c11182cf432ade839c276f1 | Python | py | |
# ResNet + Vision Transformer Block + Scale + Stochastic Depth + Kinetic Regularization
# Structure
# - device: cpu or gpu, no distributed
# - recording: results/
# - data
# - model
# - train
# - test
import os
import time
import datetime
import torch
import torch.nn as nn
from torch import optim
from da... | experiment_ViT_kinetic.py | MIT | 5,098 | 29e916b515a4a266179b3d9af4301208a1009c44 | Python | py | |
import numpy as np
import pandas as pd
import random
import torch
from torchvision.datasets.vision import VisionDataset
from .. import annotation
from .. import files
from .. import io
from .. import labeled_timebins
from .. import validators
class WindowDataset(VisionDataset):
"""Dataset class that represents a... | src/vak/datasets/window_dataset.py | BSD-3-Clause | 39,366 | 45b1cd0c10dda54b94b818ed52fb3449361e73c8 | Python | py | |
import transformers
import torch
import os
import json
import random
import numpy as np
import argparse
from torch.utils.tensorboard import SummaryWriter
from datetime import datetime
from tqdm import tqdm
from torch.nn import DataParallel
from tokenizations.bpe_tokenizer import get_encoder
def build_files(data_path,... | train.py | MIT | 11,924 | 29e92005a23cf19ff14b7d64133a6f82a9a9eb93 | Python | py | |
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from torch.autograd import Variable
import torch.nn.functional as F
from torchvision import datasets, transforms, models
import os
import time
impo... | confusion_matrix.py | BSD-2-Clause | 2,565 | 8028335de22c6c013ce62d989897bc791fe9c78e | Python | py | |
from __future__ import absolute_import, division, print_function
import math
import torch
from torch.distributions import constraints
from torch.distributions.utils import lazy_property
from pyro.distributions.torch_distribution import TorchDistribution
def _matrix_inverse_compat(matrix, matrix_chol):
"""Compu... | pyro/distributions/torch/multivariate_normal.py | MIT | 2,357 | 29e98a73f33d9aa36fbc2933a8f7ae04d4454864 | Python | py | |
"""
Collection of tests for the demos
"""
# global
import pytest
# local
import ivy
import ivy.functional.backends.numpy
import ivy_tests.test_ivy.helpers as helpers
# Tests #
# ------#
# training
def test_training_demo(dev, call):
if call is helpers.np_call:
# numpy does not support gradients
... | ivy_tests/test_ivy/test_functional/test_core/test_ivy_demos.py | Apache-2.0 | 1,605 | 529f5be18ef7680f5b016ebc8959e9bb97fd3342 | Python | py | |
"""
Large-scale Point Cloud Semantic Segmentation with Superpoint Graphs
http://arxiv.org/abs/1711.09869
2017 Loic Landrieu, Martin Simonovsky
"""
from __future__ import division
from __future__ import print_function
from builtins import range
import time
import random
import numpy as np
import... | learning/main.py | MIT | 25,706 | 29e9ef8fb7f66e2d46921667ce21d068b6c2c308 | Python | py | |
from stable_baselines3.common.vec_env import SubprocVecEnv,DummyVecEnv
from stable_baselines3.common.env_util import make_vec_env
from stable_baselines3.common.utils import set_random_seed
import gym
import time
from stable_baselines3.common.atari_wrappers import AtariWrapper
from stable_baselines3.common.monitor impor... | utils/env.py | MIT | 6,195 | fde331c54f8a169f1017d3c3165f091aeac2b2eb | Python | py | |
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
import copy
import os
import os.path as osp
import time
import warnings
import mmcv
import torch
from mmcv.cnn.utils import revert_sync_batchnorm
from mmcv.runner import get_dist_info, init_dist
from mmcv.utils import Config, DictAction, get_git_hash
fro... | tools/train.py | Apache-2.0 | 6,416 | 29ea15d5dfced07fef858730ce99067c96c117d0 | Python | py | |
# @Time : 2020/11/5
# @Author : Junyi Li, Gaole He
# @Email : lijunyi@ruc.edu.cn
# UPDATE:
# @Time : 2021/1/2
# @Author : Tianyi Tang
# @Email : steventang@ruc.edu.cn
r"""
RNN
################################################
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from textbox.m... | textbox/model/LM/rnn.py | MIT | 3,809 | 4b168563c3569e1c9b4bd68655becff4279cbba4 | Python | py | |
# ******************************************************************************
# Copyright 2017-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apa... | nlp_architect/models/transformers/quantized_bert.py | Apache-2.0 | 10,784 | 29ea4f7512c7f6c1598097a60da987340eb1b57d | Python | py | |
import torch
from tqdm import tqdm
from dataset import load_dataset
from model import load_model
from arguments import commparser as parser
from utils import *
def train(model, trainloader, optimizer, criterion, device, desc='Train'):
model.train()
train_loss, correct, total = 0, 0, 0
with tqdm(trainload... | src/train.py | MIT | 4,172 | 29ea61e7448fc7f4f3c02f3194980303fd7ceac3 | Python | py | |
# -*- coding: utf-8 -*-
"""Using AutoEncoder with Outlier Detection (PyTorch)
"""
# Author: Yue Zhao <zhaoy@cmu.edu>
# License: BSD 2 clause
from __future__ import division
from __future__ import print_function
import torch
from torch import nn
import numpy as np
from sklearn.utils import check_array
from sklearn.ut... | pyod/models/auto_encoder_torch.py | BSD-2-Clause | 13,972 | 8049e82696fdae71c4114e177c4a7dded0e4b4c9 | Python | py | |
from collections import OrderedDict
import torch
import structure.model
from concern.config import Configurable, State
class Builder(Configurable):
model = State()
model_args = State()
def __init__(self, cmd={}, **kwargs):
self.load_all(**kwargs)
if 'backbone' in cmd:
self.m... | DB/structure/builder.py | Apache-2.0 | 761 | 29eab42a4dc668c2cc72bffbf0bed27d9e31cbf4 | Python | py | |
# coding=utf-8
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless re... | src/data/enc_dec_dataset.py | MIT | 21,221 | 1058bda2accb33b868aae04fd88e14732a92c00b | Python | py | |
import torch.nn as nn
import math
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False),
nn.BatchNorm2d(oup),
nn.ReLU6(inplace=True),
)
def conv_1x1_bn(inp... | MobileNetV2.py | MIT | 4,785 | b2d0fdab75efce84de49124acdb5d368b9d319fa | Python | py | |
import torch
def artanh(x):
return 0.5*torch.log((1+x)/(1-x))
def p_exp_map(v):
normv = torch.clamp(torch.norm(v, 2, dim=-1, keepdim=True), min=1e-10)
return torch.tanh(normv)*v/normv
def p_log_map(v):
normv = torch.clamp(torch.norm(v, 2, dim=-1, keepdim=True), 1e-10, 1-1e-5)
return artanh(normv)... | utils.py | MIT | 2,752 | 29eb197a12991326e91bd270487981497b99d606 | Python | py | |
'''
the initial guesser + loss surface optimization
'''
import abc
import numpy as np
import torch
from tqdm import tqdm
from models import end_2_end_optimization_helper, loss_surface
from utils import utils, warp
class End2EndOptimFactory(object):
@staticmethod
def get_end_2_end_optimization_model(opt):
... | models/end_2_end_optimization.py | CNRI-Python,Info-ZIP | 8,296 | 4291a61257e2dc16996a8dab7d0f5025509e0ed0 | Python | py | |
'''
Function:
Implementation of CCNet
Author:
Zhenchao Jin
'''
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from ...backbones import *
from ..base import BaseModel
from mmcv.ops import CrissCrossAttention
'''CCNet'''
class CCNet(BaseModel):
def __init__(self, cfg, **kwarg... | ssseg/modules/models/ccnet/ccnet.py | MIT | 4,064 | 456d381d7b47d9c6cac19543b5f57f93ef8dc617 | Python | py | |
import json
import numpy as np
import re
from collections import Counter
import pickle
import torch
import torchtext.vocab as vocab
glove = vocab.GloVe(name='840B', dim=300)
from wordfreq import word_frequency, top_n_list
import time
# print(real_word, get_word(real_word))
top_words = top_n_list('en', 200000)
def get_... | word2vec.py | MIT | 1,248 | 29eb252f653965a12a020cada7d0e4b107bdd4fc | Python | py | |
import torch
torch.autograd.set_detect_anomaly(True)
import torch.nn as nn
from utils import *
from utils import homo_warp
from inplace_abn import InPlaceABN
from renderer import run_network_mvs
def weights_init(m):
if isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight.data)
if m.bias is n... | models.py | MIT | 35,356 | 29eb2795fb33ade454bb9c5e61e7c687c3bef87a | Python | py | |
# -----------------------------------------------------
# Copyright (c) Shanghai Jiao Tong University. All rights reserved.
# Written by Jiefeng Li (jeff.lee.sjtu@gmail.com)
# -----------------------------------------------------
import torch
import torch.nn as nn
from .builder import SPPE
from .layers.Resnet import R... | AlphaPose/alphapose/models/fastpose_duc_dense.py | MIT | 6,320 | 5f272ad3e817659d7403d69e65878f3a0629dc0c | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.