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 |
|---|---|---|---|---|---|---|
splade | splade-main/splade/tasks/transformer_trainer.py | import json
import os
from collections import defaultdict
import torch
from omegaconf import open_dict
from tqdm.auto import tqdm
from ..tasks import amp
from ..tasks.base.trainer import TrainerIter
from ..utils.metrics import init_eval
from ..utils.utils import parse
class TransformerTrainer(TrainerIter):
def ... | 17,265 | 61.33213 | 138 | py |
splade | splade-main/splade/tasks/transformer_evaluator.py | import json
import os
import pickle
import time
from collections import defaultdict
import numba
import numpy as np
import torch
from tqdm.auto import tqdm
from ..indexing.inverted_index import IndexDictOfArray
from ..losses.regularization import L0
from ..tasks.base.evaluator import Evaluator
from ..utils.utils impo... | 13,910 | 51.101124 | 120 | py |
splade | splade-main/splade/tasks/amp.py | import torch
# inspired from Colbert repo: https://github.com/stanford-futuredata/ColBERT
PyTorch_over_1_6 = float((torch.__version__.split('.')[1])) >= 6 and float((torch.__version__.split('.')[0])) >= 1
# replace this with contextlib.nullcontext if python >3.7
# see https://stackoverflow.com/a/45187287
class Nul... | 1,402 | 28.229167 | 114 | py |
splade | splade-main/splade/tasks/base/evaluator.py | import os
import torch
from ...utils.utils import restore_model
class Evaluator:
def __init__(self, model, config=None, restore=True):
"""base class for model evaluation (inference)
"""
self.model = model
self.config = config
self.device = torch.device("cuda") if torch.cu... | 1,818 | 46.868421 | 119 | py |
splade | splade-main/splade/tasks/base/trainer.py | # disclaimer: inspired from https://github.com/victoresque/pytorch-template
import os
import time
import torch
from omegaconf import open_dict
from torch.utils.tensorboard import SummaryWriter
from .early_stopping import EarlyStopping
from .saver import ValidationSaver
from ...utils.utils import makedir, remove_old_... | 7,797 | 47.7375 | 124 | py |
splade | splade-main/splade/losses/regularization.py | import torch
class L1:
def __call__(self, batch_rep):
return torch.sum(torch.abs(batch_rep), dim=-1).mean()
class L0:
"""non-differentiable
"""
def __call__(self, batch_rep):
return torch.count_nonzero(batch_rep, dim=-1).float().mean()
class FLOPS:
"""constraint from Minimizi... | 1,719 | 22.243243 | 88 | py |
splade | splade-main/splade/losses/pairwise.py | import torch
"""general API for losses: the __call__ method receives out_d, a dict containing at least scores for positives
and negatives
"""
class PairwiseNLL:
def __init__(self):
self.logsoftmax = torch.nn.LogSoftmax(dim=1)
def __call__(self, out_d):
pos_scores, neg_scores = out_d["pos_... | 3,372 | 38.682353 | 111 | py |
splade | splade-main/splade/losses/pointwise.py | import torch
class BCEWithLogitsLoss:
def __init__(self):
self.device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
self.loss = torch.nn.BCEWithLogitsLoss(reduction="mean")
def __call__(self, out_d):
pos_scores, neg_scores = out_d["pos_score"], out_d["ne... | 542 | 35.2 | 96 | py |
AmpliGraph | AmpliGraph-main/tests/ampligraph/latent_features/test_regularizer.py | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
from ampligraph.datasets import load_fb15k_237
from ampligraph.latent_features... | 1,519 | 37.974359 | 117 | py |
AmpliGraph | AmpliGraph-main/tests/ampligraph/latent_features/test_optimizers.py | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
from ampligraph.latent_features import optimizers
import pytest
import tensorf... | 3,198 | 36.635294 | 100 | py |
AmpliGraph | AmpliGraph-main/tests/ampligraph/latent_features/layers/test_predictions.py | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import tensorflow as tf
import numpy as np
from ampligraph.datasets import loa... | 3,529 | 33.271845 | 105 | py |
AmpliGraph | AmpliGraph-main/docs/conf.py | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# ampligraph documentation bui... | 6,536 | 29.834906 | 126 | py |
AmpliGraph | AmpliGraph-main/ampligraph/latent_features/loss_functions.py | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import abc
import logging
import six
import tensorflow as tf
from tensorflow.p... | 24,974 | 31.56193 | 125 | py |
AmpliGraph | AmpliGraph-main/ampligraph/latent_features/optimizers.py | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import abc
import logging
import six
import tensorflow as tf
logger = logging... | 7,263 | 34.783251 | 116 | py |
AmpliGraph | AmpliGraph-main/ampligraph/latent_features/regularizers.py | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
from functools import partial
import tensorflow as tf
def LP_regularizer(tr... | 2,295 | 32.275362 | 119 | py |
AmpliGraph | AmpliGraph-main/ampligraph/latent_features/models/ScoringBasedEmbeddingModel.py | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import tensorflow as tf
import copy
import shelve
import pickle
import numpy as... | 93,674 | 40.55945 | 172 | py |
AmpliGraph | AmpliGraph-main/ampligraph/latent_features/layers/encoding/EmbeddingLookupLayer.py | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import tensorflow as tf
import numpy as np
class EmbeddingLookupLayer(tf.kera... | 13,633 | 36.456044 | 131 | py |
AmpliGraph | AmpliGraph-main/ampligraph/latent_features/layers/calibration/calibrate.py | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import tensorflow as tf
class CalibrationLayer(tf.keras.layers.Layer):
""... | 4,064 | 30.269231 | 119 | py |
AmpliGraph | AmpliGraph-main/ampligraph/latent_features/layers/scoring/AbstractScoringLayer.py | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import tensorflow as tf
# Precision for floating point comparison
COMPARISION_... | 16,689 | 37.813953 | 120 | py |
AmpliGraph | AmpliGraph-main/ampligraph/latent_features/layers/corruption_generation/CorruptionGenerationLayerTrain.py | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import tensorflow as tf
class CorruptionGenerationLayerTrain(tf.keras.layers.... | 3,474 | 34.459184 | 94 | py |
AmpliGraph | AmpliGraph-main/ampligraph/compat/models.py | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import numpy as np
import tensorflow as tf
from ampligraph.latent_features.lo... | 29,377 | 33.849348 | 79 | py |
AmpliGraph | AmpliGraph-main/ampligraph/datasets/data_adapter.py | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import contextlib
import tqdm
from tensorflow.python.framework import errors
... | 4,961 | 33.22069 | 108 | py |
AmpliGraph | AmpliGraph-main/ampligraph/datasets/partitioned_data_manager.py | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import abc
import glob
import logging
import os
import shelve
import shutil
imp... | 38,764 | 37.998994 | 113 | py |
AmpliGraph | AmpliGraph-main/ampligraph/utils/model_utils.py | # Copyright 2019-2023 The AmpliGraph Authors. All Rights Reserved.
#
# This file is Licensed under the Apache License, Version 2.0.
# A copy of the Licence is available in LICENCE, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import glob
import logging
import os
import pickle
import shutil
from time impo... | 15,474 | 37.209877 | 118 | py |
TWM-metonymy-resolution | TWM-metonymy-resolution-main/src/run_metonymy_resolution.py | from utils_metonymy import *
import argparse
from argparse import Namespace
import logging
import os
import re
import glob
import sys
import random
from tqdm import tqdm, trange
import numpy as np
import torch
from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler)
from tensorboardX import Summar... | 17,353 | 42.603015 | 154 | py |
TWM-metonymy-resolution | TWM-metonymy-resolution-main/src/utils_metonymy.py | from transformers import BertConfig, BertTokenizer, BertPreTrainedModel, BertModel
from transformers.data import DataProcessor
from torch.utils.data import TensorDataset
import os
import copy
import json
import torch
from torch import nn
from torch.nn import CrossEntropyLoss
import random
import logging
logger = logg... | 13,434 | 40.984375 | 124 | py |
TWM-metonymy-resolution | TWM-metonymy-resolution-main/src/run_bert_tagger.py | from utils_bert_tagger import convert_examples_to_features, get_labels, read_examples_from_file
import argparse
from argparse import Namespace
import logging
import os
import re
import glob
import sys
import random
from tqdm import tqdm, trange
import numpy as np
import torch
from seqeval.metrics import precision_scor... | 22,361 | 44.084677 | 135 | py |
CA-MKD | CA-MKD-master/train_student.py | """
the general training framework
"""
from __future__ import print_function
import os
import re
import argparse
import time
import numpy
import torch
import torch.optim as optim
import torch.multiprocessing as mp
import torch.distributed as dist
import torch.nn as nn
import torch.backends.cudnn as cudnn
import tens... | 18,239 | 41.816901 | 170 | py |
CA-MKD | CA-MKD-master/train_teacher.py | from __future__ import print_function
import os
import argparse
import time
import torch
import torch.optim as optim
import torch.multiprocessing as mp
import torch.distributed as dist
import torch.nn as nn
import torch.backends.cudnn as cudnn
import tensorboard_logger as tb_logger
from models import model_dict
from... | 10,798 | 42.544355 | 161 | py |
CA-MKD | CA-MKD-master/dataset/cifar100.py | from __future__ import print_function
import os
import numpy as np
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from PIL import Image
"""
mean = {
'cifar100': (0.5071, 0.4867, 0.4408),
}
std = {
'cifar100': (0.2675, 0.2565, 0.2761),
}
"""
def get_data_folder():
"... | 7,720 | 32.137339 | 90 | py |
CA-MKD | CA-MKD-master/dataset/base.py | # https://github.com/tanglang96/DataLoaders_DALI/blob/master/base.py
from nvidia.dali.plugin.pytorch import DALIGenericIterator
class DALIDataloader(DALIGenericIterator):
def __init__(self, pipeline, size, batch_size, output_map=["data", "label"], auto_reset=True, onehot_label=False):
self.size = size
... | 1,120 | 37.655172 | 118 | py |
CA-MKD | CA-MKD-master/models/resnet_imagenet.py | # Copied from https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
# Only two changes:
# 1. Resnet.forward() is modified to return inner feature maps.
# 2. merge utils.py into this file to import load_state_dict_from_url.
import torch
import torch.nn as nn
from einops.layers.torch import Rearran... | 17,157 | 38.534562 | 107 | py |
CA-MKD | CA-MKD-master/models/resnet.py | from __future__ import absolute_import
'''Resnet for cifar dataset.
Ported form
https://github.com/facebook/fb.resnet.torch
and
https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
(c) YANG, Wei
'''
import torch.nn as nn
import torch.nn.functional as F
from einops.layers.torch import Rearrange
im... | 8,511 | 29.508961 | 116 | py |
CA-MKD | CA-MKD-master/models/mobilenetv2.py | """
MobileNetV2 implementation used in
<Knowledge Distillation via Route Constrained Optimization>
"""
import torch
import torch.nn as nn
import math
__all__ = ['mobilenetv2_T_w', 'mobile_half']
BN = None
def conv_bn(inp, oup, stride):
return nn.Sequential(
nn.Conv2d(inp, oup, 3, stride, 1, bias=False)... | 5,880 | 27.410628 | 115 | py |
CA-MKD | CA-MKD-master/models/vgg.py | '''
Three FC layers of VGG-ImageNet are replaced with single one,
thus the total layer number should be reduced by two on CIFAR-100.
For example, the actual number of layers for VGG-8 is 6.
VGG for CIFAR10. FC layers are removed.
(c) YANG, Wei
'''
import math
import torch.nn as nn
import torch.nn.functional as F
fro... | 7,054 | 29.80786 | 98 | py |
CA-MKD | CA-MKD-master/models/resnet_imagenet_semckd.py | # Copied from https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
# Only two changes:
# 1. Resnet.forward() is modified to return inner feature maps.
# 2. merge utils.py into this file to import load_state_dict_from_url.
import torch
import torch.nn as nn
from einops.layers.torch import Rearran... | 19,555 | 38.427419 | 107 | py |
CA-MKD | CA-MKD-master/models/classifier.py | from __future__ import print_function
import torch.nn as nn
#########################################
# ===== Classifiers ===== #
#########################################
class LinearClassifier(nn.Module):
def __init__(self, dim_in, n_label=10):
super(LinearClassifier, self).__init__()
self.n... | 819 | 21.777778 | 51 | py |
CA-MKD | CA-MKD-master/models/mobilenetv2_imagenet.py | # Copied from https://github.com/pytorch/vision/blob/master/torchvision/models/mobilenet.py
# Only two changes:
# 1. MobileNetV2.forward() is modified to return inner feature maps.
# 2. merge utils.py into this file to import load_state_dict_from_url.
from torch import nn
# https://github.com/pytorch/vision/blob/mast... | 8,051 | 36.626168 | 116 | py |
CA-MKD | CA-MKD-master/models/shuffleNetv2_imagenet.py | # Copied from https://github.com/pytorch/vision/blob/master/torchvision/models/shufflenetv2.py
# Only two changes:
# 1. ShuffleNet is modified to return inner feature maps.
# 2. merge utils.py into this file to import load_state_dict_from_url.
import torch
import torch.nn as nn
# https://github.com/pytorch/vision/blo... | 8,679 | 35.166667 | 114 | py |
CA-MKD | CA-MKD-master/models/vgg_imagenet.py | # Copied from https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py
# Only two changes:
# 1. VGG is modified to return inner feature maps.
# 2. merge utils.py into this file to import load_state_dict_from_url.
import torch
import torch.nn as nn
# https://github.com/pytorch/vision/blob/master/torchvi... | 9,360 | 37.522634 | 113 | py |
CA-MKD | CA-MKD-master/models/ShuffleNetv1.py | '''ShuffleNet in PyTorch.
See the paper "ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class ShuffleBlock(nn.Module):
def __init__(self, groups):
super(ShuffleBlock, self).__init_... | 4,732 | 33.05036 | 126 | py |
CA-MKD | CA-MKD-master/models/util.py | from __future__ import print_function
from numpy import append
from numpy.core.fromnumeric import transpose
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class ConvReg(nn.Module):
"""Convolutional regression for FitNet (feature map layer)"""
def __init__(self, s_shape, t_shape... | 8,202 | 31.943775 | 108 | py |
CA-MKD | CA-MKD-master/models/ShuffleNetv2.py | '''ShuffleNetV2 in PyTorch.
See the paper "ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class ShuffleBlock(nn.Module):
def __init__(self, groups=2):
super(ShuffleBlock, self).__init__()
... | 7,573 | 31.646552 | 107 | py |
CA-MKD | CA-MKD-master/models/resnetv2-org.py | '''ResNet in PyTorch.
For Pre-activation ResNet, see 'preact_resnet.py'.
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansio... | 6,438 | 33.61828 | 106 | py |
CA-MKD | CA-MKD-master/models/wrn.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
Original Author: Wei Yang
"""
__all__ = ['wrn']
class Flatten(nn.Module):
"""flatten module"""
def __init__(self):
super(Flatten, self).__init__()
def forward(self, feat):
return feat.view(feat.size(0), -1... | 6,199 | 30.958763 | 116 | py |
CA-MKD | CA-MKD-master/distiller_zoo/FitNet.py | from __future__ import print_function
import torch.nn as nn
class HintLoss(nn.Module):
"""Fitnets: hints for thin deep nets, ICLR 2015"""
def __init__(self):
super(HintLoss, self).__init__()
self.crit = nn.MSELoss()
def forward(self, f_s, f_t):
loss = self.crit(f_s, f_t)
... | 332 | 21.2 | 54 | py |
CA-MKD | CA-MKD-master/distiller_zoo/CAMKD.py | from __future__ import print_function
import torch.nn as nn
import torch.nn.functional as F
import torch
import numpy as np
class CAMKD(nn.Module):
def __init__(self):
super(CAMKD, self).__init__()
# self.crit_ce = nn.CrossEntropyLoss()
self.crit_ce = nn.CrossEntropyLoss(reduction='none'... | 1,555 | 34.363636 | 89 | py |
CA-MKD | CA-MKD-master/distiller_zoo/KD.py | from __future__ import print_function
import torch.nn as nn
import torch.nn.functional as F
class DistillKL(nn.Module):
"""Distilling the Knowledge in a Neural Network"""
def __init__(self, T):
super(DistillKL, self).__init__()
self.T = T
def forward(self, y_s, y_t, is_ca=False):
... | 619 | 28.52381 | 83 | py |
CA-MKD | CA-MKD-master/helper/pretrain.py | from __future__ import print_function, division
import time
import sys
import torch
import torch.optim as optim
import torch.backends.cudnn as cudnn
from .util import AverageMeter
def init(model_s, model_t, init_modules, criterion, train_loader, logger, opt):
model_t.eval()
model_s.eval()
init_modules.tr... | 3,376 | 34.547368 | 106 | py |
CA-MKD | CA-MKD-master/helper/optimization.py | import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# from thundersvm import OneClassSVM as tsvm
from sklearn.svm import OneClassSVM as ssvm
from torch.autograd import Variable
from torch.nn.parameter import Parameter
alpha_grad_opt = []
def fi... | 1,566 | 26.017241 | 85 | py |
CA-MKD | CA-MKD-master/helper/loops.py | from __future__ import print_function, division
import sys
import time
import torch
import math
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from .util import AverageMeter, accuracy, reduce_tensor, adjust_learning_rate, accuracy_list
from .optimization i... | 19,462 | 42.155211 | 146 | py |
CA-MKD | CA-MKD-master/helper/util.py | from __future__ import print_function
import json
import torch
import numpy as np
from collections import Counter
import torch.distributed as dist
LAYER = {'resnet20': np.arange(1, (20 - 2) // 2 + 1), # 9
'resnet56': np.arange(1, (56 - 2) // 2 + 1), # 27
'resnet110': np.arange(2, (110 - 2) // 2 + ... | 5,743 | 32.788235 | 98 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/single_objective_trainer.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
This class is used for training models and is the core of the framework.
With the help of this class, the user of the framework is able to train and
develop models. The framework gets all the relevant objects as an input, and
all the parameters ... | 16,277 | 47.159763 | 114 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/run_example_single_objective.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
Template for using the single objective trainer.
This script is a template on how to use the single objective
trainer to train and develop models. The user is encouraged
to look at the details of this script, since this is the
intended way on ho... | 3,363 | 32.979798 | 78 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/validator.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
Validator class, used for validating models on datasets with specified
metrics and/or objectives.
The Validator class is used during the validation stage of training a new model
and for testing the performance of a pretrained model on a novel d... | 11,927 | 47.096774 | 81 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/trainer.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
This class is used for training models and is the core of the framework.
With the help of this class, the user of the framework is able to train and
develop models. The framework gets all the relevant objects as an input, and
all the parameters ... | 22,403 | 46.974304 | 114 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/run_example.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
Template for using the multi-objective trainer.
This script is a template on how to use the multi-objective
trainer to train and develop models. The user is encouraged
to look at the details of this script, since this is the
intended way on how ... | 3,380 | 32.81 | 78 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/metric/top_selector_torch.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
TopSelectorTorch class, used selecting top samples.
The TopSelectorTorch class is a helper class used by different metric
implementations to select the top values from arrays. This logic is extracted
into a class of its own to increase reusabili... | 2,742 | 37.633803 | 79 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/metric/recall_at_k.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
RecallAtK, used for calculating the recall of results.
The RecallAtK class contains the implementation of the recall metric.
Its function is to evaluate results obtained using a certain model.
"""
import torch
from metric.metric_at_k import Metr... | 2,920 | 37.946667 | 79 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/metric/metric_at_k.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
Abstract Metric class, used for evaluating results.
The abstract Metric class contains a basic skeleton and some implementation
details that will be shared among its children classes. Its function is to
evaluate results obtained using a certain ... | 5,128 | 36.166667 | 78 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/models/multi_VAE.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
"""
import torch.nn as nn
import torch.nn.functional as F
import torch
import yaml
class MultiVAE(nn.Module):
"""An implementation of a Multi Variational Auto Encoder model.
VAE is an autoencoder whose encodings distribution is regular... | 6,758 | 34.387435 | 101 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/tests/unit/test_cdv.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
Unit Tests for CommonDescentVector
"""
import pytest
import torch
import numpy as np
from torch.autograd import Variable
from copsolver.analytical_solver import AnalyticalSolver
from commondescentvector.single_objective_cdv import SingleObjectiv... | 7,010 | 33.880597 | 108 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/tests/unit/test_multi_VAE.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
"""
from models.multi_VAE import MultiVAE
import torch.nn as nn
import numpy as np
import torch
"""The following tests are already covered by the pytorch module nn.ModuleList
* Either of input_size, output_size, dropout, encoder or decoder... | 4,780 | 30.045455 | 84 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/tests/unit/test_single_obj_trainer_dict_params.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
"""
import torch
import numpy as np
import os
import pytest
from dataloader.ae_data_handler import AEDataHandler
from models.multi_VAE import MultiVAE
from loss.vae_loss import VAELoss
from metric.recall_at_k import RecallAtK
from metric.revenue... | 8,902 | 38.745536 | 116 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/tests/unit/test_trainer.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
"""
import torch
import numpy as np
import os
import pytest
from dataloader.ae_data_handler import AEDataHandler
from models.multi_VAE import MultiVAE
from loss.vae_loss import VAELoss
from metric.recall_at_k import RecallAtK
from metric.revenue... | 8,234 | 38.591346 | 114 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/tests/unit/test_trainer_dict_params.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
"""
import torch
import numpy as np
import os
import pytest
from dataloader.ae_data_handler import AEDataHandler
from models.multi_VAE import MultiVAE
from loss.vae_loss import VAELoss
from metric.recall_at_k import RecallAtK
from metric.revenue... | 8,716 | 37.400881 | 114 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/tests/unit/test_single_obj_trainer.py | """
Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
"""
import torch
import numpy as np
import os
import pytest
from dataloader.ae_data_handler import AEDataHandler
from models.multi_VAE import MultiVAE
from loss.vae_loss import VAELoss
from metric.recall_at_k import RecallAtK
from metric.revenu... | 8,455 | 39.850242 | 114 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/tests/unit/test_loss.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
"""
from loss.vae_loss import VAELoss
from loss.mse_loss import MSELoss
import pytest
import torch
# variables
y_pred = torch.tensor([1., 0.]).view(1, 2)
y_true = torch.tensor([1., 1.]).view(1, 2)
y_pred_error = torch.tensor([1, 1, 0, 0, 1]).vie... | 3,064 | 31.606383 | 94 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/tests/unit/test_metrics_at_k.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
"""
from metric.recall_at_k import RecallAtK
from metric.revenue_at_k import RevenueAtK
from metric.diversity_at_k import DiversityAtK
from metric.hit_ratio_at_k import HitRatioAtK
from metric.NDCG_at_k import NDCGAtK
from metric.precision_at_k i... | 9,817 | 34.701818 | 78 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/tests/unit/test_top_selector.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
"""
from metric.top_selector import TopSelector
from metric.top_selector_torch import TopSelectorTorch
import numpy as np
import torch
import pytest
# Packages needed to run test:
# numpy
# bottleneck
# pytest
# Variables
k = 2
values = np.one... | 4,312 | 34.644628 | 79 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/tests/unit/test_validator.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
"""
from metric.recall_at_k import RecallAtK
from loss.vae_loss import VAELoss
from dataloader.mamo_dataset import MamoDataset
from validator import Validator
from torch.utils.data import DataLoader
from models.multi_VAE import MultiVAE
import os... | 7,579 | 39.319149 | 79 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/tests/unit/test_pareto.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
"""
from paretomanager.pareto_manager_class import ParetoManager
import pytest
from torch import nn
import os
import shutil
# variables
scores = [[13, 2, 3], [4, 5, 6], [7, 45, 9], [10, 11, 12], [
12, 44, 11], [13, 2, 3]]
# should be [[13,2... | 3,836 | 27.422222 | 109 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/tests/integration/test_integration_validator.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
"""
from metric.recall_at_k import RecallAtK
from dataloader.mamo_dataset import MamoDataset
from validator import Validator
from torch.utils.data import DataLoader
from tests.integration.mocks.mock_models import MockAllZeros
from tests.integrati... | 4,343 | 38.135135 | 69 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/tests/integration/mocks/mock_models.py |
import torch
import torch.nn as nn
import numpy as np
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class MockNoChange(nn.Module):
def __init__(self):
"""Initialize the model"""
super(MockNoChange, self).__init__()
def forward(self, input):
"""A single forwar... | 1,999 | 26.39726 | 75 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/tests/integration/mocks/mock_loss.py | from loss.loss_class import Loss
import torch
# I will make this into a real loss with tests soon but right now I just need
# it like this.
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class MSELoss(Loss):
def __init__(self):
"""Initialize the loss."""
super().__init__('... | 524 | 26.631579 | 77 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/paretomanager/pareto_manager_class.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
"""
import os
import torch
import warnings
from torch import nn
"""ParetoManager class for the MAMO framework.
The ParetoManager keeps the pareto-front updated and saves the best-model, i.e pareto optimal models.
Typical usage example:
f... | 7,610 | 36.492611 | 109 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/loss/mse_loss.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
MSELoss, used for calculating the Mean Squared Error.
The MSELoss class contains the implementation of the MSE.
MSE is a commonly used loss function, for example for regression.
"""
from loss.loss_class import Loss
import torch
class MSELoss(L... | 2,364 | 37.145161 | 79 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/loss/vae_loss.py |
"""Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
"""
from loss.loss_class import Loss
import torch
import torch.nn.functional as F
class VAELoss(Loss):
"""
Implementation of the Variational Auto-Encoder Loss for the VAE model, inherits from Loss.
There is multiple different inst... | 3,779 | 41.954545 | 109 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/commondescentvector/single_objective_cdv.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
SingleObjectiveCDV, used to represent a Common
Descent Vector for single objective
The SingleObjectiveCDV class is mostly a wrapper
for a single objective loss
"""
from commondescentvector.common_descent_vector import CommonDescentVector
clas... | 3,289 | 33.270833 | 87 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/dataloader/ae_data_handler.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
Implementation of the MAMO Data Handler for developing
AE recommender system models.
Since the MAMO framework is developed primarily for training
multi-objective AE recommender system models, this is
implementation of the MAMO Data Handler class... | 8,870 | 44.260204 | 112 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/dataloader/mamo_dataset.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
MamoDataset class, used by the AE Data Handler implementation
of the data handler abstract class for loading datasets.
This class is implementation of the pytorch Dataset
class and adds the functionalities required by the AE
Data Handler. Since ... | 3,590 | 38.9 | 99 | py |
ai-research-mamo-framework | ai-research-mamo-framework-master/dataloader/mamo_data_handler.py | """Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
Abstract Mamo Data Handler class, main source of feeding data
for the MAMO framework.
This is the main class that will supply data to the MAMO framework.
Users that need custom Data Loaders (ex. for multitask learning),
need to create implementa... | 5,231 | 34.114094 | 99 | py |
spotlight | spotlight-master/setup.py | from setuptools import find_packages, setup
# Import version
__builtins__.__SPOTLIGHT_SETUP__ = True
from spotlight import __version__ as version # NOQA
setup(
name='spotlight',
version=version,
packages=find_packages(),
install_requires=['torch>=0.4.0'],
license='MIT',
classifiers=['Develo... | 489 | 24.789474 | 79 | py |
spotlight | spotlight-master/examples/bloom_embeddings/example.py | import argparse
import hashlib
import json
import os
import shutil
import time
import numpy as np
from sklearn.model_selection import ParameterSampler
from spotlight.datasets.movielens import get_movielens_dataset
from spotlight.datasets.amazon import get_amazon_dataset
from spotlight.cross_validation import (random... | 12,676 | 34.019337 | 85 | py |
spotlight | spotlight-master/examples/bloom_embeddings/performance.py | import os
import pickle
import time
import numpy as np
import torch
from spotlight.layers import BloomEmbedding, ScaledEmbedding
from spotlight.factorization.implicit import ImplicitFactorizationModel
from spotlight.factorization.representations import BilinearNet
from spotlight.sequence.implicit import ImplicitSequ... | 5,801 | 30.532609 | 89 | py |
spotlight | spotlight-master/tests/test_layers.py | import numpy as np
import pytest
import torch
import torch.nn as nn
from spotlight.layers import BloomEmbedding, ScaledEmbedding
@pytest.mark.parametrize('embedding_class', [
nn.Embedding,
ScaledEmbedding,
BloomEmbedding
])
def test_embeddings(embedding_class):
num_embeddings = 1000
embedding_d... | 1,073 | 26.538462 | 80 | py |
spotlight | spotlight-master/tests/test_serialization.py | import os
import shutil
import tempfile
import numpy as np
import pytest
import torch
from spotlight.cross_validation import random_train_test_split
from spotlight.datasets import movielens
from spotlight.evaluation import mrr_score, sequence_mrr_score
from spotlight.evaluation import rmse_score
from spotlight.factor... | 3,374 | 29.963303 | 73 | py |
spotlight | spotlight-master/tests/factorization/test_implicit.py | import os
import numpy as np
import pytest
import torch
from spotlight.cross_validation import random_train_test_split
from spotlight.datasets import movielens
from spotlight.evaluation import mrr_score
from spotlight.factorization.implicit import ImplicitFactorizationModel
from spotlight.factorization.representation... | 5,509 | 32.393939 | 73 | py |
spotlight | spotlight-master/spotlight/losses.py | """
Loss functions for recommender models.
The pointwise, BPR, and hinge losses are a good fit for
implicit feedback models trained through negative sampling.
The regression and Poisson losses are used for explicit feedback
models.
"""
import torch
import torch.nn.functional as F
from spotlight.torch_utils import ... | 6,221 | 24.395918 | 94 | py |
spotlight | spotlight-master/spotlight/layers.py | """
Embedding layers useful for recommender models.
"""
import numpy as np
from sklearn.utils import murmurhash3_32
import torch
import torch.nn as nn
SEEDS = [
179424941, 179425457, 179425907, 179426369,
179424977, 179425517, 179425943, 179426407,
179424989, 179425529, 179425993, 179426447,
179425... | 8,272 | 32.767347 | 84 | py |
spotlight | spotlight-master/spotlight/torch_utils.py | import numpy as np
import torch
def gpu(tensor, gpu=False):
if gpu:
return tensor.cuda()
else:
return tensor
def cpu(tensor):
if tensor.is_cuda:
return tensor.cpu()
else:
return tensor
def minibatch(*tensors, **kwargs):
batch_size = kwargs.get('batch_size', ... | 1,507 | 20.542857 | 79 | py |
spotlight | spotlight-master/spotlight/sequence/implicit.py | """
Models for recommending items given a sequence of previous items
a user has interacted with.
"""
import numpy as np
import torch
import torch.optim as optim
from spotlight.helpers import _repr_model
from spotlight.losses import (adaptive_hinge_loss,
bpr_loss,
... | 11,631 | 34.036145 | 99 | py |
spotlight | spotlight-master/spotlight/sequence/representations.py | """
This module contains prototypes of various ways of representing users
as functions of the items they have interacted with in the past.
"""
import torch
from torch.backends import cudnn
import torch.nn as nn
import torch.nn.functional as F
from spotlight.layers import ScaledEmbedding, ZeroEmbedding
PADDING_IDX ... | 21,549 | 35.097152 | 86 | py |
spotlight | spotlight-master/spotlight/factorization/explicit.py | """
Factorization models for explicit feedback problems.
"""
import numpy as np
import torch
import torch.optim as optim
from spotlight.helpers import _repr_model
from spotlight.factorization._components import _predict_process_ids
from spotlight.factorization.representations import BilinearNet
from spotlight.losse... | 9,553 | 32.522807 | 87 | py |
spotlight | spotlight-master/spotlight/factorization/_components.py | import numpy as np
import torch
from spotlight.torch_utils import gpu
def _predict_process_ids(user_ids, item_ids, num_items, use_cuda):
if item_ids is None:
item_ids = np.arange(num_items, dtype=np.int64)
if np.isscalar(user_ids):
user_ids = np.array(user_ids, dtype=np.int64)
user_id... | 687 | 25.461538 | 73 | py |
spotlight | spotlight-master/spotlight/factorization/implicit.py | """
Factorization models for implicit feedback problems.
"""
import numpy as np
import torch
import torch.optim as optim
from spotlight.helpers import _repr_model
from spotlight.factorization._components import _predict_process_ids
from spotlight.losses import (adaptive_hinge_loss,
bpr... | 10,687 | 33.25641 | 85 | py |
spotlight | spotlight-master/spotlight/factorization/representations.py | """
Classes defining user and item latent representations in
factorization models.
"""
import torch.nn as nn
from spotlight.layers import ScaledEmbedding, ZeroEmbedding
class BilinearNet(nn.Module):
"""
Bilinear factorization representation.
Encodes both users and items as an embedding layer; the score... | 2,709 | 28.456522 | 85 | py |
TayLaNets | TayLaNets-main/examples_taylanets/brusselator/learn_dynamics.py | import argparse
import pickle
import time
# Typing functions
from typing import Tuple
from pathlib import Path
# Import JAX and utilities
import jax
import jax.numpy as jnp
import numpy as np
from jax.tree_util import tree_flatten
from jax import lax
# Haiku for Neural networks
import haiku as hk
# Optax for the o... | 28,250 | 50.741758 | 400 | py |
TayLaNets | TayLaNets-main/examples_taylanets/brusselator/learn_midpoint.py | import argparse
import pickle
import time
# Typing functions
from typing import Tuple
from pathlib import Path
# Import JAX and utilities
import jax
import jax.numpy as jnp
import numpy as np
from jax.tree_util import tree_flatten
# Haiku for Neural networks
import haiku as hk
# Optax for the optimization scheme
i... | 23,234 | 48.018987 | 281 | py |
TayLaNets | TayLaNets-main/examples_taylanets/brusselator/generate_sample.py | from jax.config import config
config.update("jax_enable_x64", True)
import yaml
import pickle
# Import JAX
import jax
import jax.numpy as jnp
from jax import grad, vmap, jit
from taylanets.utils import SampleLog, load_data_yaml
from tqdm.auto import tqdm
from scipy.integrate import odeint as scipy_ode
import numpy... | 6,239 | 37.757764 | 176 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.