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 |
|---|---|---|---|---|---|---|
delay_stability | delay_stability-master/models/modules/birelu.py | import torch
from torch.autograd.function import InplaceFunction
import torch.nn as nn
class BiReLUFunction(InplaceFunction):
@staticmethod
def forward(ctx, input, inplace=False):
if input.size(1) % 2 != 0:
raise RuntimeError("dimension 1 of input must be multiple of 2, "
... | 1,210 | 24.229167 | 77 | py |
delay_stability | delay_stability-master/models/modules/gbn.py | import torch
from torch.nn import Module, BatchNorm2d
class GhostBatchNorm(Module):
def __init__(self, num_features, chunk_size=128, momentum=0.1):
print('Using Ghost Batch Norm of size {}'.format(chunk_size))
super(GhostBatchNorm, self).__init__()
self.bn = BatchNorm2d(num_features, mome... | 815 | 31.64 | 69 | py |
delay_stability | delay_stability-master/models/modules/quantize.py | from collections import namedtuple
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd.function import InplaceFunction, Function
QParams = namedtuple('QParams', ['range', 'zero_point', 'num_bits'])
_DEFAULT_FLATTEN = (1, -1)
_DEFAULT_FLATTEN_GRAD = (0, -1)
def _deflatt... | 14,486 | 40.74928 | 154 | py |
delay_stability | delay_stability-master/models/modules/lp_norm.py | import torch
from torch.nn.parameter import Parameter
from torch.autograd import Variable, Function
import torch.nn as nn
import numpy as np
def _norm(x, dim, p=2):
"""Computes the norm over all dimensions except dim"""
if p == -1:
func = lambda x, dim: x.max(dim=dim)[0] - x.min(dim=dim)[0]
elif p... | 10,643 | 35.452055 | 112 | py |
delay_stability | delay_stability-master/models/modules/se.py | import torch
import torch.nn as nn
class SEBlock(nn.Module):
def __init__(self, in_channels, out_channels=None, ratio=16):
super(SEBlock, self).__init__()
self.in_channels = in_channels
if out_channels is None:
out_channels = in_channels
self.ratio = ratio
self.r... | 789 | 30.6 | 65 | py |
delay_stability | delay_stability-master/utils/regime.py | import torch
from copy import deepcopy
from six import string_types
def eval_func(f, x):
if isinstance(f, string_types):
f = eval(f)
return f(x)
class Regime(object):
"""
Examples for regime:
1) "[{'epoch': 0, 'optimizer': 'Adam', 'lr': 1e-3},
{'epoch': 2, 'optimizer': 'Adam'... | 2,781 | 36.594595 | 76 | py |
delay_stability | delay_stability-master/utils/optim.py | import torch
import logging.config
from copy import deepcopy
from six import string_types
def eval_func(f, x):
if isinstance(f, string_types):
f = eval(f)
return f(x)
class OptimRegime(object):
"""
Reconfigures the optimizer according to setting list.
Exposes optimizer methods - state, s... | 6,017 | 36.849057 | 94 | py |
delay_stability | delay_stability-master/utils/absorb_bn.py | import torch
import torch.nn as nn
def absorb_bn(module, bn_module):
w = module.weight.data
if module.bias is None:
zeros = torch.Tensor(module.out_channels).zero_().type(w.type())
module.bias = nn.Parameter(zeros)
b = module.bias.data
invstd = bn_module.running_var.clone().add_(bn_mod... | 1,218 | 28.731707 | 75 | py |
delay_stability | delay_stability-master/utils/functions.py | import torch
from torch.autograd.function import Function
class ScaleGrad(Function):
@staticmethod
def forward(ctx, input, scale):
ctx.scale = scale
return input
@staticmethod
def backward(ctx, grad_output):
grad_input = ctx.scale * grad_output
return grad_input, None
... | 437 | 18.909091 | 44 | py |
delay_stability | delay_stability-master/utils/cross_entropy.py | import torch
import math
import torch.nn as nn
import torch.nn.functional as F
from .misc import onehot
def _is_long(x):
if hasattr(x, 'data'):
x = x.data
return isinstance(x, torch.LongTensor) or isinstance(x, torch.cuda.LongTensor)
def cross_entropy(logits, target, weight=None, ignore_index=-100, ... | 3,240 | 36.252874 | 131 | py |
delay_stability | delay_stability-master/utils/misc.py | import random
import numpy as np
import torch
torch_dtypes = {
'float': torch.float,
'float32': torch.float32,
'float64': torch.float64,
'double': torch.double,
'float16': torch.float16,
'half': torch.half,
'uint8': torch.uint8,
'int8': torch.int8,
'int16': torch.int16,
'short':... | 1,315 | 24.803922 | 70 | py |
delay_stability | delay_stability-master/utils/tensorboard.py | # Version ICLR 11/09/2019
from torch.utils.tensorboard import SummaryWriter
import matplotlib.pyplot as plt
import json
import socket
from datetime import datetime
def export_args_namespace(args, filename):
"""
args: argparse.Namespace
arguments to save
filename: string
filename to save at... | 3,735 | 37.916667 | 117 | py |
delay_stability | delay_stability-master/utils/dataset.py | import torch
from torch.utils.data import Dataset
from torch.utils.data.sampler import Sampler, RandomSampler, BatchSampler, _int_classes
from numpy.random import choice
class RandomSamplerReplacment(torch.utils.data.sampler.Sampler):
"""Samples elements randomly, with replacement.
Arguments:
data_sour... | 3,502 | 31.738318 | 95 | py |
delay_stability | delay_stability-master/utils/log.py | import shutil
import os
from itertools import cycle
import torch
import logging.config
import json
import pandas as pd
from bokeh.io import output_file, save, show
from bokeh.plotting import figure
from bokeh.layouts import column
from bokeh.models import Div
try:
import hyperdash
HYPERDASH_AVAILABLE = True
e... | 8,143 | 31.97166 | 99 | py |
delay_stability | delay_stability-master/utils/quantize.py | from collections import namedtuple
import torch
import torch.nn as nn
QTensor = namedtuple('QTensor', ['tensor', 'scale', 'zero_point'])
def quantize_tensor(x, num_bits=8):
qmin = 0.
qmax = 2.**num_bits - 1.
min_val, max_val = x.min(), x.max()
scale = (max_val - min_val) / (qmax - qmin)
initial... | 1,833 | 28.111111 | 79 | py |
delay_stability | delay_stability-master/utils/meters.py | import torch
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
... | 2,635 | 24.346154 | 75 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/main.py | import torch
import random
import time
import argparse
from utils import *
from trainer import *
from neg_sampler import *
from load_model import *
from splitter import *
from torch.utils.tensorboard import SummaryWriter
from sklearn.model_selection import train_test_split
from model.sequence_model.bert4rec import BERT... | 47,038 | 52.091422 | 210 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/utils.py | import torch
import json
import joblib
import pickle
import torch.utils.data as data_utils
import numpy as np
import scipy.sparse as sp
import pandas as pd
from neg_sampler import *
from pathlib import Path
from sklearn.metrics import log_loss, roc_auc_score
from torch.utils.data.distributed import DistributedSampler
f... | 47,747 | 36.100233 | 153 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/metrics.py | # -*- coding: utf-8 -*-
import torch
import math
import numpy as np
import os
import pandas as pd
from tqdm import tqdm
class recall(object):
def __init__(self, user_noclick, n_users, n_items, k=10):
print("=" * 10, "Creating Hit@{:d} Metric Object".format(k), "=" * 10)
self.user_noclick = user_... | 13,159 | 29.183486 | 212 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/loggers.py | import os
import torch
# from abc import
class LoggerService(object):
def __init__(self, train_loggers=None, val_loggers=None):
self.train_loggers = train_loggers if train_loggers else []
self.val_loggers = val_loggers if val_loggers else []
def complete(self, log_data):
for logger in ... | 681 | 30 | 67 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/trainer.py | import os.path
import time
from loggers import *
from copy import deepcopy
import torch.nn as nn
import torch.nn.utils.prune as prune
import torch.nn.functional as F
from sklearn.metrics import roc_auc_score
from metrics import *
def mtlTrain(model, train_loader, val_loader, test_loader, args, train=True):
device ... | 55,409 | 48.784367 | 210 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/model_compression/cprec.py | '''
Reference:
Yang Sun et al. A generic network compression framework for sequential recommender systems. In SIGIR, 2020.
'''
import numpy as np
from torch import nn
from torch.nn import functional as F
from torch.nn.init import uniform_, xavier_normal_, constant_
from model.model_compression.adaptive import Adapt... | 7,924 | 41.837838 | 160 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/model_compression/adaptive.py | from collections import namedtuple
import torch
from torch import nn
import torch.nn.functional as F
AdaptiveSoftmaxOutput = namedtuple('AdaptiveSoftmaxOutput', ['output', 'loss'])
class AdaptiveTail(nn.Module):
def __init__(self, ndim, ntoken, cutoffs, div_value=4):
super(AdaptiveTail, self).__init__()... | 5,084 | 39.357143 | 110 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/model_compression/sas4cp.py | import torch.nn as nn
import torch.nn.functional as F
import torch
import math
from model.model_compression.adaptive import AdaptiveInput
class Attention(nn.Module):
"""
Compute 'Scaled Dot Product Attention
"""
def forward(self, query, key, value, mask=None, dropout=None):
scores = torch.mat... | 8,532 | 34.115226 | 127 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/mtl/mmoe.py | '''
Reference:
[1]Jiaqi Ma et al. Modeling task relationships in multi-task learning with multi-gate mixture-of-experts. In Proceedings of the 24th ACM SIGKDD
International Conference on Knowledge Discovery & Data Mining, pages 1930–1939, 2018.
Reference:
https://github.com/busesese/MultiTaskModel
'''
impor... | 6,927 | 47.788732 | 147 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/mtl/esmm.py | '''
Reference:
[1]Xiao Ma et al. Entire space multi-task model: An effective approach for estimating post-click conversion rate. In The 41st International
ACM SIGIR Conference on Research & Development in Information Retrieval, pages 1137–1140, 2018.
Reference:
https://github.com/busesese/MultiTaskModel
'''... | 4,726 | 47.731959 | 143 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/model_accelerate/stackrec.py | # -*- coding: utf-8 -*-
'''
Reference:
[1]Jiachun Wang et al. Stackrec: Efficient training of very deep sequential recommender models by iterative stacking. SIGIR, 2021.
'''
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.init import uniform_, xavier_normal_, ... | 7,336 | 43.466667 | 160 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/model_accelerate/sas4acc.py | import torch.nn as nn
import torch.nn.functional as F
import torch
import math
class Attention(nn.Module):
"""
Compute 'Scaled Dot Product Attention
"""
def forward(self, query, key, value, mask=None, dropout=None):
scores = torch.matmul(query, key.transpose(-2, -1)) \
/ math.... | 7,303 | 32.972093 | 119 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/cf/mf.py | '''
Reference:
[1]Yehuda Koren, Robert Bell, and Chris Volinsky. Matrix factorization techniques for recommender systems.
Computer, 42(8):30–37, 2009.
Reference:
https://github.com/recsys-benchmark/DaisyRec-v2.0
'''
import torch
import torch.nn as nn
import numpy as np
from model.cf.AbstractRecommender impo... | 4,192 | 35.46087 | 110 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/cf/ngcf.py | '''
Reference:
[1]Xiang Wang et al. Neural graph collaborative filtering. In Proceedings of the 42nd international ACM SIGIR conference on Research and development
in Information Retrieval, pages 165–174, 2019.
Reference:
https://github.com/recsys-benchmark/DaisyRec-v2.0
'''
import torch
import torch.nn as ... | 9,948 | 38.955823 | 152 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/cf/ncf.py | '''
Reference:
[1]Xiangnan He et al. Neural collaborative filtering. In Proceedings of the 26th international conference on world wide web, pages 173–182, 2017.
Reference:
https://github.com/recsys-benchmark/DaisyRec-v2.0
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
import tqdm as tqdm
fr... | 6,184 | 36.259036 | 146 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/cf/lightgcn.py | '''
Reference:
[1]Xiangnan He et al. Lightgcn: Simplifying and powering graph convolution network for recommendation. In Proceedings of the 43rd International
ACM SIGIR conference on research and development in Information Retrieval, pages 639–648, 2020.
Reference:
https://github.com/recsys-benchmark/DaisyR... | 7,980 | 37.370192 | 147 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/cf/AbstractRecommender.py | '''
Reference:
https://github.com/recsys-benchmark/DaisyRec-v2.0
'''
import torch.nn as nn
import torch.optim as optim
from metrics import *
class AbstractRecommender(nn.Module):
def __init__(self):
super(AbstractRecommender, self).__init__()
self.optimizer = None
self.initializer = Non... | 8,005 | 36.411215 | 128 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/life_long/conure.py | # -*- coding: utf-8 -*-
'''
Reference:
[1]Fajie Yuan et al. One person, one model, one world: Learning continual user representation without forgetting. SIGIR, 2021.
'''
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.init import uniform_, xavier_normal_, cons... | 7,122 | 41.652695 | 130 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/life_long/sas4life.py | import torch.nn as nn
import torch.nn.functional as F
import torch
import math
class Attention(nn.Module):
"""
Compute 'Scaled Dot Product Attention
"""
def forward(self, query, key, value, mask=None, dropout=None):
scores = torch.matmul(query, key.transpose(-2, -1)) \
/ math.... | 7,784 | 33.754464 | 119 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/life_long/bert4life.py | import torch.nn as nn
import torch.nn.functional as F
import torch
import math
class Attention(nn.Module):
"""
Compute 'Scaled Dot Product Attention
"""
def forward(self, query, key, value, mask=None, dropout=None):
scores = torch.matmul(query, key.transpose(-2, -1)) \
/ math.... | 7,785 | 33.758929 | 119 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/user_profile_representation/bert4profile.py | import torch.nn as nn
import torch.nn.functional as F
import torch
import math
class Attention(nn.Module):
"""
Compute 'Scaled Dot Product Attention
"""
def forward(self, query, key, value, mask=None, dropout=None):
scores = torch.matmul(query, key.transpose(-2, -1)) \
/ mat... | 7,147 | 33.200957 | 119 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/user_profile_representation/peter4profile.py | # -*- coding: utf-8 -*-
'''
Reference:
[1]Fajie Yuan et al. Parameter-efficient transfer from sequential behaviors for user modeling and recommendation. In SIGIR, pages 1469–1478, 2020.
'''
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.init import uniform_, ... | 11,597 | 42.766038 | 160 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/user_profile_representation/dnn4profile.py | import torch.nn as nn
class DNNModel(nn.Module):
def __init__(self, args):
super().__init__()
self.embedding_size = args.embedding_size
self.hidden_size = args.hidden_size
self.block_num = args.block_num
self.num_items = args.num_items
self.pad_token = args.pad_token... | 1,265 | 27.772727 | 114 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/dcn.py | """
Author:
chen_kkkk, bgasdo36977@gmail.com
zanshuxun, zanshuxun@aliyun.com
Reference:
[1] Wang R, Fu B, Fu G, et al. Deep & cross network for ad click predictions[C]//Proceedings of the ADKDD'17. ACM, 2017: 12. (https://arxiv.org/abs/1708.05123)
[2] Wang R, Shivanna R, Cheng D Z, et al. DCN-M: Impro... | 5,339 | 54.625 | 192 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/callbacks.py | import torch
from tensorflow.python.keras.callbacks import EarlyStopping
from tensorflow.python.keras.callbacks import ModelCheckpoint
from tensorflow.python.keras.callbacks import History
EarlyStopping = EarlyStopping
History = History
class ModelCheckpoint(ModelCheckpoint):
"""Save the model after every epoch.
... | 3,410 | 45.094595 | 97 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/dien.py | """
Author:
Ze Wang, wangze0801@126.com
Reference:
[1] Zhou G, Mou N, Fan Y, et al. Deep Interest Evolution Network for Click-Through Rate Prediction[J]. arXiv preprint arXiv:1809.03672, 2018. (https://arxiv.org/pdf/1809.03672.pdf)
"""
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
f... | 18,773 | 47.890625 | 184 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/basemodel.py | """
Author:
Weichen Shen,weichenswc@163.com
"""
from __future__ import print_function
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as Data
from sklearn.metrics import *
from torch.utils.data import DataLoader
from copy import copy
tr... | 23,247 | 45.496 | 393 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/nfm.py | # -*- coding:utf-8 -*-
"""
Author:
Weichen Shen,weichenswc@163.com
Reference:
[1] He X, Chua T S. Neural factorization machines for sparse predictive analytics[C]//Proceedings of the 40th International ACM SIGIR conference on Research and Development in Information Retrieval. ACM, 2017: 355-364. (https://arxiv.... | 4,135 | 50.061728 | 257 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/deepfm.py | # -*- coding:utf-8 -*-
"""
Author:
Weichen Shen,weichenswc@163.com
Reference:
[1] Guo H, Tang R, Ye Y, et al. Deepfm: a factorization-machine based neural network for ctr prediction[J]. arXiv preprint arXiv:1703.04247, 2017.(https://arxiv.org/abs/1703.04247)
"""
import torch
import torch.nn as nn
from .basemod... | 4,139 | 46.045455 | 184 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/xdeepfm.py | # -*- coding:utf-8 -*-
"""
Author:
Wutong Zhang
Reference:
[1] Guo H, Tang R, Ye Y, et al. Deepfm: a factorization-machine based neural network for ctr prediction[J]. arXiv preprint arXiv:1703.04247, 2017.(https://arxiv.org/abs/1703.04247)
"""
import torch
import torch.nn as nn
from .basemodel import BaseModel... | 5,876 | 53.416667 | 184 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/din.py | """
Author:
Yuef Zhang
Reference:
[1] Zhou G, Zhu X, Song C, et al. Deep interest network for click-through rate prediction[C]//Proceedings of the 24th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining. ACM, 2018: 1059-1068. (https://arxiv.org/pdf/1706.06978.pdf)
"""
from .basemodel impo... | 6,933 | 51.530303 | 256 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/dcnmix.py | """
Author:
chen_kkkk, bgasdo36977@gmail.com
zanshuxun, zanshuxun@aliyun.com
Reference:
[1] Wang R, Fu B, Fu G, et al. Deep & cross network for ad click predictions[C]//Proceedings of the ADKDD'17. ACM, 2017: 12. (https://arxiv.org/abs/1708.05123)
[2] Wang R, Shivanna R, Cheng D Z, et al. DCN-M: Impro... | 5,543 | 52.825243 | 192 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/inputs.py | # -*- coding:utf-8 -*-
"""
Author:
Weichen Shen,weichenswc@163.com
"""
from collections import OrderedDict, namedtuple, defaultdict
from itertools import chain
import torch
import torch.nn as nn
import numpy as np
from .layers.sequence import SequencePoolingLayer
from .layers.utils import concat_fun
DEFAULT_GROU... | 9,415 | 38.233333 | 129 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/wdl.py | # -*- coding:utf-8 -*-
"""
Author:
Weichen Shen,weichenswc@163.com
Reference:
[1] Cheng H T, Koc L, Harmsen J, et al. Wide & deep learning for recommender systems[C]//Proceedings of the 1st Workshop on Deep Learning for Recommender Systems. ACM, 2016: 7-10.(https://arxiv.org/pdf/1606.07792.pdf)
"""
import torch... | 3,676 | 48.026667 | 221 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/afm.py | """
Author:
Weichen Shen,weichenswc@163.com
Reference:
[1] Xiao J, Ye H, He X, et al. Attentional factorization machines: Learning the weight of feature interactions via attention networks[J]. arXiv preprint arXiv:1708.04617, 2017.
(https://arxiv.org/abs/1708.04617)
"""
import torch
from .basemodel import... | 3,161 | 46.19403 | 180 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/layers/activation.py | # -*- coding:utf-8 -*-
import torch
import torch.nn as nn
class Dice(nn.Module):
"""The Data Adaptive Activation Function in DIN,which can be viewed as a generalization of PReLu and can adaptively adjust the rectified point according to distribution of input data.
Input shape:
- 2 dims: [batch_size, ... | 2,906 | 31.662921 | 259 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/layers/core.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from .activation import activation_layer
class LocalActivationUnit(nn.Module):
"""The LocalActivationUnit used in DIN with which the representation of
user interests varies adaptively given different candidate items.
Inp... | 7,093 | 37.139785 | 259 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/layers/interaction.py | import itertools
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..layers.activation import activation_layer
from ..layers.core import Conv2dSame
from ..layers.sequence import KMaxPooling
class FM(nn.Module):
"""Factorization Machine models pairwise (order-2) feature interactions
wi... | 31,910 | 41.098945 | 297 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/layers/sequence.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import PackedSequence
from ..layers.core import LocalActivationUnit
class SequencePoolingLayer(nn.Module):
"""The SequencePoolingLayer is used to apply pooling operation(sum,mean,max) on variable-length sequence feature/mu... | 12,643 | 38.389408 | 261 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/ctr/layers/utils.py | # -*- coding:utf-8 -*-
"""
Author:
Weichen Shen,weichenswc@163.com
"""
import numpy as np
import torch
def concat_fun(inputs, axis=-1):
if len(inputs) == 1:
return inputs[0]
else:
return torch.cat(inputs, dim=axis)
def slice_arrays(arrays, start=None, stop=None):
"""Slice an array ... | 2,013 | 27.366197 | 82 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/transfer_learning/peterrec.py | '''
Reference:
[1]Fajie Yuan et al. Parameter-efficient transfer from sequential behaviors for user modeling and recommendation. In SIGIR, pages 1469–1478, 2020.
'''
import numpy as np
from torch import nn
from torch.nn import functional as F
from torch.nn.init import uniform_, constant_, normal_
class PeterRec(nn... | 11,315 | 41.382022 | 150 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/transfer_learning/sas4transfer.py | import torch.nn as nn
import torch.nn.functional as F
import torch
import math
class Attention(nn.Module):
"""
Compute 'Scaled Dot Product Attention
"""
def forward(self, query, key, value, mask=None, dropout=None):
scores = torch.matmul(query, key.transpose(-2, -1)) \
/ math... | 8,237 | 33.041322 | 119 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/inference_acceleration/skiprec.py | # -*- coding: utf-8 -*-
'''
Reference:
[1]Lei Chen et al. A user-adaptive layer selection framework for very deep sequential recommender models. In Proceedings of the AAAI Conference on
Artificial Intelligence, volume 35, pages 3984–3991, 2021.
'''
import numpy as np
import torch
import time
from torch import n... | 10,229 | 43.478261 | 160 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/inference_acceleration/sas4infacc.py | import torch.nn as nn
import torch.nn.functional as F
import torch
import time
import math
class Attention(nn.Module):
"""
Compute 'Scaled Dot Product Attention
"""
def forward(self, query, key, value, mask=None, dropout=None):
scores = torch.matmul(query, key.transpose(-2, -1)) \
... | 9,776 | 35.481343 | 119 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/sequence_model/nextitnet.py | # -*- coding: utf-8 -*-
'''
Reference:
[1]Fajie Yuan et al., "A Simple Convolutional Generative Network for Next Item Recommendation" in WSDM 2019.
Reference:
https://github.com/RUCAIBox/RecBole
'''
import numpy as np
import torch
import time
from torch import nn
from torch.nn import functional as F
from torch.... | 8,807 | 44.169231 | 160 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/sequence_model/bert4rec.py | '''
Reference:
[1]Fei Sun et al. "BERT4Rec: Sequential Recommendation with Bidirectional Encoder Representations from Transformer."
In CIKM 2019.
Reference:
https://github.com/jaywonchung/BERT4Rec-VAE-Pytorch
'''
import torch.nn as nn
import torch.nn.functional as F
import torch
import time
import math
cla... | 7,720 | 33.163717 | 120 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/sequence_model/gru4rec.py | from torch import nn
'''
Reference:
[1]Yong Kiam Tan et al. "Improved Recurrent Neural Networks for Session-based Recommendations." in DLRS 2016.
Reference:
https://github.com/RUCAIBox/RecBole
'''
class GRU4Rec(nn.Module):
r"""
Note:
Regarding the innovation of this article,we can only achieve t... | 1,542 | 34.068182 | 113 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/sequence_model/sasrec.py | '''
Reference:
[1]Wang-Cheng Kang et al. "Self-Attentive Sequential Recommendation." in ICDM 2018.
'''
import torch.nn as nn
import torch.nn.functional as F
import torch
import time
import math
# from models.bert_modules.embedding import BERTEmbedding
# from models.bert_modules.transformer import TransformerBlock
... | 8,272 | 33.470833 | 119 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/coldstart/peter4coldstart.py | # -*- coding: utf-8 -*-
'''
Reference:
[1]Fajie Yuan et al. Parameter-efficient transfer from sequential behaviors for user modeling and recommendation. In SIGIR, pages 1469–1478, 2020.
'''
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.init import uniform_, ... | 11,506 | 41.305147 | 150 | py |
2022-NIPS-Tenrec | 2022-NIPS-Tenrec-master/model/coldstart/bert4coldstart.py | import torch.nn as nn
import torch.nn.functional as F
import torch
import math
class Attention(nn.Module):
"""
Compute 'Scaled Dot Product Attention
"""
def forward(self, query, key, value, mask=None, dropout=None):
scores = torch.matmul(query, key.transpose(-2, -1)) \
/ math.... | 8,200 | 33.313808 | 119 | py |
Face-SPARNet | Face-SPARNet-master/test.py | import os
from options.test_options import TestOptions
from data import create_dataset
from models import create_model
from utils import utils
from PIL import Image
from tqdm import tqdm
import torch
if __name__ == '__main__':
opt = TestOptions().parse() # get test options
opt.num_threads = 0 # test code on... | 1,820 | 35.42 | 123 | py |
Face-SPARNet | Face-SPARNet-master/test_enhance_single_unalign.py | '''
This script enhance all faces in one image with PSFR-GAN and paste it back to the original place.
'''
import dlib
import os
import cv2
import numpy as np
from tqdm import tqdm
from skimage import transform as trans
from skimage import io
import torch
from utils import utils
from options.test_options import TestOp... | 4,524 | 36.708333 | 115 | py |
Face-SPARNet | Face-SPARNet-master/options/base_options.py | import argparse
import os
import numpy as np
import random
from utils import utils
import torch
import models
import data
from utils import utils
class BaseOptions():
"""This class defines options used during both training and test time.
It also implements several helper functions such as parsing, printing, ... | 8,396 | 53.525974 | 223 | py |
Face-SPARNet | Face-SPARNet-master/models/base_model.py | import os
import torch
from collections import OrderedDict
from abc import ABC, abstractmethod
from . import networks
class BaseModel(ABC):
"""This class is an abstract base class (ABC) for models.
To create a subclass, you need to implement the following five functions:
-- <__init__>: ... | 11,655 | 42.819549 | 260 | py |
Face-SPARNet | Face-SPARNet-master/models/sparnet.py | from models.blocks import *
import torch
from torch import nn
import numpy as np
class SPARNet(nn.Module):
"""Deep residual network with spatial attention for face SR.
# Arguments:
- n_ch: base convolution channels
- down_steps: how many times to downsample in the encoder
- res_depth: ... | 2,675 | 34.210526 | 119 | py |
Face-SPARNet | Face-SPARNet-master/models/sparnethd_model.py | import torch
import torch.nn as nn
import torch.optim as optim
import copy
from models import loss
from models import networks
from .base_model import BaseModel
from utils import utils
from models.sparnet import SPARNet
class SPARNetHDModel(BaseModel):
def modify_commandline_options(parser, is_train):
i... | 5,303 | 40.76378 | 134 | py |
Face-SPARNet | Face-SPARNet-master/models/loss.py | import torch
from torchvision import models
from utils import utils
from torch import nn, autograd
from torch.nn import functional as F
class PCPFeat(torch.nn.Module):
"""
Features used to calculate Perceptual Loss based on ResNet50 features.
Input: (B, C, H, W), RGB, [0, 1]
"""
def __init__(self, ... | 6,232 | 34.414773 | 107 | py |
Face-SPARNet | Face-SPARNet-master/models/networks.py | from models.blocks import *
import torch
from torch import nn
from torch.nn import init
from torch.optim import lr_scheduler
import torch.nn.utils as tutils
def apply_norm(net, weight_norm_type):
for m in net.modules():
if isinstance(m, nn.Conv2d):
if weight_norm_type.lower() == 'spectral_norm... | 7,025 | 40.821429 | 128 | py |
Face-SPARNet | Face-SPARNet-master/models/sparnet_model.py | import torch
import torch.nn as nn
import torch.optim as optim
from models import loss
from models import networks
from .base_model import BaseModel
from utils import utils
from models.sparnet import SPARNet
class SPARNetModel(BaseModel):
def modify_commandline_options(parser, is_train):
parser.add_argu... | 2,348 | 31.625 | 134 | py |
Face-SPARNet | Face-SPARNet-master/models/blocks.py | import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
from torch.nn import functional as F
import numpy as np
class NormLayer(nn.Module):
"""Normalization Layers.
------------
# Arguments
- channels: input channels, for batch norm and instance norm.
- input_size: input... | 7,321 | 33.214953 | 129 | py |
Face-SPARNet | Face-SPARNet-master/utils/utils.py | import torch
import numpy as np
import cv2 as cv
from skimage import io
from PIL import Image
import os
import subprocess
def img_to_tensor(img_path, device, size=None, mode='rgb'):
"""
Read image from img_path, and convert to (C, H, W) tensor in range [-1, 1]
"""
img = Image.open(img_path).convert('R... | 3,298 | 28.990909 | 97 | py |
Face-SPARNet | Face-SPARNet-master/data/base_dataset.py | """This module implements an abstract base class (ABC) 'BaseDataset' for datasets.
It also includes common transformation functions (e.g., get_transform, __scale_width), which can be later used in subclasses.
"""
import random
import numpy as np
import torch.utils.data as data
from PIL import Image
import torchvision.... | 5,660 | 33.309091 | 141 | py |
Face-SPARNet | Face-SPARNet-master/data/celeba_dataset.py | import os
import random
import numpy as np
from PIL import Image
import imgaug as ia
import imgaug.augmenters as iaa
import torch
from torch.utils.data import Dataset
from torchvision.transforms import transforms
import torchvision.transforms.functional as tf
from data.base_dataset import BaseDataset
class CelebADa... | 2,922 | 30.771739 | 93 | py |
Face-SPARNet | Face-SPARNet-master/data/image_folder.py | """A modified image folder class
We modify the official PyTorch image folder (https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py)
so that this class can load images from both current directory and its subdirectories.
"""
import torch.utils.data as data
from PIL import Image
import os
import... | 1,931 | 27.411765 | 122 | py |
Face-SPARNet | Face-SPARNet-master/data/ffhq_dataset.py | import os
import random
import numpy as np
from PIL import Image
import imgaug as ia
import imgaug.augmenters as iaa
import torch
from torch.utils.data import Dataset
from torchvision.transforms import transforms
from data.base_dataset import BaseDataset
class FFHQDataset(BaseDataset):
def __init__(self, opt):
... | 2,484 | 28.939759 | 104 | py |
Face-SPARNet | Face-SPARNet-master/data/__init__.py | """This package includes all the modules related to data loading and preprocessing
To add a custom dataset class called 'dummy', you need to add a file called 'dummy_dataset.py' and define a subclass 'DummyDataset' inherited from BaseDataset.
You need to implement four functions:
-- <__init__>: ... | 3,626 | 37.178947 | 176 | py |
reviewer-paper-matching | reviewer-paper-matching-master/evaluate_similarity.py | import io
import sentencepiece as spm
from scipy.stats import spearmanr
from scipy.stats import pearsonr
from model_utils import Example, unk_string
from sacremoses import MosesTokenizer
def get_sequences(p1, p2, model, params, fr0=0, fr1=0):
wp1 = Example(p1)
wp2 = Example(p2)
if fr0==1 and fr1==1 and no... | 3,302 | 34.138298 | 85 | py |
reviewer-paper-matching | reviewer-paper-matching-master/model_utils.py | import numpy as np
import torch
import random
from collections import Counter
unk_string = "UUUNKKK"
def get_ngrams(examples, share_vocab, max_len=200000, n=3):
def update_counter(counter, sentence):
word = " " + sentence.strip() + " "
lis = []
for j in range(len(word)):
idx = ... | 4,317 | 26.679487 | 82 | py |
reviewer-paper-matching | reviewer-paper-matching-master/suggest_ac_reviewers_by_track.py | """
This is a variant of the suggest_reviewers script tailored for assignment of papers to area chairs.
It suggests AC reviewers and allows to manually move papers to special COI track (if the ACs suggest that) via providing --moving_to.
I.e., this script is first ran without --moving_to, and later, if the track assig... | 18,022 | 48.513736 | 194 | py |
reviewer-paper-matching | reviewer-paper-matching-master/train_similarity.py | import model_utils
import random
import numpy as np
import sys
import argparse
import io
import torch
from models import Averaging, LSTM, load_model
from model_utils import Example
random.seed(1)
np.random.seed(1)
torch.manual_seed(1)
def get_data(params):
examples = []
finished = set([]) #check for duplicat... | 3,713 | 41.689655 | 122 | py |
reviewer-paper-matching | reviewer-paper-matching-master/suggest_reviewers.py | import argparse
import csv
import json
import os
import re
import sys
import time
import warnings
from collections import defaultdict
import cvxpy as cp
import numpy as np
import pandas as pd
from sacremoses import MosesTokenizer
from model_utils import Example, unk_string
from models import load_model
from suggest_u... | 50,814 | 36.978326 | 80 | py |
reviewer-paper-matching | reviewer-paper-matching-master/models.py | import torch
import torch.nn as nn
import numpy as np
import time
import torch.nn.functional as F
import sentencepiece as spm
import model_pairing
import model_utils
import random
import os
from torch.nn.modules.distance import CosineSimilarity
from torch.nn.utils.rnn import pad_packed_sequence as unpack
from torch.nn.... | 11,574 | 32.071429 | 120 | py |
reviewer-paper-matching | reviewer-paper-matching-master/model_pairing.py | import torch
from model_utils import Batch
def get_pairs_batch(model, g1, g1_lengths, g2, g2_lengths):
with torch.no_grad():
all_g1_lengths = torch.cat(g1_lengths)
all_g2_lengths = torch.cat(g2_lengths)
v_g1 = []
for i in range(len(g1)):
v_g1.append(model.encode(g1[i],... | 6,259 | 33.585635 | 109 | py |
IGB-Datasets | IGB-Datasets-main/results/IGB_260M/gnn.py | import dgl
from dgl.data import DGLDataset
import dgl.nn.pytorch as dglnn
from dgl.nn.pytorch import GATConv, GraphConv, SAGEConv
import os.path as osp
from sys import getsizeof
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import time
import numpy as np... | 20,521 | 35.777778 | 159 | py |
IGB-Datasets | IGB-Datasets-main/results/IGB_large/gnn.py | import dgl
from dgl.data import DGLDataset
import dgl.nn.pytorch as dglnn
from dgl.nn.pytorch import GATConv, GraphConv, SAGEConv
import os.path as osp
from sys import getsizeof
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import time
import numpy as np... | 20,514 | 35.503559 | 159 | py |
IGB-Datasets | IGB-Datasets-main/results/IGB_tiny/gnn.py | import dgl
from dgl.data import DGLDataset
import dgl.nn.pytorch as dglnn
from dgl.nn.pytorch import GATConv, GraphConv, SAGEConv
import os.path as osp
from sys import getsizeof
import argparse
import torch
torch.manual_seed(0)
dgl.seed(0)
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as... | 20,135 | 34.957143 | 125 | py |
IGB-Datasets | IGB-Datasets-main/results/IGB_medium/gnn.py | import dgl
from dgl.data import DGLDataset
import dgl.nn.pytorch as dglnn
from dgl.nn.pytorch import GATConv, GraphConv, SAGEConv
import os.path as osp
from sys import getsizeof
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import time
import numpy as np... | 20,244 | 35.023132 | 137 | py |
IGB-Datasets | IGB-Datasets-main/results/IGB_small/gnn.py | import dgl
from dgl.data import DGLDataset
import dgl.nn.pytorch as dglnn
from dgl.nn.pytorch import GATConv, GraphConv, SAGEConv
import os.path as osp
from sys import getsizeof
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import time
import numpy as np... | 20,748 | 35.211169 | 137 | py |
IGB-Datasets | IGB-Datasets-main/igb/train_single_gpu.py | import argparse, datetime
import dgl
import sklearn.metrics
import torch, torch.nn as nn, torch.optim as optim
import time, tqdm, numpy as np
from models import *
from dataloader import IGB260MDGLDataset
torch.manual_seed(0)
dgl.seed(0)
import warnings
warnings.filterwarnings("ignore")
def track_acc(g, args, device):... | 7,336 | 37.615789 | 114 | py |
IGB-Datasets | IGB-Datasets-main/igb/train_multi_gpu.py | import argparse, datetime
import dgl
import sklearn.metrics
import torch, torch.nn as nn, torch.optim as optim
import torch.multiprocessing as mp
import time, tqdm, numpy as np
from models import *
from dataloader import IGB260MDGLDataset
torch.manual_seed(0)
dgl.seed(0)
import warnings
warnings.filterwarnings("ignore... | 8,009 | 40.71875 | 136 | py |
IGB-Datasets | IGB-Datasets-main/igb/train_multi_hetero.py | import argparse, datetime
import dgl
import sklearn.metrics
import torch, torch.nn as nn, torch.optim as optim
import torch.multiprocessing as mp
import time, tqdm, numpy as np
from models import RGCN, RSAGE, RGAT
from dataloader import IGBHeteroDGLDataset
torch.manual_seed(0)
dgl.seed(0)
import warnings
warnings.filt... | 9,629 | 40.508621 | 136 | py |
IGB-Datasets | IGB-Datasets-main/igb/dataloader.py | import argparse
import numpy as np
import torch
import os.path as osp
import dgl
from dgl.data import DGLDataset
import warnings
warnings.filterwarnings("ignore")
class IGB260M(object):
def __init__(self, root: str, size: str, in_memory: int, \
classes: int, synthetic: int):
self.dir = root
... | 18,761 | 46.498734 | 153 | py |
IGB-Datasets | IGB-Datasets-main/igb/models.py | import torch.nn as nn
import torch.nn.functional as F
from dgl import apply_each
from dgl.nn.pytorch import GATConv, GraphConv, SAGEConv, HeteroGraphConv
class SAGE(nn.Module):
def __init__(self, in_feats, h_feats, num_classes, num_layers=2, dropout=0.2):
super(SAGE, self).__init__()
self.layers = ... | 6,169 | 39.860927 | 101 | py |
IGB-Datasets | IGB-Datasets-main/igb/train_hetero.py | import argparse, datetime
import dgl
import sklearn.metrics
import torch, torch.nn as nn, torch.optim as optim
import torchmetrics.functional as MF
import time, tqdm, numpy as np
from models import *
from dataloader import IGBHeteroDGLDataset
torch.manual_seed(0)
dgl.seed(0)
import warnings
warnings.filterwarnings("ig... | 7,160 | 37.294118 | 114 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.