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
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/utils.py
""" Code for various 1-off functions """ import argparse import functools import glob import gzip import os import pickle import sys from abc import ABC, abstractmethod from typing import List, Union, Optional, Dict, Any import numpy as np import pytorch_lightning as pl import torch import torch.nn as nn import torch....
15,038
32.871622
117
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/models.py
""" code for base VAE model """ import argparse import math from typing import Optional import pytorch_lightning as pl import torch import torch.nn.functional as torch_func from torch import nn, Tensor from torch.nn import functional as F from utils.utils_cmd import parse_dict, parse_list from weighted_retraining.we...
18,899
37.809035
120
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/metrics.py
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions...
10,528
41.800813
757
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/expr/expr_model.py
""" Contains code for the arithmetic expression model (Grammar VAE) """ from keras import backend as K import weighted_retraining.weighted_retraining.expr.eq_grammar as G masks_K = K.variable(G.masks) ind_of_ind_K = K.variable(G.ind_of_ind) MAX_LEN = 15 DIM = G.D
269
19.769231
71
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/expr/equation_vae.py
import collections import re from typing import List, Union import nltk import numpy as np import torch from torch import Tensor from weighted_retraining.weighted_retraining.expr import eq_grammar, expr_model_pt from weighted_retraining.weighted_retraining.expr.expr_model_pt import EquationVaeTorch def tokenize(s):...
6,693
37.471264
119
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/expr/expr_model_pt.py
""" Contains code for the shapes model """ from typing import Optional import torch from torch import nn, Tensor import weighted_retraining.weighted_retraining.expr.eq_grammar as eq_gram from weighted_retraining.weighted_retraining.models import BaseVAE, MLPRegressor masks_t = torch.tensor(eq_gram.masks) ind_of_ind...
8,201
37.688679
120
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/expr/expr_data.py
""" Code for loading and manipulating the arithmetic expression data """ import os from typing import Sequence, Any, Dict, Optional, Iterable, Collection import h5py import numpy as np import torch # noinspection PyUnresolvedReferences from numpy import exp, sin from torch import Tensor from torch.utils.data import D...
15,446
37.90932
119
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/expr/expr_data_pt.py
from typing import Optional import numpy as np import pytorch_lightning as pl import torch from torch.utils.data import DataLoader, TensorDataset, WeightedRandomSampler from weighted_retraining.weighted_retraining.utils import print_flush NUM_WORKERS = 3 class WeightedExprDataset(pl.LightningDataModule): """ I...
8,218
37.406542
122
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/shapes/shapes_data.py
import pytorch_lightning as pl from torch.utils.data import TensorDataset, WeightedRandomSampler NUM_WORKERS = 0 from torch.utils.data.dataloader import DataLoader, _SingleProcessDataLoaderIter, _MultiProcessingDataLoaderIter from torch.utils.data import _utils from torchvision import transforms as transforms import...
16,487
39.214634
122
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/shapes/shapes_model.py
""" Contains code for the shapes model """ import itertools from typing import Union, Optional import numpy as np import torch from torch import nn, distributions, Tensor from torchvision.utils import make_grid # My imports from weighted_retraining.weighted_retraining.models import BaseCLR, BaseVAE, UnFlatten, MLPRe...
9,584
29.623003
110
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/shapes/shapes_utils.py
from typing import Dict, Any import torch from tqdm import tqdm from weighted_retraining.weighted_retraining.shapes.shapes_model import ShapesVAE from weighted_retraining.weighted_retraining.utils import print_flush import numpy as np def get_latent_encodings(use_test_set: bool, use_full_data_for_gp: bool, model: ...
3,392
35.483871
125
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/train_scripts/train_shapes.py
""" Trains a convnet for the shapes task """ import argparse import os import shutil import sys from typing import Any, Optional, Dict, List from pathlib import Path ROOT_PROJECT = str(Path(os.path.realpath(__file__)).parent.parent.parent.parent) sys.path[0] = ROOT_PROJECT import pytorch_lightning as pl from pytorch_...
5,000
37.767442
108
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/train_scripts/train_chem.py
""" Script to train chem model """ import argparse import os import sys from pathlib import Path ROOT_PROJECT = str(Path(os.path.realpath(__file__)).parent.parent.parent.parent) sys.path[-1] = ROOT_PROJECT import pytorch_lightning as pl # My imports from pytorch_lightning.callbacks import LearningRateMonitor from ...
2,770
33.209877
90
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/train_scripts/train_expr_pt.py
""" Trains a VAE for the equation task """ import argparse import os import shutil import sys from pathlib import Path ROOT_PROJECT = str(Path(os.path.realpath(__file__)).parent.parent.parent.parent) sys.path[0] = ROOT_PROJECT import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import Learnin...
5,722
37.409396
111
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/topology/topology_data.py
import pytorch_lightning as pl from torch.utils.data import TensorDataset, WeightedRandomSampler, Dataset NUM_WORKERS = 0 from torch.utils.data.dataloader import DataLoader from torch.utils.data import _utils from torchvision import transforms as transforms import numpy as np import numbers from collections.abc impo...
8,784
37.530702
122
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/topology/topology_utils.py
from typing import Any, Dict, Optional import numpy as np import torch from torch import Tensor from tqdm import tqdm from torch.utils.data import DataLoader, TensorDataset from weighted_retraining.weighted_retraining.utils import print_flush from weighted_retraining.weighted_retraining.topology.topology_model import ...
10,106
39.590361
119
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/topology/topology_model.py
""" Contains code for the shapes model """ import itertools from typing import Union, Optional import numpy as np import torch from torch import nn, distributions, Tensor from torchvision.utils import make_grid # My imports from weighted_retraining.weighted_retraining.models import BaseVAE, UnFlatten, MLPRegressor ...
13,003
34.336957
112
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/topology/topology_dataset.py
import os from typing import Optional import torch from torch import Tensor from utils.utils_save import get_data_root import numpy as np import scipy as sp import matplotlib.pyplot as plt from sklearn.preprocessing import MaxAbsScaler, StandardScaler def get_topology_dataset_path(): return os.path.join(get_d...
4,185
38.490566
117
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/chem/chem_data.py
""" Code for chem datasets """ import pickle from typing import Any, Optional, Dict, List, Iterable import numpy as np import pytorch_lightning as pl import torch from torch import Tensor from torch.utils.data import DataLoader from tqdm import trange from tqdm.auto import tqdm import weighted_retraining.weighted_re...
22,741
36.71476
118
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/chem/chem_model.py
""" Contains code for the chem model (JT-VAE) """ import argparse import torch from torch import nn, Tensor import torch.nn.functional as torch_func # My imports from typing import List, Any, Optional from weighted_retraining.weighted_retraining import utils from weighted_retraining.weighted_retraining.models import...
6,034
34.292398
109
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/chem/jtnn/jtnn_enc.py
import torch import torch.nn as nn import torch.nn.functional as F from collections import deque from .mol_tree import Vocab, MolTree from .nnutils import index_select_ND class JTNNEncoder(nn.Module): def __init__(self, hidden_size, depth, embedding): super(JTNNEncoder, self).__init__() self.hidde...
4,824
34.477941
85
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/chem/jtnn/datautils.py
import torch from torch.utils.data import Dataset, DataLoader, IterableDataset from weighted_retraining.weighted_retraining.chem.jtnn.mol_tree import MolTree import numpy as np from weighted_retraining.weighted_retraining.chem.jtnn.jtnn_enc import JTNNEncoder from weighted_retraining.weighted_retraining.chem.jtnn.mpn i...
7,051
29.929825
93
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/chem/jtnn/nnutils.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable def index_select_ND(source, dim, index): index_size = index.size() suffix_dim = source.size()[1:] final_size = index_size + suffix_dim target = source.index_select(dim, index.view(-1)) return tar...
1,863
29.064516
59
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/chem/jtnn/mpn.py
import torch import torch.nn as nn import rdkit.Chem as Chem import torch.nn.functional as F from .nnutils import index_select_ND from .chemutils import get_mol ELEM_LIST = [ "C", "N", "O", "S", "F", "Si", "P", "Cl", "Br", "Mg", "Na", "Ca", "Fe", "Al", "I", ...
4,785
28.726708
77
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/chem/jtnn/jtnn_vae.py
import torch import torch.nn as nn import torch.nn.functional as F import pytorch_lightning as pl from .mol_tree import Vocab, MolTree from .nnutils import flatten_tensor, avg_pool from .jtnn_enc import JTNNEncoder from .jtnn_dec import JTNNDecoder from .mpn import MPN from .jtmpn import JTMPN from .datautils import te...
13,943
34.212121
97
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/chem/jtnn/jtmpn.py
import rdkit.Chem as Chem import torch import torch.nn as nn import torch.nn.functional as F from .nnutils import index_select_ND ELEM_LIST = [ "C", "N", "O", "S", "F", "Si", "P", "Cl", "Br", "Mg", "Na", "Ca", "Fe", "Al", "I", "B", "K", "Se", ...
5,718
30.949721
89
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/chem/jtnn/jtnn_dec.py
import torch import torch.nn as nn import torch.nn.functional as F from .mol_tree import Vocab, MolTree, MolTreeNode from .nnutils import GRU from .chemutils import enum_assemble, set_atommap import copy MAX_NB = 15 MAX_DECODE_LEN = 100 class JTNNDecoder(nn.Module): def __init__(self, vocab, hidden_size, latent_...
15,937
35.63908
90
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/robust_opt_scripts/robust_opt_topology.py
import argparse import gc import glob import logging import os import sys import time import traceback from pathlib import Path from typing import Dict, Any, List, Optional, Tuple import numpy as np import pytorch_lightning as pl import torch from botorch.models.transforms import Standardize from botorch.utils.transfo...
67,867
43.127438
143
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/robust_opt_scripts/robust_opt_expr.py
import argparse import gc import glob import os import sys import time import traceback from pathlib import Path from typing import Dict, Any, Tuple, List, Optional import numpy as np import torch from botorch.models.transforms import Standardize from botorch.utils.transforms import normalize, unnormalize from gpytorc...
65,068
43.204484
143
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/robust_opt_scripts/robust_opt_chem.py
import argparse import logging import os import shutil import subprocess import sys import time import traceback from pathlib import Path from typing import Dict, Any, Optional import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.loggers import TensorBoardLogger from tqdm.auto import t...
43,950
38.382616
120
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/robust_opt_scripts/utils.py
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions...
2,187
77.142857
757
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/bo_torch/mo_acquisition.py
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions...
5,172
54.623656
757
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/bo_torch/fit.py
from __future__ import annotations import time from typing import Any, Callable, Dict, List, NamedTuple, Optional, Set, Tuple, Union import numpy as np import torch from botorch.optim.numpy_converter import ( TorchAttr, ) from botorch.optim.stopping import ExpMAStoppingCriterion from botorch.optim.utils import ( ...
7,430
40.747191
120
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/bo_torch/utils.py
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions...
2,232
56.25641
757
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/bo_torch/optimize.py
r""" Methods for optimizing acquisition functions. """ from __future__ import annotations from typing import Callable, Dict, List, Optional, Tuple, Type, Union, Any, Iterable import torch from botorch.acquisition.acquisition import ( AcquisitionFunction, OneShotAcquisitionFunction, ) from botorch.acquisition...
10,502
40.027344
106
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/bo_torch/__init__.py
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions...
1,772
83.428571
757
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/bo_torch/mo_acq_func.py
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions...
14,091
51.192593
757
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/bo_torch/gp_torch.py
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions...
34,040
52.947702
757
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/partial_train_scripts/partial_train_topology.py
""" Trains a convnet for the Topology task """ import argparse import os import shutil import sys from typing import Any, Optional, Dict, List from pathlib import Path from torchvision.transforms import transforms ROOT_PROJECT = str(Path(os.path.realpath(__file__)).parent.parent.parent.parent) sys.path.insert(0, ROOT...
7,144
41.029412
112
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/partial_train_scripts/partial_train_shapes.py
""" Trains a convnet for the shapes task """ import argparse import os import shutil import sys from pathlib import Path from typing import Any, Optional, Dict, List ROOT_PROJECT = str(Path(os.path.realpath(__file__)).parent.parent.parent.parent) sys.path[0] = ROOT_PROJECT import pytorch_lightning as pl from pytorch_...
4,481
36.663866
108
py
HEBO
HEBO-master/T-LBO/weighted_retraining/weighted_retraining/partial_train_scripts/partial_train_expr.py
""" Trains a VAE for the equation task """ import argparse import os import shutil import sys from pathlib import Path ROOT_PROJECT = str(Path(os.path.realpath(__file__)).parent.parent.parent.parent) sys.path[0] = ROOT_PROJECT import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import Learnin...
6,848
39.288235
108
py
HEBO
HEBO-master/BOiLS/core/algos/GRiLLS/grills_env.py
# 2021.11.10-modified the reward function # Huawei Technologies Co., Ltd. <foss@huawei.com> import os from typing import List import abc_py import numpy as np import torch from dgl import DGLGraph from resources.abcRL.graphExtractor import extract_dgl_graph from core.action_space import Action from core.s...
8,638
36.724891
120
py
HEBO
HEBO-master/BOiLS/core/algos/GRiLLS/multi_grills_exp.py
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. Redistribution and use in source and binary # forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of condition...
12,615
39.828479
117
py
HEBO
HEBO-master/BOiLS/core/algos/bo/hebo/multi_hebo_exp.py
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. Redistribution and use in source and binary # forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of condition...
19,855
43.420582
118
py
HEBO
HEBO-master/BOiLS/core/algos/bo/combo/combo_exp.py
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. Redistribution and use in source and binary # forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of condition...
9,633
40.347639
117
py
HEBO
HEBO-master/BOiLS/core/algos/bo/combo/main_multi_combo.py
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. Redistribution and use in source and binary # forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of condition...
11,926
44.522901
120
py
HEBO
HEBO-master/BOiLS/core/algos/bo/combo/multi_combo_exp.py
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. Redistribution and use in source and binary # forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of condition...
16,989
42.121827
118
py
HEBO
HEBO-master/BOiLS/core/algos/bo/combo/main_combo.py
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. Redistribution and use in source and binary # forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of condition...
13,005
46.467153
120
py
HEBO
HEBO-master/BOiLS/core/algos/bo/boils/multi_boils_exp.py
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. Redistribution and use in source and binary # forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of condition...
21,768
42.889113
117
py
HEBO
HEBO-master/BOiLS/core/algos/bo/boils/utils.py
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. Redistribution and use in source and binary # forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions ...
2,861
47.508475
117
py
HEBO
HEBO-master/BOiLS/core/algos/bo/boils/multiseq_boils_exp.py
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. Redistribution and use in source and binary # forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of condition...
19,873
43.164444
119
py
HEBO
HEBO-master/BOiLS/DRiLLS/drills/exps/exp_gym.py
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. Redistribution and use in source and binary # forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions ...
8,380
41.979487
119
py
HEBO
HEBO-master/BOiLS/resources/casmopolitan/main.py
import argparse import logging import pandas as pd import time from resources.casmopolitan.bo.optimizer import Optimizer from resources.casmopolitan.bo.optimizer_mixed import MixedOptimizer from resources.casmopolitan.mixed_test_func import * from resources.casmopolitan.test_funcs import * from resources.casmopolitan....
6,169
42.146853
120
py
HEBO
HEBO-master/BOiLS/resources/casmopolitan/utils.py
from torch import Tensor def spearman(pred, target) -> float: """Compute the spearman correlation coefficient between prediction and target""" from scipy import stats coef_val, p_val = stats.spearmanr(pred, target) return coef_val def pearson(pred, target) -> float: from scipy import stats c...
1,711
28.016949
84
py
HEBO
HEBO-master/BOiLS/resources/casmopolitan/bo/kernels.py
# Implementation of various kernels import torch from gpytorch.constraints import Interval from gpytorch.kernels import Kernel from gpytorch.kernels.matern_kernel import MaternKernel from gpytorch.kernels.rbf_kernel import RBFKernel from torch import Tensor from resources.casmopolitan.utils import normalize class M...
15,169
41.732394
120
py
HEBO
HEBO-master/BOiLS/resources/casmopolitan/bo/seq_kernel_fast.py
# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved. Redistribution and use in source and binary # forms, with or without modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions ...
8,327
42.375
118
py
HEBO
HEBO-master/BOiLS/resources/casmopolitan/bo/localbo_utils.py
# 2021.11.10-Add support for ssk # Huawei Technologies Co., Ltd. <foss@huawei.com> import random from collections import Callable from copy import deepcopy import logging from gpytorch.distributions import MultivariateNormal from gpytorch.kernels import ScaleKernel from gpytorch.likelihoods import Gaussian...
20,669
40.011905
123
py
HEBO
HEBO-master/BOiLS/resources/casmopolitan/bo/optimizer_mixed.py
# 2021.11.10-Minor refactoring # Huawei Technologies Co., Ltd. <foss@huawei.com> from torch.quasirandom import SobolEngine from resources.casmopolitan.bo.localbo_mixed import CASMOPOLITANMixed from resources.casmopolitan.bo.localbo_utils import to_unit_cube from resources.casmopolitan.bo.optimizer import *...
9,565
50.15508
120
py
HEBO
HEBO-master/BOiLS/resources/casmopolitan/bo/localbo_mixed.py
# 2021.11.10-Specify `tr` in adjust_length # Huawei Technologies Co., Ltd. <foss@huawei.com> from copy import deepcopy import gpytorch import math import numpy as np import torch from torch.quasirandom import SobolEngine from resources.casmopolitan.bo.localbo_cat import CASMOPOLITANCat from resources.casm...
12,976
49.104247
117
py
HEBO
HEBO-master/BOiLS/resources/casmopolitan/bo/localbo_cat.py
# 2021.11.10-Add support for ssk # Huawei Technologies Co., Ltd. <foss@huawei.com> from copy import deepcopy from typing import Optional import gpytorch import math import numpy as np import sys import torch from core.algos.bo.boils.utils import InputTransformation, SentenceBertInputTransform from resourc...
15,807
44.82029
120
py
HEBO
HEBO-master/BOiLS/resources/casmopolitan/bo/optimizer.py
# 2021.11.10-Add support for ssk # Huawei Technologies Co., Ltd. <foss@huawei.com> from copy import deepcopy from typing import Optional, List, Union import numpy as np import torch import scipy.stats as ss from gpytorch.utils.errors import NotPSDError, NanError from core.algos.bo.boils.utils import Input...
12,947
48.992278
146
py
HEBO
HEBO-master/BOiLS/resources/abcRL/reinforce.py
## # @file reinforce.py # @author Keren Zhu # @date 10/30/2019 # @brief The REINFORCE algorithm # import torch from torch import nn import torch.nn.functional as F from torch.distributions import Categorical import bisect import random from dgl.nn.pytorch import GraphConv import dgl from resources.abcRL.env import En...
8,581
30.903346
105
py
HEBO
HEBO-master/BOiLS/resources/abcRL/graphExtractor.py
## # @file graphExtractor.py # @author Keren Zhu # @date 11/16/2019 # @brief The functions and classes for processing the graph # import warnings import dgl import numpy as np import torch from dgl.base import DGLWarning from numpy import linalg def symmetricLaplacian(abc): numNodes = abc.numNodes() L = np....
1,813
26.074627
62
py
HEBO
HEBO-master/BOiLS/resources/abcRL/env.py
## # @file env.py # @author Keren Zhu # @date 10/25/2019 # @brief The environment classes # # 2021.11.10-Remove one comment # Huawei Technologies Co., Ltd. <foss@huawei.com> import abc_py as abcPy import numpy as np from resources import abcRL as GE import torch class EnvNaive2(object): """ @brie...
10,913
34.093248
110
py
HEBO
HEBO-master/CompBO/core/bayes_opt.py
import time from typing import Type, Optional, List, Any, Dict, Union, Tuple import numpy as np import torch from botorch.acquisition import qUpperConfidenceBound, qExpectedImprovement, \ qProbabilityOfImprovement, AcquisitionFunction, OneShotAcquisitionFunction, qNoisyExpectedImprovement from botorch.fit import f...
37,539
46.943806
134
py
HEBO
HEBO-master/CompBO/core/es/evolution_opt.py
from typing import Dict import numpy as np import torch from botorch.utils import draw_sobol_samples from gpytorch.utils.errors import NotPSDError from pymoo.algorithms.so_cmaes import CMAES from pymoo.algorithms.so_de import DE from pymoo.configuration import Configuration from pymoo.model.problem import get_problem...
6,344
41.3
122
py
HEBO
HEBO-master/CompBO/core/comp_acquisition/compositional_acquisition.py
from abc import ABC, abstractmethod from typing import Optional, Tuple, Union, Callable import numpy as np import torch from botorch.utils import draw_sobol_normal_samples from torch import Tensor class CompositionalAcquisition(ABC): """ Abstract class for Compositional Acquisition Functions: alpha(x) = f(E[...
5,500
40.674242
120
py
HEBO
HEBO-master/CompBO/core/comp_acquisition/mc_compositional_acquisition.py
from typing import Union, Optional import torch from botorch.acquisition import qExpectedImprovement, MCAcquisitionObjective, qProbabilityOfImprovement, qSimpleRegret, \ qUpperConfidenceBound from botorch.models.model import Model from botorch.sampling import MCSampler from botorch.utils import draw_sobol_normal_s...
19,880
43.979638
121
py
HEBO
HEBO-master/CompBO/core/comp_acquisition/mc_fs_acquisition.py
import math from typing import Union, Optional from botorch.acquisition import qExpectedImprovement, qSimpleRegret, qProbabilityOfImprovement, qUpperConfidenceBound, \ MCAcquisitionObjective from botorch.models.model import Model from botorch.sampling import MCSampler import torch from botorch.utils.transforms imp...
11,339
40.386861
120
py
HEBO
HEBO-master/CompBO/core/gp/custom_gp.py
import math from typing import Optional, List import numpy as np import torch from gpytorch.constraints.constraints import GreaterThan from gpytorch.distributions.multivariate_normal import MultivariateNormal from gpytorch.functions import MaternCovariance from gpytorch.kernels import Kernel from gpytorch.kernels.scal...
12,730
47.041509
129
py
HEBO
HEBO-master/CompBO/core/utils/utils_query.py
from typing import Type, List, Optional import torch from botorch import test_functions, acquisition from botorch.acquisition import MCAcquisitionFunction from botorch.test_functions import SyntheticTestFunction from gpytorch.kernels import MaternKernel, RBFKernel, ScaleKernel, Kernel from gpytorch.priors import Gamma...
5,545
38.056338
110
py
HEBO
HEBO-master/CompBO/custom_optimizer/cadam.py
import math from typing import Optional, Callable import torch from torch.autograd.functional import vjp from torch.optim.optimizer import required from custom_optimizer.comp_opt import CompositionalOptimizer class CAdam(CompositionalOptimizer): r"""Implements Compositional Adam algorithm. Arguments: ...
7,148
46.344371
118
py
HEBO
HEBO-master/CompBO/custom_optimizer/scgd.py
from typing import Optional import torch from torch.autograd.functional import vjp from torch.optim.optimizer import required from custom_optimizer.comp_opt import CompositionalOptimizer class SCGD(CompositionalOptimizer): r"""Implements Stochastic Compositional Gradient Descent. `https://arxiv.org/pdf/1411.380...
4,114
43.247312
137
py
HEBO
HEBO-master/CompBO/custom_optimizer/adamos.py
import math import torch from torch.optim.optimizer import Optimizer class Adamos(Optimizer): r"""Implements Adam-like optimization steps with CAdam scheduling. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional)...
4,927
43.396396
114
py
HEBO
HEBO-master/CompBO/custom_optimizer/ascgd.py
from typing import Optional import torch from torch.autograd.functional import vjp from torch.optim.optimizer import required from custom_optimizer.comp_opt import CompositionalOptimizer class ASCGD(CompositionalOptimizer): r"""Implements Accelerated Stochastic Compositional Gradient Descent. `https://arxiv.org...
4,300
42.444444
136
py
HEBO
HEBO-master/CompBO/custom_optimizer/nasa.py
import math from typing import Optional, Callable import torch from torch.autograd.functional import vjp from torch.optim.optimizer import Optimizer, required from custom_optimizer.comp_opt import CompositionalOptimizer class NASA(CompositionalOptimizer): r"""Implements Nested Averaged Stochastic Approximation....
4,531
40.962963
114
py
HEBO
HEBO-master/CompBO/custom_optimizer/comp_opt.py
from torch.optim import Optimizer class CompositionalOptimizer(Optimizer): pass
86
13.5
40
py
HEBO
HEBO-master/CompBO/custom_optimizer/utils/utils.py
from botorch.optim.utils import columnwise_clamp from torch import Tensor from typing import Optional, Union def columnwise_clamp_( X: Tensor, lower: Optional[Union[float, Tensor]] = None, upper: Optional[Union[float, Tensor]] = None, raise_on_violation: bool = False, ) -> Tensor: r"""Clamp values ...
1,131
39.428571
85
py
HEBO
HEBO-master/CompBO/utils/utils_gp.py
import matplotlib.pyplot as plt import numpy as np import torch from gpytorch import ExactMarginalLogLikelihood from botorch import fit_gpytorch_model from botorch.models import SingleTaskGP def test_gp_fit(x: np.ndarray, y: np.ndarray, ax=None, title='GP fit'): n_held_out = int(.25 * len(y)) indices = np.ra...
1,390
38.742857
87
py
HEBO
HEBO-master/SIMMER/envs/utils.py
import torch import numpy as np from typing import Union Array = Union[torch.Tensor, np.ndarray] def angle_normalize(theta:Array, is_tensor:bool=True) -> Array: """Normalizes an angle theta to be between -pi and pi.""" if is_tensor: torch_pi = torch.Tensor(np.asarray(np.pi)) return ((theta + t...
422
29.214286
63
py
HEBO
HEBO-master/SIMMER/envs/pendula/single_pendulum.py
import gym from gym import spaces from gym.utils import seeding import numpy as np from typing import Callable, List, Dict, Tuple import torch from os import path from envs.utils import angle_normalize, Array from envs.wrappers.safe_env import SafeEnv from envs.wrappers.simmer_env import simmer_env from envs.wrappers...
10,248
44.14978
166
py
HEBO
HEBO-master/SIMMER/envs/wrappers/saute_env.py
import numpy as np import torch from gym import Env from gym import spaces from envs.utils import Array class SauteBaseEnv(Env): def __init__( self, saute_discount_factor:float=0.99, max_ep_len:int=200, unsafe_reward:float=0, use_reward_shaping:bool=True,...
5,996
41.835714
165
py
HEBO
HEBO-master/SIMMER/envs/wrappers/simmer_env.py
import numpy as np import torch from gym import Env from gym import spaces from envs.utils import Array class SimmerBaseEnv(Env): def __init__( self, saute_discount_factor:float=0.99, max_ep_len:int=200, unsafe_reward:float=0, use_reward_shaping:bool=True...
6,501
41.220779
144
py
HEBO
HEBO-master/SIMMER/tf_algos/safety_starter_agents/run_agents.py
""" Main run file copied from safety starter agents with the following modifications: - added a capability for Sauteing Vanilla and Lagrangian methods - added a capability to use CVaR constraints """ import numpy as np from tensorboardX.writer import SummaryWriter import tensorflow as tf import pandas as pd import time...
31,506
42.759722
141
py
VSR-Transformer
VSR-Transformer-main/setup.py
#!/usr/bin/env python from setuptools import find_packages, setup import os import subprocess import sys import time import torch from torch.utils.cpp_extension import (BuildExtension, CppExtension, CUDAExtension) version_file = 'basicsr/version.py' def readme(): with ope...
5,365
29.662857
77
py
VSR-Transformer
VSR-Transformer-main/scripts/publish_models.py
import glob import subprocess import torch from os import path as osp from torch.serialization import _is_zipfile, _open_file_like def update_sha(paths): print('# Update sha ...') for idx, path in enumerate(paths): print(f'{idx+1:03d}: Processing {path}') net = torch.load(path, map_location=to...
2,463
40.066667
79
py
VSR-Transformer
VSR-Transformer-main/scripts/model_conversion/convert_ridnet.py
import torch from collections import OrderedDict from basicsr.models.archs.ridnet_arch import RIDNet if __name__ == '__main__': ori_net_checkpoint = torch.load( 'experiments/pretrained_models/RIDNet/RIDNet_official_original.pt', map_location=lambda storage, loc: storage) rid_net = RIDNet(3, 64...
768
29.76
75
py
VSR-Transformer
VSR-Transformer-main/scripts/model_conversion/convert_models.py
import torch def convert_edvr(): ori_net = torch.load('experiments/pretrained_models/EDVR_REDS_SR_M.pth') crt_net = torch.load('xxx/net_g_8.pth') save_path = './edvr_medium_x4_reds_sr_official.pth' # for k, v in ori_net.items(): # print(k) # print('*****') # for k, v in crt_net.items...
17,432
41.938424
79
py
VSR-Transformer
VSR-Transformer-main/scripts/model_conversion/convert_dfdnet.py
import torch from basicsr.models.archs.dfdnet_arch import DFDNet from basicsr.models.archs.vgg_arch import NAMES def convert_net(ori_net, crt_net): for crt_k, crt_v in crt_net.items(): # vgg feature extractor if 'vgg_extractor' in crt_k: ori_k = crt_k.replace('vgg_extractor', ...
3,023
36.8
77
py
VSR-Transformer
VSR-Transformer-main/scripts/model_conversion/convert_stylegan.py
import torch from basicsr.models.archs.stylegan2_arch import (StyleGAN2Discriminator, StyleGAN2Generator) def convert_net_g(ori_net, crt_net): """Convert network generator.""" for crt_k, crt_v in crt_net.items(): if 'style_mlp' in crt_k: o...
3,612
35.13
119
py
VSR-Transformer
VSR-Transformer-main/scripts/metrics/calculate_fid_stats_from_datasets.py
import argparse import math import numpy as np import torch from torch.utils.data import DataLoader from basicsr.data import create_dataset from basicsr.metrics.fid import (extract_inception_features, load_patched_inception_v3) def calculate_stats_from_dataset(): device = torch.d...
2,294
30.438356
76
py
VSR-Transformer
VSR-Transformer-main/scripts/metrics/calculate_fid_folder.py
import argparse import math import numpy as np import torch from torch.utils.data import DataLoader from basicsr.data import create_dataset from basicsr.metrics.fid import (calculate_fid, extract_inception_features, load_patched_inception_v3) def calculate_fid_folder(): device = ...
2,643
30.47619
76
py
VSR-Transformer
VSR-Transformer-main/scripts/metrics/calculate_stylegan2_fid.py
import argparse import math import numpy as np import torch from torch import nn from basicsr.metrics.fid import (calculate_fid, extract_inception_features, load_patched_inception_v3) from basicsr.models.archs.stylegan2_arch import StyleGAN2Generator def calculate_stylegan2_fid(): ...
2,858
34.7375
76
py
VSR-Transformer
VSR-Transformer-main/scripts/metrics/calculate_lpips.py
import cv2 import glob import numpy as np import os.path as osp from torchvision.transforms.functional import normalize from basicsr.utils import img2tensor try: import lpips except ImportError: print('Please install lpips: pip install lpips') def main(): # Configurations # -------------------------...
1,854
31.54386
79
py
VSR-Transformer
VSR-Transformer-main/tests/test_ffhq_dataset.py
import math import os import torch import torchvision.utils from basicsr.data import create_dataloader, create_dataset def main(): """Test FFHQ dataset.""" opt = {} opt['dist'] = False opt['gpu_ids'] = [0] opt['phase'] = 'train' opt['name'] = 'FFHQ' opt['type'] = 'FFHQDataset' opt['...
1,402
21.629032
64
py
VSR-Transformer
VSR-Transformer-main/tests/test_vimeo90k_dataset.py
import math import os import torchvision.utils from basicsr.data import create_dataloader, create_dataset def main(mode='lmdb'): """Test vimeo90k dataset. Args: mode: There are two modes: 'lmdb', 'folder'. """ opt = {} opt['dist'] = False opt['phase'] = 'train' opt['name'] = 'Vi...
2,951
30.741935
115
py
VSR-Transformer
VSR-Transformer-main/tests/test_discriminator_backward.py
import copy import random import torch from torch import nn as nn class ToyDiscriminator(nn.Module): def __init__(self): super(ToyDiscriminator, self).__init__() self.conv0 = nn.Conv2d(3, 4, 3, 1, 1, bias=True) self.bn0 = nn.BatchNorm2d(4, affine=True) self.conv1 = nn.Conv2d(4, 4,...
2,923
25.825688
70
py
VSR-Transformer
VSR-Transformer-main/tests/test_paired_image_dataset.py
import math import os import torchvision.utils from basicsr.data import create_dataloader, create_dataset def main(mode='folder'): """Test paired image dataset. Args: mode: There are three modes: 'lmdb', 'folder', 'meta_info_file'. """ opt = {} opt['dist'] = False opt['phase'] = 'tra...
2,396
27.879518
98
py
VSR-Transformer
VSR-Transformer-main/tests/test_lr_scheduler.py
import torch from basicsr.models.lr_scheduler import CosineAnnealingRestartLR try: import matplotlib as mpl from matplotlib import pyplot as plt from matplotlib import ticker as mtick except ImportError: print('Please install matplotlib.') mpl.use('Agg') def main(): optim_params = [ { ...
1,880
24.418919
79
py
VSR-Transformer
VSR-Transformer-main/tests/test_reds_dataset.py
import math import os import torchvision.utils import time from basicsr.data import create_dataloader, create_dataset def main(mode='lmdb'): """Test reds dataset. Args: mode: There are two modes: 'lmdb', 'folder'. """ opt = {} opt['dist'] = False opt['phase'] = 'train' opt['name'...
2,955
28.858586
102
py