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
ReAgent
ReAgent-master/reagent/optimizer/utils.py
#!/usr/bin/env python3 import inspect import torch def is_strict_subclass(a, b): if not inspect.isclass(a) or not inspect.isclass(b): return False return issubclass(a, b) and a != b def is_torch_optimizer(cls): return is_strict_subclass(cls, torch.optim.Optimizer) def is_torch_lr_scheduler(c...
399
19
73
py
ReAgent
ReAgent-master/reagent/optimizer/scheduler.py
#!/usr/bin/env python3 import inspect from typing import Any, Dict import torch from reagent.core.dataclasses import dataclass from reagent.core.registry_meta import RegistryMeta from .utils import is_torch_lr_scheduler @dataclass(frozen=True) class LearningRateSchedulerConfig(metaclass=RegistryMeta): def make...
1,054
27.513514
77
py
ReAgent
ReAgent-master/reagent/optimizer/optimizer.py
#!/usr/bin/env python3 """ For each Torch optimizer, we create a wrapper pydantic dataclass around it. We also add this class to our Optimizer registry. Usage: Whenever you want to use this Optimizer__Union, specify it as the type. E.g. class Parameters: rl: RLParameters = field(default_factory=RLParameters) ...
2,673
31.609756
101
py
ReAgent
ReAgent-master/reagent/workflow/gym_batch_rl.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import json import logging import random from typing import Optional import gym import numpy as np import pandas as pd import pytorch_lightning as pl import torch from reagent.data.spark_utils import call_spark_class, get_s...
5,597
31.358382
87
py
ReAgent
ReAgent-master/reagent/workflow/training.py
#!/usr/bin/env python3 import dataclasses import logging import time from typing import Dict, Optional import torch from reagent.core.parameters import NormalizationData from reagent.core.tensorboardX import summary_writer_context from reagent.data.manual_data_module import get_sample_range from reagent.data.oss_data...
10,454
32.944805
118
py
ReAgent
ReAgent-master/reagent/workflow/utils.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import logging from typing import Dict, List, Optional import pytorch_lightning as pl import torch # pyre-fixme[21]: Could not find `petastorm`. from petastorm import make_batch_reader # pyre-fixme[21]: Could not find mod...
4,998
32.326667
88
py
ReAgent
ReAgent-master/reagent/reporting/discrete_crr_reporter.py
#!/usr/bin/env python3 import itertools import logging from typing import List, Optional import torch from reagent.core import aggregators as agg from reagent.core.observers import IntervalAggregatingObserver from reagent.reporting.reporter_base import ( ReporterBase, ) from reagent.workflow.training_reports impo...
4,053
37.245283
86
py
ReAgent
ReAgent-master/reagent/reporting/seq2reward_reporter.py
#!/usr/bin/env python3 import itertools import logging from typing import List import torch from reagent.core import aggregators as agg from reagent.core.observers import IntervalAggregatingObserver from reagent.reporting.reporter_base import ReporterBase from reagent.workflow.training_reports import Seq2RewardTraini...
5,987
38.137255
85
py
ReAgent
ReAgent-master/reagent/reporting/reporter_base.py
#!/usr/bin/env python3 import abc import logging from typing import Dict import torch from reagent.core.observers import ( CompositeObserver, EpochEndObserver, IntervalAggregatingObserver, ValueListObserver, ) from reagent.core.result_registries import TrainingReport from reagent.core.tracker import O...
2,631
32.316456
81
py
ReAgent
ReAgent-master/reagent/reporting/discrete_dqn_reporter.py
#!/usr/bin/env python3 import itertools import logging from collections import OrderedDict from typing import List, Optional import torch from reagent.core import aggregators as agg from reagent.core.observers import IntervalAggregatingObserver, ValueListObserver from reagent.reporting.reporter_base import ( Repo...
4,086
37.196262
86
py
ReAgent
ReAgent-master/reagent/replay_memory/prioritized_replay_buffer.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # Copyright 2018 The Dopamine Authors. # # 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 # # ...
7,773
41.480874
88
py
ReAgent
ReAgent-master/reagent/replay_memory/circular_replay_buffer.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. # We removed Tensorflow dependencies. # OutOfGraphReplayBuffer is renamed ReplayBuffer # Copyright 2018 The Dopamine Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file e...
37,435
41.015713
141
py
ReAgent
ReAgent-master/reagent/net_builder/discrete_dqn_net_builder.py
#!/usr/bin/env python3 import abc from typing import List import reagent.core.types as rlt import torch from reagent.core.fb_checker import IS_FB_ENVIRONMENT from reagent.core.parameters import NormalizationData from reagent.models.base import ModelBase from reagent.prediction.predictor_wrapper import ( DiscreteD...
3,123
32.234043
91
py
ReAgent
ReAgent-master/reagent/net_builder/continuous_actor_net_builder.py
#!/usr/bin/env python3 import abc import reagent.core.types as rlt import torch from reagent.core.fb_checker import IS_FB_ENVIRONMENT from reagent.core.parameters import NormalizationData from reagent.models.base import ModelBase from reagent.prediction.predictor_wrapper import ( ActorWithPreprocessor, Rankin...
3,653
33.471698
86
py
ReAgent
ReAgent-master/reagent/net_builder/slate_ranking_net_builder.py
#!/usr/bin/env python3 import abc import torch from reagent.core.registry_meta import RegistryMeta class SlateRankingNetBuilder: """ Base class for slate ranking network builder. """ @abc.abstractmethod def build_slate_ranking_network( self, state_dim, candidate_dim, candidate_size, sla...
367
18.368421
66
py
ReAgent
ReAgent-master/reagent/net_builder/synthetic_reward_net_builder.py
#!/usr/bin/env python3 import abc from typing import List, Optional import torch from reagent.core.fb_checker import IS_FB_ENVIRONMENT from reagent.core.parameters import NormalizationData from reagent.models.base import ModelBase from reagent.preprocessing.preprocessor import Preprocessor if IS_FB_ENVIRONMENT: ...
2,259
33.242424
91
py
ReAgent
ReAgent-master/reagent/net_builder/parametric_dqn_net_builder.py
#!/usr/bin/env python3 import abc import torch from reagent.core.fb_checker import IS_FB_ENVIRONMENT from reagent.core.parameters import NormalizationData from reagent.core.registry_meta import RegistryMeta from reagent.models.base import ModelBase from reagent.prediction.predictor_wrapper import ParametricDqnWithPre...
1,777
30.192982
82
py
ReAgent
ReAgent-master/reagent/net_builder/slate_reward_net_builder.py
#!/usr/bin/env python3 import abc import torch class SlateRewardNetBuilder: """ Base class for slate reward network builder. """ @abc.abstractmethod def build_slate_reward_network( self, state_dim, candidate_dim, candidate_size, slate_size ) -> torch.nn.Module: pass @ab...
400
17.227273
66
py
ReAgent
ReAgent-master/reagent/net_builder/discrete_actor_net_builder.py
#!/usr/bin/env python3 import abc from typing import List import reagent.core.types as rlt import torch from reagent.core.fb_checker import IS_FB_ENVIRONMENT from reagent.core.parameters import NormalizationData from reagent.models.base import ModelBase from reagent.prediction.predictor_wrapper import ActorWithPrepro...
1,608
27.732143
82
py
ReAgent
ReAgent-master/reagent/net_builder/value_net_builder.py
#!/usr/bin/env python3 import abc import torch from reagent.core.parameters import NormalizationData from reagent.core.registry_meta import RegistryMeta class ValueNetBuilder: """ Base class for value-network builder. """ @abc.abstractmethod def build_value_network( self, state_normaliz...
389
18.5
57
py
ReAgent
ReAgent-master/reagent/net_builder/categorical_dqn_net_builder.py
#!/usr/bin/env python3 import abc from typing import List import reagent.core.types as rlt import torch from reagent.core.fb_checker import IS_FB_ENVIRONMENT from reagent.core.parameters import NormalizationData from reagent.core.registry_meta import RegistryMeta from reagent.models.base import ModelBase from reagent...
2,019
30.076923
82
py
ReAgent
ReAgent-master/reagent/net_builder/quantile_dqn_net_builder.py
#!/usr/bin/env python3 import abc from typing import List import reagent.core.types as rlt import torch from reagent.core.fb_checker import IS_FB_ENVIRONMENT from reagent.core.parameters import NormalizationData from reagent.core.registry_meta import RegistryMeta from reagent.models import ModelBase, Sequential from ...
2,210
30.140845
81
py
ReAgent
ReAgent-master/reagent/net_builder/synthetic_reward/ngram_synthetic_reward.py
#!/usr/bin/env python3 from typing import List, Optional import torch from reagent.core.dataclasses import dataclass, field from reagent.core.parameters import NormalizationData, param_hash, ConvNetParameters from reagent.models.base import ModelBase from reagent.models.synthetic_reward import ( NGramConvolutiona...
3,678
34.375
86
py
ReAgent
ReAgent-master/reagent/net_builder/slate_ranking/slate_ranking_scorer.py
#!/usr/bin/env python3 from dataclasses import asdict from typing import List from typing import Optional import torch import torch.nn as nn from reagent.core.dataclasses import dataclass, field from reagent.core.parameters import param_hash from reagent.models.base import ModelBase from reagent.models.fully_connect...
2,915
27.871287
80
py
ReAgent
ReAgent-master/reagent/net_builder/value/fully_connected.py
#!/usr/bin/env python3 from typing import List import torch from reagent.core.dataclasses import dataclass, field from reagent.core.parameters import NormalizationData, param_hash from reagent.models.fully_connected_network import FloatFeatureFullyConnected from reagent.net_builder.value_net_builder import ValueNetBu...
1,410
33.414634
78
py
ReAgent
ReAgent-master/reagent/net_builder/value/seq2reward_rnn.py
#!/usr/bin/env python3 import torch from reagent.core.dataclasses import dataclass from reagent.core.parameters import NormalizationData, param_hash from reagent.models.seq2reward_model import Seq2RewardNetwork from reagent.net_builder.value_net_builder import ValueNetBuilder from reagent.preprocessing.normalization i...
966
30.193548
71
py
ReAgent
ReAgent-master/reagent/model_utils/seq2slate_utils.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import copy import logging import math from enum import Enum import torch import torch.nn as nn import torch.nn.functional as F logger = logging.getLogger(__name__) PADDING_SYMBOL = 0 DECODER_START_SYMBOL = 1 class Seq2S...
6,842
34.455959
105
py
ReAgent
ReAgent-master/reagent/preprocessing/sparse_preprocessor.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import abc import logging from typing import Dict, Tuple import reagent.core.types as rlt import torch logger = logging.getLogger(__name__) @torch.jit.script def map_id_list(raw_values: torch.Tensor, id2index: Dict[int,...
7,650
34.752336
88
py
ReAgent
ReAgent-master/reagent/preprocessing/postprocessor.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. from typing import Dict, Tuple import torch import torch.nn as nn from reagent.core.parameters import NormalizationParameters from reagent.preprocessing.identify_types import ( CONTINUOUS_ACTION, DISCRETE_ACTION, ...
2,812
36.013158
96
py
ReAgent
ReAgent-master/reagent/preprocessing/sparse_to_dense.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. from typing import Dict, List, Tuple import torch from reagent.preprocessing import normalization class SparseToDenseProcessor: def __init__( self, sorted_features: List[int], set_missing_value_to_zero: bool ...
2,628
31.45679
86
py
ReAgent
ReAgent-master/reagent/preprocessing/batch_preprocessor.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. from typing import Dict import torch import torch.nn as nn import torch.nn.functional as F from reagent.core import types as rlt from reagent.preprocessing.preprocessor import Preprocessor class BatchPreprocessor(nn.Modul...
6,551
41
87
py
ReAgent
ReAgent-master/reagent/preprocessing/normalization.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import json import logging from dataclasses import asdict from typing import Dict, List, Optional, Tuple import numpy as np import reagent.core.types as rlt import six import torch from reagent.core.parameters import Normal...
11,199
34.897436
88
py
ReAgent
ReAgent-master/reagent/preprocessing/preprocessor.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import logging from typing import Dict, List, Optional, Tuple, cast import torch from reagent.core.parameters import NormalizationParameters from reagent.preprocessing.identify_types import DO_NOT_PREPROCESS, ENUM, FEATURE_...
23,384
38.040067
88
py
ReAgent
ReAgent-master/reagent/preprocessing/transforms.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import logging from typing import Callable, List, Optional import numpy as np import reagent.core.types as rlt import torch import torch.nn.functional as F from reagent.core.parameters import NormalizationData from reagent....
12,655
32.217848
111
py
ReAgent
ReAgent-master/reagent/prediction/predictor_wrapper.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. import logging from typing import Dict, List, Optional, Tuple import reagent.core.types as rlt import torch import torch.nn.functional as F from reagent.core.torch_utils import gather from reagent.model_utils.seq2slate_util...
31,722
35.75898
99
py
ReAgent
ReAgent-master/reagent/prediction/synthetic_reward/synthetic_reward_predictor_wrapper.py
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. from typing import Tuple import torch import torch.nn as nn from reagent.models.base import ModelBase from reagent.preprocessing.preprocessor import Preprocessor def split_features( state_and_action_with_presence: Tupl...
2,372
35.507692
83
py
ReAgent
ReAgent-master/reagent/prediction/ranking/predictor_wrapper.py
from enum import Enum from typing import Tuple, List, Optional import torch import torch.nn.functional as F class Kernel(Enum): # <x, y> = dot_product(x, y) Linear = "linear" # <x, y> = exp(-||x-y||^2 / (2 * sigma^2)) RBF = "rbf" class DeterminantalPointProcessPredictorWrapper(torch.jit.ScriptModu...
3,643
29.881356
85
py
ReAgent
ReAgent-master/docs/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: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- from __future__ import abso...
2,292
29.171053
82
py
EFT
EFT-main/incremental_dataloader.py
''' TaICML incremental learning Copyright (c) Jathushan Rajasegaran, 2019 ''' import random import numpy as np import torch from PIL import Image from torch.utils.data import DataLoader from torch.utils.data.sampler import SubsetRandomSampler from torch.utils.data import Sampler from torchvision import datasets, transf...
18,859
36.871486
210
py
EFT
EFT-main/idatasets/CUB200.py
import os import pandas as pd from torchvision.datasets.folder import default_loader from torchvision.datasets.utils import download_url from torch.utils.data import Dataset class Cub2011(Dataset): base_folder = 'CUB_200_2011/images' url = 'http://www.vision.caltech.edu/visipedia-data/CUB-200-2011/CUB_200_201...
3,104
35.104651
107
py
EFT
EFT-main/idatasets/tinyimagenet.py
from __future__ import print_function import os import shutil import tempfile import torch from .folder import ImageFolder from .utils import check_integrity, download_and_extract_archive, extract_archive, \ verify_str_arg ARCHIVE_DICT = { 'train': { 'url': 'http://www.image-net.org/challenges/LSVRC/20...
6,657
38.39645
100
py
EFT
EFT-main/idatasets/omniglot.py
import os import pandas as pd from torchvision.datasets.folder import default_loader from torchvision.datasets.utils import download_url from torch.utils.data import Dataset class Omniglot(Dataset): """`Omniglot <https://github.com/brendenlake/omniglot>`_ Dataset. Args: root (string): Root directory ...
5,662
39.45
117
py
EFT
EFT-main/idatasets/celeb_1m.py
import os import pandas as pd from torchvision.datasets.folder import default_loader from torchvision.datasets.utils import download_url from torch.utils.data import Dataset import numpy as np import random from collections import Counter class MS1M(Dataset): def __init__(self, root, train=True, transform=None, l...
2,478
28.511905
95
py
EFT
EFT-main/idatasets/imagenet.py
from __future__ import print_function import os import shutil import tempfile import torch from .folder import ImageFolder from .utils import check_integrity, download_and_extract_archive, extract_archive, \ verify_str_arg ARCHIVE_DICT = { 'train': { 'url': 'http://www.image-net.org/challenges/LSVRC/20...
6,657
38.39645
100
py
EFT
EFT-main/idatasets/data_celeb.py
import random import numpy as np import torch from PIL import Image from torch.utils.data import DataLoader from torch.utils.data.sampler import SubsetRandomSampler from torch.utils.data import Sampler from torchvision import datasets, transforms # from imagenet import ImageNet from CUB200 import Cub2011 import collec...
14,326
34.72818
188
py
IAN
IAN-master/test.py
import os import torch import logging from train import parse_options from network import create_model from options.yaml_opt import dict2str from dataset import create_dataloader, create_dataset from base_utils.utils import get_time_str, make_exp_dirs from base_utils.logger import get_root_logger, get_env_info def m...
1,890
31.603448
79
py
IAN
IAN-master/train.py
import os import math import time import torch import random import logging import argparse import datetime from network import create_model from options.yaml_opt import parse, dict2str from dataset.data_sampler import EnlargedSampler from dataset import create_dataset, create_dataloader from base_utils.logger import g...
8,133
36.483871
111
py
IAN
IAN-master/dataset/AdobeMI_dataset.py
import ast import torch import numpy as np from torch.utils import data as data from dataset.data_utils import img2tensor, imread, parse_adobe_dataset, select_one2one_data from dataset.transforms import augment, multi_random_crop def showimg(img, name): import numpy as np import cv2 img = (img + 1) / 2 * ...
9,494
34.830189
121
py
IAN
IAN-master/dataset/anytoany_dataset.py
import os import torch import numpy as np from torch.utils import data as data from base_utils.utils import load_depth from dataset.data_utils import img2tensor, imread from dataset.transforms import multi_random_crop, dir_augment '''Image{idx}_{color}_{angle}.png''' class Any2anyTrainingDataset(data.Dataset): de...
14,109
40.378299
182
py
IAN
IAN-master/dataset/paired_dataset.py
from dataset.data_utils import paired_paths_from_folder, img2tensor, imread from dataset.transforms import augment, paired_random_crop from torch.utils import data as data # from data_utils import paired_paths_from_folder, img2tensor, imread # from transforms import augment, paired_random_crop # from torch.utils import...
3,237
36.651163
100
py
IAN
IAN-master/dataset/paired_with_auxiliary_dataset.py
import torch import numpy as np from torch.utils import data as data from base_utils.utils import load_depth from dataset.transforms import augment, multi_random_crop from dataset.data_utils import paired_paths_from_folder, img2tensor, imread class PairedImageWithAuxiliaryDataset(data.Dataset): def __init__(self...
4,611
39.45614
160
py
IAN
IAN-master/dataset/data_utils.py
import cv2 import numpy as np import os import math from torch.utils import data from torchvision.utils import make_grid import torch import json def imread(path, float32=True): ''' params: path: str float32: bool output: img: ndarray(uint8/float32) [-1, 1] description: ...
10,844
34.097087
109
py
IAN
IAN-master/dataset/data_sampler.py
import math import torch from torch.utils.data.sampler import Sampler class EnlargedSampler(Sampler): """Sampler that restricts data loading to a subset of the dataset. Modified from torch.utils.data.distributed.DistributedSampler Support enlarging the dataset for iteration-based training, for saving ...
1,649
34.106383
75
py
IAN
IAN-master/dataset/videodemo_dataset.py
import math import torch import numpy as np from torch.utils import data as data from dataset.data_utils import img2tensor, imread def load_light(path): with open(path, 'r') as fr: lines = fr.readlines() light_params = np.array([float(l[:-1]) for l in lines]) return light_params def get_pos(l): ...
3,804
32.086957
82
py
IAN
IAN-master/dataset/__init__.py
import importlib import numpy as np import random import torch import torch.utils.data from functools import partial import os from base_utils.logger import get_root_logger # import .anytoany_Dataset __all__ = ['create_dataset', 'create_dataloader'] # automatically scan and import dataset modules # scan all the file...
3,932
34.116071
77
py
IAN
IAN-master/dataset/DPR_dataset.py
from dataset.data_utils import img2tensor, imread from dataset.transforms import multi_random_crop from torch.utils import data as data import os import os.path as osp import torch import numpy as np def load_light(path): with open(path, 'r') as fr: lines = fr.readlines() light_params = np.array([floa...
2,987
34.571429
132
py
IAN
IAN-master/dataset/transforms.py
import cv2 import torch import random import torchvision.transforms as transforms def mod_crop(img, scale): """Mod crop images, used during testing. Args: img (ndarray): Input image. scale (int): Scale factor. Returns: ndarray: Result image. """ img = img.copy() if img.n...
7,111
31.623853
90
py
IAN
IAN-master/lpips-pytorch/setup.py
from setuptools import setup setup( name='lpips_pytorch', version='latest', description='LPIPS as a Package.', packages=['lpips_pytorch', 'lpips_pytorch.modules'], author='So Uchida', author_email='s.aiueo32@gmail.com', install_requires=["torch", "torchvision"], url='https://github.com/...
348
25.846154
56
py
IAN
IAN-master/lpips-pytorch/tests/test_allclose.py
from pathlib import Path import torchvision.transforms.functional as TF from PIL import Image from torch.testing import assert_allclose from lpips_pytorch import LPIPS from lpips_pytorch import lpips from PerceptualSimilarity.models import PerceptualLoss img = Image.open(Path(__file__).parents[1].joinpath('data/lenn...
1,889
27.636364
70
py
IAN
IAN-master/lpips-pytorch/lpips_pytorch/__init__.py
import torch from .modules.lpips import LPIPS def lpips(x: torch.Tensor, y: torch.Tensor, net_type: str = 'alex', version: str = '0.1'): r"""Function that measures Learned Perceptual Image Patch Similarity (LPIPS). Arguments: x, y (torch.Tensor): the input tensors t...
635
27.909091
68
py
IAN
IAN-master/lpips-pytorch/lpips_pytorch/modules/lpips.py
import torch import torch.nn as nn from .networks import get_network, LinLayers from .utils import get_state_dict class LPIPS(nn.Module): r"""Creates a criterion that measures Learned Perceptual Image Patch Similarity (LPIPS). Arguments: net_type (str): the network type to compare the features: ...
1,151
30.135135
71
py
IAN
IAN-master/lpips-pytorch/lpips_pytorch/modules/utils.py
from collections import OrderedDict import torch def normalize_activation(x, eps=1e-10): norm_factor = torch.sqrt(torch.sum(x ** 2, dim=1, keepdim=True)) return x / (norm_factor + eps) def get_state_dict(net_type: str = 'alex', version: str = '0.1'): # build url url = 'https://raw.githubusercontent...
885
27.580645
79
py
IAN
IAN-master/lpips-pytorch/lpips_pytorch/modules/networks.py
from typing import Sequence from itertools import chain import torch import torch.nn as nn from torchvision import models from .utils import normalize_activation def get_network(net_type: str): if net_type == 'alex': return AlexNet() elif net_type == 'squeeze': return SqueezeNet() elif ...
2,654
26.371134
79
py
IAN
IAN-master/network/lr_scheduler.py
import math from collections import Counter from torch.optim.lr_scheduler import _LRScheduler class MultiStepRestartLR(_LRScheduler): """ MultiStep with restarts learning rate scheme. Args: optimizer (torch.nn.optimizer): Torch optimizer. milestones (list): Iterations that will decrease learni...
4,312
37.508929
79
py
IAN
IAN-master/network/base_model.py
import logging import os import torch from collections import OrderedDict from copy import deepcopy from torch.nn.parallel import DataParallel, DistributedDataParallel from network import lr_scheduler as lr_scheduler logger = logging.getLogger('relighting') class BaseModel(): """Base model.""" def __init__...
11,448
37.163333
80
py
IAN
IAN-master/network/relight_model.py
import os import cv2 import torch import importlib import numpy as np from tqdm import tqdm from copy import deepcopy from network.loss import MSELoss from collections import OrderedDict from base_utils.utils import col_stitch from network.arch import define_network from network.base_model import BaseModel from torch.n...
32,717
39.69403
121
py
IAN
IAN-master/network/arch/full_model_one2one_arch.py
import torch import torch.nn as nn import torch.nn.functional as F conv_s2 = 4 pad0 = 1 align_corners=True def mean_channels(F): assert(F.dim() == 4) spatial_sum = F.sum(3, keepdim=True).sum(2, keepdim=True) return spatial_sum / (F.size(2) * F.size(3)) def std_channels(F): assert(F.dim() == 4) F...
14,082
40.178363
120
py
IAN
IAN-master/network/arch/full_model_one2one_woaux_arch.py
import torch import torch.nn as nn import torch.nn.functional as F conv_s2 = 4 pad0 = 1 align_corners=True def mean_channels(F): assert(F.dim() == 4) spatial_sum = F.sum(3, keepdim=True).sum(2, keepdim=True) return spatial_sum / (F.size(2) * F.size(3)) def std_channels(F): assert(F.dim() == 4) ...
13,759
39.351906
115
py
IAN
IAN-master/network/arch/vgg_arch.py
import os import torch from collections import OrderedDict from torch import nn as nn from torchvision.models import vgg as vgg VGG_PRETRAIN_PATH = 'experiments/pretrained_models/vgg19-dcbb9e9d.pth' NAMES = { 'vgg11': [ 'conv1_1', 'relu1_1', 'pool1', 'conv2_1', 'relu2_1', 'pool2', 'conv3_1', 'relu3...
6,223
36.721212
79
py
IAN
IAN-master/network/arch/any2any_arch.py
import torch import torch.nn as nn import torch.nn.functional as F conv_s2 = 4 pad0 = 1 align_corners=True def mean_channels(F): assert(F.dim() == 4) spatial_sum = F.sum(3, keepdim=True).sum(2, keepdim=True) return spatial_sum / (F.size(2) * F.size(3)) def std_channels(F): assert(F.dim() == 4) F_...
16,008
41.128947
120
py
IAN
IAN-master/network/arch/any2any_woaux_arch.py
import torch import torch.nn as nn import torch.nn.functional as F conv_s2 = 4 pad0 = 1 align_corners=True def mean_channels(F): assert(F.dim() == 4) spatial_sum = F.sum(3, keepdim=True).sum(2, keepdim=True) return spatial_sum / (F.size(2) * F.size(3)) def std_channels(F): assert(F.dim() == 4) F...
15,796
40.680739
122
py
IAN
IAN-master/network/arch/DPR_arch.py
import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import sys import numpy as np import time # we define Hour Glass network based on the paper # Stacked Hourglass Networks for Human Pose Estimation # Alejandro Newell, Kaiyu Yang, and Jia Deng # the code is ada...
10,302
39.72332
104
py
IAN
IAN-master/network/loss/losses.py
import math import torch from torch import autograd as autograd from torch import nn as nn from torch.nn import functional as F from network.arch.vgg_arch import VGGFeatureExtractor from network.loss.loss_utils import weighted_loss, ssim, create_window, rgb2gray _reduction_modes = ['none', 'mean', 'sum'] @weighted_l...
21,903
36.635739
131
py
IAN
IAN-master/network/loss/loss_utils.py
import functools from torch.nn import functional as F import torch from math import exp def gaussian(window_size, sigma): gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)]) return gauss/gauss.sum() def create_window(window_size, channel=1): _1D_window = ga...
5,179
30.975309
103
py
IAN
IAN-master/base_utils/utils.py
import numpy as np import cv2 import random import torch import time import os from PIL import Image from tqdm import tqdm def get_time_str(): return time.strftime('%Y%m%d_%H%M%S', time.localtime()) def set_random_seed(seed): """Set random seeds.""" random.seed(seed) np.random.seed(seed) torch.ma...
7,695
32.754386
152
py
IAN
IAN-master/base_utils/logger.py
import datetime import logging import time import os def get_env_info(): import torch import torchvision msg = ('\nVersion Information: ' f'\n\tPyTorch: {torch.__version__}' f'\n\tTorchVision: {torchvision.__version__}') return msg def init_tb_logger(log_dir): from torch....
4,431
35.933333
79
py
IAN
IAN-master/base_utils/matlab_utils.py
import math import numpy as np import torch def cubic(x): """cubic function used for calculate_weights_indices.""" absx = torch.abs(x) absx2 = absx**2 absx3 = absx**3 return (1.5 * absx3 - 2.5 * absx2 + 1) * ( (absx <= 1).type_as(absx)) + (-0.5 * absx3 + 2.5 * absx2 - 4 * absx + ...
13,720
39.958209
79
py
IAN
IAN-master/base_utils/gen_surface_normals.py
import numpy as np import cv2 import random import torch import os from tqdm import tqdm import argparse # from base_utils.utils import load_depth # args = argparse.ArgumentParser(description='Gen_Surface_Normal') # args.add_argument('--save_dir', type=str) # args.add_argument('--input_dir', type=str) # args = args.pa...
2,297
28.844156
114
py
SiPRNet
SiPRNet-main/Save_result_SiPRNet.py
import h5py import torch import os from pathlib import Path import numpy as np from Utils.Util import save_tensor_img from Model.model_SiPRNet import MyNet import random # Seed everything seed = 123 random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) # Set the device os.env...
1,633
29.259259
88
py
SiPRNet
SiPRNet-main/Model/model_SiPRNet.py
import torch # to load PyTorch library import torch.nn as nn # to load PyTorch library import torch.nn.functional as F class MyNet(nn.Module): def __init__(self): super(MyNet, self).__init__() in_dim = 1 out_dim = 2 in_size = 128 dim = 32 num_layer_res = 1 ...
7,166
39.954286
115
py
Molformer
Molformer-master/model/tr_msa.py
import copy import math import torch import torch.nn as nn import torch.nn.functional as F from model.tr_spe import Embeddings, FeedForward, clones, Generator3D, Feat_Embedding from model.tr_cpe import Encoder, EncoderLayer def build_model(vocab, tgt, dist_bar, N=6, embed_dim=512, ffn_dim=2048, head=8, dropout=0.1,...
4,202
35.868421
110
py
Molformer
Molformer-master/model/tr_all.py
import copy import torch.nn as nn from model.tr_spe import Embeddings, FeedForward, Generator3D from model.tr_afps import MultiRelationEncoder, EncoderLayer from model.tr_msa import MultiScaleMultiHeadedAttention def build_model(vocab, tgt, dist_bar, k, N=6, embed_dim=512, ffn_dim=2048, head=8, dropout=0.1): ass...
1,179
34.757576
107
py
Molformer
Molformer-master/model/tr_lsa.py
import copy import math import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable def build_model(vocab, tgt, dist_bar, N=6, embed_dim=512, ffn_dim=2048, head=8, dropout=0.1, out_both=False): c = copy.deepcopy attn = MultiHeadedAttention(head, embed_dim) ff = ...
7,868
31.25
116
py
Molformer
Molformer-master/model/tr_cpe.py
import copy import math import torch import torch.nn as nn import torch.nn.functional as F import sys sys.path.append("..") from model.tr_spe import Embeddings, FeedForward from model.tr_spe import LayerNorm, SublayerConnection, clones, Generator3D def build_model(vocab, tgt, N=6, embed_dim=512, ffn_dim=2048, head...
4,071
33.803419
112
py
Molformer
Molformer-master/model/tr_spe.py
""" reference from Harvard NLP: https://nlp.seas.harvard.edu/2018/04/03/attention.html""" import copy import math import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from mendeleev import element import sys sys.path.append("..") ####################################...
9,470
33.819853
117
py
Molformer
Molformer-master/model/tr_afps.py
import copy import torch import torch.nn as nn import sys sys.path.append("..") from model.tr_spe import Embeddings, FeedForward, LayerNorm, SublayerConnection, clones, Generator3D from model.tr_cpe import MultiHeadedAttention def build_model(vocab, tgt, k, N=6, embed_dim=512, ffn_dim=2048, head=8, dropout=0.1): ...
3,849
32.478261
116
py
SeqOT
SeqOT-main/tools/read_samples.py
#!/usr/bin/env python3 # Developed by Junyi Ma, Xieyuanli Chen # This file is covered by the LICENSE file in the root of the project SeqOT: https://github.com/BIT-MJY/SeqOT # SeqOT is the sequence enhanced version of our previous work OverlapTransformer: https://github.com/haomo-ai/OverlapTransformer # Brief: read samp...
7,579
49.198675
158
py
SeqOT
SeqOT-main/tools/loss.py
import torch import torch.nn as nn import os import numpy as np import sys def best_pos_distance(query, pos_vecs): num_pos = pos_vecs.shape[0] query_copies = query.repeat(int(num_pos), 1) diff = ((pos_vecs - query_copies) ** 2).sum(1) min_pos, _ = diff.min(0) max_pos, _ = diff.max(0) return mi...
3,410
33.11
111
py
SeqOT
SeqOT-main/modules/gem.py
import torch import torch.nn as nn import torch.nn.functional as F class GeM(nn.Module): def __init__(self, p=3, eps=1e-6): super(GeM, self).__init__() self.p = nn.Parameter(torch.ones(1) * p) self.eps = eps def forward(self, x): return self.gem(x, p=self.p, eps=self.eps) ...
701
29.521739
117
py
SeqOT
SeqOT-main/modules/netvlad.py
import torch import torch.nn as nn import torch.nn.functional as F import math class NetVLADLoupe(nn.Module): def __init__(self, feature_size, max_samples, cluster_size, output_dim, gating=True, add_batch_norm=True, is_training=True): super(NetVLADLoupe, self).__init__() self.feat...
3,612
33.740385
83
py
SeqOT
SeqOT-main/modules/seqTransformerCat.py
#!/usr/bin/env python3 # Developed by Junyi Ma, Xieyuanli Chen # This file is covered by the LICENSE file in the root of the project SeqOT: https://github.com/BIT-MJY/SeqOT # SeqOT is the sequence enhanced version of our previous work OverlapTransformer: https://github.com/haomo-ai/OverlapTransformer # Brief: architect...
3,992
41.031579
144
py
SeqOT
SeqOT-main/test/test_gem_prepare.py
#!/usr/bin/env python3 # Developed by Junyi Ma, Xieyuanli Chen # This file is covered by the LICENSE file in the root of the project SeqOT: https://github.com/BIT-MJY/SeqOT # SeqOT is the sequence enhanced version of our previous work OverlapTransformer: https://github.com/haomo-ai/OverlapTransformer # Brief: generate ...
4,373
41.057692
129
py
SeqOT
SeqOT-main/visualize/viz.py
#!/usr/bin/env python3 # Developed by Junyi Ma, Xieyuanli Chen # This file is covered by the LICENSE file in the root of the project SeqOT: https://github.com/BIT-MJY/SeqOT # SeqOT is the sequence enhanced version of our previous work OverlapTransformer: https://github.com/haomo-ai/OverlapTransformer # Brief: Visualiza...
6,135
42.828571
129
py
SeqOT
SeqOT-main/train/gen_sub_descriptors.py
#!/usr/bin/env python3 # Developed by Junyi Ma, Xieyuanli Chen # This file is covered by the LICENSE file in the root of the project SeqOT: https://github.com/BIT-MJY/SeqOT # SeqOT is the sequence enhanced version of our previous work OverlapTransformer: https://github.com/haomo-ai/OverlapTransformer # Brief: generate ...
4,032
47.011905
150
py
SeqOT
SeqOT-main/train/training_seqot.py
#!/usr/bin/env python3 # Developed by Junyi Ma, Xieyuanli Chen # This file is covered by the LICENSE file in the root of the project SeqOT: https://github.com/BIT-MJY/SeqOT # SeqOT is the sequence enhanced version of our previous work OverlapTransformer: https://github.com/haomo-ai/OverlapTransformer # Brief: train Seq...
8,499
41.288557
141
py
SeqOT
SeqOT-main/train/training_gem.py
#!/usr/bin/env python3 # Developed by Junyi Ma, Xieyuanli Chen # This file is covered by the LICENSE file in the root of the project SeqOT: https://github.com/BIT-MJY/SeqOT # SeqOT is the sequence enhanced version of our previous work OverlapTransformer: https://github.com/haomo-ai/OverlapTransformer # Brief: train GeM...
8,258
39.886139
144
py
mlcube
mlcube-master/mlcube/mlcube/shell.py
"""Various utils to work with shell (mostly - running external processes). - `Shell`: This class provides a collection of methods to work with shell to run external processes. """ import copy import logging import os import shutil import sys import typing as t from distutils import dir_util from pathlib import Path f...
19,348
48.997416
120
py
Relation-CZSL
Relation-CZSL-master/eval.py
import os, shutil import json import os.path as osp import re import logging import time import random from functools import reduce import resource # rlimit = resource.getrlimit(resource.RLIMIT_NOFILE) # resource.setrlimit(resource.RLIMIT_NOFILE, (2048, rlimit[1])) import numpy as np import scipy as sp from scipy.spat...
13,469
46.263158
183
py
Relation-CZSL
Relation-CZSL-master/train.py
import os, shutil import json import os.path as osp import re import logging import time import random from functools import reduce import resource rlimit = resource.getrlimit(resource.RLIMIT_NOFILE) resource.setrlimit(resource.RLIMIT_NOFILE, (2048, rlimit[1])) import numpy as np import scipy as sp from scipy.spatial....
29,461
46.983713
238
py
Relation-CZSL
Relation-CZSL-master/model/SepMask.py
import itertools import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torchvision.models import resnet18 from scipy.sparse import diags VIS_BACKBONE_FEAT_DIM = 512 class Discriminator(nn.Module): def __init__(self, input_dims=512, hidden_dims=512, output_dims=2)...
12,973
41.260586
161
py