python_code
stringlengths
0
4.04M
repo_name
stringlengths
7
58
file_path
stringlengths
5
147
# 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. from __future__ import print_function import pickle import glob import os import pdb import math import numpy as np import ...
deep-variance-reduction-main
reproduce/plot_finetuning.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 import sys import run archs = ['default', 'resnet-small', 'densenet-40-36', 'resnet110'] try: pindex = int(s...
deep-variance-reduction-main
reproduce/reproduce_ratio_plots.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. from __future__ import print_function import pickle import glob import os import re import numpy as np import itertools imp...
deep-variance-reduction-main
reproduce/plot_iterate_distance.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 import sys import run methods = ["sgd", "recompute_svrg", "scsg"] try: pindex = int(sys.argv[1]) seed = i...
deep-variance-reduction-main
reproduce/reproduce_test_error_imagenet.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 import sys import run methods = ["sgd", "recompute_svrg", "scsg"] try: pindex = int(sys.argv[1]) seed = i...
deep-variance-reduction-main
reproduce/reproduce_test_error_resnet110.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. from __future__ import print_function import pickle import glob import os import pdb import matplotlib as mpl mpl.use('agg'...
deep-variance-reduction-main
reproduce/plot_test_error_with_bars.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 import sys import run methods = ["sgd", "recompute_svrg", "scsg"] try: pindex = int(sys.argv[1]) seed = i...
deep-variance-reduction-main
reproduce/reproduce_test_error_lenet.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. from __future__ import print_function import pickle import glob import os import re import matplotlib.ticker as plticker im...
deep-variance-reduction-main
reproduce/plot_variance_ratio.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 import sys import run transform_locking = [True, False] try: pindex = int(sys.argv[1]) print(f"problem i...
deep-variance-reduction-main
reproduce/reproduce_locking_plot.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. from __future__ import print_function import pickle import glob import os import pdb import matplotlib as mpl mpl.use('agg'...
deep-variance-reduction-main
reproduce/plot_test_error.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. from __future__ import print_function import pickle import glob import os import re import numpy as np import itertools imp...
deep-variance-reduction-main
reproduce/plot_transform_locking.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import sys class Fab_HDD(): def __init__(self, config="BarraCuda"): ############################### # Carbo...
ACT-main
hdd_model.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import sys class Fab_Logic(): def __init__(self, process_node=14, gpa="97", c...
ACT-main
logic_model.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import sys from dram_model import Fab_DRAM from ssd_model import Fab_SSD from logic_model import Fab_Logic def main(): ...
ACT-main
model.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import sys class Fab_DRAM(): def __init__(self, config = "ddr4_10nm", fab_yield=0.875): #########################...
ACT-main
dram_model.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import sys class Fab_SSD(): def __init__(self, config="nand_10nm", fab_yield=0.875): ##############################...
ACT-main
ssd_model.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import sys from dram_model import Fab_DRAM from hdd_model import Fab_HDD from ssd_model import Fab_SSD from logic_model impo...
ACT-main
exps/dellr740/dellr740.py
# Copyright (c) Meta Platforms, Inc. and affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import json import sys from dram_model import Fab_DRAM from hdd_model import Fab_HDD from ssd_model import Fab_SSD from logic_model impo...
ACT-main
exps/fairphone3/fairphone3.py
# Copyright 2020 LMNT, Inc. 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 applicable law or ag...
diffwave-master
setup.py
# Copyright 2020 LMNT, Inc. 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 applicable law or ag...
diffwave-master
src/diffwave/params.py
# Copyright 2020 LMNT, Inc. 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 applicable law or ag...
diffwave-master
src/diffwave/preprocess.py
diffwave-master
src/diffwave/__init__.py
# Copyright 2020 LMNT, Inc. 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 applicable law or ag...
diffwave-master
src/diffwave/model.py
# Copyright 2020 LMNT, Inc. 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 applicable law or ag...
diffwave-master
src/diffwave/dataset.py
# Copyright 2020 LMNT, Inc. 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 applicable law or ag...
diffwave-master
src/diffwave/inference.py
# Copyright 2020 LMNT, Inc. 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 applicable law or ag...
diffwave-master
src/diffwave/__main__.py
# Copyright 2020 LMNT, Inc. 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 applicable law or ag...
diffwave-master
src/diffwave/learner.py
# Copyright (c) 2017-present, Facebook, Inc. # 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 time import faiss import numpy as np from PIL import Image from PIL import ImageFile from scipy.sparse import csr_matrix...
deepcluster-main
clustering.py
# Copyright (c) 2017-present, Facebook, Inc. # 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 import pickle import numpy as np import torch from torch.utils.data.sampler import Sampler import models def load_...
deepcluster-main
util.py
# Copyright (c) 2017-present, Facebook, Inc. # 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 from collections import OrderedDict import os import pickle import subprocess import sys import numpy as np f...
deepcluster-main
eval_retrieval.py
deepcluster-main
__init__.py
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # #!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import os import math import time import glob from collections im...
deepcluster-main
eval_voc_classif.py
# Copyright (c) 2017-present, Facebook, Inc. # 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 os import pickle import time import faiss import numpy as np from sklearn.metrics.cluster import normali...
deepcluster-main
main.py
# Copyright (c) 2017-present, Facebook, Inc. # 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 os import time import numpy as np import torch import torch.nn as nn import torch.backends.cudnn as cud...
deepcluster-main
eval_linear.py
# Copyright (c) 2017-present, Facebook, Inc. # 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 os from scipy.ndimage.filters import gaussian_filter import sys import numpy as np from PIL import Image...
deepcluster-main
visu/gradient_ascent.py
# Copyright (c) 2017-present, Facebook, Inc. # 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 os from shutil import copyfile import sys import numpy as np from PIL import Image import torch import t...
deepcluster-main
visu/activ-retrieval.py
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # from .vgg16 import * from .alexnet import *
deepcluster-main
models/__init__.py
# Copyright (c) 2017-present, Facebook, Inc. # 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 torch import torch.nn as nn import math from random import random as rd __all__ = [ 'VGG', 'vgg16'] class VGG(nn.Modul...
deepcluster-main
models/vgg16.py
# Copyright (c) 2017-present, Facebook, Inc. # 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 numpy as np import torch import torch.nn as nn __all__ = [ 'AlexNet', 'alexnet'] # (number of filters, ke...
deepcluster-main
models/alexnet.py
import argparse import os import numpy as np import pytorch_lightning as pl import torch import torch.nn.functional as F import torchaudio import hydra from omegaconf import OmegaConf from torch.distributions import Categorical from tqdm.auto import tqdm from src import utils from src.dataloaders.audio import mu_law...
state-spaces-main
generate.py
''' Train an S4 model on sequential CIFAR10 / sequential MNIST with PyTorch for demonstration purposes. This code borrows heavily from https://github.com/kuangliu/pytorch-cifar. This file only depends on the standalone S4 layer available in /models/s4/ * Train standard sequential CIFAR: python -m example * Train ...
state-spaces-main
example.py
import copy import os import random import time from functools import partial, wraps from typing import Callable, List, Optional import hydra import numpy as np import pytorch_lightning as pl import torch import torch.nn as nn import wandb from hydra.utils import get_original_cwd from omegaconf import DictConfig, Omeg...
state-spaces-main
train.py
import argparse import torch from pathlib import Path from train import SequenceLightningModule parser = argparse.ArgumentParser() parser.add_argument("ckpt_path", type=str) args = parser.parse_args() ckpt = torch.load(args.ckpt_path, map_location='cuda') state_dict = ckpt['state_dict'] torch.save(state_dict, Pat...
state-spaces-main
checkpoints/convert_pl_to_pt.py
from tqdm.auto import tqdm import hydra import torch import numpy as np from pathlib import Path import pytorch_lightning as pl import matplotlib.pyplot as plt from torch.nn.modules import module import torch.nn.functional as F from torch.distributions import Categorical from src import utils from einops import rearran...
state-spaces-main
checkpoints/evaluate.py
"""Convert a V3 model to V4. See checkpoints/README.md for usage.""" from tqdm.auto import tqdm import hydra import torch import numpy as np from pathlib import Path import pytorch_lightning as pl import matplotlib.pyplot as plt from torch.nn.modules import module import torch.nn.functional as F from torch.distributio...
state-spaces-main
checkpoints/convert_v3_to_v4.py
"""Standalone version of Structured State Space sequence model (S4).""" from collections import defaultdict from typing import Optional, Mapping, Tuple, Union import logging from functools import partial import math import numpy as np from scipy import special as ss import torch import torch.nn as nn import torch.nn.f...
state-spaces-main
models/s4/s4.py
"""Minimal version of S4D with extra options and features stripped out, for pedagogical purposes.""" import math import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat from src.models.nn import DropoutNd class S4DKernel(nn.Module): """Generate convolution kernel f...
state-spaces-main
models/s4/s4d.py
import numpy as np from scipy import linalg from scipy.stats import norm, entropy from sklearn.cluster import KMeans def fid(feat_data, feat_gen): """ Calculate Frechet Inception Distance """ # Means mu_data = np.mean(feat_data, axis=0) mu_gen = np.mean(feat_gen, axis=0) # Covariances ...
state-spaces-main
models/sashimi/metrics.py
""" SaShiMi backbone. Use this backbone in your own models. You'll also need to copy over the standalone S4 layer, which can be found at `state-spaces/models/s4/` It's Raw! Audio Generation with State-Space Models Karan Goel, Albert Gu, Chris Donahue, Christopher Re. """ import sys sys.path.append('../') import torc...
state-spaces-main
models/sashimi/sashimi.py
#!/usr/bin/env python """Train a CNN for Google speech commands.""" __author__ = 'Yuan Xu, Erdene-Ochir Tuguldur' """With modifications from Karan Goel.""" import argparse import time import torch import torchvision from torch.autograd import Variable from torch.utils.data import DataLoader from torch.utils.data.sa...
state-spaces-main
models/sashimi/sc09_classifier/train_speech_commands.py
"""Google speech commands dataset.""" __author__ = 'Yuan Xu' """With modifications by Karan Goel to support training an SC09 classifier.""" import os import numpy as np import librosa from torch.utils.data import Dataset __all__ = [ 'CLASSES', 'SpeechCommandsDataset', 'BackgroundNoiseDataset' ] CLASSES = 'zero, on...
state-spaces-main
models/sashimi/sc09_classifier/speech_commands_dataset.py
""" Taken from https://github.com/tugstugi/pytorch-speech-commands and modified by Karan Goel. """ import argparse import os import torch import numpy as np from functools import reduce from natsort import natsorted from scipy import linalg from scipy.stats import norm, entropy from sklearn.cluster import KMeans fro...
state-spaces-main
models/sashimi/sc09_classifier/test_speech_commands.py
"""Splits the google speech commands into train, validation and test sets. """ import os import shutil import argparse def move_files(src_folder, to_folder, list_file): with open(list_file) as f: for line in f.readlines(): line = line.rstrip() dirname = os.path.dirname(line) ...
state-spaces-main
models/sashimi/sc09_classifier/datasets/speech_commands/split_dataset.py
# -*- coding: utf-8 -*- """Imported from https://github.com/prlz77/ResNeXt.pytorch/blob/master/models/model.py and added support for the 1x32x32 mel spectrogram for the speech recognition. Creates a ResNeXt Model as defined in: Xie, S., Girshick, R., Dollár, P., Tu, Z., & He, K. (2016). Aggregated residual transform...
state-spaces-main
models/sashimi/sc09_classifier/models/resnext.py
"""Transforms on raw wav samples.""" __author__ = 'Yuan Xu' import random import numpy as np import librosa import torch from torch.utils.data import Dataset def should_apply_transform(prob=0.5): """Transforms are only randomly applied with the given probability.""" return random.random() < prob class Load...
state-spaces-main
models/sashimi/sc09_classifier/transforms/transforms_wav.py
from .transforms_wav import * from .transforms_stft import *
state-spaces-main
models/sashimi/sc09_classifier/transforms/__init__.py
"""Transforms on the short time fourier transforms of wav samples.""" __author__ = 'Erdene-Ochir Tuguldur' import random import numpy as np import librosa from torch.utils.data import Dataset from .transforms_wav import should_apply_transform class ToSTFT(object): """Applies on an audio the short time fourier...
state-spaces-main
models/sashimi/sc09_classifier/transforms/transforms_stft.py
TEMPL = """ <style> th, td {{ border: 2px solid black; padding: 8px; }} th {{ width: 100px; vertical-align: text-top; font-weight: normal; }} .noborder {{ border: 0px solid black; }} .thlab {{ margin-bottom: 1em; }} .td {{ text-align: center; vertical-align: middle; }} input[ty...
state-spaces-main
models/sashimi/mturk/template_speech.py
import argparse import numpy as np import os import shutil from natsort import natsorted digits = 'zero one two three four five six seven eight nine'.split() def move_files(src_dir, src_files, target_dir, indices, discard=False): os.makedirs(target_dir, exist_ok=True) for i, digit in enumerate(digits): ...
state-spaces-main
models/sashimi/mturk/prepare_sc09.py
TEMPL = """ <style> th, td {{ border: 2px solid black; padding: 8px; }} th {{ width: 100px; vertical-align: text-top; font-weight: normal; }} .noborder {{ border: 0px solid black; }} .thlab {{ margin-bottom: 1em; }} .td {{ text-align: center; vertical-align: middle; }} input[ty...
state-spaces-main
models/sashimi/mturk/template_music.py
import argparse import random import shutil import uuid from natsort import natsorted from pathlib import Path from types import SimpleNamespace rd = random.Random() rd.seed(0) uuid.uuid4 = lambda: uuid.UUID(int=rd.getrandbits(128)) class Experiment: def __init__( self, condition, input_dir, out...
state-spaces-main
models/sashimi/mturk/turk_create_batch.py
import math import torch import torch.nn.functional as F import pytest from einops import rearrange from src.ops.vandermonde import log_vandermonde, log_vandermonde_fast @pytest.mark.parametrize('L', [3, 17, 489, 2**10, 1047, 2**11, 2**12]) @pytest.mark.parametrize('N', [4, 8, 16, 32, 64, 128, 256]) # @pytest.mark...
state-spaces-main
extensions/kernels/test_vandermonde.py
import torch from structured_kernels import vand_log_mult_sym_fwd, vand_log_mult_sym_bwd def log_vandermonde_cuda(v, z, L): """ Wrap the cuda method to deal with shapes """ v, z = torch.broadcast_tensors(v, z) shape = v.shape v = v.contiguous() z = z.contiguous() N = v.size(-1) assert z....
state-spaces-main
extensions/kernels/vandermonde.py
from pathlib import Path import torch from einops import rearrange from structured_kernels import cauchy_mult_sym_fwd, cauchy_mult_sym_bwd # try: # from cauchy_mult import cauchy_mult_sym_fwd, cauchy_mult_sym_bwd # except ImportError: # from torch.utils.cpp_extension import load # current_dir = Path(__fil...
state-spaces-main
extensions/kernels/cauchy.py
from setuptools import setup import torch.cuda from torch.utils.cpp_extension import CppExtension, CUDAExtension, BuildExtension from torch.utils.cpp_extension import CUDA_HOME ext_modules = [] if torch.cuda.is_available() and CUDA_HOME is not None: extension = CUDAExtension( 'structured_kernels', [ ...
state-spaces-main
extensions/kernels/setup.py
import math from functools import partial import torch from einops import rearrange from .cauchy import cauchy_mult_torch, cauchy_mult_keops, cauchy_mult from benchmark.utils import benchmark_all, benchmark_combined, benchmark_forward, benchmark_backward def generate_data(batch_size, N, L, symmetric=True, device='...
state-spaces-main
extensions/kernels/benchmark_cauchy.py
import importlib import json import argparse import torch from benchmark.utils import benchmark_forward def generate_data(batch_size, N, L, symmetric=True, device='cuda'): if not symmetric: v = torch.randn(batch_size, N, dtype=torch.complex64, device=device, requires_grad=True) w = torch.randn(b...
state-spaces-main
extensions/kernels/benchmark_cauchy_tune.py
import os import shutil import subprocess import sys # import tempfile # import importlib import random import string import json from functools import partial from multiprocessing import Pipe, Pool, Process from pathlib import Path from tqdm import tqdm import numpy as np def read_file(filename): """ return ...
state-spaces-main
extensions/kernels/tuner.py
import os from setuptools import setup from pathlib import Path import torch.cuda from torch.utils.cpp_extension import CppExtension, CUDAExtension, BuildExtension from torch.utils.cpp_extension import CUDA_HOME extensions_dir = Path(os.getenv('TUNING_SOURCE_DIR')).absolute() assert extensions_dir.exists() source_fi...
state-spaces-main
extensions/kernels/tuning_setup.py
import math import json import argparse import itertools from pathlib import Path from tuner import KernelTuner def forward_params_list(N): blocksize_params = ('MAX_BLOCK_SIZE_VALUE', [64, 128, 256, 512, 1024]) thread_value_default = [2, 4, 8, 16, 32, 32, 32, 32, 32, 32] thread_values_supported = [2, 4, ...
state-spaces-main
extensions/kernels/tune_cauchy.py
import math import torch import pytest from einops import rearrange from cauchy import cauchy_mult_torch, cauchy_mult_keops, cauchy_mult def generate_data(batch_size, N, L, symmetric=True, device='cuda'): if not symmetric: v = torch.randn(batch_size, N, dtype=torch.complex64, device=device, requires_gr...
state-spaces-main
extensions/kernels/test_cauchy.py
"""Implementations of general metric functions.""" import math import torch import torch.nn.functional as F from sklearn.metrics import f1_score, roc_auc_score from functools import partial def _student_t_map(mu, sigma, nu): sigma = F.softplus(sigma) nu = 2.0 + F.softplus(nu) return mu.squeeze(axis=-1), s...
state-spaces-main
src/tasks/metrics.py
"""Implements Task interface, which consists of encoder + decoder + loss/metrics.""" from typing import Optional, List, Tuple import math import functools import collections import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from omegaconf import ListConfig from src.models....
state-spaces-main
src/tasks/tasks.py
"""Decoders that interface between targets and model.""" import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, reduce import src.models.nn.utils as U import src.utils as utils class Decoder(nn.Module): """Abstract class defining the interface for Decoders. TODO: i...
state-spaces-main
src/tasks/decoders.py
"""Encoders that interface between input data and model.""" import datetime import math from typing import ForwardRef import torch from torch import nn import torch.nn.functional as F from einops import rearrange import src.models.nn.utils as U import src.utils as utils import src.utils.config from src.models.sequen...
state-spaces-main
src/tasks/encoders.py
"""Log parameter counts to WandB.""" from typing import Any import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_only from pytorch_lightning.utilities.parsing import AttributeDict class ParamsLog(pl.Callback): """ Log the number of parameters of the model """ def __init__( ...
state-spaces-main
src/callbacks/params.py
"""PL callbacks for logging to WandB. From https://github.com/HazyResearch/transformers/blob/master/src/callbacks/wandb_callbacks.py. """ import glob import os from typing import List import matplotlib.pyplot as plt import pandas as pd import seaborn as sn import torch import wandb from pytorch_lightning import Call...
state-spaces-main
src/callbacks/wandb.py
"""PL callbacks for monitoring computation speed. Adapted from https://github.com/HazyResearch/transformers/blob/master/src/callbacks/speed_monitor.py. In turn adapted from https://pytorch-lightning.readthedocs.io/en/latest/_modules/pytorch_lightning/callbacks/gpu_stats_monitor.html#GPUStatsMonitor. We only need the ...
state-spaces-main
src/callbacks/timer.py
import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_only from pytorch_lightning.utilities.parsing import AttributeDict from omegaconf import OmegaConf class TrackNorms(pl.Callback): # TODO do callbacks happen before or after the method in the main LightningModule? # @rank_zero_onl...
state-spaces-main
src/callbacks/norms.py
"""Callbacks for progressive resizing of images, used in S4ND paper.""" import numpy as np from pytorch_lightning.callbacks import Callback import src.utils as utils from src.utils import registry class ProgressiveResizing(Callback): def __init__(self, stage_params: list): """ stage_params is a...
state-spaces-main
src/callbacks/progressive_resizing.py
"""Synthetic datasets.""" import numpy as np import torch import torchvision from einops.layers.torch import Rearrange from src.utils import permutations from src.dataloaders.base import SequenceDataset class Copying(SequenceDataset): _name_ = "copying" @property def init_defaults(self): return...
state-spaces-main
src/dataloaders/synthetic.py
"""Long Range Arena datasets.""" import io import logging import os import pickle from pathlib import Path import torch from torch import nn import torch.nn.functional as F import torchtext import torchvision from einops.layers.torch import Rearrange, Reduce from PIL import Image # Only used for Pathfinder from data...
state-spaces-main
src/dataloaders/lra.py
"""Miscellaneous vision datasets.""" import os import torch from torch import nn from torch.nn import functional as F import torchvision from src.dataloaders.base import default_data_path, SequenceDataset class CIFAR100(SequenceDataset): _name_ = "cifar100" d_output = 100 l_output = 0 @property ...
state-spaces-main
src/dataloaders/vision.py
"""ET Dataset from Informer Paper. Dataset: https://github.com/zhouhaoyi/ETDataset Dataloader: https://github.com/zhouhaoyi/Informer2020 """ from typing import List import os import numpy as np import pandas as pd from pandas.tseries import offsets from pandas.tseries.frequencies import to_offset import torch from to...
state-spaces-main
src/dataloaders/et.py
from . import audio, basic, et, lm, lra, synthetic, ts, vision from .base import SequenceDataset
state-spaces-main
src/dataloaders/__init__.py
"""Time series datasets, especially for medical time series.""" import numpy as np import torch from torch import nn from torch.nn import functional as F from src.dataloaders.base import default_data_path, SequenceDataset, deprecated class BIDMC(SequenceDataset): """BIDMC datasets for Respiratory Rate / Heart R...
state-spaces-main
src/dataloaders/ts.py
"""Implementation of basic benchmark datasets used in S4 experiments: MNIST, CIFAR10 and Speech Commands.""" import numpy as np import torch import torchvision from einops.layers.torch import Rearrange from src.utils import permutations from src.dataloaders.base import default_data_path, ImageResolutionSequenceDatase...
state-spaces-main
src/dataloaders/basic.py
# Copyright (c) 2019-2020, 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/licenses/LICENSE-2.0 # # Unless required by...
state-spaces-main
src/dataloaders/lm.py
"""Audio datasets and utilities.""" import os from os import listdir from os.path import join import torch import torchaudio from torch import nn from torch.nn import functional as F from src.dataloaders.base import default_data_path, SequenceDataset, deprecated def minmax_scale(tensor, range_min=0, range_max=1): ...
state-spaces-main
src/dataloaders/audio.py
"""Core dataloader interface.""" import os import pickle from functools import partial from pathlib import Path import numpy as np import torch import torchaudio.functional as TF import torchvision from einops import rearrange from einops.layers.torch import Rearrange from src.utils import is_list, permutations from ...
state-spaces-main
src/dataloaders/base.py
"""Utilities for working with .ts files. Taken from https://github.com/ChangWeiTan/TS-Extrinsic-Regression/blob/master/utils/data_loader.py. Required to handle the @targetlabel tag which sktime.data_io.load_from_tsfile_to_dataframe does not support. """ import numpy as np import pandas as pd from tqdm import tqdm na...
state-spaces-main
src/dataloaders/prepare/bidmc/data_loader.py
import os import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import sktime from sktime.datasets import load_from_tsfile_to_dataframe import data_loader as data DATA_PATH = "data/" def split_data( X_train_orig, y_train_orig, X_test_orig, y_test_orig, shuffle=True, seed=0 ...
state-spaces-main
src/dataloaders/prepare/bidmc/process_data.py
"""Implementation of standard Copying dataset. Originally used in Arjovsky's Unitary RNN, maybe earlier? """ import random import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from src.utils import distributed def np_copying_data(L, M, A, batch_shape=()): seq = np.random.randin...
state-spaces-main
src/dataloaders/datasets/copying.py
"""Speech Commands dataset. Adapted from https://github.com/dwromero/ckconv/blob/dc84dceb490cab2f2ddf609c380083367af21890/datasets/speech_commands.py which is adapted from https://github.com/patrick-kidger/NeuralCDE/blob/758d3a7134e3a691013e5cc6b7f68f277e9e6b69/experiments/datasets/speech_commands.py """ import os im...
state-spaces-main
src/dataloaders/datasets/sc.py
"""RNN Vocal Generation Model. Blizzard, Music, and Huckleberry Finn data feeders. """ import numpy as np #import scikits.audiolab import random import time import os import glob import torch import sklearn from scipy.io import wavfile def normalize01(data): """To range [0., 1.]""" data -= np.min(data) ...
state-spaces-main
src/dataloaders/datasets/music.py
"""Implementation of Celeb-A dataset.""" from functools import partial import torch import os import PIL from typing import Any, Callable, List, Optional, Union, Tuple from torchvision.datasets import VisionDataset try: import gdown DOWNLOAD = True except ImportError: DOWNLOAD = False import numpy as np c...
state-spaces-main
src/dataloaders/datasets/celeba.py
"""Implementation of standard Adding dataset. Originally used in Arjovsky's Unitary RNN, maybe earlier? """ import torch import torch.nn as nn import torch.nn.functional as F def torch_adding_data(L, batch_shape=()): assert L >= 2 mid = L//2 idx0 = torch.randint(low=0, high=mid, size=batch_shape) id...
state-spaces-main
src/dataloaders/datasets/adding.py
"""Implementation of "Continuous Delay" dataset from How to Train Your HIPPO.""" import torch import torch.nn as nn import torch.nn.functional as F from src.dataloaders.utils.signal import whitesignal class DelayTrainDataset(torch.utils.data.Dataset): def __init__(self, samples, l_seq=1024, n_lag=1, l_lag=None, ...
state-spaces-main
src/dataloaders/datasets/delay.py
import torch import torch.nn as nn import torch.nn.functional as F from src.dataloaders.utils.signal import whitesignal class ReconstructTrainDataset(torch.utils.data.Dataset): def __init__(self, samples, l_seq=1024, l_mem=1024, dt=1e-3, freq=1.0, seed=0): """ """ super().__init__() ...
state-spaces-main
src/dataloaders/datasets/reconstruct.py
"""Data utilities for generating signals.""" import numpy as np def whitesignal(period, dt, freq, rms=0.5, batch_shape=()): """ Produces output signal of length period / dt, band-limited to frequency freq Output shape (*batch_shape, period/dt) Adapted from the nengo library """ if freq is not...
state-spaces-main
src/dataloaders/utils/signal.py