python_code
stringlengths
0
4.04M
repo_name
stringlengths
7
58
file_path
stringlengths
5
147
# Copyright (c) Meta Platforms, Inc. and 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 torch # from PIL import Image import imageio import numpy as np from cotracker.datasets.utils import CoT...
co-tracker-main
cotracker/datasets/fast_capture_dataset.py
# Copyright (c) Meta Platforms, Inc. and 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.
co-tracker-main
cotracker/datasets/__init__.py
# Copyright (c) Meta Platforms, Inc. and 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 torch import dataclasses import torch.nn.functional as F from dataclasses import dataclass from typing import Any,...
co-tracker-main
cotracker/datasets/utils.py
# Copyright (c) Meta Platforms, Inc. and 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.
co-tracker-main
cotracker/utils/__init__.py
# Copyright (c) Meta Platforms, Inc. and 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 numpy as np import cv2 import torch import flow_vis from matplotlib import cm import torch.nn.functional...
co-tracker-main
cotracker/utils/visualizer.py
# Copyright (c) Meta Platforms, Inc. and 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.
co-tracker-main
cotracker/models/__init__.py
# Copyright (c) Meta Platforms, Inc. and 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 torch import torch.nn.functional as F from typing import Tuple from cotracker.models.core.cotracker.cotracker impo...
co-tracker-main
cotracker/models/evaluation_predictor.py
# Copyright (c) Meta Platforms, Inc. and 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 torch from cotracker.models.core.cotracker.cotracker import CoTracker def build_cotracker( checkpoint: str, ...
co-tracker-main
cotracker/models/build_cotracker.py
# Copyright (c) Meta Platforms, Inc. and 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 torch EPS = 1e-6 def smart_cat(tensor1, tensor2, dim): if tensor1 is None: return tensor2 return...
co-tracker-main
cotracker/models/core/model_utils.py
# Copyright (c) Meta Platforms, Inc. and 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.
co-tracker-main
cotracker/models/core/__init__.py
# Copyright (c) Meta Platforms, Inc. and 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 torch import numpy as np def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0): ...
co-tracker-main
cotracker/models/core/embeddings.py
# Copyright (c) Meta Platforms, Inc. and 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.
co-tracker-main
cotracker/models/core/cotracker/__init__.py
# Copyright (c) Meta Platforms, Inc. and 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 torch import torch.nn as nn from einops import rearrange from cotracker.models.core.cotracker.blocks import ( ...
co-tracker-main
cotracker/models/core/cotracker/cotracker.py
# Copyright (c) Meta Platforms, Inc. and 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 torch import torch.nn.functional as F from cotracker.models.core.model_utils import reduce_masked_mean EPS = 1e-6 ...
co-tracker-main
cotracker/models/core/cotracker/losses.py
# Copyright (c) Meta Platforms, Inc. and 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 torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from timm.models.vision_t...
co-tracker-main
cotracker/models/core/cotracker/blocks.py
# Copyright (c) Meta Platforms, Inc. and 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.
co-tracker-main
cotracker/evaluation/__init__.py
# Copyright (c) Meta Platforms, Inc. and 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 json import os from dataclasses import dataclass, field import hydra import numpy as np import torch from omegaco...
co-tracker-main
cotracker/evaluation/evaluate.py
# Copyright (c) Meta Platforms, Inc. and 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.
co-tracker-main
cotracker/evaluation/core/__init__.py
# Copyright (c) Meta Platforms, Inc. and 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 numpy as np from typing import Iterable, Mapping, Tuple, Union def compute_tapvid_metrics( query_points: np....
co-tracker-main
cotracker/evaluation/core/eval_utils.py
# Copyright (c) Meta Platforms, Inc. and 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 collections import defaultdict import os from typing import Optional import torch from tqdm import tqdm import numpy ...
co-tracker-main
cotracker/evaluation/core/evaluator.py
import os import torch import timm import einops import tqdm import cv2 import gradio as gr from cotracker.utils.visualizer import Visualizer, read_video_from_path def cotracker_demo( input_video, grid_size: int = 10, grid_query_frame: int = 0, backward_tracking: bool = False, tracks_leave_tra...
co-tracker-main
gradio_demo/app.py
''' Standalone Long Conv class. The `LongConvModel` class defined in this file provides a simple backbone to train models. ''' import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from opt_einsum import contract class OurModule(nn.Module): """ Interface for Module that...
safari-main
standalone_long_convs.py
''' Train a long conv model on sequential CIFAR10 / sequential MNIST with PyTorch for demonstration purposes. This code borrows heavily from https://github.com/kuangliu/pytorch-cifar and is based on https://github.com/HazyResearch/state-spaces. * Train standard sequential CIFAR: python -m standalone_cifar * Train ...
safari-main
standalone_cifar.py
""" Simplified standalone version of Hyena: https://arxiv.org/abs/2302.10866, designed for quick experimentation. A complete version is available under `src.models.sequence.hyena`. """ import math import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange def fftconv(u, k, D): ...
safari-main
standalone_hyena.py
import copy import os import random import time from functools import partial, wraps from typing import Callable, List, Sequence 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...
safari-main
train.py
import torch import torch.nn.functional as F from einops import rearrange from fftconv import fftconv_fwd, fftconv_bwd def fftconv_ref(u, k, D, dropout_mask): seqlen = u.shape[-1] fft_size = 2 * seqlen k_f = torch.fft.rfft(k, n=fft_size) / fft_size u_f = torch.fft.rfft(u.to(dtype=k.dtype), n=fft_siz...
safari-main
csrc/fftconv/launch_fftconv.py
# Adapted from https://github.com/NVIDIA/apex/blob/master/setup.py import torch from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension, CUDA_HOME from setuptools import setup, find_packages import subprocess import sys import warnings import os # ninja build does not work unless include_dir...
safari-main
csrc/fftconv/setup.py
import math import re import numpy as np # N = 8192 N = 16384 # The case of 0 / N is special, we want to simplify it to 0 / 2 instead of 0 / 1 numerator = np.arange(1, N // 8 + 1) gcd = np.gcd(numerator, N) num = numerator // gcd denom = N // gcd lut_vals = ['T_2_0'] + [f'T_{d}_{n}' for n, d in zip(num, denom)] lut_...
safari-main
csrc/fftconv/lut_code_gen.py
import torch import argparse import os import sys import yaml from tqdm import tqdm import json sys.path.append(os.environ.get("SAFARI_PATH", ".")) from src.models.sequence.long_conv_lm import ConvLMHeadModel from transformers import AutoTokenizer, GPT2LMHeadModel from spacy.lang.en.stop_words import STOP_WORDS ...
safari-main
evals/lambada.py
import sys from pathlib import Path import torch import torch.utils.benchmark as benchmark from src.models.sequence.hyena import HyenaOperator from flash_attn.flash_attention import FlashMHA def benchmark_forward(fn, *inputs, repeats = 10, desc='', verbose=True, **kwinputs): if verbose: print(desc, '- F...
safari-main
benchmarks/runtime_hyena_flashmha.py
import math import torch import torch.nn.functional as F from sklearn.metrics import f1_score, roc_auc_score from functools import partial import torchmetrics.functional as tm_f def _student_t_map(mu, sigma, nu): sigma = F.softplus(sigma) nu = 2.0 + F.softplus(nu) return mu.squeeze(axis=-1), sigma.squeeze(...
safari-main
src/tasks/metrics.py
# Inspired by https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/common/metrics/perplexity.py # But we compute the perplexity correctly: exp(average(nll)), not average(exp(nll)) # Also adapted from https://github.com/Lightning-AI/metrics/blob/master/src/torchmetrics/text/perplexity.py # But we pass in the loss t...
safari-main
src/tasks/torchmetrics.py
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.nn.components import ReversibleInstanceNorm1dInput, ReversibleInstanceNorm1dOutput, \ ...
safari-main
src/tasks/tasks.py
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 import src.utils.config import src.utils.train log = src.utils.train.get_logger(__name__) class Decoder(nn.Module): """This class doesn't do much but ...
safari-main
src/tasks/decoders.py
import datetime import math from typing import ForwardRef import torch from torch import nn import torch.nn.functional as F from einops import rearrange, repeat import src.models.nn.utils as U import src.utils as utils import src.utils.config from src.models.sequence.block import SequenceResidualBlock from src.models...
safari-main
src/tasks/encoders.py
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__( self, total: bool = True, ...
safari-main
src/callbacks/params.py
### 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 Callback, Trainer from pytorch_lightning.loggers ...
safari-main
src/callbacks/wandb.py
### https://github.com/HazyResearch/transformers/blob/master/src/callbacks/speed_monitor.py # Adapted from https://pytorch-lightning.readthedocs.io/en/latest/_modules/pytorch_lightning/callbacks/gpu_stats_monitor.html#GPUStatsMonitor # We only need the speed monitoring, not the GPU monitoring import time from typing i...
safari-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...
safari-main
src/callbacks/norms.py
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 list of dicts e.g. stage_params = [ {'resolution': 4...
safari-main
src/callbacks/progressive_resizing.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 datase...
safari-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 ImageNet(SequenceDataset): """ .. figure:: https://3qeqpr26caki16dnhd19sv6by6v-wpengine.netdna-s...
safari-main
src/dataloaders/vision.py
'''Synthetic datasets to test in-context learning ability.''' import os import torch from torch.utils.data import TensorDataset, Dataset, DataLoader from typing import Dict import numpy as np from tqdm import tqdm from collections import Counter from src.dataloaders.base import SequenceDataset class Vocab: """Cu...
safari-main
src/dataloaders/synthetics.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...
safari-main
src/dataloaders/et.py
# Adapted from https://github.com/huggingface/transformers/blob/master/examples/pytorch/language-modeling/run_clm.py # Adapted from https://github.com/HazyResearch/flash-attention/blob/main/training/src/datamodules/language_modeling_hf.py from itertools import chain from pathlib import Path import pickle from typing im...
safari-main
src/dataloaders/language_modeling_hf.py
from . import basic, et, lra, language_modeling_hf, synthetics, vision from .base import SequenceDataset
safari-main
src/dataloaders/__init__.py
# Adapted from https://github.com/Lightning-AI/lightning/blob/2845e7565dbe6b765ae32870e7d2bc456529c30a/tests/tests_pytorch/utilities/test_auto_restart.py#L1397 from typing import Iterator import math import torch from torch.utils.data import RandomSampler, DistributedSampler class RandomFaultTolerantSampler(RandomSa...
safari-main
src/dataloaders/fault_tolerant_sampler.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, ImageResolutionSequenceDataset...
safari-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...
safari-main
src/dataloaders/lm.py
""" Datasets for core experimental results """ import os import pickle from functools import partial from pathlib import Path import numpy as np import torch import torchvision from einops import rearrange from einops.layers.torch import Rearrange from src.utils import is_list, permutations from torch.nn import funct...
safari-main
src/dataloaders/base.py
# Copied from https://github.com/stanford-crfm/mistral/blob/main/src/corpora/detokenization.py # Which was originally from https://github.com/NVIDIA/Megatron-LM/blob/aed2f75e209e525c842aec7c044af7acae2a4614/tasks/zeroshot_gpt/detokenizer.py """ Handle detokenization for different dataset for zero-shot LM evaluation. "...
safari-main
src/dataloaders/datasets/detokenizer.py
# Inspired by https://github.com/NVIDIA/Megatron-LM/blob/main/tasks/zeroshot_gpt/datasets.py # Except we don't pad the last block and don't use overlapping eval # And we return both the input and the target import math import numpy as np import torch class LMDataset(torch.utils.data.Dataset): def __init__(self,...
safari-main
src/dataloaders/datasets/lm_dataset.py
""" Borrowed from https://github.com/hysts/pytorch_image_classification/tree/9ff4248905850c68aa9c09c17914307eb81769e7/pytorch_image_classification/transforms """ import torch import numpy as np import PIL import PIL.Image from PIL.Image import Image class NpNormalize: def __init__(self, mean: np.ndarray, std: np....
safari-main
src/dataloaders/utils/cifar_augmentations.py
import torch from timm.data import Mixup from timm.data.mixup import mixup_target class TimmMixup(Mixup): """ Wrap timm.data.Mixup that avoids the assert that batch size must be even. """ def __call__(self, x, target, *args): if self.mode == 'elem': lam = self._mix_elem(x) eli...
safari-main
src/dataloaders/utils/timm_mixup.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...
safari-main
src/dataloaders/utils/vocabulary.py
"""Utilities for special optimizer hyperparameters. group_parameters_for_optimizer is a modification of timm's optimizer logic, which is currently unused add_optimizer_hooks is an improved version that uses this codebase's _optim dictionary """ import inspect import torch.nn as nn import hydra def add_optimizer_h...
safari-main
src/utils/optim_groups.py
""" Utilities for dealing with collection objects (lists, dicts) and configs """ from typing import Sequence, Mapping, Optional, Callable import functools import hydra from omegaconf import ListConfig, DictConfig # TODO this is usually used in a pattern where it's turned into a list, so can just do that here def is_li...
safari-main
src/utils/config.py
optimizer = { "adam": "torch.optim.Adam", "adamw": "torch.optim.AdamW", "rmsprop": "torch.optim.RMSprop", "sgd": "torch.optim.SGD", "lamb": "src.utils.optim.lamb.JITLamb", } scheduler = { "constant": "transformers.get_constant_schedule", "plateau": "torch.optim.lr_scheduler.ReduceLROnPlatea...
safari-main
src/utils/registry.py
from .config import is_list, is_dict, to_list, to_dict, get_class, instantiate
safari-main
src/utils/__init__.py
import math import numpy as np import torch ### Bit reversal permutation def bitreversal_po2(n): m = int(math.log(n)/math.log(2)) perm = np.arange(n).reshape(n,1) for i in range(m): n1 = perm.shape[0]//2 perm = np.hstack((perm[:n1],perm[n1:])) return perm.squeeze(0) def bitreversal_p...
safari-main
src/utils/permutations.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...
safari-main
src/utils/distributed.py
""" Utils for the training loop. Copied from https://github.com/HazyResearch/transformers/blob/master/src/utils/utils.py """ import logging import os import warnings from typing import List, Sequence import torch.nn as nn import pytorch_lightning as pl import rich.syntax import rich.tree from omegaconf import DictConf...
safari-main
src/utils/train.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...
safari-main
src/utils/optim/lamb.py
"""Custom learning rate schedulers""" import math import warnings import torch from timm.scheduler import CosineLRScheduler # https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html class CosineWarmup(torch.optim.lr_scheduler.CosineAnnealingLR): def __init__(self, optimizer, T_max, eta_min=0, wa...
safari-main
src/utils/optim/schedulers.py
""" Implementations of different types of residual functions. """ import torch from torch import nn class Residual(nn.Module): """ Residual connection with constant affine weights. Can simulate standard residual, no residual, and "constant gates". """ def __init__(self, i_layer, d_input, d_model, alpha=1.0, ...
safari-main
src/models/nn/residual.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...
safari-main
src/models/nn/adaptive_softmax.py
from .components import LinearActivation, Activation, Normalization, DropoutNd
safari-main
src/models/nn/__init__.py
""" Utility wrappers around modules to let them handle Args and extra arguments """ import inspect from functools import wraps import torch from torch import nn def wrap_kwargs(f): """ Given a callable f that can consume some named arguments, wrap it with a kwargs that passes back any unused args EXA...
safari-main
src/models/nn/utils.py
""" Defines flexible gating mechanisms based on ideas from LSSL paper and UR-LSTM paper https://arxiv.org/abs/1910.09890 """ import torch import torch.nn as nn class Gate(nn.Module): """ Implements gating mechanisms. TODO update this with more detailed description with reference to LSSL paper when it's on arxiv ...
safari-main
src/models/nn/gate.py
"""Implementations of several types of Discrete Sin/Cosine Transforms with various reductions to FFT. Currently not used by S4 """ import torch import torch.nn as nn import numpy as np import scipy.fft from einops import rearrange, repeat class DCT(nn.Module): """ Reductions adapted from https://dsp.stackexchang...
safari-main
src/models/nn/dxt.py
""" Utility nn components, in particular handling activations, initializations, and normalization layers """ from functools import partial import math from typing import ForwardRef import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from opt_einsum import contract def stoc...
safari-main
src/models/nn/components.py
# Copyright (c) 2023, Tri Dao, Dan Fu. # Simplified, mostly standalone version of LongConvLM for synthetics. import math from functools import partial from collections import namedtuple import torch import torch.nn as nn import torch.nn.functional as F from torchvision.ops import StochasticDepth from einops import ...
safari-main
src/models/sequence/simple_lm.py
""" Implementation of FFN block in the style of Transformers """ from functools import partial from torch import nn from src.models.sequence.base import SequenceModule from src.models.nn import LinearActivation, DropoutNd class FF(SequenceModule): def __init__(self, d_input, expand=2, d_output=None, transposed=Fa...
safari-main
src/models/sequence/ff.py
import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from src.models.sequence.ssm.ss_kernel import SSKernel try: from src.ops.fftconv import fftconv_func except ImportError: fftconv_func = None @torch.jit.script def mul_sum(q, y): return (q * y).sum(dim=1) c...
safari-main
src/models/sequence/h3.py
'''PyTorch version of the block FFT convolution as described in the H3 paper.''' import torch from einops import rearrange import math from torch import nn from src.models.nn import Activation from src.utils.train import OptimModule def ref_dft_matrix(N, H=1): """Compute the DFT matrix of size N x N. Thi...
safari-main
src/models/sequence/block_fft.py
from .base import SequenceModule, TransposedModule from .model import SequenceModel from .ff import FF
safari-main
src/models/sequence/__init__.py
import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange import opt_einsum as oe optimized = True if optimized: contract = oe.contract else: contract = torch.einsum from src.models.nn import LinearActivation, Activation, DropoutNd from src.models.sequence.block_fft impo...
safari-main
src/models/sequence/long_conv.py
# Copyright (c) 2023, Tri Dao, Dan Fu. import copy import math import re from functools import partial from collections import namedtuple, OrderedDict from collections.abc import Sequence import torch import torch.nn as nn import torch.nn.functional as F from transformers.models.gpt2.configuration_gpt2 import GPT2C...
safari-main
src/models/sequence/long_conv_lm.py
""" Isotropic deep sequence model backbone, in the style of ResNets / Transformers. The SequenceModel class implements a generic (batch, length, d_input) -> (batch, length, d_output) transformation """ from functools import partial import torch import torch.nn as nn from einops import rearrange from src.utils.confi...
safari-main
src/models/sequence/model.py
import torch import torch.nn as nn import torch.nn.functional as F from einops import repeat from src.utils.train import OptimModule class LongConvKernel(OptimModule): def __init__( self, H, L, channels=1, learning_rate=None, lam=0.1, causal=True, ...
safari-main
src/models/sequence/long_conv_kernel.py
import math from re import U import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from einops import rearrange, repeat try: from src.ops.fftconv import fftconv_ref, fftconv_func except ImportError: fftconv_func = None try: from flash_attn.ops.fused_dense impo...
safari-main
src/models/sequence/hyena.py
import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange from src.models.sequence.long_conv_kernel import LongConvKernel try: from src.ops.fftconv import fftconv_func except ImportError: fftconv_func = None @torch.jit.script def mul_sum(q, y): return (q * y).sum(d...
safari-main
src/models/sequence/h3_conv.py
""" Implements a full residual block around a black box layer Configurable options include: normalization position: prenorm or postnorm normalization type: batchnorm, layernorm etc. subsampling/pooling residual options: feedforward, residual, affine scalars, depth-dependent scaling, etc. """ from torch import nn fro...
safari-main
src/models/sequence/block.py
"""Implements downsampling and upsampling on sequences.""" import torch from torch import nn import torch.nn.functional as F from einops import rearrange, repeat, reduce from src.models.sequence import SequenceModule from src.models.nn import LinearActivation """ Simple pooling functions that just downsample or repe...
safari-main
src/models/sequence/pool.py
from torch import nn import functools class SequenceModule(nn.Module): """Abstract sequence model class. All models must adhere to this interface A SequenceModule is generally a model that transforms an input of shape (n_batch, l_sequence, d_model) to (n_batch, l_sequence, d_output) REQUIRED methods ...
safari-main
src/models/sequence/base.py
""" Wrapper around nn.MultiheadAttention to adhere to SequenceModule interface. """ import torch import torch.nn.functional as F from torch import nn import hydra from src.models.sequence.base import SequenceModule, TransposedModule import src.models.nn.utils as U from einops import rearrange @TransposedModule class ...
safari-main
src/models/sequence/mha.py
""" Standalone version of Structured (Sequence) State Space (S4) model. """ 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.functional as F from pytorch_lightning.utilities import rank_zero_only from einops ...
safari-main
src/models/sequence/ssm/s4d.py
# TD: [2023-01-05]: Extracted the SSKernel class from # https://github.com/HazyResearch/state-spaces/blob/06dbbdfd0876501a7f12bf3262121badbc7658af/src/models/sequence/ss/kernel.py # We add option to use the shift kernel, and remove the option of SSKernelNPLR """SSM convolution kernels. SSKernel wraps different kernels...
safari-main
src/models/sequence/ssm/ss_kernel.py
# Copied from https://github.com/HazyResearch/state-spaces/blob/06dbbdfd0876501a7f12bf3262121badbc7658af/src/models/hippo/hippo.py """ Definitions of A and B matrices for various HiPPO operators. """ import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from scipy import special as ss ...
safari-main
src/models/sequence/ssm/hippo.py
# TD: [2023-01-05]: Extracted the SSKernelDiag class from # https://github.com/HazyResearch/state-spaces/blob/06dbbdfd0876501a7f12bf3262121badbc7658af/src/models/sequence/ss/kernel.py # We make a small change to use the log_vandermonde CUDA code. """SSKernelDiag is the S4D kernel, a simpler algorithm for computing the...
safari-main
src/models/sequence/ssm/ss_kernel_shift.py
import torch import torch.nn as nn from src.models.nn import LinearActivation, Activation, DropoutNd from einops import rearrange, repeat import opt_einsum as oe import math class OurModule(nn.Module): def __init__(self): super().__init__() def register(self, name, tensor, trainable=False, lr=None, wd=None): ...
safari-main
src/models/sequence/ssm/s4_simple.py
# TD: [2023-01-05]: Extracted the SSKernelDiag class from # https://github.com/HazyResearch/state-spaces/blob/06dbbdfd0876501a7f12bf3262121badbc7658af/src/models/sequence/ss/kernel.py # We make a small change to use the log_vandermonde CUDA code. """SSKernelDiag is the S4D kernel, a simpler algorithm for computing the...
safari-main
src/models/sequence/ssm/ss_kernel_diag.py
# Copied from https://github.com/HazyResearch/state-spaces/blob/06dbbdfd0876501a7f12bf3262121badbc7658af/src/models/sequence/ss/dplr.py """Initializations of structured state space models""" import math import torch import torch.nn as nn import torch.nn.functional as F from einops import rearrange, repeat from src.mo...
safari-main
src/models/sequence/ssm/dplr.py
""" The original Vision Transformer (ViT) from timm, copyright belongs to / Copyright 2020 Ross Wightman """ import math import logging from functools import partial from collections import OrderedDict from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as F from timm.models.helpe...
safari-main
src/models/baselines/vit_all.py
import math import torch import torch.nn.functional as F from einops import rearrange from fftconv import fftconv_fwd, fftconv_bwd @torch.jit.script def _mul_sum(y, q): return (y * q).sum(dim=1) # reference convolution with residual connection def fftconv_ref(u, k, D, dropout_mask, gelu=True, k_rev=None): ...
safari-main
src/ops/fftconv.py
"""pykeops implementations of the Vandermonde matrix multiplication kernel used in the S4D kernel.""" import math import torch from einops import rearrange, repeat from opt_einsum import contract import os try: import pykeops from pykeops.torch import LazyTensor, Genred except: pass try: from cauchy...
safari-main
src/ops/vandermonde.py
""" Old utilities for parallel scan implementation of Linear RNNs. """ # TODO this file could use much cleanup import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import math from src.models.functional.toeplitz import triangular_toeplitz_multiply, triangular_toeplitz_multiply_padded ...
safari-main
src/ops/unroll.py
""" Compute a Krylov function efficiently. (S4 renames the Krylov function to a "state space kernel") A : (N, N) b : (N,) c : (N,) Return: [c^T A^i b for i in [L]] """ import torch import torch.nn.functional as F from einops import rearrange, repeat from src.ops.toeplitz import causal_convolution def krylov_sequent...
safari-main
src/ops/krylov.py
""" Utilities for computing convolutions. There are 3 equivalent views: 1. causal convolution 2. multiplication of (lower) triangular Toeplitz matrices 3. polynomial multiplication (mod x^N) """ import torch import torch.nn as nn import torch.nn.functional as F def construct_toeplitz(v, f=0.0): """E...
safari-main
src/ops/toeplitz.py
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # import math import torch import torch.nn.functional as F from torch.autograd import grad def gPenalty(inputs, loss, la...
AdversarialAndDimensionality-master
penalties.py