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 |
|---|---|---|---|---|---|---|
FACIL | FACIL-master/src/datasets/exemplars_selection.py | import random
import time
from contextlib import contextmanager
from typing import Iterable
import numpy as np
import torch
from torch.utils.data import DataLoader, ConcatDataset
from torchvision.transforms import Lambda
from datasets.exemplars_dataset import ExemplarsDataset
from networks.network import LLL_Net
cl... | 11,550 | 47.129167 | 119 | py |
FACIL | FACIL-master/src/datasets/memory_dataset.py | import random
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
class MemoryDataset(Dataset):
"""Characterizes a dataset for PyTorch -- this dataset pre-loads all images in memory"""
def __init__(self, data, transform, class_indices=None):
"""Initialization"""
self... | 4,930 | 38.448 | 112 | py |
FACIL | FACIL-master/src/tests/test_datasets_transforms.py | import numpy as np
from torchvision.transforms import Lambda
from torch.utils.data.dataset import ConcatDataset
from datasets.memory_dataset import MemoryDataset
from datasets.exemplars_selection import override_dataset_transform
def pic(i):
return np.array([[i]], dtype=np.int8)
def test_dataset_transform_over... | 1,333 | 36.055556 | 93 | py |
FACIL | FACIL-master/src/tests/__init__.py | import os
import torch
import shutil
from main_incremental import main
import datasets.dataset_config as c
def run_main(args_line, result_dir='results_test', clean_run=False):
assert "--results-path" not in args_line
print('Staring dir:', os.getcwd())
if os.getcwd().endswith('tests'):
os.chdir('... | 1,791 | 32.811321 | 83 | py |
FACIL | FACIL-master/src/tests/test_finetuning.py | import torch
import pytest
from tests import run_main_and_assert
FAST_LOCAL_TEST_ARGS = "--exp-name local_test --datasets mnist" \
" --network LeNet --num-tasks 3 --seed 1 --batch-size 32" \
" --nepochs 2 --lr-factor 10 --momentum 0.9 --lr-min 1e-7" \
... | 2,601 | 31.936709 | 83 | py |
FACIL | FACIL-master/src/tests/test_dataloader.py | import torch
from torch.utils.data import DataLoader
from torch.utils.data.dataset import TensorDataset
from main_incremental import main
def test_dataloader_dataset_swap():
# given
data1 = TensorDataset(torch.arange(10))
data2 = TensorDataset(torch.arange(10, 20))
dl = DataLoader(data1, batch_size=2... | 1,255 | 28.209302 | 92 | py |
FACIL | FACIL-master/src/approach/eeil.py | import torch
import warnings
from copy import deepcopy
from argparse import ArgumentParser
from torch.nn import functional as F
from torch.utils.data import DataLoader
from .incremental_learning import Inc_Learning_Appr
from datasets.exemplars_dataset import ExemplarsDataset
class Appr(Inc_Learning_Appr):
"""Cla... | 8,431 | 48.023256 | 129 | py |
FACIL | FACIL-master/src/approach/dmc.py | import torch
from torch import nn
from copy import deepcopy
from argparse import ArgumentParser
from datasets.data_loader import get_loaders
from .incremental_learning import Inc_Learning_Appr
from datasets.exemplars_dataset import ExemplarsDataset
class Appr(Inc_Learning_Appr):
""" Class implementing the Deep M... | 9,070 | 50.248588 | 120 | py |
FACIL | FACIL-master/src/approach/lwm.py | import os
import torch
from copy import deepcopy
import torch.nn.functional as F
from argparse import ArgumentParser
from torchvision.utils import save_image
from networks.network import LLL_Net
from .incremental_learning import Inc_Learning_Appr
from datasets.exemplars_dataset import ExemplarsDataset
class Appr(Inc... | 13,847 | 47.083333 | 122 | py |
FACIL | FACIL-master/src/approach/ewc.py | import torch
import itertools
from argparse import ArgumentParser
from datasets.exemplars_dataset import ExemplarsDataset
from .incremental_learning import Inc_Learning_Appr
class Appr(Inc_Learning_Appr):
"""Class implementing the Elastic Weight Consolidation (EWC) approach
described in http://arxiv.org/abs/... | 8,048 | 53.385135 | 120 | py |
FACIL | FACIL-master/src/approach/lwf.py | import torch
from copy import deepcopy
from argparse import ArgumentParser
from .incremental_learning import Inc_Learning_Appr
from datasets.exemplars_dataset import ExemplarsDataset
class Appr(Inc_Learning_Appr):
"""Class implementing the Learning Without Forgetting (LwF) approach
described in https://arxiv... | 7,243 | 48.278912 | 120 | py |
FACIL | FACIL-master/src/approach/lucir.py | import copy
import math
import torch
import warnings
from torch import nn
import torch.nn.functional as F
from argparse import ArgumentParser
from torch.nn import Module, Parameter
from torch.utils.data import DataLoader
from .incremental_learning import Inc_Learning_Appr
from datasets.exemplars_dataset import Exempla... | 14,001 | 48.302817 | 120 | py |
FACIL | FACIL-master/src/approach/mas.py | import torch
import itertools
from argparse import ArgumentParser
from .incremental_learning import Inc_Learning_Appr
from datasets.exemplars_dataset import ExemplarsDataset
class Appr(Inc_Learning_Appr):
"""Class implementing the Memory Aware Synapses (MAS) approach (global version)
described in https://arx... | 7,724 | 55.801471 | 120 | py |
FACIL | FACIL-master/src/approach/joint.py | import torch
from argparse import ArgumentParser
from torch.utils.data import DataLoader, Dataset
from .incremental_learning import Inc_Learning_Appr
from datasets.exemplars_dataset import ExemplarsDataset
class Appr(Inc_Learning_Appr):
"""Class implementing the joint baseline"""
def __init__(self, model, d... | 4,692 | 41.663636 | 120 | py |
FACIL | FACIL-master/src/approach/il2m.py | import torch
import numpy as np
from .incremental_learning import Inc_Learning_Appr
from datasets.exemplars_dataset import ExemplarsDataset
class Appr(Inc_Learning_Appr):
"""Class implementing the Class Incremental Learning With Dual Memory (IL2M) approach described in
https://openaccess.thecvf.com/content_I... | 7,115 | 53.738462 | 137 | py |
FACIL | FACIL-master/src/approach/path_integral.py | import torch
from argparse import ArgumentParser
from .incremental_learning import Inc_Learning_Appr
from datasets.exemplars_dataset import ExemplarsDataset
class Appr(Inc_Learning_Appr):
"""Class implementing the Path Integral (aka Synaptic Intelligence) approach
described in http://proceedings.mlr.press/v7... | 7,704 | 52.506944 | 121 | py |
FACIL | FACIL-master/src/approach/r_walk.py | import torch
import itertools
from argparse import ArgumentParser
from torch.utils.data import DataLoader
from .incremental_learning import Inc_Learning_Appr
from datasets.exemplars_dataset import ExemplarsDataset
class Appr(Inc_Learning_Appr):
"""Class implementing the Riemannian Walk (RWalk) approach described... | 11,727 | 55.384615 | 120 | py |
FACIL | FACIL-master/src/approach/finetuning.py | import torch
from argparse import ArgumentParser
from .incremental_learning import Inc_Learning_Appr
from datasets.exemplars_dataset import ExemplarsDataset
class Appr(Inc_Learning_Appr):
"""Class implementing the finetuning baseline"""
def __init__(self, model, device, nepochs=100, lr=0.05, lr_min=1e-4, lr... | 3,066 | 48.467742 | 120 | py |
FACIL | FACIL-master/src/approach/freezing.py | import torch
from argparse import ArgumentParser
from .incremental_learning import Inc_Learning_Appr
from datasets.exemplars_dataset import ExemplarsDataset
class Appr(Inc_Learning_Appr):
"""Class implementing the freezing baseline"""
def __init__(self, model, device, nepochs=100, lr=0.05, lr_min=1e-4, lr_f... | 4,921 | 44.574074 | 120 | py |
FACIL | FACIL-master/src/approach/bic.py | import time
import torch
import numpy as np
from copy import deepcopy
from argparse import ArgumentParser
from torch.utils.data import DataLoader
from .incremental_learning import Inc_Learning_Appr
from datasets.exemplars_dataset import ExemplarsDataset
class Appr(Inc_Learning_Appr):
"""Class implementing the Bi... | 16,339 | 53.648829 | 119 | py |
FACIL | FACIL-master/src/approach/incremental_learning.py | import time
import torch
import numpy as np
from argparse import ArgumentParser
from loggers.exp_logger import ExperimentLogger
from datasets.exemplars_dataset import ExemplarsDataset
class Inc_Learning_Appr:
"""Basic class for implementing incremental learning approaches"""
def __init__(self, model, device... | 10,304 | 46.930233 | 118 | py |
FACIL | FACIL-master/src/approach/icarl.py | import torch
import warnings
import numpy as np
from copy import deepcopy
from argparse import ArgumentParser
from torch.utils.data import DataLoader
from .incremental_learning import Inc_Learning_Appr
from datasets.exemplars_dataset import ExemplarsDataset
from datasets.exemplars_selection import override_dataset_tra... | 9,888 | 50.505208 | 119 | py |
fedlearner | fedlearner-master/test/trainer/test_step_trainer.py |
# Copyright 2020 The FedLearner 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 applic... | 13,110 | 36.893064 | 82 | py |
fedlearner | fedlearner-master/test/trainer/test_horizontal_nn_trainer.py | # Copyright 2020 The FedLearner 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 applica... | 18,484 | 37.510417 | 100 | py |
fedlearner | fedlearner-master/test/trainer/test_nn_trainer.py | # Copyright 2020 The FedLearner 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 applica... | 20,074 | 37.384321 | 109 | py |
fedlearner | fedlearner-master/test/fedavg/test_fedavg.py | import threading
import unittest
import tensorflow as tf
import numpy as np
import fedlearner.common.fl_logging as logging
from fedlearner.fedavg import train_from_keras_model
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train.reshape(x_train.shape[0], -1).astype(np.float32) /... | 3,130 | 33.406593 | 75 | py |
fedlearner | fedlearner-master/example/privacy/DPAUC/label_on_device_auc_computation_util.py | from itertools import chain
import random
# import datetime
from functools import reduce
# from visualization_util import visualize_roc_auc
# import multiprocessing as mp
from multiprocessing.pool import ThreadPool as Pool
import tensorflow as tf
from sklearn import metrics
import numpy as np
run_parallel = False
npro... | 16,906 | 38.875 | 80 | py |
fedlearner | fedlearner-master/example/privacy/embedding_protection/FMNIST_Embedding_Protection_Framework_Demo.py | import argparse
import datetime
import time
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras.datasets import fashion_mnist
parser = argparse.ArgumentParser()
parser.add_argument("--batch_size", type=int, default=200)
parser.add_argument('--gpu_option', action='store_true')
parser.add_a... | 31,162 | 42.342142 | 80 | py |
fedlearner | fedlearner-master/example/privacy/label_protection/FL_Label_Protection_FMNIST_Demo.py | #!/usr/bin/env python
# coding: utf-8
import sys
import os
import argparse
import datetime
import time
import random
# import logging
import numpy as np
import tensorflow as tf
from tensorflow.keras.datasets import fashion_mnist
from solver import solve_isotropic_covariance, symKL_objective
import shared_var
parser = a... | 35,016 | 36.815335 | 80 | py |
fedlearner | fedlearner-master/example/fedavg/mnist/leader.py | import os
from fedlearner.fedavg import train_from_keras_model
from .model import create_model, x_train, y_train, x_test, y_test
fed_leader_address = os.getenv("FL_LEADER_ADDRESS", "0.0.0.0:6870")
fl_name = "leader"
fl_cluster = {
"leader": {
"name": "leader",
"address": fed_leader_address
},
... | 776 | 24.9 | 67 | py |
fedlearner | fedlearner-master/example/fedavg/mnist/follower.py | import os
from fedlearner.fedavg import train_from_keras_model
from .model import create_model, x_train, y_train, x_test, y_test
fed_leader_address = os.getenv("FL_LEADER_ADDRESS", "0.0.0.0:6870")
fl_name = "follower"
fl_cluster = {
"leader": {
"name": "leader",
"address": fed_leader_address
},... | 778 | 24.966667 | 67 | py |
fedlearner | fedlearner-master/example/fedavg/mnist/model.py | import tensorflow as tf
import numpy as np
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train = x_train.reshape(x_train.shape[0], -1).astype(np.float32) / 255.0
y_train = y_train.astype(np.int32)
x_test = x_test.reshape(x_test.shape[0], -1).astype(np.float32) / 255.0
y_test = y_test.as... | 769 | 34 | 75 | py |
fedlearner | fedlearner-master/example/tree_model/make_data.py | # pylint: disable=unsubscriptable-object
import os
import argparse
import numpy as np
import tensorflow as tf
from sklearn.datasets import load_iris
def quantize_data(header, dtypes, X):
for i, (h, dtype) in enumerate(zip(header, dtypes)):
if h[0] != 'f' or dtype != np.int32:
continue
... | 5,382 | 35.371622 | 77 | py |
fedlearner | fedlearner-master/example/mnist/make_data.py | # Copyright 2020 The FedLearner 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 applica... | 2,381 | 34.552239 | 79 | py |
fedlearner | fedlearner-master/fedlearner/fedavg/__init__.py |
from .fedavg import train_from_keras_model
| 44 | 14 | 42 | py |
fedlearner | fedlearner-master/fedlearner/fedavg/fedavg.py | import os
import tensorflow as tf
from fedlearner.common import metrics
from fedlearner.common.metric_collector import metric_collector
from fedlearner.fedavg.master import LeaderMaster, FollowerMaster
from fedlearner.fedavg.cluster.cluster_spec import FLClusterSpec
from fedlearner.fedavg._global_context import global_... | 4,118 | 31.952 | 74 | py |
houdini | houdini-master/Data/DataProvider.py | import numpy as np
from random import randint
import random
import matplotlib.pyplot as plt
import torchvision
from Data.MazeGenerator import MazeGenerator
from Data.DataGenerator import NumpyDataSetIterator, ImageGraphDataGenerator
import re
from PIL import Image
import glob
import pickle
import abc
import urllib.req... | 34,683 | 42.300874 | 150 | py |
houdini | houdini-master/Baselines/CountingSeqLongSeq.py | import os
import numpy as np
import torch
import torch.nn.functional as F
from HOUDINI.Eval.CS_LS import TaskType, Dataset, get_task_name, \
get_sequence_from_string, \
mk_default_lib, get_task_settings, get_sequence_info, print_sequence
from HOUDINI.Eval.EvaluatorHelperFunctions import get_graph_a
from HOUDI... | 11,585 | 48.512821 | 167 | py |
houdini | houdini-master/Baselines/SummingSequence.py | import os
import torch
import torch.nn.functional as F
from Baselines.PNN import NetPNN, NetPNN_RNN
from HOUDINI.Eval.EvaluatorHelperFunctions import get_graph_a
from HOUDINI.Eval.EvaluatorUtils import get_io_examples_classify_digits, get_io_examples_sum_digits
# from HOUDINI.Eval.EvaluatorBaselinePNN_original_size i... | 9,478 | 43.712264 | 140 | py |
houdini | houdini-master/Baselines/PNN/EvaluatorBaselinePNN.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
from abc import abstractmethod
import json
from HOUDINI.Interpreter.NeuralModules import SaveableNNModule
class NetPNN(SaveableNNModule):
def __init__(self, name, input_dim, input... | 11,870 | 43.460674 | 120 | py |
houdini | houdini-master/Baselines/PNN/EvaluatorBaselinePNN_original_size.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
from abc import abstractmethod
import json
from HOUDINI.Interpreter.NeuralModules import SaveableNNModule
class NetPNN(SaveableNNModule):
def __init__(self, name, input_dim, input... | 12,829 | 44.017544 | 120 | py |
houdini | houdini-master/Baselines/PNN/EvaluatorBaselinePNN_Main.py | #from NeuralProgramming.Data.DataProvider import split_into_train_and_validation, get_batch_count_iseven, \
# get_batch_count_var_len
from Data import *
from HOUDINI.Interpreter.Interpreter import Interpreter, ProgramOutputType
from HOUDINI.FnLibrary import FnLibrary
from HOUDINI.Interpreter.LibraryTensorFunctions i... | 18,066 | 49.75 | 133 | py |
houdini | houdini-master/HOUDINI/FnLibrary.py | from typing import Dict, Optional
import torch.nn as nn
import pickle
import os.path
from HOUDINI.Synthesizer.AST import *
from HOUDINI.Synthesizer.AST import PPSort
from HOUDINI.Synthesizer.GenUtils import createDir
"""
t = PPSortVar('T')
t1 = PPSortVar('T1')
t2 = PPSortVar('T2')
"""
class PPLibItem(NamedTuple('PP... | 3,197 | 27.810811 | 93 | py |
houdini | houdini-master/HOUDINI/FnLibraryFunctions.py | import torch
import torch.nn.functional as F
from functools import reduce
from HOUDINI.FnLibrary import FnLibrary, PPLibItem
from HOUDINI.Interpreter.NeuralModules import NetCNN, SaveableNNModule
from HOUDINI.Synthesizer.AST import PPImageSort, PPInt
from HOUDINI.Synthesizer.ASTDSL import mkTensorSort, mkFuncSort, mkL... | 12,119 | 31.934783 | 136 | py |
houdini | houdini-master/HOUDINI/Tests/Scribble.py | # How to derive from a named tuple
import numpy as np
import torch
from HOUDINI.NeuralSynthesizer import NeuralSynthesizer
from matplotlib import pyplot as plt
from torch.autograd import Variable
from HOUDINI.Eval.EvaluatorUtils import get_io_examples_classify_digits
from HOUDINI.Interpreter.Interpreter import Interp... | 15,935 | 36.320843 | 132 | py |
houdini | houdini-master/HOUDINI/Tests/TestSynthesizer.py | import torch.nn.functional as F
from HOUDINI.Interpreter.NeuralModules import NetCNN
from HOUDINI.NeuralSynthesizer import NeuralSynthesizer
from Data import split_into_train_and_validation, get_batch_count_iseven
from HOUDINI.Interpreter.Interpreter import Interpreter
from HOUDINI.FnLibraryFunctions import pp_map, pp... | 17,560 | 29.225473 | 118 | py |
houdini | houdini-master/HOUDINI/Eval/LongerSeqPlotting2.py | from Data import *
from HOUDINI.Interpreter.Interpreter import Interpreter, ProgramOutputType
from HOUDINI.FnLibrary import FnLibrary
from HOUDINI.Interpreter.LibraryTensorFunctions import addImageFunctionsToLibrary
# from HOUDINI.Interpreter.NeuralModules import *
# from HOUDINI.NewLibrary import PPLibItem
import torc... | 8,153 | 32.281633 | 113 | py |
houdini | houdini-master/HOUDINI/Eval/EvaluatorHelperFunctions.py | import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from HOUDINI.Interpreter.Interpreter import Interpreter, ProgramOutputType
from HOUDINI.FnLibrary import PPLibItem
from Data import DataProvider
import os
def display_graph_a(label_to_tuple_of_numpy_... | 6,022 | 40.826389 | 129 | py |
houdini | houdini-master/HOUDINI/Synthesizer/SymbolicSynthesizer.py | from typing import Iterable, Tuple, Dict
import torch.nn.functional as F
from HOUDINI.Synthesizer.ASTDSL import mkRealTensorSort, mkBoolTensorSort
from HOUDINI.Synthesizer.IntermediateTypeHandler import instantiateSortVar
from HOUDINI.FnLibrary import FnLibrary
from HOUDINI.Synthesizer import ASTUtils, Rules, MiscUti... | 3,617 | 31.017699 | 104 | py |
houdini | houdini-master/HOUDINI/Interpreter/Interpreter.py | import random
import sys
from collections import OrderedDict
from enum import Enum
from functools import reduce
# from torch.utils.data import DataLoader, TensorDataset
from typing import Dict
import numpy as np
from Data.DataProvider import NumpyDataSetIterator
from HOUDINI.Interpreter.NeuralModules import *
from HO... | 22,979 | 47.58351 | 135 | py |
houdini | houdini-master/HOUDINI/Interpreter/NeuralModules.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
from abc import abstractmethod
import json
import os
class SaveableNNModule(nn.Module):
def __init__(self, params_dict: dict = None):
self.params_dict = params_dict
super(SaveableNNMo... | 13,623 | 36.949861 | 121 | py |
FlexGen | FlexGen-main/flexgen/profile_matmul.py | """
Usage:
python3 profile_matmul.py
"""
import numpy as np
import torch
from flexgen.profile_bandwidth import benchmark_func
def bench_matmul():
for device in ["cuda", "cpu"]:
for n in [1024, 2048]:
if device == "cuda":
dtype = torch.float16
else:
... | 800 | 21.885714 | 96 | py |
FlexGen | FlexGen-main/flexgen/profile_bandwidth.py | """
Usage:
bash /usr/local/bin/pagecache-management.sh python3 profile_bandwidth.py
"""
import argparse
import numpy as np
import os
import time
import torch
from flexgen.utils import GB, MB, KB
def benchmark_func(func, number, repeat, warmup=3):
for i in range(warmup):
func()
costs = [0]
for ... | 2,852 | 32.174419 | 95 | py |
FlexGen | FlexGen-main/flexgen/compression.py | import dataclasses
import torch
import numpy as np
from flexgen.pytorch_backend import (TorchTensor, TorchDevice,
DeviceType, general_copy, fix_recursive_import)
from flexgen.utils import np_dtype_to_torch_dtype
@dataclasses.dataclass
class CompressionConfig:
"""Group-wise quantization."""
num_bits: int... | 13,405 | 35.728767 | 94 | py |
FlexGen | FlexGen-main/flexgen/dist_utils.py | import torch
import torch.distributed as dist
_COMM_DEVICE = None
_PIPELINE_PARALLEL_PRED_GROUP = None
_PIPELINE_PARALLEL_SUCC_GROUP = None
def initialize_distributed(head_ip, port, world_size, rank, local_rank,
comm_device):
print(f'Initializing distributed environment at {head_ip}:{po... | 2,167 | 32.353846 | 84 | py |
FlexGen | FlexGen-main/flexgen/utils.py | import argparse
import dataclasses
from attr import define, field
from attr.setters import frozen
import functools
import gc
import math
import os
from typing import Tuple, Union, Optional, Any, Sequence, List
import numpy as np
import torch
KB = 1 << 10
MB = 1 << 20
GB = 1 << 30
T = 1e12
@dataclasses.dataclass(fr... | 8,174 | 25.980198 | 96 | py |
FlexGen | FlexGen-main/flexgen/pytorch_backend.py | """Implement tensor computations with pytorch."""
from enum import Enum, auto
from functools import partial
from itertools import count
import os
import queue
import shutil
import time
import threading
from typing import Optional, Union, Tuple
import torch
import torch.nn.functional as F
import numpy as np
from flexg... | 35,101 | 37.701213 | 97 | py |
FlexGen | FlexGen-main/flexgen/opt_config.py | """
The OPT model configurations and weight downloading utilities.
Some functions are adopted from https://github.com/alpa-projects/alpa/tree/main/examples/llm_serving/model.
"""
import argparse
import dataclasses
import glob
import os
import shutil
import numpy as np
from tqdm import tqdm
@dataclasses.dataclass(f... | 9,540 | 35.140152 | 107 | py |
FlexGen | FlexGen-main/flexgen/flex_opt.py | """
Usage:
python3 -m flexgen.flex_opt --model facebook/opt-1.3b --gpu-batch-size 32 --percent 100 0 100 0 100 0
"""
import argparse
import dataclasses
import os
import pickle
import time
from typing import Union, List, Optional
import numpy as np
from tqdm import tqdm
import torch
from transformers import AutoTokeni... | 50,747 | 37.213855 | 101 | py |
FlexGen | FlexGen-main/flexgen/dist_flex_opt.py | import argparse
from itertools import count
import os
import pickle
import traceback
from typing import Union, List, Optional
import numpy as np
import torch
import torch.distributed as dist
from transformers import AutoTokenizer
from flexgen.compression import CompressionConfig
from flexgen.dist_utils import initial... | 28,665 | 40.424855 | 137 | py |
FlexGen | FlexGen-main/scripts/step_2_consolidate_992_shards_to_singleton.py | # Copied from
# https://github.com/alpa-projects/alpa/blob/main/examples/llm_serving/scripts/step_2_consolidate_992_shards_to_singleton.py
"""Convert the 992 shards into 1 singleton (code adapted from Metaseq and fairscale)."""
from typing import List, Dict, Any
import argparse
import gc
import logging
import os
impor... | 18,985 | 37.668024 | 124 | py |
FlexGen | FlexGen-main/scripts/step_3_convert_to_numpy_weights.py | # Copied from
# https://github.com/alpa-projects/alpa/blob/main/examples/llm_serving/scripts/step_3_convert_to_numpy_weights.py
"""Convert Metaseq's OPT model weights into Alpa numpy weights."""
import time
import argparse
import os
import numpy as np
from scripts.utils import torch_load_cpu
def save_numpy(weight_... | 1,147 | 33.787879 | 113 | py |
FlexGen | FlexGen-main/scripts/utils.py | import torch
from omegaconf.dictconfig import DictConfig
def recursively_cast_dictconfigs(cfg):
if isinstance(cfg, DictConfig):
return {k2: recursively_cast_dictconfigs(v2) for k2, v2 in cfg.items()}
else:
return cfg
def torch_load_cpu(path):
state = torch.load(path, map_location=torch.d... | 924 | 27.90625 | 87 | py |
FlexGen | FlexGen-main/benchmark/petals/run_opt_requests.py | import time
from argparse import ArgumentParser
from statistics import mean
import torch
from petals import DistributedBloomConfig, DistributedBloomForCausalLM
from torch.multiprocessing import Process, Event, Queue
from transformers import AutoTokenizer, BloomConfig, OPTConfig
def _patch_bloom_config(bloom_config: ... | 4,583 | 33.208955 | 108 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/setup.py | """
Copyright 2020 The Microsoft DeepSpeed Team
DeepSpeed library
To build wheel on Windows:
1. Install pytorch, such as pytorch 1.12 + cuda 11.6
2. Install visual cpp build tool
3. Include cuda toolkit
4. Launch cmd console with Administrator privilege for creating required symlink folders
Create a ... | 11,210 | 34.365931 | 139 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/env_report.py | import torch
import deepspeed
import subprocess
import argparse
from .ops.op_builder import ALL_OPS
from .git_version_info import installed_ops, torch_info
GREEN = '\033[92m'
RED = '\033[91m'
YELLOW = '\033[93m'
END = '\033[0m'
SUCCESS = f"{GREEN} [SUCCESS] {END}"
OKAY = f"{GREEN}[OKAY]{END}"
WARNING = f"{YELLOW}[WARN... | 4,710 | 32.411348 | 136 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/git_version_info.py | try:
# This is populated by setup.py
from .git_version_info_installed import * # noqa: F401
except ModuleNotFoundError:
import os
if os.path.isfile('version.txt'):
# Will be missing from checkouts that haven't been installed (e.g., readthedocs)
version = open('version.txt', 'r').read()... | 652 | 35.277778 | 88 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/__init__.py | '''
Copyright 2020 The Microsoft DeepSpeed Team
'''
import sys
import types
import json
from typing import Optional, Union
import torch
from torch.optim import Optimizer
from torch.optim.lr_scheduler import _LRScheduler
from packaging import version as pkg_version
from . import ops
from . import module_inject
from .... | 11,822 | 36.652866 | 132 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/checkpoint/zero_checkpoint.py | import torch
from .constants import (BASE_OPTIMIZER_STATE,
GROUP_PADDINGS,
OPTIMIZER_STATE_DICT,
PARTITION_COUNT)
from .reshape_utils import (basic_folder_validation, get_zero_files, merge_state)
from .reshape_3d_utils import (model_3d_desc, get... | 5,661 | 37.517007 | 110 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/checkpoint/reshape_utils.py | import os
import torch
from collections import OrderedDict
from .constants import (ZERO_FILE_PREFIX, FP16_ZERO_FILE_PREFIX, BF16_ZERO_FILE_PREFIX)
def basic_folder_validation(dir):
assert os.path.exists(dir), f'{dir} path does not exist'
assert os.path.isdir(dir), f'{dir} is not a folder'
def get_files_with... | 2,951 | 28.818182 | 91 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/checkpoint/universal_checkpoint.py | """
Copyright 2022 The Microsoft DeepSpeed Team
"""
import os
import torch
import types
from .constants import (FP32_WEIGHT_KEY,
PARAM,
VOCAB_DIVISIBILITY_PADDING_TENSOR,
CAT_DIM)
def load_hp_checkpoint_state(self, folder, tp_rank, tp_world_size)... | 5,439 | 48.908257 | 141 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/checkpoint/deepspeed_checkpoint.py | import os
from typing import Dict
import torch
from .reshape_3d_utils import model_3d_desc
from .reshape_utils import (basic_folder_validation,
merge_state,
partition_data,
get_files,
get_files_with_prefix)
... | 12,504 | 38.572785 | 134 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/accelerator/cuda_accelerator.py | from deepspeed.accelerator.abstract_accelerator import DeepSpeedAccelerator
import torch.cuda
class CUDA_Accelerator(DeepSpeedAccelerator):
def __init__(self):
self._name = 'cuda'
self._communication_backend_name = 'nccl'
# Device APIs
def device_name(self, device_index=None):
if ... | 8,258 | 33.26971 | 249 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/profiling/flops_profiler/profiler.py | import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from functools import partial
from typing import List, Optional
from collections import OrderedDict
import numpy as np
Tensor = torch.Tensor
module_flop_count = []
module_mac_count = []
old_functions = {}
class FlopsProfiler(object):
... | 46,989 | 37.296659 | 650 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/compression/basic_layer.py | import torch
import math
from torch import nn
from torch.nn import init
import deepspeed.comm as dist
from .utils import TopKBinarizer, SymQuantizer, AsymQuantizer, TernaryQuantizer, BinaryQuantizer
from deepspeed.utils import logger
g_mpu = None
class QuantAct(nn.Module):
"""
Class to quantize given activat... | 39,202 | 41.427489 | 169 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/compression/compress.py | import re
from .helper import compression_preparation, fix_compression, recursive_getattr, is_module_compressible
from .config import get_compression_config
from ..runtime.config_utils import dict_raise_error_on_duplicate_keys
from .constants import *
import os
import json
def check_deepspeed_config(config):
if i... | 10,572 | 44.573276 | 167 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/compression/utils.py | import torch
from torch import autograd
import math
class TopKBinarizer(autograd.Function):
"""
Top-k Binarizer.
Computes a binary mask M from a real value matrix S such that `M_{i,j} = 1` if and only if `S_{i,j}`
is among the k% highest values of S.
Implementation is inspired from:
https:... | 7,778 | 34.847926 | 105 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/compression/helper.py | import torch
from .basic_layer import Embedding_Compress, LinearLayer_Compress, Conv2dLayer_Compress, BNLayer_Compress, ColumnParallelLinear_Compress, RowParallelLinear_Compress
from .constants import *
def recursive_getattr(model, module_name):
"""
Recursively get the attribute of a module.
Args:
... | 12,800 | 44.393617 | 165 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/lr_schedules.py | """
Copyright 2019 The Microsoft DeepSpeed Team
Implementation of learning rate schedules.
Taken and modified from PyTorch v1.0.1 source
https://github.com/pytorch/pytorch/blob/v1.1.0/torch/optim/lr_scheduler.py
"""
import argparse
from torch.optim import Optimizer
import math
from deepspeed.utils import logger
LR... | 35,464 | 40.479532 | 164 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/bf16_optimizer.py | """
Copyright 2022 The Microsoft DeepSpeed Team
"""
from collections import OrderedDict
import torch
import sys
import os
from deepspeed import comm as dist
from deepspeed.runtime.constants import PIPE_REPLICATED
from deepspeed.ops.op_builder import UtilsBuilder
from deepspeed.runtime import ZeROOptimizer
from packagi... | 18,989 | 40.372549 | 130 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/engine.py | """
Copyright 2019 The Microsoft DeepSpeed Team
"""
import os
import re
import stat
import torch
import hashlib
from collections import defaultdict, OrderedDict
from shutil import copyfile
from torch.nn.modules import Module
from torch.nn.parameter import Parameter
from torch.optim import Optimizer
from torch.optim.l... | 146,904 | 42.514514 | 227 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/weight_quantizer.py | import torch
from ..module_inject.replace_policy import HFBertLayerPolicy, replace_policies
class WeightQuantization(object):
def __init__(self, mlp_extra_grouping=True, mp_size=1):
self.dense_scales = []
self.qkv_scales = []
self.mlp4hh_scales = []
self.mlph4h_scales = []
... | 7,414 | 44.213415 | 105 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/dataloader.py | '''
Copyright 2019 The Microsoft DeepSpeed Team
'''
import torch
from torch.utils.data import DataLoader, RandomSampler
from torch.utils.data.distributed import DistributedSampler
class RepeatingLoader:
def __init__(self, loader):
"""Wraps an iterator to allow for infinite iteration. This is especially u... | 3,972 | 33.850877 | 90 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/eigenvalue.py | import torch
from deepspeed.utils import log_dist
import numpy as np
import logging
class Eigenvalue(object):
def __init__(self,
verbose=False,
max_iter=100,
tol=1e-2,
stability=0,
gas_boundary_resolution=1,
laye... | 5,760 | 36.653595 | 211 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/utils.py | '''
Copyright 2019 The Microsoft DeepSpeed Team
Copyright NVIDIA/Megatron
Helper functions and classes from multiple sources.
'''
from collections.abc import Iterable
from deepspeed.moe.utils import is_moe_param
import os
import psutil
import gc
from math import sqrt
from math import floor
from bisect import bisect_... | 36,550 | 34.86948 | 103 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/state_dict_factory.py | '''
Copyright 2020 The Microsoft DeepSpeed Team
'''
import torch
import os
import copy
import collections
import json
from abc import ABC, abstractmethod
from deepspeed.utils import logger
from deepspeed.runtime.checkpoint_engine.torch_checkpoint_engine import TorchCheckpointEngine
from .weight_quantizer import Weig... | 19,721 | 40.52 | 164 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/config.py | """
Copyright (c) Microsoft Corporation
Licensed under the MIT license.
"""
import os
from typing import Union
import torch
import json
import copy
import base64
from .constants import *
from .fp16.loss_scaler import (
INITIAL_LOSS_SCALE,
SCALE_WINDOW,
DELAYED_SHIFT,
MIN_LOSS_SCALE,
)
from .config_uti... | 40,662 | 36.931903 | 174 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/sparse_tensor.py | """
Copyright 2020 The Microsoft DeepSpeed Team
Implementation of a compressed sparse tensor. Similar in
functionality to TensorFlow's IndexedSlices implementation.
"""
import torch
class SparseTensor(object):
""" Compressed Sparse Tensor """
def __init__(self, dense_tensor=None):
self.orig_dense_te... | 2,480 | 33.943662 | 80 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/quantize.py | import torch
import math
from deepspeed.utils import logger
from deepspeed.ops.quantizer import ds_quantizer
TWO_D_PARAMS = 6
class Quantizer(object):
def __init__(self,
q_groups=1,
q_mixed_fp16=False,
q_change_ratio=0.01,
q_type=0,
... | 7,641 | 39.86631 | 171 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/activation_checkpointing/checkpointing.py | '''
Copyright (c) Microsoft Corporation
Licensed under the MIT license.
Use to partition the activations stored for backward propagation
Therefore reduces the memory consumption
Also implements CPU checkpointing and contiguous memory checkpointing
Reduces memory consumption and memory fragmentation
Code for rng check... | 33,522 | 35.280303 | 168 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/fp16/fused_optimizer.py | '''
Copyright 2019 The Microsoft DeepSpeed Team
Copyright NVIDIA/apex
This file is adapted from FP16_Optimizer in NVIDIA/apex
'''
import torch
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from deepspeed.runtime import DeepSpeedOptimizer
from deepspeed.runtime.utils import get_global_norm... | 20,841 | 39.866667 | 126 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/fp16/loss_scaler.py | # Copyright 2019 The Microsoft DeepSpeed Team
# Copyright (c) 2019, 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 copy of the License at
#
# http://www.apache.org/lic... | 9,375 | 40.486726 | 325 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/fp16/unfused_optimizer.py | '''
Copyright 2019 The Microsoft DeepSpeed Team
Copyright NVIDIA/apex
This file is adapted from FP16_Optimizer in NVIDIA/apex
'''
from deepspeed.moe.utils import split_params_grads_into_shared_and_expert_params
import torch
from torch._utils import _flatten_dense_tensors
from deepspeed.runtime import DeepSpeedOptimi... | 18,751 | 40.486726 | 126 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/fp16/onebit/adam.py | '''
Copyright 2020 The Microsoft DeepSpeed Team
'''
import types
import torch
import numpy as np
from deepspeed import comm as dist
class OnebitAdam(torch.optim.Optimizer):
"""Implements the 1-bit Adam algorithm. Currently GPU-only.
For usage example please see https://www.deepspeed.ai/tutorials/onebit-adam/
... | 15,456 | 47.914557 | 239 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/fp16/onebit/zoadam.py | '''
Copyright 2020 The Microsoft DeepSpeed Team
'''
import types
import torch
import numpy as np
from deepspeed import comm as dist
class ZeroOneAdam(torch.optim.Optimizer):
"""Implements the 0/1 Adam algorithm. Currently GPU-only.
For usage example please see https://www.deepspeed.ai/tutorials/zero-one-adam/... | 19,562 | 50.891247 | 237 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/fp16/onebit/lamb.py | '''
Copyright 2021 The Microsoft DeepSpeed Team
'''
import types
import torch
import numpy as np
from deepspeed import comm as dist
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
class OnebitLamb(torch.optim.Optimizer):
"""Implements the 1-bit Lamb algorithm. Currently GPU-only.
For... | 23,821 | 49.685106 | 239 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/swap_tensor/optimizer_utils.py | """
Copyright 2020 The Microsoft DeepSpeed Team.
Licensed under the MIT license.
Functionality of swapping tensors to/from (NVMe) storage devices.
"""
import os
import torch
from deepspeed import comm as dist
from deepspeed.utils.logging import logger
from deepspeed.runtime.swap_tensor.constants import *
from deepsp... | 19,951 | 36.931559 | 206 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/swap_tensor/utils.py | """
Copyright 2020 The Microsoft DeepSpeed Team
Licensed under the MIT license.
Functionality of swapping tensors to/from (NVMe) storage devices.
"""
import torch
from deepspeed.utils.logging import logger
from deepspeed import comm as dist
MIN_AIO_BYTES = 1024**2
AIO_ALIGNED_BYTES = 1024
def swap_in_tensors(swap... | 7,838 | 31.6625 | 117 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/swap_tensor/async_swapper.py | """
Copyright 2020 The Microsoft DeepSpeed Team.
Licensed under the MIT license.
Functionality of swapping tensors to/from (NVMe) storage devices.
"""
import torch
from deepspeed import comm as dist
from deepspeed.utils.logging import logger
from deepspeed.runtime.swap_tensor.utils import swap_out_tensors, SwapBuffer... | 6,294 | 34.971429 | 90 | py |
FlexGen | FlexGen-main/benchmark/third_party/DeepSpeed/deepspeed/runtime/swap_tensor/partitioned_param_swapper.py | """
Copyright 2020 The Microsoft DeepSpeed Team.
Licensed under the MIT license.
Functionality of swapping tensors to/from (NVMe) storage devices.
"""
import os
import shutil
from enum import Enum
import torch
from deepspeed import comm as dist
from deepspeed.ops.aio import AsyncIOBuilder
from .constants import *
fr... | 18,323 | 42.319149 | 165 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.