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 |
|---|---|---|---|---|---|---|
FATE | FATE-master/python/federatedml/nn/hetero/nn_component/bottom_model.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/lic... | 3,119 | 32.913043 | 120 | py |
FATE | FATE-master/python/federatedml/nn/hetero/nn_component/top_model.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/lic... | 5,348 | 35.636986 | 117 | py |
FATE | FATE-master/python/federatedml/nn/hetero/nn_component/torch_model.py | import numpy as np
import tempfile
from federatedml.util import LOGGER
try: # for the situation that torch is not installed, but other modules still can be used
import torch
import torch as t
import copy
from types import SimpleNamespace
from torch import autograd
from federatedml.nn.backend.t... | 6,909 | 30.697248 | 112 | py |
FATE | FATE-master/python/federatedml/nn/hetero/protection_enhance/coae.py | from federatedml.util import LOGGER
from federatedml.util import consts
try:
import torch
import torch as t
from torch import nn
from torch.nn import Module
from torch.nn import functional as F
except ImportError:
Module = object
def entropy(tensor):
return -t.sum(tensor * t.log2(tensor))... | 4,246 | 25.710692 | 79 | py |
FATE | FATE-master/python/federatedml/nn/hetero/interactive/he_interactive_layer.py | #
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 36,890 | 37.071207 | 122 | py |
FATE | FATE-master/python/federatedml/nn/hetero/interactive/utils/numpy_layer.py | import torch
import numpy as np
from federatedml.util import consts
from federatedml.secureprotol.paillier_tensor import PaillierTensor
class NumpyDenseLayer(object):
"""
NumpyDenseLayer is designed for Pailler Tensor compute
"""
def __init__(self):
self.input = None
self.model_weig... | 6,956 | 27.62963 | 123 | py |
FATE | FATE-master/python/federatedml/nn/loss/cross_entropy.py | import torch as t
from federatedml.util import consts
from torch.nn.functional import one_hot
def cross_entropy(p2, p1, reduction='mean'):
p2 = p2 + consts.FLOAT_ZERO # to avoid nan
assert p2.shape == p1.shape
if reduction == 'sum':
return -t.sum(p1 * t.log(p2))
elif reduction == 'mean':
... | 913 | 25.114286 | 66 | py |
FATE | FATE-master/python/federatedml/nn/loss/weighted_loss.py | import torch as t
from torch.nn import BCELoss
class WeightedBCE(t.nn.Module):
def __init__(self) -> None:
super().__init__()
self.loss_fn = BCELoss(reduce=False)
def forward(self, pred, label_and_weight):
label, weights = label_and_weight
losses = self.loss_fn(pred, label)
... | 425 | 24.058824 | 47 | py |
FATE | FATE-master/python/federatedml/linear_model/coordinated_linear_model/logistic_regression/homo_logistic_regression/homo_lr_client.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/lic... | 11,511 | 35.087774 | 106 | py |
FATE | FATE-master/python/federatedml/linear_model/coordinated_linear_model/logistic_regression/homo_logistic_regression/homo_lr_base.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/lic... | 8,574 | 42.090452 | 129 | py |
FATE | FATE-master/python/federatedml/util/consts.py | #
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 8,740 | 22.882514 | 120 | py |
FATE | FATE-master/python/federatedml/transfer_learning/hetero_ftl/ftl_dataloder.py | import numpy as np
import tensorflow as tf
from federatedml.util import LOGGER
class FTLDataLoader(tf.keras.utils.Sequence):
def __init__(self, non_overlap_samples, overlap_samples, batch_size, guest_side=True):
self.batch_size = batch_size
self.guest_side = guest_side
self._overlap_ind... | 3,111 | 31.416667 | 114 | py |
FATE | FATE-master/python/federatedml/transfer_learning/hetero_ftl/ftl_base.py | import copy
import json
import functools
import numpy as np
from federatedml.util import LOGGER
from federatedml.transfer_learning.hetero_ftl.backend.nn_model import get_nn_builder
from federatedml.model_base import ModelBase
from federatedml.param.ftl_param import FTLParam
from federatedml.transfer_learning.hetero_ftl... | 12,882 | 37.804217 | 116 | py |
FATE | FATE-master/python/federatedml/transfer_learning/hetero_ftl/backend/nn_model.py | #
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 1,611 | 25 | 98 | py |
FATE | FATE-master/python/federatedml/transfer_learning/hetero_ftl/backend/data_generator.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/lic... | 1,238 | 25.361702 | 75 | py |
FATE | FATE-master/python/federatedml/transfer_learning/hetero_ftl/backend/tf_keras/losses.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/lic... | 1,019 | 33 | 75 | py |
FATE | FATE-master/python/federatedml/transfer_learning/hetero_ftl/backend/tf_keras/nn_model.py | #
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 9,949 | 33.548611 | 102 | py |
FATE | FATE-master/python/federatedml/transfer_learning/hetero_ftl/backend/tf_keras/data_generator.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/lic... | 1,238 | 25.361702 | 75 | py |
FATE | FATE-master/python/federatedml/transfer_learning/hetero_ftl/backend/tf_keras/layers/pooling.py | #
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 4,149 | 39.291262 | 79 | py |
FATE | FATE-master/python/federatedml/transfer_learning/hetero_ftl/backend/tf_keras/layers/baisc.py | #
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 1,881 | 43.809524 | 117 | py |
FATE | FATE-master/python/federatedml/transfer_learning/hetero_ftl/backend/tf_keras/layers/util.py | #
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 1,052 | 30.909091 | 75 | py |
FATE | FATE-master/python/federatedml/transfer_learning/hetero_ftl/backend/tf_keras/layers/conv.py | #
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 3,710 | 41.655172 | 118 | py |
FATE | FATE-master/python/federatedml/transfer_learning/hetero_ftl/test/test_ftl_modules.py | #
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 3,947 | 44.906977 | 705 | py |
FATE | FATE-master/python/federatedml/secureprotol/encrypt.py | #
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 12,519 | 29.990099 | 116 | py |
FATE | FATE-master/python/federatedml/param/ftl_param.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/lic... | 8,927 | 44.090909 | 120 | py |
FATE | FATE-master/python/federatedml/param/hetero_nn_param.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/lic... | 12,596 | 41.557432 | 139 | py |
FATE | FATE-master/python/federatedml/param/boosting_param.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/lic... | 35,803 | 51.268613 | 130 | py |
FATE | FATE-master/python/federatedml/param/homo_nn_param.py | from federatedml.param.base_param import BaseParam
class TrainerParam(BaseParam):
def __init__(self, trainer_name=None, **kwargs):
super(TrainerParam, self).__init__()
self.trainer_name = trainer_name
self.param = kwargs
def check(self):
if self.trainer_name is not None:
... | 2,502 | 31.506494 | 107 | py |
FATE | FATE-master/python/federatedml/ensemble/basic_algorithms/decision_tree/tree_core/splitter.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2019 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/lic... | 23,387 | 44.063584 | 122 | py |
FATE | FATE-master/python/federatedml/protobuf/homo_model_convert/homo_model_convert.py | #
# Copyright 2021 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 6,574 | 38.136905 | 94 | py |
FATE | FATE-master/python/federatedml/protobuf/homo_model_convert/test/homo_nn_test.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2021 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/lice... | 3,476 | 33.425743 | 106 | py |
FATE | FATE-master/python/federatedml/protobuf/homo_model_convert/tf_keras/nn.py | #
# Copyright 2021 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 1,695 | 35.869565 | 103 | py |
FATE | FATE-master/python/federatedml/protobuf/homo_model_convert/pytorch/nn.py | #
# Copyright 2021 The FATE Authors. 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 copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | 1,278 | 28.744186 | 80 | py |
FATE | FATE-master/python/federatedml/framework/homo/aggregator/secure_aggregator.py | from federatedml.framework.homo.blocks import RandomPaddingCipherClient, RandomPaddingCipherServer, PadsCipher, RandomPaddingCipherTransVar
from federatedml.framework.homo.aggregator.aggregator_base import AggregatorBaseClient, AutoSuffix, AggregatorBaseServer
import numpy as np
from federatedml.framework.weights impor... | 11,628 | 39.378472 | 139 | py |
ClusterQ | ClusterQ-master/main.py | import argparse
import datetime
import logging
import os
import time
import traceback
import sys
import copy
import torch
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
import torch.nn as nn
from torch.utils.tensorboard import SummaryWriter
import torchvision
# option file should be modified ... | 10,933 | 32.335366 | 125 | py |
ClusterQ | ClusterQ-master/dataloader.py | """
data loder for loading data
"""
import os
import math
import torch
import torch.utils.data as data
import numpy as np
from PIL import Image
import torchvision
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import struct
from data_utils.get_imagenet import get_train_dataloader, get_... | 4,929 | 27.49711 | 109 | py |
ClusterQ | ClusterQ-master/gan.py | import torch.nn as nn
import torch
from conditional_batchnorm import CategoricalConditionalBatchNorm2d
from options import Option
# original c-gan
class Generator(nn.Module):
def __init__(self, options=None, conf_path=None):
super(Generator, self).__init__()
self.settings = options or Option(conf_path)
self.la... | 5,309 | 35.875 | 129 | py |
ClusterQ | ClusterQ-master/options.py | import os
import shutil
from pyhocon import ConfigFactory
from utils.opt_static import NetOption
class Option(NetOption):
def __init__(self, conf_path):
super(Option, self).__init__()
self.conf = ConfigFactory.parse_file(conf_path)
# ------------ General options ----------------------------------------
se... | 4,549 | 39.990991 | 120 | py |
ClusterQ | ClusterQ-master/visual.py | import torch
import torch.nn as nn
from torchvision.utils import save_image
from torchvision.io import read_image
import utils as utils
from options import Option
import os
import sys
import copy
import logging
import argparse
from dataloader import DataLoader as DLR
from gan import Generator, Generator_imagenet, Qimer... | 12,051 | 39.307692 | 133 | py |
ClusterQ | ClusterQ-master/trainer.py | """
basic trainer
"""
import time
import torch.autograd
import torch.nn as nn
from torch.autograd import Variable
from torchvision import transforms
import torch.nn.functional as F
import utils as utils
import numpy as np
import random
import torch
__all__ = ["Trainer"]
class Trainer(object):
"""
trainer for trai... | 17,287 | 30.721101 | 157 | py |
ClusterQ | ClusterQ-master/quantization_utils/quant_modules.py | # *
# @file Different utility functions
# Copyright (c) Yaohui Cai, Zhewei Yao, Zhen Dong, Amir Gholami
# All rights reserved.
# This file is part of ZeroQ repository.
#
# ZeroQ is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Soft... | 5,819 | 29.15544 | 121 | py |
ClusterQ | ClusterQ-master/quantization_utils/quant_utils.py | #*
# @file Different utility functions
# Copyright (c) Yaohui Cai, Zhewei Yao, Zhen Dong, Amir Gholami
# All rights reserved.
# This file is part of ZeroQ repository.
#
# ZeroQ is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Softw... | 5,077 | 35.271429 | 100 | py |
ClusterQ | ClusterQ-master/utils/model_transform.py | import torch.nn as nn
import torch
import numpy as np
__all__ = ["data_parallel", "model2list",
"list2sequential", "model2state_dict"]
def data_parallel(model, ngpus, gpu0=0):
"""
assign model to multi-gpu mode
:params model: target model
:params ngpus: number of gpus to use
:params gp... | 1,928 | 27.791045 | 79 | py |
ClusterQ | ClusterQ-master/utils/opt_static.py | """
TODO: add doc for module
"""
import torch
__all__ = ["NetOption"]
"""
You can run your script with CUDA_VISIBLE_DEVICES=5,6 python your_script.py
or set the environment variable in the script by os.environ['CUDA_VISIBLE_DEVICES'] = '5,6'
to map GPU 5, 6 to device_ids 0, 1, respectively.
"""
class NetOption(object)... | 4,045 | 42.978261 | 137 | py |
ClusterQ | ClusterQ-master/utils/warmup.py | from torchlearning.mio import MIO
train_dataset = MIO("/home/datasets/imagenet_mio/train/")
test_dataset = MIO("/home/datasets/imagenet_mio/val/")
for i in range(train_dataset.size):
print(i)
train_dataset.fetchone(i)
for i in range(test_dataset.size):
print(i)
test_dataset.fetchone(i) | 304 | 26.727273 | 57 | py |
ClusterQ | ClusterQ-master/utils/compute.py | import numpy as np
import math
import torch
__all__ = ["compute_tencrop", "compute_singlecrop", "AverageMeter"]
def compute_tencrop(outputs, labels):
output_size = outputs.size()
outputs = outputs.view(output_size[0] / 10, 10, output_size[1])
outputs = outputs.sum(1).squeeze(1)
# compute top1
_,... | 2,820 | 30 | 88 | py |
ClusterQ | ClusterQ-master/data_utils/get_imagenet.py | import os
import lmdb
import io
import pickle
from PIL import Image
import numpy as np
from torch.utils.data import DistributedSampler
import torchvision.transforms as transforms
from torch.utils.data import DataLoader, Dataset
from .map_imagenet import label2num
def get_train_dataloader(data_path, batchsize, num_work... | 4,871 | 39.6 | 141 | py |
ClusterQ | ClusterQ-master/data_utils/map_imagenet.py | label2num = {
'n01440764': 0, #tench
'n01443537': 1, #goldfish
'n01484850': 2, #great_white_shark
'n01491361': 3, #tiger_shark
'n01494475': 4, #hammerhead
'n01496331': 5, #electric_ray
'n01498041': 6, #stingray
'n01514668': 7, #cock
'n01514859': 8, #hen
'n01518878': 9, #ostrich
'n01530575': 10, #b... | 31,378 | 30.285145 | 51 | py |
METER | METER-main/azure_distributed_run.py | import os
import copy
import pytorch_lightning as pl
import os
os.environ["NCCL_DEBUG"] = "INFO"
from meter.config import ex
from meter.modules import METERTransformerSS
from meter.datamodules.multitask_datamodule import MTDataModule
import resource
rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)
resource.setrlim... | 4,388 | 31.272059 | 97 | py |
METER | METER-main/setup.py | from setuptools import setup, find_packages
setup(
name="meter",
packages=find_packages(
exclude=[".dfc", ".vscode", "dataset", "notebooks", "result", "scripts"]
),
version="0.1.0",
license="MIT",
description="METER: Multimodal End-to-end TransformER",
author="Microsoft Corporation"... | 511 | 29.117647 | 80 | py |
METER | METER-main/run.py | import os
import copy
import pytorch_lightning as pl
import os
os.environ["NCCL_DEBUG"] = "INFO"
from meter.config import ex
from meter.modules import METERTransformerSS
from meter.datamodules.multitask_datamodule import MTDataModule
import resource
rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)
resource.setrlim... | 2,373 | 29.050633 | 97 | py |
METER | METER-main/meter/datamodules/multitask_datamodule.py | import functools
from pytorch_lightning import LightningDataModule
from torch.utils.data import DataLoader
from torch.utils.data.dataset import ConcatDataset
from torch.utils.data.distributed import DistributedSampler
from . import _datamodules
class MTDataModule(LightningDataModule):
def __init__(self, _config... | 2,712 | 31.686747 | 85 | py |
METER | METER-main/meter/datamodules/datamodule_base.py | import torch
from pytorch_lightning import LightningDataModule
from torch.utils.data import DataLoader
from transformers import (
DataCollatorForLanguageModeling,
DataCollatorForWholeWordMask,
BertTokenizer,
RobertaTokenizer,
)
def get_pretrained_tokenizer(from_pretrained):
if torch.distributed.i... | 6,097 | 30.926702 | 83 | py |
METER | METER-main/meter/gadgets/my_metrics.py | import torch
from pytorch_lightning.metrics import Metric
class Accuracy(Metric):
def __init__(self, dist_sync_on_step=False):
super().__init__(dist_sync_on_step=dist_sync_on_step)
self.add_state("correct", default=torch.tensor(0.0), dist_reduce_fx="sum")
self.add_state("total", default=to... | 2,359 | 32.714286 | 82 | py |
METER | METER-main/meter/modules/clip_model.py | from collections import OrderedDict
from typing import Tuple, Union
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn
class LayerNorm(nn.LayerNorm):
"""Subclass torch's LayerNorm to handle fp16."""
def forward(self, x: torch.Tensor):
orig_type = x.dtype
ret... | 11,071 | 38.971119 | 142 | py |
METER | METER-main/meter/modules/meter_utils.py | import torch
import random
from transformers.optimization import AdamW
from transformers import (
get_polynomial_decay_schedule_with_warmup,
get_cosine_schedule_with_warmup,
)
from .dist_utils import all_gather
from .objectives import compute_irtr_recall
from ..gadgets.my_metrics import Accuracy, VQAScore, Sca... | 11,926 | 38.363036 | 100 | py |
METER | METER-main/meter/modules/swin_transformer.py | """ Swin Transformer
A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows`
- https://arxiv.org/pdf/2103.14030
Code/weights from https://github.com/microsoft/Swin-Transformer, original copyright/license info below
"""
# --------------------------------------------------------
... | 27,086 | 41.191589 | 125 | py |
METER | METER-main/meter/modules/bert_model.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... | 76,724 | 41.863128 | 213 | py |
METER | METER-main/meter/modules/meter_module.py | import torch
import torch.nn as nn
import pytorch_lightning as pl
import numpy as np
from transformers.models.bert.modeling_bert import BertConfig, BertEmbeddings, BertModel, BertEncoder, BertLayer
from .bert_model import BertCrossLayer, BertAttention
from . import swin_transformer as swin
from . import heads, objecti... | 12,770 | 40.330097 | 134 | py |
METER | METER-main/meter/modules/dist_utils.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
This file contains primitives for multi-gpu communication.
This is useful when doing distributed training.
"""
import functools
import logging
import numpy as np
import pickle
import torch
import torch.distributed as dist
import torch
_LOCAL_... | 7,814 | 27.837638 | 100 | py |
METER | METER-main/meter/modules/objectives.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import os
import glob
import json
import tqdm
import functools
from torch.utils.data.distributed import DistributedSampler
from einops import rearrange
from .dist_utils import all_gather
def compute_mlm(pl_module, batch):
infer = pl_module.infer... | 17,360 | 33.514911 | 88 | py |
METER | METER-main/meter/modules/swin_helpers.py | """ Model creation / weight loading / state_dict helpers
Hacked together by / Copyright 2020 Ross Wightman
"""
import logging
import os
import math
from collections import OrderedDict
from copy import deepcopy
from typing import Any, Callable, Optional, Tuple
import torch
import torch.nn as nn
from timm.models.featu... | 23,550 | 43.519849 | 153 | py |
METER | METER-main/meter/modules/heads.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers.models.bert.modeling_bert import BertPredictionHeadTransform
class Pooler(nn.Module):
def __init__(self, hidden_size):
super().__init__()
self.dense = nn.Linear(hidden_size, hidden_size)
self.activation =... | 1,257 | 27.590909 | 83 | py |
METER | METER-main/meter/datasets/base_dataset.py | import random
import torch
import io
import pyarrow as pa
import os
from PIL import Image
from ..transforms import keys_to_transforms
class BaseDataset(torch.utils.data.Dataset):
def __init__(
self,
data_dir: str,
transform_keys: list,
image_size: int,
names: list,
... | 9,448 | 36.054902 | 111 | py |
METER | METER-main/meter/transforms/transform.py | from .utils import (
inception_normalize,
imagenet_normalize,
MinMaxResize,
)
from PIL import Image
from torchvision import transforms
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
from .randaug import RandAugment
def pixelbert_transform(size=800):
longer = int((1... | 2,733 | 26.34 | 93 | py |
METER | METER-main/meter/transforms/utils.py | from torchvision import transforms
from PIL import Image
class MinMaxResize:
def __init__(self, shorter=800, longer=1333):
self.min = shorter
self.max = longer
def __call__(self, x):
w, h = x.size
scale = self.min / min(w, h)
if h < w:
newh, neww = self.min... | 1,792 | 27.919355 | 98 | py |
METER | METER-main/meter/transforms/randaug.py | # code in this file is adpated from rpmcruz/autoaugment
# https://github.com/rpmcruz/autoaugment/blob/master/transformations.py
import random
import PIL, PIL.ImageOps, PIL.ImageEnhance, PIL.ImageDraw
import numpy as np
import torch
from PIL import Image
def ShearX(img, v): # [-0.3, 0.3]
assert -0.3 <= v <= 0.3
... | 6,990 | 24.892593 | 134 | py |
MCL | MCL-main/train_mcl.py | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
import os
import argparse
from tqdm import tqdm
from loaders.domainnet import build_dataset
from loaders.office_home import build_dataset_officehome
from loaders.visda impor... | 12,118 | 37.230284 | 109 | py |
MCL | MCL-main/loaders/office_home.py | import numpy as np
import os
import os.path
from PIL import Image
from loaders.randaugment import RandAugmentMC
from torchvision import transforms
import pickle
import torch.utils.data as TorchData
from torch.utils.data.distributed import DistributedSampler
from loaders.utils import TransformFixMatch, TransformFixMatch... | 9,778 | 38.273092 | 146 | py |
MCL | MCL-main/loaders/visda.py | import numpy as np
import os
import os.path
from PIL import Image
from loaders.randaugment import RandAugmentMC
from torchvision import transforms
import pickle
import torch.utils.data as TorchData
from torch.utils.data.distributed import DistributedSampler
from loaders.utils import TransformFixMatch, TransformFixMatch... | 9,553 | 37.680162 | 145 | py |
MCL | MCL-main/loaders/utils.py | import numpy as np
import os
import os.path
from PIL import Image
from loaders.randaugment import RandAugmentMC
from torchvision import transforms
import pickle
import torch.utils.data as TorchData
from typing import Callable
import torch
import torch.utils.data
import torchvision
class TransformFixMatch(object):
... | 5,552 | 36.02 | 116 | py |
MCL | MCL-main/loaders/domainnet.py | import numpy as np
import os
import os.path
from PIL import Image
from loaders.randaugment import RandAugmentMC
from torchvision import transforms
import pickle
import torch.utils.data as TorchData
from torch.utils.data.distributed import DistributedSampler
from loaders.utils import TransformFixMatch, TransformFixMatch... | 9,726 | 38.221774 | 145 | py |
MCL | MCL-main/loaders/gaussian_blur.py | import torch
from torch import Tensor
from torchvision.transforms.functional import to_pil_image, to_tensor
from torch.nn.functional import conv2d, pad as torch_pad
from typing import Any, List, Sequence, Optional
import numbers
import numpy as np
import torch
from PIL import Image
from typing import Tuple
class Gaus... | 9,305 | 39.995595 | 112 | py |
MCL | MCL-main/loaders/simsiam_aug.py | import torchvision.transforms as T
try:
from torchvision.transforms import GaussianBlur
except ImportError:
from .gaussian_blur import GaussianBlur
T.GaussianBlur = GaussianBlur
import random
from PIL import ImageFilter
imagenet_mean_std = [[0.485, 0.456, 0.406], [0.229, 0.224, 0.225]]
class GaussianBlu... | 2,991 | 36.4 | 103 | py |
MCL | MCL-main/loaders/randaugment.py | # code in this file is adpated from
# https://github.com/ildoonet/pytorch-randaugment/blob/master/RandAugment/augmentations.py
# https://github.com/google-research/fixmatch/blob/master/third_party/auto_augment/augmentations.py
# https://github.com/google-research/fixmatch/blob/master/libml/ctaugment.py
import logging
i... | 6,303 | 26.055794 | 99 | py |
MCL | MCL-main/utils/losses.py | import numpy as np
import torch
import torch.nn.functional as F
import ot
def loss_unl(net_G, net_F, imgs_tu_w, imgs_tu_s, proto_s, args):
'''The proposed losses for unlabeled target samples
Parameters:
net_G (network) --The backbone
net_F (network) --The classifier (fc-l2norm-fc)
... | 3,896 | 31.206612 | 91 | py |
MCL | MCL-main/utils/utils.py | import os
import torch
import torch.nn as nn
import os.path as osp
import numpy as np
import random
import time
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.1)
elif classname.find('Linear') != -1:
nn.init.xavier_normal_... | 3,798 | 26.729927 | 95 | py |
MCL | MCL-main/utils/ema.py | from copy import deepcopy
import torch
class ModelEMA(object):
def __init__(self, model, decay):
self.ema = deepcopy(model)
self.ema.cuda()
self.ema.eval()
self.decay = decay
self.ema_has_module = hasattr(self.ema, 'module')
# Fix EMA. https://github.com/valencebon... | 1,282 | 31.897436 | 78 | py |
MCL | MCL-main/model/resnet.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from torch.autograd import Function
import torch
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
're... | 8,501 | 31.083019 | 80 | py |
MCL | MCL-main/model/ema.py | from copy import deepcopy
import torch
class ModelEMA(object):
def __init__(self, args, model, decay):
self.ema = deepcopy(model)
self.ema.to(args.device)
self.ema.eval()
self.decay = decay
self.ema_has_module = hasattr(self.ema, 'module')
# Fix EMA. https://github... | 1,297 | 32.282051 | 78 | py |
MCL | MCL-main/model/basenet.py | from torchvision import models
import torch.nn.functional as F
import torch
import torch.nn as nn
from torch.autograd import Function
class GradReverse(Function):
def __init__(self, lambd):
self.lambd = lambd
def forward(self, x):
return x.view_as(x)
def backward(self, grad_output):
... | 3,973 | 28.879699 | 75 | py |
TheThresher | TheThresher-main/infer_kernel.py | '''
Infer the convolution kernel and sky background
'''
# imports
import torch
import numpy as np
import matplotlib.pyplot as plt
import os
import time
# custom imports
import noise_models
import math_utils
import utils
import config
# make sure to enable GPU acceleration!
if torch.cuda.is_available() is True:
dev... | 7,290 | 36.010152 | 130 | py |
TheThresher | TheThresher-main/utils.py | # imports
import numpy as np
import torch
from astropy.io import fits
from skimage.feature import register_translation
from scipy.ndimage import shift
# Convert np.ndarrays to torch.Tensors whith dims: NHWC
def convert_to_tensor(image):
if type(image) is np.ndarray:
image = image.astype(np.float32)
image... | 957 | 28.9375 | 88 | py |
TheThresher | TheThresher-main/thresh.py | '''
The Thresher is a tool for fitting image models to spools of high
frame-rate imaging data.
'''
## imports
# standard imports
import torch
import numpy as np
from astropy.io import fits
import os
from pathlib import Path
import matplotlib.pyplot as plt
from matplotlib.colors import SymLogNorm
# custom imports
impo... | 5,970 | 34.541667 | 111 | py |
TheThresher | TheThresher-main/noise_models.py | import torch
import numpy as np
import math_utils
# EMCCD noise model - 'Poisson-Gamma-Normal' negative log-likelihood
def emccd_nll(model, targ, EMCCD_params, phi = 0, w = None):
## units
# model (ADU)
# targ (ADU)
# g (e-_EM), electrons generated after the EM amplification
# n (e-_phot), electro... | 3,070 | 30.989583 | 108 | py |
TheThresher | TheThresher-main/math_utils.py | # Function for quickly computing the modified Bessel function of the first kind
# as implemented in Salahat et al. 2013 for approximating the
import os
import torch
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import i1
from scipy import stats
import config
### Optional - Estimate parameter u... | 5,174 | 29.263158 | 104 | py |
ssm_ecg | ssm_ecg-main/code/train_ecg_model.py | from platform import architecture
from pyexpat import model
import time
import logging
import os
import pdb
from os.path import exists, join, dirname
from argparse import ArgumentParser
import pickle
import torch
from torch import Tensor
import torch.nn.functional as F
import numpy as np
import pytorch_lightning as pl... | 21,043 | 36.645796 | 144 | py |
ssm_ecg | ssm_ecg-main/code/save_predictions.py | from train_ecg_model import *
import sys
import glob
import os
from tqdm import tqdm
from collections import defaultdict
import pdb
import click
from tqdm import tqdm
def load_from_checkpoint(pl_model, checkpoint_path):
print("load model..")
lightning_state_dict = torch.load(checkpoint_path)
state_dict = ... | 6,805 | 43.48366 | 202 | py |
ssm_ecg | ssm_ecg-main/code/pretraining.py | #python pretraining.py --normalize --epochs 200 --lr 0.0001 --batch-size 32 --input-size 1000 --fc-encoder --negatives-from-same-seq-only --mlp --exclude-ptbxl
#python pretraining.py --normalize --epochs 200 --lr 0.0001 --batch-size 32 --input-size 1000 --precision 32 --fc-encoder --negatives-from-same-seq-only --mlp ... | 25,286 | 51.901674 | 820 | py |
ssm_ecg | ssm_ecg-main/code/ecg_datamodule.py |
import os
import torch
from pytorch_lightning import LightningDataModule
from clinical_ts.ecg_dataset_wrapper import ECGDataSetWrapper
class ECGDataModule(LightningDataModule):
name = 'ecg_dataset'
extra_args = {}
def __init__(
self,
batch_size,
target_folder,
... | 4,479 | 45.185567 | 311 | py |
ssm_ecg | ssm_ecg-main/code/finetuning.py |
import yaml
import tensorboard
import torch
import torch.nn as nn
import os
import shutil
import sys
import csv
import argparse
import pickle
from dl_models.cpc import CPCModel
import torch.nn.functional as F
from tqdm import tqdm
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PC... | 48,660 | 43.848848 | 278 | py |
ssm_ecg | ssm_ecg-main/code/clinical_ts/misc_utils.py | from pytorch_lightning.callbacks import Callback
import argparse
class LRMonitorCallback(Callback):
def __init__(self,interval="epoch",start=True,end=True):
self.interval = interval
self.start = start
self.end = end
def on_train_batch_start(self, trainer, *args, **kwargs): ... | 8,842 | 52.271084 | 191 | py |
ssm_ecg | ssm_ecg-main/code/clinical_ts/timeseries_utils.py | __all__ = ['nn_upsample','resample_labels','butter_filter', 'butter_filter_frequency_response', 'apply_butter_filter', 'save_dataset', 'load_dataset',
'dataset_add_chunk_col', 'dataset_add_length_col', 'dataset_add_labels_col', 'dataset_add_mean_col',
'dataset_add_median_col', 'dataset_add_std_col... | 40,436 | 43.830377 | 368 | py |
ssm_ecg | ssm_ecg-main/code/clinical_ts/ecg_dataset_wrapper.py | from numpy.lib import index_tricks
from sklearn.utils.validation import _num_samples
from .create_logger import create_logger
import numpy as np
import torch
from torch.utils.data import DataLoader
# from .customDataLoader import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
import torchvision.tr... | 14,076 | 43.40694 | 208 | py |
ssm_ecg | ssm_ecg-main/code/dl_models/xresnet1d.py | __all__ = ['init_default', 'BatchNorm', 'NormType', 'ResBlock', 'init_cnn', 'XResNet1d', 'xresnet1d18', 'xresnet1d34', 'xresnet1d50',
'xresnet1d101', 'xresnet1d152', 'xresnet1d18_deep', 'xresnet1d34_deep', 'xresnet1d50_deep',
'xresnet1d18_deeper', 'xresnet1d34_deeper', 'xresnet1d50_deeper', 'xbotn... | 9,563 | 48.046154 | 187 | py |
ssm_ecg | ssm_ecg-main/code/dl_models/basic_conv1d.py | __all__ = ['AdaptiveConcatPool1d', 'SqueezeExcite1d',
'weight_init', 'create_head1d', 'basic_conv1d', 'fcn', 'fcn_wang', 'schirrmeister', 'sen', 'basic1d']
# Cell
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from typing import Iterable
class Flatten(nn.Module):
"Flatt... | 10,219 | 53.074074 | 431 | py |
ssm_ecg | ssm_ecg-main/code/dl_models/cpc.py | # AUTOGENERATED! DO NOT EDIT! File to edit: nbs/17_cpc.ipynb (unless otherwise specified).
__all__ = ['CPCEncoder', 'CPCModel']
# Cell
import torch
import torch.nn.functional as F
import torch.nn as nn
import numpy as np
from collections.abc import Iterable
from .basic_conv1d import bn_drop_lin, _conv1d
from .modifi... | 10,592 | 46.932127 | 245 | py |
ssm_ecg | ssm_ecg-main/code/dl_models/s4_model.py | # adapted from https://github.com/HazyResearch/state-spaces/blob/main/example.py
import torch
import torch.nn as nn
import sys
import os
egg_path = "/home/mehari/anaconda3/envs/stsp/lib/python3.9/cauchy_mult-0.0.0-py3.9-linux-x86_64.egg"
egg_path = "/home/mehari/clones/stsp/code/extensions/cauchy/cauchy_mult-0.0.0-py3... | 5,417 | 32.239264 | 117 | py |
ssm_ecg | ssm_ecg-main/code/dl_models/xresnet1d_oldbnfinal.py | # AUTOGENERATED! DO NOT EDIT! File to edit: nbs/13_xresnet1d.ipynb (unless otherwise specified).
__all__ = ['delegates', 'store_attr', 'init_default', 'BatchNorm', 'NormType', 'ConvLayer', 'AdaptiveAvgPool',
'MaxPool', 'AvgPool', 'ResBlock', 'init_cnn', 'XResNet1d', 'xresnet1d18', 'xresnet1d34', 'xresnet1d5... | 9,797 | 46.563107 | 186 | py |
ssm_ecg | ssm_ecg-main/code/dl_models/modified_s4_model.py | #adapted from https://github.com/HazyResearch/state-spaces/blob/main/example.py
import torch
import torch.nn as nn
import os
import sys
# egg_path = "/home/mehari/anaconda3/envs/stsp/lib/python3.9/cauchy_mult-0.0.0-py3.9-linux-x86_64.egg"
# egg_path = "/home/mehari/clones/stsp/code/extensions/cauchy/cauchy_mult-0.0.... | 5,366 | 34.309211 | 125 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.