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 |
|---|---|---|---|---|---|---|
DraftRec | DraftRec-master/src/models/nn.py | from .base import BaseModel
from ..common.initialization import NormInitializer
from .blocks.layers import *
from .blocks.transformer import TransformerBlock
from .heads import *
import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
class NN(BaseModel):
def __init__(self, args):
s... | 1,767 | 29.482759 | 78 | py |
DraftRec | DraftRec-master/src/models/draftrec.py | from .base import BaseModel
from ..common.initialization import NormInitializer
from .blocks.layers import *
from .blocks.transformer import TransformerBlock
from .heads import *
import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
class DraftRec(BaseModel):
def __init__(self, args):
... | 5,690 | 39.077465 | 103 | py |
DraftRec | DraftRec-master/src/models/lr.py | from .base import BaseModel
from ..common.initialization import NormInitializer
from .blocks.layers import *
from .blocks.transformer import TransformerBlock
from .heads import *
import torch
import torch.nn as nn
import torch.nn.functional as F
import copy
class LogisticRegression(BaseModel):
def __init__(self, ... | 1,653 | 30.207547 | 78 | py |
DraftRec | DraftRec-master/src/models/blocks/layers.py | import math
import torch
import torch.nn as nn
from torch.autograd import Variable
class PositionalEncoding(nn.Module):
def __init__(self, max_seq_len, d_model):
super(PositionalEncoding, self).__init__()
pe = torch.zeros(max_seq_len, d_model)
position = torch.arange(0,ma... | 2,157 | 32.71875 | 100 | py |
DraftRec | DraftRec-master/src/models/blocks/transformer.py | import torch
from torch import nn as nn
from torch.nn import functional as F
from .layers import *
class TransformerBlock(nn.Module):
def __init__(self, args):
super().__init__()
attn_heads = args.num_heads
hidden = args.hidden_units
feed_forward_hidden = 4 * hidden # inverted bot... | 2,920 | 34.192771 | 110 | py |
DraftRec | DraftRec-master/src/models/heads/__init__.py | from ..blocks.layers import GELU
import torch
import torch.nn as nn
class LinearPredictionHead(nn.Module):
def __init__(self, d_model, d_out):
super().__init__()
self.head = nn.Sequential(
nn.Linear(d_model, d_model),
GELU(),
nn.Linear(d_model, d_out)
)
... | 1,379 | 30.363636 | 86 | py |
DraftRec | DraftRec-master/src/dataloaders/base.py | import torch.utils.data as data_utils
from abc import *
import random
class BaseDataloader(metaclass=ABCMeta):
def __init__(self, args, mode, match_df, user_history_dict):
self.args = args
self.mode = mode
self.match_df = match_df
self.user_history_dict = user_history_dict
... | 2,168 | 29.549296 | 98 | py |
DraftRec | DraftRec-master/src/dataloaders/match.py | from .base import BaseDataloader
import torch
import tqdm
import numpy as np
import pickle
import os
from collections import defaultdict
class MatchDataloader(BaseDataloader):
def __init__(self, args, mode, match_df, user_history_dict):
super().__init__(args, mode, match_df, user_history_dict)
@classm... | 6,054 | 38.575163 | 124 | py |
DraftRec | DraftRec-master/src/trainers/base.py | from ..common.logger import LoggerService, AverageMeterSet
from ..common.metrics import *
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from abc import *
from pathlib import Path
from tqdm import tqdm
import numpy as np
import pandas as pd
import os
import copy
class ... | 5,916 | 33.202312 | 113 | py |
DraftRec | DraftRec-master/src/trainers/match.py | from .base import BaseTrainer
from ..common.metrics import *
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class MatchTrainer(BaseTrainer):
def __init__(self, args, train_loader, val_loader, test_loader, model):
super().__init__(args, train_loader, val_loader, test_... | 1,804 | 33.056604 | 101 | py |
deepmeg-recurrent-encoder | deepmeg-recurrent-encoder-main/neural/__main__.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import json
import random
import shutil
from dataclasses import dataclass, field
from functools import part... | 11,659 | 35.21118 | 100 | py |
deepmeg-recurrent-encoder | deepmeg-recurrent-encoder-main/neural/extraction.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# import libraries
from concurrent.futures import ProcessPoolExecutor
import argparse
import os
import traceback
from skl... | 10,536 | 34.962457 | 98 | py |
deepmeg-recurrent-encoder | deepmeg-recurrent-encoder-main/neural/utils.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import os.path
import shutil
import numpy as np
def create_directory(path, overwrite=False):
# if it is not there, c... | 1,902 | 26.185714 | 87 | py |
deepmeg-recurrent-encoder | deepmeg-recurrent-encoder-main/neural/model.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import math
import torch as th
from torch import nn
from torch.nn import functional as F
from .utils import center_trim
... | 3,973 | 31.048387 | 99 | py |
deepmeg-recurrent-encoder | deepmeg-recurrent-encoder-main/neural/dataset.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
'''Fits all extracted files from the MOUS dataset into a usable,
self-contained MEGDatasets structure.
It comprises:
-- tor... | 9,344 | 34.532319 | 94 | py |
deepmeg-recurrent-encoder | deepmeg-recurrent-encoder-main/neural/train.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
'''Trains a model with a train_eval_model function.'''
from collections import namedtuple
import torch as th
from torch i... | 4,455 | 33.015267 | 98 | py |
deepmeg-recurrent-encoder | deepmeg-recurrent-encoder-main/neural/linear/__main__.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# import libraries
import argparse
from concurrent.futures import ProcessPoolExecutor
from pathlib import Path
import nump... | 12,308 | 33.771186 | 97 | py |
deepmeg-recurrent-encoder | deepmeg-recurrent-encoder-main/neural/linear/stats.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# import libraries
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy
import scipy.linalg... | 14,776 | 29.721414 | 94 | py |
CL-CORe-App | CL-CORe-App-master/app/src/main/cpp/libsroot/arm64-v8a/Release/python/caffe/proto/caffe_pb2.py | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: caffe/proto/caffe.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from go... | 277,028 | 44.207082 | 30,043 | py |
CCRL_Exploration | CCRL_Exploration-main/train/evaluate_multi_seeds.py | import sys
import os
sys.path.append(os.path.abspath(os.path.join(__file__, "..", "..")))
import torch
import numpy as np
import argparse
from agent.network import Actor_Critic
import grid_simulator
import gym
import time
import random
import matplotlib.pyplot as plt
import seaborn as sns
from utils.str2bool import st... | 5,325 | 40.609375 | 185 | py |
CCRL_Exploration | CCRL_Exploration-main/train/PPO_main.py | import sys
import os
sys.path.append(os.path.abspath(os.path.join(__file__, "..", "..")))
import torch
import numpy as np
from torch.utils.tensorboard import SummaryWriter
import grid_simulator
import gym
import time
from agent.ppo_discrete import PPO_Discrete
from configs import get_configs
class Runner:
def _... | 6,673 | 47.014388 | 217 | py |
CCRL_Exploration | CCRL_Exploration-main/train/CCPPO_main.py | import sys
import os
sys.path.append(os.path.abspath(os.path.join(__file__, "..", "..")))
import torch
import numpy as np
from torch.utils.tensorboard import SummaryWriter
import grid_simulator
import gym
import time
from agent.ppo_discrete import PPO_Discrete
from configs import get_configs
class Runner:
def _... | 8,586 | 50.113095 | 217 | py |
CCRL_Exploration | CCRL_Exploration-main/train/CPPO_main.py | import sys
import os
sys.path.append(os.path.abspath(os.path.join(__file__, "..", "..")))
import torch
import numpy as np
from torch.utils.tensorboard import SummaryWriter
import grid_simulator
import gym
import time
from agent.ppo_discrete import PPO_Discrete
from configs import get_configs
class Runner:
def _... | 7,996 | 48.98125 | 231 | py |
CCRL_Exploration | CCRL_Exploration-main/utils/data_augmentation.py | from copy import deepcopy
import torch
def rotation_s(s_map, s_sensor, k): # Clockwise rotation 90,180,210
aug_s_map = torch.rot90(s_map, k=-k, dims=[2, 3])
aug_s_sensor = deepcopy(s_sensor)
aug_s_sensor[:, -1] = (aug_s_sensor[:, -1] + 0.25 * k) % 1 # The steering angle is modified accordingly
retur... | 346 | 33.7 | 108 | py |
CCRL_Exploration | CCRL_Exploration-main/agent/ppo_discrete.py | import torch
import torch.nn.functional as F
from torch.utils.data.sampler import BatchSampler, SubsetRandomSampler
from torch.distributions import Categorical
import numpy as np
from .network import Actor_Critic
from .buffer import PPO_Buffer
from utils.data_augmentation import rotation_s
class PPO_Discrete:
de... | 5,790 | 47.258333 | 164 | py |
CCRL_Exploration | CCRL_Exploration-main/agent/network.py | import torch
import torch.nn as nn
import math
def orthogonal_init(layer, gain=math.sqrt(2)):
for name, param in layer.named_parameters():
if 'bias' in name:
nn.init.constant_(param, 0)
elif 'weight' in name:
nn.init.orthogonal_(param, gain=gain)
return layer
class Ac... | 2,183 | 30.652174 | 132 | py |
CCRL_Exploration | CCRL_Exploration-main/agent/buffer.py | import torch
class PPO_Buffer:
def __init__(self, config, num_envs):
self.device = config.device
self.gamma = config.gamma
self.lamda = config.lamda
self.s_map_dim = config.s_map_dim
self.s_sensor_dim = config.s_sensor_dim
self.rollout_steps = config.rollout_steps
... | 3,596 | 55.203125 | 179 | py |
HETFORMER | HETFORMER-main/hetformer/heterformer.py | from typing import List
import math
import torch
from torch import nn
import json
import torch.nn.functional as F
from hetformer.diagonaled_mm_tvm import diagonaled_mm as diagonaled_mm_tvm, mask_invalid_locations
from hetformer.sliding_chunks import sliding_chunks_matmul_qk, sliding_chunks_matmul_pv
from hetformer.slid... | 21,579 | 63.41791 | 188 | py |
HETFORMER | HETFORMER-main/hetformer/sliding_chunks.py | import torch
import torch.nn.functional as F
from hetformer.diagonaled_mm_tvm import mask_invalid_locations
def _skew(x, direction, padding_value):
'''Convert diagonals into columns (or columns into diagonals depending on `direction`'''
x_padded = F.pad(x, direction, value=padding_value)
x_padded = x_padd... | 8,233 | 45.519774 | 123 | py |
HETFORMER | HETFORMER-main/hetformer/diagonaled_mm_tvm.py | from typing import Union
from functools import lru_cache
import torch
import os.path
class DiagonaledMM(torch.autograd.Function):
'''Class to encapsulate tvm code for compiling a diagonal_mm function, in addition to calling
this function from PyTorch
'''
function_dict = {} # save a list of function... | 17,440 | 51.691843 | 189 | py |
HETFORMER | HETFORMER-main/hetformer/modeling_roberta.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a cop... | 14,925 | 52.117438 | 134 | py |
HETFORMER | HETFORMER-main/src/run_BertSum.py | #!/usr/bin/env python
"""
Main training workflow
"""
from __future__ import division
import argparse
import glob
import os
import random
import signal
import time
import torch
from pytorch_pretrained_bert import BertConfig
import distributed
from models import data_loader, model_builder
from models.data_loader i... | 13,096 | 36.31339 | 122 | py |
HETFORMER | HETFORMER-main/src/distributed.py | """ Pytorch Distributed utils
This piece of code was heavily inspired by the equivalent of Fairseq-py
https://github.com/pytorch/fairseq
"""
from __future__ import print_function
import math
import pickle
import torch.distributed
from others.logging import logger
def is_master(gpu_ranks, device_id):
... | 3,895 | 30.168 | 77 | py |
HETFORMER | HETFORMER-main/src/models/stats.py | """ Statistics calculation utility """
from __future__ import division
import sys
import time
from others.logging import logger
class Statistics(object):
"""
Accumulator for loss statistics.
Currently calculates:
* accuracy
* perplexity
* elapsed time
"""
def __init__(self, loss=0,... | 3,559 | 28.421488 | 79 | py |
HETFORMER | HETFORMER-main/src/models/data_loader.py | import gc
import glob
import random
import numpy as np
import torch
from itertools import permutations
from others.logging import logger
class Batch(object):
def _pad(self, data, pad_id, width=-1):
if (width == -1):
width = max(len(d) for d in data)
rtn_data = [d + [pad_id] * (width -... | 8,927 | 32.690566 | 84 | py |
HETFORMER | HETFORMER-main/src/models/optimizers.py | """ Optimizers class """
import torch
import torch.optim as optim
from torch.nn.utils import clip_grad_norm_
# from onmt.utils import use_gpu
def use_gpu(opt):
"""
Creates a boolean if gpu used
"""
return (hasattr(opt, 'gpu_ranks') and len(opt.gpu_ranks) > 0) or \
(hasattr(opt, 'gpu') and... | 9,412 | 38.55042 | 158 | py |
HETFORMER | HETFORMER-main/src/models/encoder.py | import torch.nn as nn
class Classifier(nn.Module):
def __init__(self, hidden_size):
super(Classifier, self).__init__()
self.linear1 = nn.Linear(hidden_size, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x, mask_cls):
h = self.linear1(x).squeeze(-1)
sent_scores = sel... | 382 | 21.529412 | 56 | py |
HETFORMER | HETFORMER-main/src/models/model_builder.py |
import torch
import torch.nn as nn
from longformer import Heterformer, HeterformerConfig
from torch.nn.init import xavier_uniform_
from models.optimizers import Optimizer
from models.encoder import Classifier
def build_optim(args, model, checkpoint):
""" Build optimizer """
saved_optimizer_state_dict = None
... | 3,227 | 39.860759 | 105 | py |
HETFORMER | HETFORMER-main/src/models/trainer.py | import os
import numpy as np
import torch
from tensorboardX import SummaryWriter
from itertools import permutations, combinations
import distributed
from rouge import Rouge
rouge = Rouge()
from models.reporter import ReportMgr
from models.stats import Statistics
from others.logging import logger
from others.utils impo... | 17,958 | 39.087054 | 113 | py |
HETFORMER | HETFORMER-main/src/prepro/data_builder.py | import gc
import glob
import hashlib
import itertools
import json
import os
import re
import subprocess
import time
from os.path import join as pjoin
import torch
from multiprocess import Pool
from pytorch_pretrained_bert import BertTokenizer
from others.logging import logger
from others.utils import clean
from prepr... | 12,160 | 36.189602 | 253 | py |
topic-rnn | topic-rnn-master/library/models/topic_rnn.py | from collections import Counter
from typing import Dict, Optional
import torch
import torch.nn as nn
from allennlp.data.vocabulary import (DEFAULT_OOV_TOKEN, DEFAULT_PADDING_TOKEN,
Vocabulary)
from allennlp.models.archival import load_archive
from allennlp.models.model import Mode... | 19,197 | 47.602532 | 136 | py |
topic-rnn | topic-rnn-master/library/metrics/perplexity.py | from typing import Optional
from overrides import overrides
import torch
from allennlp.training.metrics.metric import Metric
@Metric.register("perplexity")
class Perplexity(Metric):
"""
Computes per-word perplexity for a validation / test corpus.
Raw probabilities predicted for each ground truth token ... | 2,886 | 33.369048 | 107 | py |
topic-rnn | topic-rnn-master/library/dataset_readers/imdb_review_reader.py | import logging
from typing import Dict
from allennlp.common.file_utils import cached_path
from allennlp.common.util import END_SYMBOL, START_SYMBOL
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.data.fields import LabelField, TextField
from allennlp.data.instance import Instance
f... | 9,912 | 46.430622 | 109 | py |
FedNest | FedNest-main/main_hr_joint.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
import yaml
import time
from core.test import test_img
from utils.Fed import FedAvg, FedAvgGradient
from models.SvrgUpdate import LocalUpdate
from utils.options import args_parser
from utils.dataset_normal import load_data
from models.ModelBuilder imp... | 2,594 | 33.6 | 101 | py |
FedNest | FedNest-main/main_imbalance.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
import yaml
import time
from core.test import test_img
from utils.Fed import FedAvg, FedAvgGradient
from models.SvrgUpdate import LocalUpdate
from utils.options import args_parser
from utils.dataset import load_data
from models.ModelBuilder import bui... | 3,368 | 35.225806 | 103 | py |
FedNest | FedNest-main/main_hr.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
import yaml
import time
from core.test import test_img
from utils.Fed import FedAvg, FedAvgGradient
from models.SvrgUpdate import LocalUpdate
from utils.options import args_parser
from utils.dataset_normal import load_data
from models.ModelBuilder imp... | 3,216 | 35.146067 | 105 | py |
FedNest | FedNest-main/core/SGDClient.py | import torch
from core.Client import Client
class SGDClient(Client):
def __init__(self, args, client_id, net, dataset=None, idxs=None, hyper_param= None) -> None:
super().__init__(args, client_id, net, dataset, idxs, hyper_param)
def train_epoch(self):
self.net.train()
# train and updat... | 1,413 | 38.277778 | 104 | py |
FedNest | FedNest-main/core/SGDClient_hr.py | import torch
from core.Client_hr import Client
class SGDClient(Client):
def __init__(self, args, client_id, net, dataset=None, idxs=None, hyper_param= None) -> None:
super().__init__(args, client_id, net, dataset, idxs, hyper_param)
def train_epoch(self):
self.net.train()
# train and up... | 1,761 | 41.97561 | 142 | py |
FedNest | FedNest-main/core/test.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @python: 3.6
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
def test_img(net_g, datatest, args):
net_g.eval()
# testing
test_loss = 0
correct = 0
data_loader = DataLoader(datatest, batch_siz... | 1,145 | 31.742857 | 86 | py |
FedNest | FedNest-main/core/Client.py | import copy
from math import ceil
from warnings import catch_warnings
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset
from core.function import gather_flat_grad, get_trainable_hyper_params, loss_adjust_cross_entropy, gather_flat_hyper_params
from utils.svrg import SVRG_Snapshot
from n... | 6,620 | 37.271676 | 123 | py |
FedNest | FedNest-main/core/Client_hr.py | import copy
from math import ceil
from warnings import catch_warnings
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset
from core.function import gather_flat_grad, get_trainable_hyper_params, loss_adjust_cross_entropy, gather_flat_hyper_params
from utils.svrg import SVRG_Snapshot
from n... | 7,286 | 38.819672 | 123 | py |
FedNest | FedNest-main/core/function.py | from numpy import dtype
import torch.nn.functional as F
import torch
from torch.autograd import grad
def gather_flat_grad(loss_grad):
# convert the gradient output from list of tensors to to flat vector
return torch.cat([p.contiguous().view(-1) for p in loss_grad if not p is None])
def neumann_hyperstep_pr... | 2,756 | 36.256757 | 116 | py |
FedNest | FedNest-main/core/ClientManage.py | import copy
from cv2 import log
import numpy as np
import torch
from utils.Fed import FedAvg,FedAvgGradient, FedAvgP
from core.SGDClient import SGDClient
from core.SVRGClient import SVRGClient
from core.Client import Client
class ClientManage():
def __init__(self,args, net_glob, client_idx, dataset, dict_users,... | 5,179 | 34 | 129 | py |
FedNest | FedNest-main/core/ClientManage_hr.py | import copy
from cv2 import log
import numpy as np
import torch
from utils.Fed import FedAvg,FedAvgGradient, FedAvgP
from core.SGDClient_hr import SGDClient
from core.SVRGClient_hr import SVRGClient
from core.Client_hr import Client
from core.ClientManage import ClientManage
class ClientManageHR(ClientManage):
... | 6,340 | 34.424581 | 124 | py |
FedNest | FedNest-main/core/ClientManage_hr_joint.py | import copy
from cv2 import log
import numpy as np
import torch
from utils.Fed import FedAvg,FedAvgGradient, FedAvgP
from core.SGDClient_hr import SGDClient
from core.SVRGClient_hr import SVRGClient
from core.Client_hr import Client
from core.ClientManage import ClientManage
class ClientManageHR(ClientManage):
... | 8,006 | 34.273128 | 124 | py |
FedNest | FedNest-main/models/SvrgUpdate.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
import torch
from torch import nn, autograd
from torch.utils.data import DataLoader, Dataset
import numpy as np
import random
from sklearn import metrics
from utils.svrg import SVRG_k,SVRG_Snapshot
import copy
class DatasetSplit(Dataset):
def __i... | 2,801 | 34.025 | 109 | py |
FedNest | FedNest-main/models/Nets.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
from importlib_metadata import requires
from numpy import dtype
import torch
from torch import nn
import torch.nn.functional as F
class Linear(nn.Module):
def __init__(self, d, n):
super(Linear, self).__init__()
self.y_inner = tor... | 6,689 | 38.585799 | 144 | py |
FedNest | FedNest-main/models/Update.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
import torch
from torch import nn, autograd
from torch.utils.data import DataLoader, Dataset
import numpy as np
import random
from sklearn import metrics
class DatasetSplit(Dataset):
def __init__(self, dataset, idxs):
self.dataset = data... | 1,951 | 33.857143 | 109 | py |
FedNest | FedNest-main/utils/dataset.py | from torchvision import datasets, transforms
from utils.sampling import mnist_iid, mnist_noniid, cifar_iid
def load_data(args):
# load dataset and split users
if args.dataset == 'mnist':
trans_mnist = transforms.Compose(
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
... | 1,563 | 49.451613 | 92 | py |
FedNest | FedNest-main/utils/svrg.py | from torch.optim import Optimizer
import copy
import torch
class SVRG_k(Optimizer):
r"""Optimization class for calculating the gradient of one iteration.
Args:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float): learning rate
"""
... | 2,507 | 34.828571 | 88 | py |
FedNest | FedNest-main/utils/sampling.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
from math import ceil
import numpy as np
from torchvision import datasets, transforms
import torch
def mnist_iid_normal(dataset, num_users):
"""
Sample I.I.D. client data from MNIST dataset
:param dataset:
:param num_users:
:retu... | 12,205 | 33.286517 | 108 | py |
FedNest | FedNest-main/utils/dataset_normal.py | import torch
from torchvision import datasets, transforms
from utils.sampling import mnist_iid, mnist_iid_normal, mnist_noniid, cifar_iid, mnist_noniid_normal, minmax_dataset, fmnist_iid_normal, fmnist_noniid_normal
import numpy as np
import random
def load_data(args):
# load dataset and split users
if args.dat... | 3,994 | 52.266667 | 157 | py |
FedNest | FedNest-main/utils/Fed.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
import copy
from numpy import dtype
import torch
from torch import nn
def FedAvg(w):
w_avg = copy.deepcopy(w[0])
for k in w_avg.keys():
for i in range(1, len(w)):
w_avg[k] += w[i][k]
w_avg[k] = torch.div(w_avg[k],... | 982 | 25.567568 | 82 | py |
FedNest | FedNest-main/utils/options.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.6
import argparse
import torch
def args_parser():
parser = argparse.ArgumentParser()
# federated arguments
parser.add_argument('--epochs', type=int, default=100, help="rounds of training")
parser.add_argument('--round', type=int, defaul... | 3,697 | 61.677966 | 106 | py |
URUST | URUST-main/inference.py | import argparse
import os
from pathlib import Path
from torch.utils.data import DataLoader
from torchvision.utils import save_image
from models.model import get_model
from models.kin import KernelizedInstanceNorm
from utils.dataset import XInferenceDataset
from utils.util import (
read_yaml_config,
reverse_im... | 6,463 | 32.319588 | 78 | py |
URUST | URUST-main/metric_images_with_ref.py | import os
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
import torch
from metrics.calculate_fid import calculate_fid_given_two_paths
from metrics.inception import InceptionV3
parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument(
"--exp_name",
type=st... | 2,592 | 21.946903 | 79 | py |
URUST | URUST-main/train.py | import argparse
import os
from collections import defaultdict
from torch.utils.data import DataLoader
from torchvision.utils import save_image
from models.model import get_model
from utils.dataset import get_dataset
from utils.util import read_yaml_config, reverse_image_normalize
def main():
parser = argparse.A... | 2,595 | 29.186047 | 87 | py |
URUST | URUST-main/appendix/proof_of_concept.py | import argparse
import inspect
import os
import sys
from collections import defaultdict
from pathlib import Path
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir)
import matplotlib.pyplot as plt
import numpy as ... | 12,569 | 30.346633 | 86 | py |
URUST | URUST-main/models/base.py | import os
from abc import ABC, abstractmethod
from collections import OrderedDict
import torch
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__>: initialize the c... | 8,859 | 34.019763 | 79 | py |
URUST | URUST-main/models/tin.py | import torch
import torch.nn as nn
class ThumbInstanceNorm(nn.Module):
def __init__(self, num_features, affine=True):
super(ThumbInstanceNorm, self).__init__()
self.thumb_mean = None
self.thumb_std = None
self.normal_instance_normalization = False
self.collection_mode = Fal... | 2,161 | 32.78125 | 77 | py |
URUST | URUST-main/models/kin.py | from enum import IntEnum
from functools import cached_property
import torch
import torch.nn as nn
from utils.util import get_kernel
class KernelizedInstanceNorm(nn.Module):
class Mode(IntEnum):
PHASE_CACHING = 1
PHASE_INFERENCE = 2
"""
Attributes:
num_features (int): The numbe... | 5,849 | 33.821429 | 96 | py |
URUST | URUST-main/models/lsesim.py | import itertools
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from utils.util import ImagePool
from models.base import BaseModel
from models.discriminator import Discriminator
from models.generator import Generator
from models.kin import (
init_kernelized_ins... | 14,534 | 34.108696 | 78 | py |
URUST | URUST-main/models/projector.py | import torch
import torch.nn as nn
from models.generator import Generator
class MLP(nn.Module):
def __init__(self, input_nc, output_nc):
super().__init__()
self.mlp = nn.Sequential(
*[
nn.Linear(input_nc, output_nc),
nn.ReLU(),
nn.Linear... | 1,462 | 27.134615 | 68 | py |
URUST | URUST-main/models/discriminator.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from models.downsample import Downsample
from models.normalization import make_norm_layer
class DiscriminatorBasicBlock(nn.Module):
def __init__(
self,
in_features,
out_features,
do_downsample=True,
do_inst... | 2,846 | 26.375 | 89 | py |
URUST | URUST-main/models/cyclegan.py | import itertools
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from utils.util import ReplayBuffer, weights_init
from models.base import BaseModel
from models.discriminator import Discriminator
from models.generator import Generator
from models.kin import (
in... | 8,848 | 32.266917 | 78 | py |
URUST | URUST-main/models/cut.py | import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from models.base import BaseModel
from models.discriminator import Discriminator
from models.generator import Generator
from models.kin import (
init_kernelized_instance_norm,
)
from models.projector import Head
fro... | 6,770 | 32.029268 | 77 | py |
URUST | URUST-main/models/generator.py | import torch
import torch.nn as nn
from models.downsample import Downsample
from models.normalization import make_norm_layer
from models.upsample import Upsample
class ResnetBlock(nn.Module):
def __init__(self, features, norm_cfg=None):
super().__init__()
self.norm_cfg = norm_cfg or {'type': 'in'... | 10,765 | 30.758112 | 85 | py |
URUST | URUST-main/models/downsample.py | import torch.nn as nn
class Downsample(nn.Module):
def __init__(self, features):
super().__init__()
self.reflectionpad = nn.ReflectionPad2d(1)
self.conv = nn.Conv2d(features, features, kernel_size=3, stride=2)
def forward(self, x):
x = self.reflectionpad(x)
x = self.co... | 343 | 23.571429 | 74 | py |
URUST | URUST-main/models/normalization.py | from copy import deepcopy
from typing import Any, Dict
import torch.nn as nn
from models.kin import KernelizedInstanceNorm
from models.tin import ThumbInstanceNorm
# TODO: To be deprecated
def get_normalization_layer(num_features, normalization="kin"):
if normalization == "kin":
return KernelizedInstanc... | 1,641 | 29.407407 | 89 | py |
URUST | URUST-main/models/upsample.py | import torch.nn as nn
class Upsample(nn.Module):
def __init__(self, features):
super().__init__()
layers = [
nn.ReplicationPad2d(1),
nn.ConvTranspose2d(
features,
features,
kernel_size=4,
stride=2,
... | 468 | 21.333333 | 43 | py |
URUST | URUST-main/models/lsesim_loss.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
from torch.nn import init
class GANLoss(nn.Module):
"""Define different GAN objectives.
The GANLoss class abstracts away the need to create the target label tensor
that has the same si... | 25,627 | 34.943899 | 79 | py |
URUST | URUST-main/models/tests/test_cyclegan.py | import os
import numpy as np
import pytest
import torch
from models.model import get_model
from models.kin import KernelizedInstanceNorm
from PIL import Image
from torch.utils.data import DataLoader
from torchvision.utils import make_grid
from utils.dataset import XInferenceDataset
from utils.util import (read_yaml_co... | 5,277 | 25.928571 | 78 | py |
URUST | URUST-main/models/tests/test_cut.py | import os
import numpy as np
import pytest
import torch
from models.model import get_model
from models.kin import KernelizedInstanceNorm
from PIL import Image
from torch.utils.data import DataLoader
from torchvision.utils import make_grid
from utils.dataset import XInferenceDataset
from utils.util import (read_yaml_co... | 5,270 | 26.030769 | 78 | py |
URUST | URUST-main/models/tests/test_kin.py | import numpy as np
import pytest
import torch
from ..kin import KernelizedInstanceNorm
def normalize(x):
std, mean = torch.std_mean(x, dim=(2, 3), keepdim=True)
return (x - mean) / std
def test_forward_normal():
layer = KernelizedInstanceNorm(num_features=3, device='cpu')
x = np.random.normal(size=... | 2,828 | 31.895349 | 102 | py |
URUST | URUST-main/F-LSeSim/inference.py | import argparse
import os
import time
from collections import defaultdict
from pathlib import Path
import numpy as np
import torch
import yaml
from scipy import signal
from torch.utils.data import DataLoader
from torchvision.utils import save_image
from yaml.loader import SafeLoader
from data import create_dataset
fr... | 7,039 | 34.024876 | 135 | py |
URUST | URUST-main/F-LSeSim/test.py | """General-purpose test script for image-to-image translation.
Once you have trained your model with train.py, you can use this script to test the model.
It will load a saved model from '--checkpoints_dir' and save the results to '--results_dir'.
It first creates model and dataset given the option. It will hard-code ... | 4,286 | 47.168539 | 126 | py |
URUST | URUST-main/F-LSeSim/train.py | """General-purpose training script for image-to-image translation.
This script works for various models (with option '--model': e.g., pix2pix, cyclegan, colorization) and
different datasets (with option '--dataset_mode': e.g., aligned, unaligned, single, colorization).
You need to specify the dataset ('--dataroot'), e... | 5,659 | 42.538462 | 138 | py |
URUST | URUST-main/F-LSeSim/test_fid.py | """General-purpose test script for image-to-image translation.
Once you have trained your model with train.py, you can use this script to test the model.
It will load a saved model from '--checkpoints_dir' and save the results to '--results_dir'.
It first creates model and dataset given the option. It will hard-code ... | 5,726 | 44.094488 | 130 | py |
URUST | URUST-main/F-LSeSim/options/base_options.py | import argparse
import os
import torch
import data
import models
from util import util
class BaseOptions:
"""This class defines options used during both training and test time.
It also implements several helper functions such as parsing, printing, and saving the options.
It also gathers additional opti... | 10,621 | 34.289037 | 182 | py |
URUST | URUST-main/F-LSeSim/models/base_model.py | import os
from abc import ABC, abstractmethod
from collections import OrderedDict
import torch
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,326 | 40.643382 | 260 | py |
URUST | URUST-main/F-LSeSim/models/losses.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
from .cyclegan_networks import init_net
class GANLoss(nn.Module):
"""Define different GAN objectives.
The GANLoss class abstracts away the need to create the target label tensor
that... | 21,996 | 35.907718 | 143 | py |
URUST | URUST-main/F-LSeSim/models/stylegan_networks.py | """
The network architectures is based on PyTorch implemenation of StyleGAN2Encoder.
Original PyTorch repo: https://github.com/rosinality/style-based-gan-pytorch
Original PyTorch repo of CUT: https://github.com/taesungp/contrastive-unpaired-translation
Origianl StyelGAN2 paper: https://github.com/NVlabs/stylegan2
We us... | 28,078 | 30.408277 | 100 | py |
URUST | URUST-main/F-LSeSim/models/tin.py | import torch
import torch.nn as nn
class ThumbInstanceNorm(nn.Module):
def __init__(self, num_features, affine=True):
super(ThumbInstanceNorm, self).__init__()
self.thumb_mean = None
self.thumb_std = None
self.normal_instance_normalization = False
self.collection_mode = Fal... | 2,145 | 33.063492 | 80 | py |
URUST | URUST-main/F-LSeSim/models/kin.py | from enum import IntEnum
from functools import cached_property
import torch
import torch.nn as nn
from utils.util import get_kernel
class KernelizedInstanceNorm(nn.Module):
class Mode(IntEnum):
PHASE_CACHING = 1
PHASE_INFERENCE = 2
"""
Attributes:
num_features (int): The numbe... | 5,849 | 33.821429 | 96 | py |
URUST | URUST-main/F-LSeSim/models/cyclegan_networks.py | """
The network architectures is based on the implementation of CycleGAN and CUT
Original PyTorch repo of CycleGAN: https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix
Original PyTorch repo of CUT: https://github.com/taesungp/contrastive-unpaired-translation
Original CycleGAN paper: https://arxiv.org/pdf/1703.10593... | 23,226 | 33.615499 | 132 | py |
URUST | URUST-main/F-LSeSim/models/discriminator.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from models.downsample import Downsample
from models.normalization import make_norm_layer
class DiscriminatorBasicBlock(nn.Module):
def __init__(
self,
in_features,
out_features,
do_downsample=True,
do_inst... | 2,627 | 29.55814 | 89 | py |
URUST | URUST-main/F-LSeSim/models/colorization_model.py | import numpy as np
import torch
from skimage import color # used for lab2rgb
from .pix2pix_model import Pix2PixModel
class ColorizationModel(Pix2PixModel):
"""This is a subclass of Pix2PixModel for image colorization (black & white image -> colorful images).
The model training requires '-dataset_model colo... | 3,015 | 41.478873 | 141 | py |
URUST | URUST-main/F-LSeSim/models/pix2pix_model.py | import torch
from . import networks
from .base_model import BaseModel
class Pix2PixModel(BaseModel):
"""This class implements the pix2pix model, for learning a mapping from input images to output images given paired data.
The model training requires '--dataset_mode aligned' dataset.
By default, it uses ... | 6,784 | 41.672956 | 150 | py |
URUST | URUST-main/F-LSeSim/models/networks.py | from torch.optim import lr_scheduler
from models.generator import Generator
from . import cyclegan_networks, stylegan_networks
##################################################################################
# Networks
##################################################################################
def define_G... | 5,218 | 35.753521 | 113 | py |
URUST | URUST-main/F-LSeSim/models/template_model.py | """Model class template
This module provides a template for users to implement custom models.
You can specify '--model template' to use this model.
The class name should be consistent with both the filename and its model option.
The filename should be <model>_dataset.py
The class name should be <Model>Dataset.py
It im... | 6,114 | 51.715517 | 177 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.