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 PIL
from torch.utils.collect_env import get_pretty_env_info
def get_pil_version():
return "\n Pillow ({})".format(PIL.__version__)
def collect_env_info():
env_str = get_pretty_env_info()
env_str += get_pil_version()
... | kindler/utils/collect_env.py | MIT | 337 | 104cb044164332ecd53834825901e37286703773 | Python | py | |
import torch.utils.data as data
import pdb
from PIL import Image
import os
import os.path
import numpy as np
IMG_EXTENSIONS = [
'.jpg', '.JPG', '.jpeg', '.JPEG',
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
]
def is_image_file(filename):
return any(filename.endswith(extension) for extension in IMG_EX... | dataloader/KITTIloader2015.py | MIT | 1,324 | 3a9004712f701eb5c7fb193386aabddc9611fc60 | 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 torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import os
import sys
BASE_DIR = os.path.dirname(os.path... | models/obj_mlp.py | MIT | 2,133 | 3a90224ca6c0bcde44e48fe97d7b5ba3edaba714 | Python | py | |
from einops.layers.torch import Rearrange
from torch import nn
from torch.nn.modules.utils import _pair
from .layers import MLPMixerBlock
__all__ = ['MixerS32', 'MixerS16', 'MixerB32', 'MixerB16', 'MixerL32', 'MixerL16', 'MixerH14']
class MLPMixer(nn.Module):
"""MLP-Mixer.
A PyTorch implement of : `MLP-Mixe... | luffy/models/mlp_mixer.py | MIT | 3,118 | b2f0995e88213615eb6d78158a1a46b253e189e2 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
from math import sqrt
from utils.masking import TriangularCausalMask, ProbMask
class FullAttention(nn.Module):
def __init__(self, mask_flag=True, factor=5, scale=None, attention_dropout=0.1, output_attention=False):... | models/attn.py | Apache-2.0 | 7,656 | 3a90399c5aff325fba234bad4596baca07d7f71b | Python | py | |
from util.typing.typeclass import *
from util.typing.torch import *
from util.experiment import *
from util.typing.data import Iter
from torch import Tensor
class SwitchDeviceTensor(SwitchDevice[Tensor]):
def switch(self, device, data: Tensor):
return data.to(device)
end(switch)
end(SwitchDeviceTensor)
... | src/dataset/common.py | MIT | 1,481 | 347f630e676a4d64baf0c3168f98effdbb49de6c | Python | py | |
# coding=utf-8
# Copyright 2018 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable... | src/transformers/convert_transfo_xl_original_tf_checkpoint_to_pytorch.py | Apache-2.0 | 4,913 | 3a9048ba8e831446330fad4cde255d566d4f9e7c | Python | py | |
import os
import cv2
import mmcv
import numpy as np
import torch
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from mmpose.datasets.pipelines import Compose
from mmpose.models import build_posenet
from mmpose.utils.hooks import OutputHook
os.environ['KMP_DUPLICATE_LIB_OK'] = 'TRU... | mmpose/apis/inference.py | Apache-2.0 | 27,730 | 6b09189005137d8d18781b9d459e9b82d0dfc7ab | Python | py | |
from det3d import torchie
import numpy as np
import torch
from ..registry import PIPELINES
class DataBundle(object):
def __init__(self, data):
self.data = data
@PIPELINES.register_module
class Reformat(object):
def __init__(self, **kwargs):
double_flip = kwargs.get('double_flip', False)
... | det3d/datasets/pipelines/formating.py | MIT | 3,651 | d77f940ef6d90c921427f54b3d2cd36214158994 | Python | py | |
import cfg
import models
import datasets
import random
from functions import train, validate, LinearLrDecay, load_params, copy_params
from utils.utils import set_log_dir, save_checkpoint, create_logger
from utils.inception_score import _init_inception
from utils.fid_score import create_inception_graph, check_or_downloa... | SNGAN/train_less.py | MIT | 6,052 | 3a906234becfc2d0ce08210ef1d5a072f2af3e06 | Python | py | |
# Copyright 2020 Skillfactory LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | nn_classifier/data_utils.py | Apache-2.0 | 3,176 | 7cfe50ec9af81b5c1b893c6551947f47703ae181 | Python | py | |
import torch
from torch_complex.tensor import ComplexTensor
def complex_matrix2real_matrix(c: ComplexTensor) -> torch.Tensor:
# NOTE(kamo):
# Complex value can be expressed as follows
# a + bi => a * x + b y
# where
# x = |1 0| y = |0 -1|
# |0 1|, |1 0|
# A complex matrix ... | torch_complex/utils.py | MIT | 1,338 | 10546082b705891bdb2637acc9c459af7b678d05 | 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 os
import numpy as np
import torch
from fairseq.data import (
data_utils,
Dictionary,
encoders,
IdDataset,
MaskTo... | fairseq/tasks/masked_lm.py | MIT | 8,309 | 34001eec00780e8e62c6358fcc010dac937d6aed | Python | py | |
from typing import Optional, Dict
import numpy as np
import torch
from jina import Executor, DocumentArray, requests
from jina.types.arrays.memmap import DocumentArrayMemmap
from transformers import AutoModel, AutoTokenizer
class MyTransformer(Executor):
"""Transformer executor class """
def __init__(
... | jina/helloworld/chatbot/my_executors.py | Apache-2.0 | 3,877 | df981eeebda1b40f023d1f61a8b55394bb039d4b | Python | py | |
import torch
import torch.nn as nn
class BasicBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1)
self.bn1 = nn.BatchNorm2d(in_channels)
... | models/resnet.py | MIT | 3,774 | 28ab6ffb09641e879287276c8e5575ff9c7ab205 | Python | py | |
import numpy as np
import skimage
import skimage.measure
import torch
import tqdm
import multiprocessing
from skimage.measure import compare_ssim, compare_psnr
from .perceptual_similarity import PerceptualLoss
from deep_privacy import torch_utils
from .fid_pytorch import fid as fid_api
from typing import List, Dict
d... | deep_privacy/metrics/metric_api.py | MIT | 4,731 | 3a9085aa5f9993626ee087908e67ceec5e7e03d4 | Python | py | |
# -*- coding: utf-8 -*-
from collections.abc import Sequence
import io
import math
import warnings
from typing import Optional, Tuple
import torch
from torch import Tensor
from torchaudio._internal import module_utils as _mod_utils
import torchaudio
__all__ = [
"spectrogram",
"inverse_spectrogram",
"grif... | torchaudio/functional/functional.py | BSD-2-Clause | 65,083 | a973230d2aa10605f81fe87019f58c040d9d87aa | Python | py | |
from torch import nn
def init_bn(module):
if module.weight is not None:
nn.init.ones_(module.weight)
if module.bias is not None:
nn.init.zeros_(module.bias)
def set_bn(module, momentum):
for m in module.modules():
if isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d))... | multi_model/utils/pn2_utils/nn/init.py | MIT | 1,114 | b2381fe24de7ca346688e6c7276a59ea2096c088 | Python | py | |
"""Automatically apply torch.jit to a function by just adding @autojit annotation to that function.
Only works for functions that only take positional arguments, which are all torch Tensors.
Re-traces the function for every shape of input.
"""
import time
import torch
def autojit(func):
"""Dynamically jit-compile ... | autojit.py | Apache-2.0 | 857 | e64a0ba7208c49d15383ed701e3707fcb8ab4435 | Python | py | |
""" Loader Factory, Fast Collate, CUDA Prefetcher
Prefetcher and Fast Collate inspired by NVIDIA APEX example at
https://github.com/NVIDIA/apex/commit/d5e2bb4bdeedd27b1dfaf5bb2b24d6c000dee9be#diff-cf86c282ff7fba81fad27a559379d5bf
Hacked together by / Copyright 2020 Ross Wightman
Modified by YANG Ruixin for multi-lab... | timm/data/loader.py | Apache-2.0 | 9,430 | 3a90e18a623233be09eb976fc04dd3983ab5391d | Python | py | |
#!/usr/bin/env python
# coding: utf-8
#
# Author: Kazuto Nakashima
# URL: http://kazuto1011.github.io
# Created: 2017-10-30
# Modified by: Subhabrata Choudhury
from __future__ import print_function
import glob
import os.path as osp
import random
from collections import defaultdict
from glob import glob
impor... | zs3/dataloaders/cocostuff.py | Apache-2.0 | 12,164 | 3a90e788e0d306a9511a36bb050a5202e497b421 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
from typing import Any, List
import torch
from torch.nn import functional as F
from detectron2.config import CfgNode
from detectron2.structures import Instances
from .mask_or_segm import MaskOrSegmentationLoss
from .registry import DENSEPOSE_LOSS_REGISTRY
from .util... | AdelaiDet/detectron2/projects/DensePose/densepose/modeling/losses/chart.py | Apache-2.0 | 14,428 | fcba988696af0a49d51d564c5fe9999c183effff | Python | py | |
from overrides import overrides
import torch
from allennlp.data import Vocabulary
from allennlp.modules.language_model_heads.language_model_head import LanguageModelHead
@LanguageModelHead.register("linear")
class LinearLanguageModelHead(LanguageModelHead):
"""
Uses `torch.nn.Linear` as a language model head... | allennlp/tests/modules/language_model_heads/linear.py | Apache-2.0 | 1,316 | f959276580454aae5baebe60e904e76c2ab61d2b | Python | py | |
from comet_ml import Experiment
import copy
import glob
import os
import time
from collections import deque
import gym
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from a2c_ppo_acktr import algo
from a2c_ppo_acktr.arguments import get_args
from a2c... | main.py | MIT | 9,447 | 3a90ff88d4ccc0fbd34881cb6497681851117c2c | Python | py | |
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
"""
@Time : 2021-01-03 2:57
@Author : uyplayer
@Site : uyplayer.pw
@contact : uyplayer@qq.com
@File : BERT_tweets.py
@Software: PyCharm
"""
# https://pytorch.org/hub/huggingface_pytorch-transformers/
# https://huggingface.co/transformers/model_doc/bert.html#transfor... | src/BERT_tweets.py | MIT | 11,618 | 3a9120933726bf384fa23920675a8907b5f9f763 | Python | py | |
from typing import Tuple, Optional, Dict, List, Callable, Any, Union
from re import L
import logging
from logging import getLogger, StreamHandler, Formatter
import dataclasses
import torch
from torch import nn
from torch.nn import functional as F
from torch import Tensor
from torchtyping import TensorType
from .ca... | prompt2slip/base_attacker.py | MIT | 8,486 | 3a912b9285817fc9a3c012340fc7bfb7e24ebf38 | Python | py | |
import functools
import torch
import torch.nn as nn
from torch.nn import init
####################
# initialize
####################
def weights_init_normal(m, std=0.02):
classname = m.__class__.__name__
if isinstance(m, (nn.Conv2d, nn.ConvTranspose2d)):
if classname != "MeanShift":
pri... | networks/__init__.py | MIT | 5,201 | 3a913154075e70b3f42cbe565ccc481ee18f009a | Python | py | |
from torch import nn
class MNISTFeatureLayer(nn.Sequential):
def __init__(self, dropout_rate, shallow=False):
super().__init__()
self.shallow = shallow
if shallow:
self.add_module(
"conv1", nn.Conv2d(1, 64, kernel_size=15, padding=1, stride=5)
)
... | extract_layer.py | MIT | 2,286 | 3a913309d011a9cf7ccd473491ec86ad10214125 | Python | py | |
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
"""Assistant utility for automatically load network from network
description."""
import torch
class Assistant:
"""Assistant that bundles training, validation and testing workflow.
Parameters
----------
net : torch.nn.Mo... | src/lava/lib/dl/slayer/utils/assistant.py | BSD-3-Clause | 7,683 | 1058f0c39cf793e1bce0e9b61eccba0d8b66fe5f | Python | py | |
import json, os, random, math
import PIL
import torch
import numpy as np
import pickle as pkl
import torchvision.transforms as T
from torch.utils.data import Dataset, DataLoader
from models.SketchTransformer.models.utils import *
from .utils import resize_strokes
STROKE_DIMS = {'stroke-6':6, 'stroke-5':5, 'stroke-4'... | data/tuberlin_dataset.py | Apache-2.0 | 34,973 | fcbe7b42204120eac5681c56f89aca3e57b60625 | Python | py | |
from __future__ import annotations
import inspect
import logging
import os
import re
from collections import abc
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, TypeVar
import numpy as np
import pytorch_lightning as pl
import torch
from more_itertools import always_iterable
from omega... | gdmtl/utils.py | MIT | 5,480 | a99cb157b5f1dbc0f79ae57125ee8175a31b9cb0 | Python | py | |
from collections import namedtuple
from typing import Any, NamedTuple, Optional, Tuple
import opt_einsum
import torch
import torch.fx
from torch.fx.node import Node, map_aggregate
def einsum_shape(subscripts, *shapes):
Shaped = namedtuple('Shaped', ['shape'])
input_subscripts, output_subscript, _ = opt_eins... | opt_einsum_fx/_shape_prop.py | MIT | 3,888 | f980e9fb4304b24b5e619467e5995b4d54335abc | Python | py | |
from collections import defaultdict
from contextlib import contextmanager
import dataclasses
import datetime
from distutils.version import LooseVersion
import logging
from pathlib import Path
import time
from typing import ContextManager
from typing import Dict
from typing import List
from typing import Optional
from t... | muskit/train/reporter.py | Apache-2.0 | 19,051 | 12f42a14b6fa160115be6469ad6863f9795d2bdb | Python | py | |
import os
import random
import argparse
import torch
import torch.nn as nn
import numpy as np
import net as net
from utils import load_data
from sklearn.metrics import f1_score
import pdb
import pruning
import copy
from scipy.sparse import coo_matrix
import warnings
warnings.filterwarnings('ignore')
def run_fix_mask... | NodeClassification/main_pruning_imp_pretrain.py | MIT | 8,619 | 3a916bff667838c8a3753ecbf3eaa05aec94fae8 | Python | py | |
"""
Copyright (c) 2019-2020 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.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in w... | nncf/composite_compression.py | Apache-2.0 | 4,307 | 3a91785d5052255c6d3d138ef3d348ef7065418a | Python | py | |
r"""
.. _isingmodel_PyTorch:
3-qubit Ising model in PyTorch
==============================
.. meta::
:property="og:description": This demonstration uses the PyTorch interface of
PennyLane to optimize a 3-qubit Ising model.
:property="og:image": https://pennylane.ai/qml/_images/isingspins.png
.. relat... | demonstrations/tutorial_isingmodel_PyTorch.py | Apache-2.0 | 9,098 | d7c79221565545622441229c5da9800a37b953ba | Python | py | |
import os
import tqdm
import torch
import numpy as np
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
from data.dataset import ImageDataset
from torch.utils.data import DataLoader
from losses.loss import PerceptualLoss, ColorLoss, SSIMLoss, TotalVariationalLoss
class Trainer():
de... | src/training/trainer.py | MIT | 7,314 | 5eb0a6069725d287cb270055d65a3096d7dd6715 | Python | py | |
import numpy as np
import cv2
import torch
import scipy.misc
from torchvision import transforms
import torch.nn.functional as F
from scipy.ndimage import maximum_filter
from PIL import Image
from copy import deepcopy
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
def im_to_torch(img):
im... | AlphaPose/SPPE/src/utils/img.py | MIT | 15,446 | 3a919c7ada72458237f9a00220389584b95a10c0 | Python | py | |
from . import functional as F
from torch.nn import Module
from torch import Tensor
import torch
from torchtext.data.functional import load_sp_model
from torchtext.utils import get_asset_local_path
from torchtext.vocab import Vocab
from torchtext._torchtext import GPT2BPEEncoder as GPT2BPEEncoderPyBind, CLIPEncoder as C... | torchtext/transforms.py | BSD-3-Clause | 15,896 | 3a91af3963aef54521ab33e2360e03cc9fe96893 | Python | py | |
import torch
import torch.distributed as dist
import ignite.distributed as idist
from tests.ignite.distributed.utils import _sanity_check, _test_sync
def test_no_distrib(capsys):
assert idist.backend() is None
if torch.cuda.is_available():
assert idist.device().type == "cuda"
else:
asser... | tests/ignite/distributed/utils/test_serial.py | BSD-3-Clause | 1,763 | 3a91baa13fc1e8318ad3331df97f4a7e960d1866 | Python | py | |
#
# BSD 3-Clause License
#
# Copyright (c) 2017 xxxx
# All rights reserved.
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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 ... | built-in/PyTorch/Official/cv/image_classification/DenseNet169_ID0454_for_Pytorch/torchvision/datasets/video_utils.py | Apache-2.0 | 10,026 | e9550cfef2728a59e690f5ea51b841b7e1eee565 | Python | py | |
# Copyright 2022 The OFA-Sys Team.
# All rights reserved.
# This source code is licensed under the Apache 2.0 license
# found in the LICENSE file in the root directory.
import logging
import warnings
import torch
import numpy as np
from data import data_utils
from data.ofa_dataset import OFADataset
logger = loggin... | data/nlu_data/mnli_dataset.py | Apache-2.0 | 4,669 | 1e842c73a318f756eee0f64e8ae88b469ae81679 | 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.
''' Modified based on: https://github.com/erikwijmans/Pointnet2_PyTorch '''
from __future__ import (
division,
absolute_import,
w... | fairnr/clib/__init__.py | MIT | 15,165 | 702e5d669c206fb0441e61555e205e6dac66fdc4 | Python | py | |
import argparse
from collections import defaultdict
from typing import Any, Dict, List, Optional, Tuple
import pytorch_lightning as pl
import torch
from torch import Tensor
from torchvision import transforms
from firewood.common.backend import set_runtime_build
from firewood.common.types import INT
from firewood.mode... | firewood/trainer/gan/DCGAN.py | MIT | 8,648 | 3a91f3d28a8cb53fab7138597bed01c74638d2a3 | Python | py | |
import torch
import numpy as np
class MultiAgentStateWithDelay(object):
def __init__(self, device, args, env_state, prev_state=None, k=None):
"""
Create the state object that keeps track of the current state and GSO and history information
:param device: CUDA device to use with PyTorch
... | learner/state_with_delay.py | MIT | 2,419 | 3a91ffe5d1382f6a0d826288e775dbcd22b14a12 | Python | py | |
import torch
import torch.nn.functional as F
import numpy as np
import torch.nn as nn
import matplotlib.pyplot as plt
import cv2 as cv
import os
from torch.autograd import Variable
import colorsys
from skimage.measure import find_contours
from matplotlib.patches import Polygon
import random
import imageio
class Focal... | src/miscellaneous/utils.py | Apache-2.0 | 16,061 | 3a921be09de64327b488f28e7dbbf8eb73ce2bb2 | Python | py | |
'''
Passing all possible actions (centroids) into the value network
'''
import gym
import sys
import time
import numpy
import random
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')))
from common import utils_for_q_learning, buffer_class, utils
from common.nois... | rainbow/RBFDQN_dis.py | MIT | 23,448 | 3a9242c1aeb1b336bd65723b4345faeda3fbe1b8 | Python | py | |
import abc
import torch
import torch.nn as nn
import torch.nn.functional as F
from gym import Space
from habitat import Config
from habitat_baselines.rl.models.rnn_state_encoder import RNNStateEncoder
from habitat_baselines.rl.ppo.policy import Net
from vlnce_baselines.common.aux_losses import AuxLosses
from vlnce_ba... | vlnce_baselines/models/seq2seq_policy2.py | MIT | 8,586 | 12ba67f9ec8981664410c71e0a8497f90116e5b7 | Python | py | |
import sys
sys.path += ["../"]
import pandas as pd
from transformers import glue_compute_metrics as compute_metrics, glue_output_modes as output_modes, glue_processors as processors
from transformers import (
AdamW,
RobertaConfig,
RobertaForSequenceClassification,
RobertaTokenizer,
get_linear_schedu... | ance/drivers/run_warmup.py | MIT | 25,234 | 3a925f1a43f3a38a7c5176d24468e7db6d4071e4 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn.utils.rnn import pad_sequence
import numpy as np, itertools, random, copy, math
class MaskedNLLLoss(nn.Module):
def __init__(self, weight=None):
super(MaskedNLLLoss, self).__init__()
... | model_utils.py | Apache-2.0 | 15,291 | 12a01df15112c046f52d83e167403a76296b830f | Python | py | |
import math
import torch
import torch.nn as nn
from torch.distributions import Normal
from distributions.conditional import ConditionalDistribution
from utils import sum_except_batch
class ConditionalMeanNormal(ConditionalDistribution):
"""A multivariate Normal with conditional mean and fixed std."""
def _... | distributions/conditional/normal.py | Apache-2.0 | 3,489 | 3a92b021feddc88f005391ff29a15201e0a9784d | Python | py | |
import logging
from typing import Dict, Optional
import torch
from allennlp.data import TextFieldTensors, Vocabulary
from allennlp.models.model import Model
from allennlp.modules.transformer import (
TransformerEmbeddings,
ImageFeatureEmbeddings,
BiModalEncoder,
)
from allennlp.nn import util
from allen... | allennlp_models/vision/models/vilbert_vqa.py | Apache-2.0 | 4,852 | 7cc29e80e1ce438eab76d68c33618d9be63e749c | Python | py | |
from functools import partial
from typing import Any, List, Optional
import torch
from torch import nn
from torch.nn import functional as F
from ...transforms._presets import SemanticSegmentation
from .._api import WeightsEnum, Weights
from .._meta import _VOC_CATEGORIES
from .._utils import IntermediateLayerGetter, ... | torchvision/models/segmentation/deeplabv3.py | BSD-3-Clause | 14,110 | a961c4e0b2befd4436a39d881d939b11a11fb710 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets
from torchvision import transforms
from torchvision.utils import make_grid
from torchvision.utils import save_image
from torch.utils.data import DataLoader
import sys
import os
import ya... | sk_detector.py | MIT | 4,218 | fdd6cd56fd3abb9743d1c03f8e393bbc7bcff272 | Python | py | |
# Copyright 2021 Tomoki Hayashi
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""StyleMelGAN's TADEResBlock Modules.
This code is modified from https://github.com/kan-bayashi/ParallelWaveGAN.
"""
from functools import partial
import torch
class TADELayer(torch.nn.Module):
"""TADE Layer module."... | espnet2/gan_tts/style_melgan/tade_res_block.py | Apache-2.0 | 5,864 | 3a930466821099800f1ff2fc788f97314cf927c5 | Python | py | |
import time
import os
import matplotlib.pyplot as plt
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
parser = argparse.ArgumentParser()
parser.add_argument('--tol', type=float, default=1e-3)
parser.add_argument('--adjoint', type=eval, default=False)
parser.add_argume... | experiments/vdp_oscillator/vdp_anode.py | MIT | 6,229 | 3a931856c3c37cfe4437af8bc018c0e2d07360b9 | Python | py | |
import torch.nn as nn
from base.layers import Conv2dWithConstraint, LinearWithConstraint
from utils.utils import init_weight
class OneDCNN(nn.Module):
def __init__(self,
n_classes,
input_shape,
F1=None,
D=None,
F2=None,
... | models/OneDCNN_model.py | MIT | 1,685 | 3a93287ba0961193eecaa9232ef0c2a44245723d | Python | py | |
"""Pytorch impl of Gluon Xception
This is a port of the Gluon Xception code and weights, itself ported from a PyTorch DeepLab impl.
Gluon model: (https://gluon-cv.mxnet.io/_modules/gluoncv/model_zoo/xception.html)
Original PyTorch DeepLab impl: https://github.com/jfzhang95/pytorch-deeplab-xception
Hacked together by ... | timm_esam/models/gluon_xception.py | Apache-2.0 | 8,710 | 3a933eb59c09db14aae0e328466f45bf0cad45b4 | Python | py | |
# coding=utf-8
# Copyright 2020 The Facebook AI Research 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/LIC... | src/transformers/modeling_bart.py | Apache-2.0 | 59,527 | 3a936163dbb1d57f29a6ea15ee274f2d98b03101 | Python | py | |
#!/usr/bin/env python3
# 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.
#
import torch
import torch.nn as nn
import torch.nn.functional as F
from layers import convnet, co... | daqa-mod/malimo.py | CC-BY-4.0 | 11,200 | 8020e34bf540313e103a22036002dca71ac78b7f | Python | py | |
import logging
import time
import numpy as np
import torch
try:
from fedml_core.trainer.model_trainer import ModelTrainer
except ImportError:
from FedML.fedml_core.trainer.model_trainer import ModelTrainer
from .utils import SegmentationLosses, Evaluator, LR_Scheduler, EvaluationMetricsKeeper
class MyModel... | fedml_api/distributed/fedseg/MyModelTrainer.py | Apache-2.0 | 5,787 | 3a9368fdbc69146248b24939f9b6566a22326fce | Python | py | |
# MODELNET40 CLASSIFICATION WITH DECLARATIVE ROBUST POOLING NODES
# Dylan Campbell <dylan.campbell@anu.edu.au>
# Stephen Gould <stephen.gould@anu.edu.au>
#
# Modified from PyTorch PointNet code:
# https://github.com/yanx27/Pointnet_Pointnet2_pytorch/tree/31deedb10b85ec30178df57a6389b2f326f7c970
import torch
import tor... | apps/classification/pointcloud/pointnet.py | MIT | 12,975 | fcc5a9d047f02c17c38c4a6da09aa1e7e7c1f287 | Python | py | |
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
import math
import numpy as np
from typing import Dict, List, Tuple
import torch
from fvcore.nn import giou_loss, sigmoid_focal_loss_jit, smooth_l1_loss
from torch import Tensor, nn
from torch.nn import functional as F
from detectron2.config import conf... | detectron2/modeling/meta_arch/retinanet.py | Apache-2.0 | 26,564 | 103f1ab950d9925e17a91da3debd5c2afb61de7d | Python | py | |
import sys
import os
import time
import math
import torch
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import itertools
import struct # get_image_size
import imghdr # get_image_size
def sigmoid(x):
return 1.0/(math.exp(-x)+1.)
def softmax(x):
x = torch.exp(x - torch.max(x))
x = x/x.sum()... | utils.py | MIT | 17,097 | 3a939a4e694ad0409825e892b78d555b55f4b9b8 | Python | py | |
# -*- coding: utf-8 -*- #
"""*********************************************************************************************"""
# FileName [ dataloader.py ]
# Synopsis [ Datasets for transformer pre-training and downstream task supervised training ]
# Author [ Andy T. Liu (Andi611) ]
# Copyright ... | dataloader.py | MIT | 35,706 | 3a93a6f2c1ae94960279bde7fd9bad2e697cb1de | Python | py | |
import matplotlib.pyplot as plt
import numpy as np
import torch
from scipy.stats import friedmanchisquare
from sklearn.metrics import roc_curve, auc, roc_auc_score, classification_report
NAME_MODEL_LOSS = 'gender_2_0_loss_D_0__A_relu__P_mean__CS_entire__CHC_8__FS_True__GCN_False__GAT_False_0.0001_0.005_20_5_roi_norm_... | post_analysis/plots.py | Apache-2.0 | 23,867 | 705c77bd4b96cd711f89919922cfc21633a87f6d | Python | py | |
import os
import sys
import time
from copy import deepcopy
import numpy as np
import torch
from torch import nn
import goalrepresent as gr
from goalrepresent import dnn
from goalrepresent.helper import tensorboardhelper
""" =============================================================================================... | goalrepresent/models/clr.py | MIT | 11,494 | 3a93bf85e97611be873145e0eed749d52e69eb25 | Python | py | |
import numpy as np
import torch
import torch.nn as nn
import torchvision
import pandas as pd
import matplotlib.pyplot as plt
import torch.nn.functional as F
from sklearn import metrics
import torchvision.transforms as transforms
class AE_PIMA(nn.Module):
def __init__(self, **kwargs):
super().__init__()
In_... | Network/PIMANet.py | MIT | 1,320 | 3a93c934ca79c18441f41a3e3c852273ba40302e | Python | py | |
import functools
import torch.nn as nn
from vqgan.modules.util import ActNorm
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find('BatchNorm') != -1:
nn.init.normal_(m.weight.data, 1.0, 0.02)... | ReFit/modules/discriminator/model.py | MIT | 2,549 | 7cb612d3917983e1357a5562f0a7b2c95f2e86d1 | Python | py | |
import gc
import os
from typing import List, Union
import cv2
import numpy as np
import torch
from detectron2.checkpoint import DetectionCheckpointer
from detectron2.config import CfgNode
from detectron2.data.transforms import apply_transform_gens
from detectron2.modeling import build_model
from tqdm import tqdm
from... | resin_bubble/predict.py | MIT | 6,653 | 3a93fabd4dfb5a2680c55809fb507c4cff8ae143 | Python | py | |
import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torchvision
from torchvision import datasets, transforms
import os
import os.path
from collections import OrderedDict
import matplotlib.pyplot as plt
import numpy as np
import sea... | main_cifar100_affine_f.py | MIT | 18,805 | ff2c0abe2ff51070efa9c36416fc400dd389c674 | Python | py | |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import argparse
import logging
import random
import numpy as np
import torch
import torch.nn as nn
from dataloader import get_imagenet_iter_dali
from nni.nas.pytorch.fixed import apply_fixed_architecture
from nni.nas.pytorch.utils import Average... | examples/nas/spos/scratch.py | MIT | 5,579 | 3a944a790969ed537f05c5fb24aa93d5aef0b9ed | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .clf_base import Net as _Net
class Net(_Net):
def __init__(self, n_classes=10, d_key=-1, use_fixed_layer=False):
super().__init__(n_classes, 256, d_key, use_fixed_layer)
self.conv = nn.Sequential(
nn.Conv2d(1, 32,... | key-protected-classification-master/src/networks/clf_mnist.py | MIT | 512 | 3a94550532421a4411a1840710b172473e0da02a | Python | py | |
import pytest
import torch
from mmpose.models import CPM
def test_cpm_backbone():
with pytest.raises(AssertionError):
# CPM's num_stacks should larger than 0
CPM(in_channels=3, out_channels=17, num_stages=-1)
with pytest.raises(AssertionError):
# CPM's in_channels should be 3
... | tests/test_backbones/test_cpm.py | Apache-2.0 | 1,248 | 3a9481539a0484a0b56f7ad6f608a2a5aa63b9e1 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import math
import random
from dataset import START, PAD
class CNN(nn.Module):
def __init__(self, nc, leakyRelu=False):
super(CNN, self).__init__()
ks = [3, 3, 3, 3, 3, 3, 2]
ps = [1, 1, 1, 1, 1, 1, 0]
... | networks/Attention.py | MIT | 9,867 | dfe183663e98bd596df0e611e136dec270b01186 | Python | py | |
import os, argparse, codecs, glob
import torch
import numpy as np
from pretrained_model import Pretrained_Model_for_Sent
from distiller import Distiller
from sts_unsupervised import STS12Eval, STS13Eval, STS14Eval, STS15Eval, STS16Eval, STS17Eval
from util import Cosine
from scipy.stats import spearmanr, pearsonr
impor... | src/eval_sts.py | MIT | 7,222 | 3a94b448e9d6d83463e33888d2f453df8479f8b5 | Python | py | |
# ***************************************************************
# Copyright (c) 2020 Jittor. Authors:
# Dun Liang <randonlang@gmail.com>.
# Meng-Hao Guo <guomenghao1997@gmail.com>
#
# All Rights Reserved.
# This file is subject to the terms and conditions defined in
# file 'LICENSE.txt', which is part of this sou... | python/jittor/__init__.py | Apache-2.0 | 21,589 | 3a94bed082733c37da8257a784831c3512b9fded | Python | py | |
import inspect
from collections import defaultdict
import torch
from fastNLP import Vocabulary
from fastNLP import seq_len_to_mask
from fastNLP.core.metrics import MetricBase
from myClue.core import logger
def _get_func_signature(func):
"""
Given a function or method, return its signature.
For example... | myClue/core/metrics.py | Apache-2.0 | 9,173 | 65207ff9e041c4c6c350661349cc8915e4c40cda | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
__all__ = ["transI_fusebn", "transII_addbranch", "transIII_1x1_kxk",
"transIV_depthconcat", "transV_avg", "transVI_multiscale", "DBBORIGIN", "DBB1x1", "DBBAVG", "DBB1x1kxk"]
#######################
# auxiliary operation ... | hyperbox/networks/repnas/rep_ops.py | MIT | 9,632 | 3a94d4da918511411e97ba0e31ee1ae05970d4b8 | Python | py | |
# Copyright 2021 MosaicML. All Rights Reserved.
"""ADE20K Semantic segmentation and scene parsing dataset.
Please refer to the `ADE20K dataset <https://groups.csail.mit.edu/vision/datasets/ADE20K/>`_ for more details about this
dataset.
"""
import os
from dataclasses import dataclass
from math import ceil
from typin... | composer/datasets/ade20k.py | Apache-2.0 | 23,776 | 1e1ea4f48a2fe1c972e20c1e64c908b4684222dc | Python | py | |
import time
import unittest
import plaidml.bridge.pytorch as plaidml_pytorch
import torch
def printf(*args, **kwargs):
print(*args, **kwargs, flush=True)
class TestBase(unittest.TestCase):
def _run_jit(self, func, inputs):
with torch.no_grad():
trace_jit = torch.jit.trace(func, inputs)... | plaidml/bridge/pytorch/test_utils.py | Apache-2.0 | 2,683 | 3a94f01ff20f3d950a9f7ef5680f584da704a6e6 | Python | py | |
import os
import warnings
import numpy as np
import paddle.fluid as fluid
import torch
import torch.nn.functional as F
from paddle.fluid.dygraph import BatchNorm, Conv2D, Linear
from paddletools import logger
from paddletools.checkpoints import (dynamic2static, static2dynamic,
torc... | test/demo.py | MIT | 5,325 | 3a94f17ca9220b4456d5b7ea934f707f5d793505 | Python | py | |
import torch
from facenet_pytorch import MTCNN
import pickle
from torchvision import transforms
from torchvision.datasets import ImageFolder
#from classifiers.VGGFace2.VGGFace2Classifier import VGGFace2Classifier
from classifiers.VGGFace2.inception_resnet import InceptionResnetV1
# This is for normal pretrained mode... | classifiers/VGGFace2/check_accuracy.py | MIT | 2,220 | fdf03ffb8bb2ac736218ba53c43676c7e1d4f8e0 | Python | py | |
import torch
import torch.nn as nn
from mmcv.cnn import normal_init
from mmdet.core import distance2bbox, force_fp32, multi_apply, multiclass_nms
from ..builder import build_loss
from ..registry import HEADS
from ..utils import ConvModule, Scale, bias_init_with_prob
from IPython import embed
INF = 1e8
@HEADS.registe... | mmdet/models/anchor_heads/box_coding_iou_head.py | Apache-2.0 | 23,376 | 3a9521acbc0da94a54696f3831323075a64565a2 | Python | py | |
from pathlib import Path
from PIL import Image
from torch.utils import data
from torchvision import datasets
from dataset.utils import get_raw_data_dir
class OfficeCaltech10(data.Dataset):
def __init__(self, domain, transform=None, target_transform=None):
self.raw_data_dir = (
get_raw_data_dir()
... | dataset/da/office_caltech_10.py | MIT | 899 | f9a1c58924a2a17fe254f6f6249a592fe7d30476 | Python | py | |
import torch.nn as nn
import torch
import torch.utils.checkpoint as cp
from mmcv.cnn import (build_conv_layer, build_norm_layer, build_plugin_layer,
constant_init, kaiming_init)
from mmcv.runner import load_checkpoint
from torch.nn.modules.batchnorm import _BatchNorm
from mmdet.utils import get_r... | mmdet/models/backbones/resnet_se.py | Apache-2.0 | 23,509 | 80066d49db987c26bfe1f1b88b1b3d02ed953ac1 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import BertPreTrainedModel, BertModel
class GATLayer(nn.Module):
def __init__(self, in_features, out_features, dropout, alpha, concat=True, get_att=False):
super(GATLayer, self).__init__()
self.in_features = in_fe... | models/sesy.py | MIT | 8,111 | 29f966b3033277a32a22fbff42a15d1ee99f6bc9 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
import torchvision.models as models
import copy
# create a module to normalize input image so we can easily put it in a
# ... | models/stylized.py | MIT | 6,560 | 1e76917c6340c486628f1d781c7609423136ccf6 | Python | py | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# import cv2
import matplotlib.pyplot as plt
import numpy as np
import torch
import torchvision.transforms as T
from PIL import Image
# cv2.setNumThreads(0)
__author__ = 'cnheider'
resize = T.Compose([T.ToPILImage(), T.Resize(40, interpolation=Image.CUBIC), T.ToTensor()... | utilities/transformation/extraction.py | Apache-2.0 | 1,814 | 3a9552eea0b960b90edb047553d2f4a5f45badbd | Python | py | |
"""
This module contains a Trainer class for quickly and easily building
VAE or FeedForward property predictors from the extracted structural protein
features.
"""
import time
import os
import sys
import copy
import torch
import torch.nn as nn
import torch.utils.data
import torch.optim as optim
import numpy as np
impor... | cnns4qspr/trainer_func.py | MIT | 25,763 | 3a9567bc011fdf2a74703fbf341495f0f71352c5 | Python | py | |
import ipdb
import torch
import torch.nn as nn
from torch.nn import functional as F
import numpy as np
def center_crop(x, height, width):
crop_h = torch.FloatTensor([x.size()[2]]).sub(height).div(-2)
crop_w = torch.FloatTensor([x.size()[3]]).sub(width).div(-2)
# fixed indexing for PyTorch 0.4
return ... | models/dsam_layers.py | MIT | 2,517 | 7ca8b613e9df3da549ad67e36f9f71edd699711c | Python | py | |
from matplotlib.pyplot import sci
from numpy.core.numeric import ones_like
from numpy.ma.core import asarray
import scipy, numpy as np
import scipy.interpolate
from scipy.optimize import LinearConstraint, minimize, Bounds, NonlinearConstraint
import torch
from torch import Tensor
import scipy.sparse
import time
np.se... | deepracing_py/deepracing/path_utils/optimization.py | Apache-2.0 | 9,772 | 4b0d3ff4649b736bad0c5aedf9033481df88dbc9 | Python | py | |
from __future__ import print_function
import numpy as np
import os
import time
from PIL import Image, ImageFont, ImageDraw
from copy import deepcopy
import argparse
import os
import random
import sys
import pprint
import datetime
import dateutil.tz
import time
import torch
import torch.backends.cudnn as cudnn
import ... | gan/test.py | MIT | 5,812 | 3a959d78d7d1d4eddf3d5358337bfa762ad00a74 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = ['NonLocalBlock', 'GCA_Channel', 'GCA_Element', 'AGCB_Element', 'AGCB_Patch', 'CPM']
class NonLocalBlock(nn.Module):
def __init__(self, planes, reduce_ratio=8):
super(NonLocalBlock, self).__init__()
inter_planes = plan... | models/context.py | MIT | 12,225 | 3a95ae559435a30a68aba572eee4bea130369136 | Python | py | |
import torch
import torch.nn as nn
class Bert_Spc_Lay(nn.Module):
def __init__(self, bert, opt):
super(Bert_Spc_Lay, self).__init__()
self.opt = opt
self.bert = bert
self.dropout = nn.Dropout(opt.dropout)
layers = [nn.Linear(
opt.bert_dim*3, opt.bert_dim), nn.Re... | models/bert_spc_lay.py | MIT | 1,089 | 343fbac62946cd88a1573da25bb4a78a1ecde23d | Python | py | |
import torch
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision import transforms
from dataset.tupac_dataset import TUPACDataset
from torchvision.transforms import Compose
from tqdm import tqdm
from postprocessing.evaluator import Evaluator
from utils import abs_path, argmax
... | inference/tupac.py | MIT | 2,645 | 4b15eaa734ae3795aaa1b1bd5e9b7a5bcd9ad8e1 | Python | py | |
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from modules.word_embedding import WordEmbedding
from modules.aggregator_predict import AggPredictor
from modules.selection_predict import SelPredictor
from modules.sqlnet_condition_pred... | sqlnet/model/sqlnet.py | BSD-3-Clause | 18,153 | e99dcd2235707a11675af50b507cb88f5920b7c7 | Python | py | |
import torch
import torch.nn as nn
import torch.nn.functional as F
from seq2seq import utils
from seq2seq.models import Seq2SeqModel, Seq2SeqEncoder, Seq2SeqDecoder
from seq2seq.models import register_model, register_model_architecture
@register_model('lstm')
class LSTMModel(Seq2SeqModel):
""" Defines the sequen... | seq2seq/models/lstm.py | MIT | 16,884 | 3a960a3b8c5350a39abfb94a877690425e8e27c4 | Python | py | |
"""
A script which prints the training data according to the given sample index.
Note, that it's crucial that exactly the same corresponding arguments are passed as in the training script. Including the seed. Only then the random sequence from the generated by megatron .npy files will match.
Here is how to decipher t... | tools/sample_idxs_to_text.py | MIT | 6,363 | ff35e19f51004a9a79385b96376a6592206cc190 | Python | py | |
import torch
import numpy
sample_prob = torch.FloatTensor(6).uniform_(0, 1)
sample_mask = sample_prob < 0.2
a = sample_mask.nonzero()
print(sample_mask)
b = numpy.array([[[5,6,4,1],
[7,8,3,2],
[1,2,1,3]]])
c = numpy.array([[[5],[6],[7]]])
x = torch.tensor([[3,3],[3,3]])
y = b*c #x.do... | test.py | MIT | 673 | 7c4d627a84e57390b31d0eaf26f5309d669c0de0 | Python | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.