repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
pyGPCCA | pyGPCCA-main/docs/source/conf.py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
from pathlib import Path
from datetime import datetime
import os
# -- Path setup -----... | 4,539 | 32.382353 | 211 | py |
EVA | EVA-main/src/arguments.py | # coding=utf-8
"""argparser configuration"""
import argparse
import os
import torch
import deepspeed
def add_model_config_args(parser: argparse.ArgumentParser):
"""Model arguments"""
group = parser.add_argument_group("model", "model configuration")
group.add_argument("--model-config", type=str,
... | 9,826 | 45.13615 | 126 | py |
EVA | EVA-main/src/learning_rates.py | # coding=utf-8
import torch
from torch.optim.lr_scheduler import _LRScheduler
import math
class AnnealingLR(_LRScheduler):
"""Anneals the learning rate from start to zero along a cosine curve."""
DECAY_STYLES = ['linear', 'cosine', 'exponential', 'constant', 'None', 'noam']
def __init__(self, optimizer... | 2,860 | 40.463768 | 176 | py |
EVA | EVA-main/src/utils.py | # coding=utf-8
"""Utilities for logging and serialization"""
import os
import random
import numpy as np
import torch
import mpu
import deepspeed
def print_rank_0(message):
if torch.distributed.is_initialized():
if torch.distributed.get_rank() == 0:
print(message, flush=True)
else:
... | 5,109 | 30.158537 | 221 | py |
EVA | EVA-main/src/eva_finetune.py | # coding=utf-8
"""Finetune EVA"""
import os
import json
import torch
import mpu
import torch.distributed as dist
from torch.utils.data import DataLoader, SequentialSampler
from arguments import get_args
from tokenization_eva import EVATokenizer
from utils import save_checkpoint, load_checkpoint
from utils import p... | 19,465 | 37.394477 | 160 | py |
EVA | EVA-main/src/generation_utils.py | # coding=utf-8
import os
import torch
import mpu
import torch.nn.functional as F
from collections import defaultdict
from tokenization_eva import EVATokenizer
class BeamHypotheses(object):
def __init__(self, num_beams, max_length, length_penalty, early_stopping, tokenizer=None):
"""
Initialize ... | 25,763 | 42.52027 | 146 | py |
EVA | EVA-main/src/change_mp.py | import sys
import os
import torch
import copy
import tqdm
def merge(model_parts):
print("Merging Model")
if len(model_parts) == 1:
return model_parts[0]
new_model = {}
for k, v in model_parts[0].items():
assert len(v.size()) < 3
if len(v.shape) == 2 and "role_embeds.weight... | 4,790 | 35.022556 | 149 | py |
EVA | EVA-main/src/eva_interactive.py | # coding=utf-8
"""Inference EVA"""
import os
import torch
import torch.nn.functional as F
from arguments import get_args
from utils import load_checkpoint
from tokenization_eva import EVATokenizer
import mpu
import deepspeed
import torch.distributed as dist
from model import EVAModel, EVAConfig
from fp16 import FP16_... | 7,740 | 29.718254 | 133 | py |
EVA | EVA-main/src/samplers.py | # coding=utf-8
import torch
from torch.utils import data
class RandomSampler(data.sampler.Sampler):
"""Based off of pytorch RandomSampler and DistributedSampler. Essentially
a RandomSampler, but this class lets the user set an epoch like
DistributedSampler Samples elements randomly. If without replacemen... | 5,243 | 39.030534 | 78 | py |
EVA | EVA-main/src/eva_datasets.py | # coding=utf-8
"""Datasets of EVA"""
import os
import pickle
import torch
import torch.distributed as dist
from tqdm import tqdm
from torch.utils.data import Dataset
from tokenization_eva import EVATokenizer
from utils import print_rank_0, save_rank_0
class EVADataset(Dataset):
def __init__(self, args, tokeniz... | 5,212 | 41.040323 | 168 | py |
EVA | EVA-main/src/fp16/fp16util.py | # coding=utf-8
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
import mpu
class tofp16(nn.Module):
"""
Utility module that implements::
def forward(self, input):
return input.half()
"""
... | 7,071 | 35.833333 | 337 | py |
EVA | EVA-main/src/fp16/loss_scaler.py | # coding=utf-8
import torch
import mpu
# item() is a recent addition, so this helps with backward compatibility.
def to_python_float(t):
if hasattr(t, 'item'):
return t.item()
else:
return t[0]
class LossScaler:
"""
Class that manages a static loss scale. This class is intended to in... | 9,166 | 39.742222 | 326 | py |
EVA | EVA-main/src/fp16/fp16.py | # coding=utf-8
"""Stable version of apex FP16 Optimizer"""
import torch
from torch import nn
from torch.autograd import Variable
from torch.nn.parameter import Parameter
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from .loss_scaler import DynamicLossScaler, LossScaler
from .fp16util imp... | 31,110 | 49.179032 | 437 | py |
EVA | EVA-main/src/ds_fix/engine.py | '''
Copyright 2019 The Microsoft DeepSpeed Team
'''
import os
import time
import torch
import warnings
import torch.distributed as dist
from torch.nn.modules import Module
from torch.distributed.distributed_c10d import _get_global_rank
from tensorboardX import SummaryWriter
from deepspeed.runtime.zero.stage2 import ... | 62,693 | 40.740346 | 227 | py |
EVA | EVA-main/src/ds_fix/stage1.py | import math
import torch
import torch.distributed as dist
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from collections import defaultdict
from deepspeed.runtime.zero.utils import _initialize_parameter_parallel_groups
from deepspeed.runtime.fp16.loss_scaler import LossScaler, DynamicLossSc... | 52,782 | 45.79344 | 155 | py |
EVA | EVA-main/src/mpu/mappings.py | # coding=utf-8
import torch
from .initialize import get_model_parallel_group
from .utils import split_tensor_along_last_dim
def _reduce(input_):
"""All-reduce the the input tensor across model parallel group."""
group = get_model_parallel_group()
# Bypass the function if we are using only 1 GPU.
if... | 3,526 | 26.341085 | 76 | py |
EVA | EVA-main/src/mpu/initialize.py | # coding=utf-8
"""Model and data parallel groups."""
import torch
from .utils import ensure_divisibility
# Model parallel group that the current rank belongs to.
_MODEL_PARALLEL_GROUP = None
# Data parallel group that the current rank belongs to.
_DATA_PARALLEL_GROUP = None
def initialize_model_parallel(model_pa... | 4,272 | 34.02459 | 77 | py |
EVA | EVA-main/src/mpu/cross_entropy.py | # coding=utf-8
import torch
from .initialize import get_model_parallel_group
from .initialize import get_model_parallel_rank
from .initialize import get_model_parallel_world_size
from .utils import VocabUtility
class _VocabParallelCrossEntropy(torch.autograd.Function):
@staticmethod
def forward(ctx, vocab_... | 4,105 | 41.770833 | 80 | py |
EVA | EVA-main/src/mpu/utils.py | # coding=utf-8
import torch
def ensure_divisibility(numerator, denominator):
"""Ensure that numerator is divisible by the denominator."""
assert numerator % denominator == 0, '{} is not divisible by {}'.format(
numerator, denominator)
def divide(numerator, denominator):
"""Ensure that numerator... | 2,100 | 35.859649 | 80 | py |
EVA | EVA-main/src/mpu/data.py | # coding=utf-8
import torch
from .initialize import get_model_parallel_group
from .initialize import get_model_parallel_rank
from .initialize import get_model_parallel_src_rank
_MAX_DATA_DIM = 7
def _check_data_types(keys, data, target_dtype):
"""Check that all the keys have the same target data type."""
... | 1,789 | 28.344262 | 80 | py |
EVA | EVA-main/src/mpu/grads.py | # coding=utf-8
import torch
from torch._six import inf
from .initialize import get_model_parallel_group
from .initialize import get_model_parallel_rank
def clip_grad_norm(parameters, max_norm, norm_type=2):
"""Clips gradient norm of an iterable of parameters.
This is adapted from torch.nn.utils.clip_grad.c... | 2,309 | 39.526316 | 79 | py |
EVA | EVA-main/src/mpu/layers.py | # coding=utf-8
import torch
import torch.nn.functional as F
import torch.nn.init as init
from torch.nn.parameter import Parameter
from .initialize import get_model_parallel_rank
from .initialize import get_model_parallel_world_size
from .mappings import copy_to_model_parallel_region
from .mappings import gather_from_... | 12,692 | 40.345277 | 80 | py |
EVA | EVA-main/src/mpu/transformer.py | # coding=utf-8
"""Encoder-Decoder Model"""
import math
import torch
import torch.nn as nn
import deepspeed
from .initialize import get_model_parallel_world_size
from .layers import ColumnParallelLinear
from .layers import RowParallelLinear
from .random import checkpoint
from .random import get_cuda_rng_tracker
fr... | 33,790 | 41.773418 | 179 | py |
EVA | EVA-main/src/mpu/random.py | # coding=utf-8
import contextlib
import torch.distributed as dist
import torch
from torch import _C
from torch.cuda import _lazy_call, device as device_ctx_manager
import torch.distributed as dist
PARTITION_ACTIVATIONS = False
PA_CORRECTNESS_TEST= False
def see_memory_usage(message, force=False):
if not force:
... | 13,751 | 36.57377 | 151 | py |
EVA | EVA-main/src/model/distributed.py | # coding=utf-8
import torch
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
import torch.distributed as dist
from torch.nn.modules import Module
from torch.autograd import Variable
import mpu
class DistributedDataParallel(Module):
def __init__(self, module):
super(DistributedD... | 4,286 | 42.30303 | 103 | py |
EVA | EVA-main/src/model/eva_modeling.py | # coding=utf-8
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
import mpu
from .configuration_eva import EVAConfig
def init_method_normal(std):
"""Init method based on normal distribution.
This is only used for embeddings. The transformer has its
own initializer.
"""... | 4,392 | 33.865079 | 144 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/utils.py | import os
import random
import torch
import numpy as np
from time import time
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
class ConfusionMatrix():
def __init__(self, n_classes):
self.n_classes = n_classes
self.mat = np.zeros([n_classes, n_classes])
def update_mat... | 4,423 | 26.141104 | 72 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/test_extractor_pa_vit_prefix.py | """
This code allows you to evaluate performance of a single feature extractor + pa with NCC
on the test splits of all datasets (ilsvrc_2012, omniglot, aircraft, cu_birds, dtd, quickdraw, fungi,
vgg_flower, traffic_sign, mscoco, mnist, cifar10, cifar100).
To test the url model on the test splits of all datasets, run... | 5,560 | 38.439716 | 176 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/models/tsa.py | '''
tsa.py
Created by Wei-Hong Li [https://weihonglee.github.io]
This code allows you to attach task-specific parameters, including adapters, pre-classifier alignment (PA) mapping
from 'Universal Representation Learning from Multiple Domains for Few-shot Classification'
(https://arxiv.org/pdf/2103.13841.pdf), to a pret... | 6,286 | 37.335366 | 132 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/models/cka.py | """
This code allows you to computing CKA (https://arxiv.org/abs/1905.00414) similarity using pytorch.
The code is adapted from https://github.com/yuanli2333/CKA-Centered-Kernel-Alignment
"""
import math
import numpy as np
import torch
def centering(K):
n = K.size(0)
unit = torch.ones(n,n).cuda()
I = torc... | 1,545 | 28.169811 | 98 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/models/losses.py | import torch
import gin
import numpy as np
from torch import nn
import torch.nn.functional as F
from models.cka import linear_CKA, kernel_CKA
from sklearn.linear_model import LogisticRegression
from sklearn import svm
from sklearn.svm import SVC, LinearSVC
from sklearn.pipeline import make_pipeline
from sklearn import... | 8,896 | 40 | 128 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/models/adaptors.py | """
This code allows you to use adaptors for aligning features
between multi-domain learning network and single domain learning networks.
The code is adapted from https://github.com/VICO-UoE/KD4MTL.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import pdb
class adaptor(torch.nn.Module):
... | 1,776 | 29.118644 | 98 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/models/vit_dino.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | 18,105 | 38.190476 | 141 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/models/model_utils.py | import os
import torch
import shutil
import numpy as np
from torch import nn
from torch.optim.lr_scheduler import (MultiStepLR, ExponentialLR,
CosineAnnealingWarmRestarts,
CosineAnnealingLR)
from utils import check_dir, device
sigmoid = nn.Si... | 9,260 | 39.797357 | 97 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/models/utils.py | import yaml
import copy
import pickle
import shutil
import argparse
import json
from os import environ
from pathlib import Path
from ast import literal_eval
from typing import Any, List, Tuple, Union, cast
import torch
import numpy as np
import matplotlib.pyplot as plt
import torch.nn.functional as F
import torch.dist... | 16,801 | 29.003571 | 120 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/models/scm.py | # This code is adapted from https://github.com/peymanbateni/simple-cnaps
import torch
import torch.nn as nn
from collections import OrderedDict
import torch.nn.functional as F
import numpy as np
NUM_SAMPLES=1
def scm(context_features, context_labels, target_features):
class_representations = OrderedDict() # Dic... | 6,532 | 48.120301 | 156 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/models/model_helpers.py | import os
import gin
import torch
from functools import partial
from models.model_utils import CheckPointer
from models.models_dict import DATASET_MODELS_RESNET18
from utils import device
def get_model(num_classes, args):
train_classifier = args['model.classifier']
model_name = args['model.backbone']
dro... | 6,498 | 39.61875 | 108 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/models/pa_prefix.py | import torch
import numpy as np
import math
import torch.nn.init as init
import torch.nn as nn
import torch.optim as optim
from models.model_utils import sigmoid, cosine_sim
from models.losses import prototype_loss
from utils import device
import torch.nn.functional as F
from torchvision import transforms
import cv2
... | 5,576 | 38.274648 | 190 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/pretrain_code_snippet/dataset.py | from torch.utils.data import Dataset
import json
from torchvision.datasets import ImageFolder
import sys
import torch
from ft_util.datasets import build_dataset, build_transform
from torchvision import transforms
import PIL.Image as Image
import numpy as np
class FilterDataset(Dataset):
def __init__(self, dataset,... | 2,522 | 31.346154 | 134 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/pretrain_code_snippet/main_dino_metadataset.py | # Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... | 23,354 | 47.354037 | 114 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/data/lmdb_dataset.py | import os
import torch
import random
import numpy as np
from tqdm import tqdm
import lmdb
import pickle as pkl
from utils import SerializableArray, device
from paths import META_DATA_ROOT
class LMDBDataset:
"""
Opens several LMDB readers and loads data from there
"""
def __init__(self, extractor_doma... | 5,515 | 33.691824 | 106 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/data/meta_dataset_reader.py | import os
import gin
import sys
import torch
import numpy as np
import tensorflow as tf
from utils import device
from paths import META_DATASET_ROOT, META_RECORDS_ROOT, PROJECT_ROOT
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # Quiet the TensorFlow warnings
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) ... | 14,288 | 42.831288 | 186 | py |
eTT_TMLR2022 | eTT_TMLR2022-main/data/create_features_db.py | import os
import sys
import torch
import numpy as np
import tensorflow as tf
from tqdm import tqdm
import json
import lmdb
import pickle as pkl
sys.path.insert(0, '/'.join(os.path.realpath(__file__).split('/')[:-2]))
from data.meta_dataset_reader import MetaDatasetEpisodeReader, MetaDatasetBatchReader
from models.mo... | 4,809 | 40.111111 | 99 | py |
HRNet-Semantic-Segmentation | HRNet-Semantic-Segmentation-master/tools/test.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
import argparse
import os
import pprint
import shutil... | 4,462 | 30.878571 | 80 | py |
HRNet-Semantic-Segmentation | HRNet-Semantic-Segmentation-master/tools/train.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
import argparse
import os
import pprint
import shutil... | 9,247 | 36.901639 | 80 | py |
HRNet-Semantic-Segmentation | HRNet-Semantic-Segmentation-master/lib/core/function.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
import logging
import os
import time
import numpy as... | 6,245 | 34.691429 | 80 | py |
HRNet-Semantic-Segmentation | HRNet-Semantic-Segmentation-master/lib/core/criterion.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
import torch
import torch.nn as nn
from torch.nn impo... | 2,385 | 40.137931 | 80 | py |
HRNet-Semantic-Segmentation | HRNet-Semantic-Segmentation-master/lib/models/seg_hrnet.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
from __future__ import absolute_import
from __future_... | 18,630 | 37.100204 | 93 | py |
HRNet-Semantic-Segmentation | HRNet-Semantic-Segmentation-master/lib/models/sync_bn/inplace_abn/functions.py | from os import path
import torch.autograd as autograd
import torch.cuda.comm as comm
from torch.autograd.function import once_differentiable
from torch.utils.cpp_extension import load
_src_path = path.join(path.dirname(path.abspath(__file__)), "src")
_backend = load(name="inplace_abn",
extra_cflags=["... | 8,605 | 32.486381 | 104 | py |
HRNet-Semantic-Segmentation | HRNet-Semantic-Segmentation-master/lib/models/sync_bn/inplace_abn/bn.py | import os, sys
import torch
import torch.nn as nn
import torch.nn.functional as functional
try:
from queue import Queue
except ImportError:
from Queue import Queue
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, '../src'))
from functions i... | 6,947 | 37.815642 | 112 | py |
HRNet-Semantic-Segmentation | HRNet-Semantic-Segmentation-master/lib/datasets/base_dataset.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
import os
import cv2
import numpy as np
import rando... | 8,251 | 39.058252 | 80 | py |
HRNet-Semantic-Segmentation | HRNet-Semantic-Segmentation-master/lib/datasets/cityscapes.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
import os
import cv2
import numpy as np
from PIL imp... | 8,108 | 39.343284 | 80 | py |
HRNet-Semantic-Segmentation | HRNet-Semantic-Segmentation-master/lib/datasets/pascal_ctx.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# Referring to the implementation in
# https://github.com/zhanghang1989/PyTorch-Encoding
# -------------------------------------------... | 5,021 | 35.656934 | 80 | py |
HRNet-Semantic-Segmentation | HRNet-Semantic-Segmentation-master/lib/datasets/lip.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
import os
import cv2
import numpy as np
import torc... | 5,050 | 36.414815 | 80 | py |
HRNet-Semantic-Segmentation | HRNet-Semantic-Segmentation-master/lib/utils/utils.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
from __future__ import absolute_import
from __future_... | 4,233 | 30.132353 | 80 | py |
HRNet-Semantic-Segmentation | HRNet-Semantic-Segmentation-master/lib/utils/modelsummary.py | # ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# Modified by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
from ... | 4,817 | 34.688889 | 120 | py |
PSENet-Image-Enhancement | PSENet-Image-Enhancement-main/source/main.py | import data
import framework
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.utilities.cli import DATAMODULE_REGISTRY, MODEL_REGISTRY, LightningCLI
class CustomLightningCLI(LightningCLI):
def add_arguments_to_parser(self, parser):
parser.add_ar... | 1,653 | 30.807692 | 93 | py |
PSENet-Image-Enhancement | PSENet-Image-Enhancement-main/source/iqa.py | import torch
import torch.nn as nn
class IQA(nn.Module):
def __init__(
self,
):
super().__init__()
ps = 25
self.exposed_level = 0.5
self.mean_pool = torch.nn.Sequential(torch.nn.ReflectionPad2d(ps // 2), torch.nn.AvgPool2d(ps, stride=1))
def forward(self, images):
... | 847 | 32.92 | 113 | py |
PSENet-Image-Enhancement | PSENet-Image-Enhancement-main/source/loss.py | import torch
class TVLoss(torch.nn.Module):
def forward(self, x):
x = torch.log(x + 1e-3)
h_tv = torch.pow((x[:, :, 1:, :] - x[:, :, :-1, :]), 2)
w_tv = torch.pow((x[:, :, :, 1:] - x[:, :, :, :-1]), 2)
return torch.mean(h_tv) + torch.mean(w_tv)
| 283 | 27.4 | 63 | py |
PSENet-Image-Enhancement | PSENet-Image-Enhancement-main/source/model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class Hswish(nn.Module):
def __init__(self, inplace=True):
super(Hswish, self).__init__()
self.inplace = inplace
def forward(self, x):
return x * F.relu6(x + 3.0, inplace=self.inplace) / 6.0
class Hsigmoid(nn.Module)... | 5,089 | 32.267974 | 115 | py |
PSENet-Image-Enhancement | PSENet-Image-Enhancement-main/source/data.py | import glob
import os
import cv2
import torch
from pytorch_lightning.core import LightningDataModule
from pytorch_lightning.utilities.cli import DATAMODULE_REGISTRY
from torch.utils import data
from torch.utils.data import DataLoader
class NoGTDataset(data.Dataset):
def __init__(self, root_folder, pattern, resiz... | 4,979 | 35.617647 | 118 | py |
PSENet-Image-Enhancement | PSENet-Image-Enhancement-main/source/framework.py | import os
import piq
import torch
import torchvision
from iqa import IQA
from loss import TVLoss
from model import UnetTMO
from pytorch_lightning.core.lightning import LightningModule
from pytorch_lightning.utilities.cli import MODEL_REGISTRY
def save_image(im, p):
base_dir = os.path.split(p)[0]
if not os.pa... | 6,097 | 45.19697 | 221 | py |
PSENet-Image-Enhancement | PSENet-Image-Enhancement-main/source/demo.py | import argparse
import glob
import os
import cv2
import torch
import torchvision
from model import UnetTMO
def read_image(path):
img = cv2.imread(path)[:, :, ::-1]
img = img / 255.0
img = torch.from_numpy(img).float().permute(2, 0, 1).unsqueeze(0)
return img
def read_pytorch_lightning_state_dict(ck... | 1,354 | 25.568627 | 87 | py |
proxynca_pp | proxynca_pp-master/loss.py | from similarity import pairwise_distance
import torch
import torch.nn.functional as F
import numpy as np
import torch.nn as nn
import copy
import math
def binarize_and_smooth_labels(T, nb_classes, smoothing_const = 0):
import sklearn.preprocessing
T = T.cpu().numpy()
T = sklearn.preprocessing.label_binariz... | 2,638 | 30.416667 | 86 | py |
proxynca_pp | proxynca_pp-master/utils.py |
from __future__ import print_function
from __future__ import division
import evaluation
import numpy as np
import torch
import logging
import loss
import json
import networks
import time
#import margin_net
import similarity
# __repr__ may contain `\n`, json replaces it by `\\n` + indent
json_dumps = lambda **kwargs:... | 6,215 | 31.041237 | 77 | py |
proxynca_pp | proxynca_pp-master/networks.py | import torchvision.models as models
import torch.nn as nn
import torch
import numpy as np
import torch.nn.functional as F
class Feature(nn.Module):
def __init__(self, model='resnet50', pool='avg', use_lnorm=False):
nn.Module.__init__(self)
self.model = model
self.base = models.__dict__[mod... | 1,683 | 27.066667 | 76 | py |
proxynca_pp | proxynca_pp-master/similarity.py |
import torch
import sklearn
def pairwise_distance(a, squared=False):
"""Computes the pairwise distance matrix with numerical stability."""
pairwise_distances_squared = torch.add(
a.pow(2).sum(dim=1, keepdim=True).expand(a.size(0), -1),
torch.t(a).pow(2).sum(dim=0, keepdim=True).expand(a.size(... | 1,338 | 27.489362 | 73 | py |
proxynca_pp | proxynca_pp-master/train.py |
import logging
import dataset
import utils
import loss
import os
import torch
import numpy as np
import matplotlib
matplotlib.use('agg', warn=False, force=True)
import matplotlib.pyplot as plt
import time
import argparse
import json
import random
from utils import JSONEncoder, json_dumps
parser = argparse.ArgumentP... | 17,258 | 29.764706 | 169 | py |
proxynca_pp | proxynca_pp-master/dataset/base.py |
from __future__ import print_function
from __future__ import division
import os
import torch
import torchvision
import numpy as np
import PIL.Image
from distutils.dir_util import copy_tree
import io
import h5py
from shutil import copyfile
import time
'''
class BaseDataset(torch.utils.data.Dataset):
def __init__(s... | 10,435 | 31.510903 | 84 | py |
proxynca_pp | proxynca_pp-master/dataset/cub.py | from .base import *
import h5py
import torch
class CUBirds(BaseDatasetMod):
def __init__(self, root, source, classes, transform = None):
BaseDatasetMod.__init__(self, root, source, classes, transform)
index = 0
for i in torchvision.datasets.ImageFolder(root =
os.path.join(r... | 3,981 | 36.566038 | 78 | py |
proxynca_pp | proxynca_pp-master/dataset/make_cub_hdf5.py | import h5py
import os
import numpy as np
from tqdm import tqdm
import torchvision
root = '/mnt/datasets/CUB_200_2011'
img_count = 0
for i in torchvision.datasets.ImageFolder(root = os.path.join(root, 'images')).imgs:
fn = os.path.split(i[0])[1]
if fn[:2] != '._':
img_count += 1
data = h5py.File(os... | 1,139 | 26.804878 | 90 | py |
proxynca_pp | proxynca_pp-master/dataset/utils.py | from __future__ import print_function
from __future__ import division
import torchvision
from torchvision import transforms
import PIL.Image
import torch
from torch._six import int_classes as _int_classes
import numpy as np
import numbers
def std_per_channel(images):
images = torch.stack(images, dim = 0)
retu... | 7,935 | 38.879397 | 115 | py |
proxynca_pp | proxynca_pp-master/dataset/sop.py | from .base import *
from tqdm import tqdm
class SOProducts(BaseDatasetMod):
nb_train_all = 59551
nb_test_all = 60502
def __init__(self, root, source, classes, transform=None):
BaseDatasetMod.__init__(self, root, source, classes, transform)
classes_train = range(0, 11318)
classes_te... | 2,337 | 31.027397 | 115 | py |
proxynca_pp | proxynca_pp-master/dataset/cars.py |
from .base import *
import scipy.io
'''
class Cars(BaseDatasetMod):
def __init__(self, root, source, classes, transform = None):
BaseDatasetMod.__init__(self, root, source, classes, transform)
annos_fn = 'cars_anno.pt'
cars = torch.load(os.path.join(root, annos_fn))
index = 0
... | 1,994 | 34 | 73 | py |
proxynca_pp | proxynca_pp-master/dataset/make_inshop_hdf5.py | import h5py
import os
import numpy as np
from tqdm import tqdm
import torchvision
import scipy.io
root = '/mnt/datasets/inshop'
####
with open(
os.path.join(
root, 'Eval/list_eval_partition.txt'
), 'r'
) as f:
lines = f.readlines()
# store for using later '__getitem__'
nb_samples = int(lines[0]... | 3,663 | 29.533333 | 78 | py |
proxynca_pp | proxynca_pp-master/dataset/make_cars_hdf5.py | import h5py
import os
import numpy as np
from tqdm import tqdm
import torchvision
import scipy.io
root = '/mnt/datasets/cars196_alt'
annos_fn = 'cars_annos.mat'
cars = scipy.io.loadmat(os.path.join(root, annos_fn))
ys = [int(a[5][0] - 1) for a in cars['annotations'][0]]
im_paths = [a[0][0] for a in cars['annotations'... | 939 | 23.102564 | 66 | py |
proxynca_pp | proxynca_pp-master/dataset/make_sop_hdf5.py | import h5py
import os
import numpy as np
from tqdm import tqdm
import torchvision
import scipy.io
nb_train_all = 59551
nb_test_all = 60502
img_count = nb_train_all + nb_test_all
root = '/mnt/datasets/sop'
data = h5py.File(os.path.join(root, 'sop.h5'), 'w')
dt = h5py.special_dtype(vlen=np.dtype('uint8'))
data.create_... | 1,632 | 19.935897 | 85 | py |
proxynca_pp | proxynca_pp-master/dataset/inshop.py |
"""NOTE: I've checked the images for correctnes manually, i.e. each image
of gallery should have a corresponding pair in query (i.e. should look the
same) and also have the same label."""
#import PIL
#import torch
#import os
from .base import *
class InShop(BaseDatasetMod):
"""
For the In-Shop Clothes Retrie... | 5,265 | 36.347518 | 115 | py |
nas-env | nas-env-master/test/test_default_nasenv.py | """Test the creation of the network."""
import os
import unittest
import numpy as np
import tensorflow as tf
from gym import spaces
from nasgym.envs.default_nas_env import DefaultNASEnvParser
from nasgym.envs.default_nas_env import DefaultNASEnv
from nasgym.dataset_handlers.default_handler import DefaultDatasetHandler... | 4,888 | 33.429577 | 79 | py |
nas-env | nas-env-master/test/test_net_trainer.py | """Expose tests to verify the correct training of network's encoding.
In the NAS environment, the networks are represented in Neural Structure Code
(NSC). The nasgym/net_ops/net_trainer.py module is in charge of training these
networks on a given dataset, by first building the network with the functions
exposed in nas... | 12,390 | 35.337243 | 79 | py |
nas-env | nas-env-master/nasgym/__init__.py | """Register the different NAS environments we makea available by default."""
import tensorflow as tf
from gym.envs.registration import register
from nasgym.dataset_handlers.default_handler import DefaultDatasetHandler
# (train_data, train_labels), (eval_data, eval_labels) = \
# tf.keras.datasets.mnist.load_data(... | 1,080 | 24.139535 | 76 | py |
nas-env | nas-env-master/nasgym/net_ops/net_builder.py | """Classes and methods for Net building."""
import logging
import tensorflow as tf
from nasgym.net_ops import LTYPE_ADD
from nasgym.net_ops import LTYPE_AVGPOOLING
from nasgym.net_ops import LTYPE_CONCAT
from nasgym.net_ops import LTYPE_CONVULUTION
from nasgym.net_ops import LTYPE_IDENTITY
from nasgym.net_ops import L... | 8,300 | 31.940476 | 79 | py |
DeepANPR | DeepANPR-master/recognition/test.py | import para
import model
import os
from os.path import join
import cv2
import numpy as np
from argparse import ArgumentParser
import keras.backend as K
from keras.models import load_model
BATCHSIZE = 64
parser = ArgumentParser(description='parser for testing the crnn model')
parser.add_argument(
'--model', type=... | 4,617 | 31.293706 | 131 | py |
DeepANPR | DeepANPR-master/recognition/resnet.py | from __future__ import division
import six
from keras.models import Model
from keras.layers import (
Input,
Activation,
Dense,
Flatten
)
from keras.layers.convolutional import (
Conv2D,
MaxPooling2D,
AveragePooling2D
)
from keras.layers.merge import add
from keras.layers.normalization impor... | 10,229 | 38.045802 | 129 | py |
DeepANPR | DeepANPR-master/recognition/model.py |
import numpy as np
from argparse import ArgumentParser
import keras
from keras.models import Model
from keras.layers.recurrent import GRU
from keras.layers import Input, Dense, Lambda, Reshape, BatchNormalization, Activation
from keras.layers.merge import add, concatenate
from keras import backend as K
import para
# ... | 4,784 | 42.108108 | 145 | py |
DeepANPR | DeepANPR-master/recognition/common.py | from argparse import ArgumentTypeError
import logging
import os
import numpy as np
# Commandline argument parsing
###
def probility_float(arg):
try:
value = float(arg)
except ValueError:
raise ArgumentTypeError('The argument "{}" is not an {}.'.format(
arg, float.__name__))
i... | 6,048 | 30.341969 | 95 | py |
DeepANPR | DeepANPR-master/recognition/load_img.py | import xml.etree.ElementTree as ET
import numpy as np
from os.path import join
import cv2
path_to_data = '/data1000G/steven/ML_PLATE/data/train/'
classes = ["plate"]
def images_crop_by_annotation(image_id, model_w,model_h,model_c, resize=False):
in_file = open(join(path_to_data, 'labels/plate_original/%s.xml'%(... | 5,173 | 29.615385 | 155 | py |
DeepANPR | DeepANPR-master/recognition/callback.py | from LRTensorBoard import LRTensorBoard
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras.optimizers import Adam
import numpy as np
from os.path import join
decay_epoch = 30
total_epoch = 50
lr_base = 1e-4
def lr_scheduler(epoch):
global decay_epoch
global total_epoch
... | 1,015 | 28.882353 | 138 | py |
DeepANPR | DeepANPR-master/recognition/LRTensorBoard.py | from keras import backend as K
from keras.callbacks import TensorBoard
class LRTensorBoard(TensorBoard):
def __init__(self, log_dir): # add other arguments to __init__ if you need
super().__init__(log_dir=log_dir)
def on_epoch_end(self, epoch, logs=None):
logs.update({'lr': K.eval(self.model.... | 377 | 36.8 | 79 | py |
DeepANPR | DeepANPR-master/recognition/train.py |
import random
import os
from os.path import join
import numpy as np
import json
import common
import load_img
import model
import para
import callback
from argparse import ArgumentParser
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from keras.applications.densenet import pr... | 5,529 | 30.6 | 179 | py |
DeepANPR | DeepANPR-master/recognition/7_experiment_acc_0988_aug2/resnet.py | from __future__ import division
import six
from keras.models import Model
from keras.layers import (
Input,
Activation,
Dense,
Flatten
)
from keras.layers.convolutional import (
Conv2D,
MaxPooling2D,
AveragePooling2D
)
from keras.layers.merge import add
from keras.layers.normalization impor... | 9,976 | 37.521236 | 112 | py |
DeepANPR | DeepANPR-master/recognition/7_experiment_acc_0988_aug2/model.py |
import numpy as np
from argparse import ArgumentParser
import keras
from keras.models import Model
from keras.layers.recurrent import GRU
from keras.layers import Input, Dense, Lambda, Reshape, BatchNormalization, Activation
from keras.layers.merge import add, concatenate
from keras import backend as K
import para
# ... | 4,552 | 41.551402 | 143 | py |
DeepANPR | DeepANPR-master/recognition/7_experiment_acc_0988_aug2/train.py |
import random
import os
from os.path import join
import numpy as np
import json
import common
import load_img
import model
import para
import callback
from argparse import ArgumentParser
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from keras.applications.densenet import pr... | 5,529 | 30.6 | 179 | py |
DeepANPR | DeepANPR-master/recognition/6_experiment_acc_0987_aug/model.py |
import numpy as np
from argparse import ArgumentParser
import keras
from keras.models import Model
from keras.layers.recurrent import GRU
from keras.layers import Input, Dense, Lambda, Reshape, BatchNormalization, Activation
from keras.layers.merge import add, concatenate
from keras import backend as K
import para
# ... | 4,552 | 41.551402 | 143 | py |
DeepANPR | DeepANPR-master/recognition/8_experiement_acc_09886_2222_filters64/resnet.py | from __future__ import division
import six
from keras.models import Model
from keras.layers import (
Input,
Activation,
Dense,
Flatten
)
from keras.layers.convolutional import (
Conv2D,
MaxPooling2D,
AveragePooling2D
)
from keras.layers.merge import add
from keras.layers.normalization impor... | 10,229 | 38.045802 | 129 | py |
DeepANPR | DeepANPR-master/recognition/8_experiement_acc_09886_2222_filters64/model.py |
import numpy as np
from argparse import ArgumentParser
import keras
from keras.models import Model
from keras.layers.recurrent import GRU
from keras.layers import Input, Dense, Lambda, Reshape, BatchNormalization, Activation
from keras.layers.merge import add, concatenate
from keras import backend as K
import para
# ... | 4,784 | 42.108108 | 145 | py |
DeepANPR | DeepANPR-master/recognition/8_experiement_acc_09886_2222_filters64/train.py |
import random
import os
from os.path import join
import numpy as np
import json
import common
import load_img
import model
import para
import callback
from argparse import ArgumentParser
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
from keras.applications.densenet import pr... | 5,529 | 30.6 | 179 | py |
Pgnet | Pgnet-main/Pgnet.py | # -*- coding: utf-8 -*-
"""
@author: lsl
E-mail: cug_lsl@cug.edu.cn
"""
import sys
import argparse
sys.path.append("/home/aistudio/code")
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import time
from .Pgnet_structure import Pg_net
from .Pgnet_dataset import Mydata
fro... | 4,474 | 35.382114 | 119 | py |
Pgnet | Pgnet-main/Pgnet_dataset.py | from torch.utils.data import Dataset
class Mydata(Dataset):
def __init__(self, lrhs, pan, label):
super(Mydata, self).__init__()
self.lrhs = lrhs
self.pan = pan
self.label = label
def __getitem__(self, idx):
assert idx < self.pan.shape[0]
return self.lrhs[idx, :... | 435 | 26.25 | 88 | py |
Pgnet | Pgnet-main/save_img_jiaxing.py | import numpy as np
import torch
from function import all_valid, Downsampler
# from function import Crop_traindata
def Crop_traindata_three(image_ms, image_pan, image_label, size, test=False, step_facter=1, ratio=3):
image_ms_all = []
image_pan_all = []
label = []
"""crop images"""
temp_name = 'te... | 4,170 | 36.241071 | 110 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.