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
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/utils/extract_process.py
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.runner import get_dist_info from mmselfsup.utils.collect import (dist_forward_collect, nondist_forward_collect) from .multi_pooling import MultiPooling class ExtractProcess(object): """Global aver...
3,770
36.71
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/utils/multi_pooling.py
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.runner import BaseModule class MultiPooling(BaseModule): """Pooling layers for features from multiple depth. Args: pool_type (str): Pooling type for the feature map. Options are 'adaptive' and 'specified'. Def...
1,756
34.14
70
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/utils/knn_classifier.py
# Copyright (c) Facebook, Inc. and its affiliates. # This file is borrowed from # https://github.com/facebookresearch/dino/blob/main/eval_knn.py import torch import torch.nn as nn @torch.no_grad() def knn_classifier(train_features, train_labels, test_features, ...
2,949
40.549296
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/utils/sobel.py
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn from mmcv.runner import BaseModule class Sobel(BaseModule): """Sobel layer.""" def __init__(self): super(Sobel, self).__init__() grayscale = nn.Conv2d(3, 1, kernel_size=1, stride=1, padding=0) grayscale...
924
33.259259
74
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/utils/transformer_blocks.py
# Copyright (c) OpenMMLab. All rights reserved. from typing import Sequence import torch import torch.nn as nn from mmcls.models.backbones.vision_transformer import \ TransformerEncoderLayer as _TransformerEncoderLayer from mmcls.models.utils import MultiheadAttention as _MultiheadAttention from mmcv.cnn import bu...
20,969
38.566038
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/utils/gather_layer.py
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.distributed as dist class GatherLayer(torch.autograd.Function): """Gather tensors from all process, supporting backward propagation.""" @staticmethod def forward(ctx, input): ctx.save_for_backward(input) output = [ ...
669
26.916667
75
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/utils/hog_layer.py
# Copyright (c) OpenMMLab. All rights reserved. import math import torch import torch.nn as nn import torch.nn.functional as F class HOGLayerC(nn.Module): """Generate hog feature for each batch images. This module is used in Maskfeat to generate hog feature. This code is borrowed from. <https://github.c...
3,958
36
89
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/utils/multi_prototypes.py
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.runner import BaseModule class MultiPrototypes(BaseModule): """Multi-prototypes for SwAV head. Args: output_dim (int): The output dim from SwAV neck. num_prototypes (list[int]): The number of prototypes needed. ...
851
30.555556
68
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/backbones/cae_vit.py
# Copyright (c) OpenMMLab. All rights reserved. import numpy as np import torch from mmcls.models import VisionTransformer from mmcv.cnn.utils.weight_init import trunc_normal_ from mmcv.runner.base_module import ModuleList from torch import nn from ..builder import BACKBONES from ..utils import TransformerEncoderLayer...
6,323
40.333333
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/backbones/simmim_swin.py
# Copyright (c) OpenMMLab. All rights reserved. from typing import Optional, Sequence, Tuple, Union import torch import torch.nn as nn from mmcls.models import SwinTransformer from mmcv.cnn.utils.weight_init import trunc_normal_ from ..builder import BACKBONES @BACKBONES.register_module() class SimMIMSwinTransforme...
5,446
36.054422
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/backbones/maskfeat_vit.py
# Copyright (c) OpenMMLab. All rights reserved. from typing import Optional, Tuple, Union import torch from mmcls.models import VisionTransformer from mmcv.cnn.utils.weight_init import trunc_normal_ from torch import nn from ..builder import BACKBONES @BACKBONES.register_module() class MaskFeatViT(VisionTransformer...
4,864
37.611111
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/backbones/resnet.py
# Copyright (c) OpenMMLab. All rights reserved. from mmcls.models.backbones import ResNet as _ResNet from mmcls.models.backbones.resnet import BasicBlock, Bottleneck from ..builder import BACKBONES @BACKBONES.register_module() class ResNet(_ResNet): """ResNet backbone. Please refer to the `paper <https://ar...
6,699
38.411765
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/backbones/mae_vit.py
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmcls.models import VisionTransformer from torch import nn from ..builder import BACKBONES from ..utils import build_2d_sincos_position_embedding @BACKBONES.register_module() class MAEViT(VisionTransformer): """Vision Transformer for MAE pre-train...
6,229
36.305389
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/backbones/resnext.py
# Copyright (c) OpenMMLab. All rights reserved. from mmcls.models.backbones.resnet import ResLayer from mmcls.models.backbones.resnext import Bottleneck from ..builder import BACKBONES from .resnet import ResNet @BACKBONES.register_module() class ResNeXt(ResNet): """ResNeXt backbone. Please refer to the `pa...
3,808
41.797753
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/backbones/vision_transformer.py
# Copyright (c) OpenMMLab. All rights reserved. import math from functools import reduce from operator import mul import torch.nn as nn from mmcls.models.backbones import VisionTransformer as _VisionTransformer from mmcls.models.utils import to_2tuple from mmcv.cnn.bricks.transformer import PatchEmbed from torch.nn.mo...
5,260
37.123188
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/backbones/mim_cls_vit.py
# Copyright (c) OpenMMLab. All rights reserved. import numpy as np import torch from mmcls.models import VisionTransformer from mmcv.cnn import build_norm_layer from mmcv.runner.base_module import ModuleList from ..builder import BACKBONES from ..utils import TransformerEncoderLayer @BACKBONES.register_module() clas...
5,282
37.007194
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/heads/contrastive_head.py
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn from mmcv.runner import BaseModule from ..builder import HEADS @HEADS.register_module() class ContrastiveHead(BaseModule): """Head for contrastive learning. The contrastive loss is implemented in this head and is used in SimC...
1,282
28.159091
75
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/heads/swav_head.py
# Copyright (c) OpenMMLab. All rights reserved. import numpy as np import torch import torch.distributed as dist import torch.nn as nn from mmcv.runner import BaseModule from mmselfsup.utils import distributed_sinkhorn from ..builder import HEADS from ..utils import MultiPrototypes @HEADS.register_module() class SwA...
4,523
39.035398
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/heads/mae_head.py
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmcls.models import LabelSmoothLoss from mmcv.cnn.utils.weight_init import trunc_normal_ from mmcv.runner import BaseModule from torch import nn from ..builder import HEADS @HEADS.register_module() class MAEPretrainHead(BaseModule): """Pre-trainin...
4,138
28.776978
77
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/heads/cae_head.py
# Copyright (c) OpenMMLab. All rights reserved. import os import warnings import torch from mmcv.runner import BaseModule from torch import nn from ..builder import HEADS from ..utils import Encoder @HEADS.register_module() class CAEHead(BaseModule): """Pretrain Head for CAE. Compute the align loss and the...
2,336
32.385714
151
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/heads/maskfeat_head.py
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmcls.models import LabelSmoothLoss from mmcv.cnn.utils.weight_init import trunc_normal_ from mmcv.runner import BaseModule from torch import nn from ..builder import HEADS @HEADS.register_module() class MaskFeatPretrainHead(BaseModule): """Pre-tr...
3,341
31.134615
75
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/heads/cls_head.py
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.runner import BaseModule from ..builder import HEADS from ..utils import accuracy @HEADS.register_module() class ClsHead(BaseModule): """Simplest classifier head, with only one fc layer. Args: with_avg_pool (bool): Wheth...
2,431
31.864865
76
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/heads/simmim_head.py
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmcv.runner import BaseModule from torch.nn import functional as F from ..builder import HEADS @HEADS.register_module() class SimMIMHead(BaseModule): """Pretrain Head for SimMIM. Args: patch_size (int): Patch size of each token. ...
1,114
29.972222
76
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/heads/multi_cls_head.py
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from mmcv.cnn import build_norm_layer from mmcv.runner import BaseModule from ..builder import HEADS from ..utils import MultiPooling, accuracy @HEADS.register_module() class MultiClsHead(BaseModule): """Multiple classifier heads. This he...
3,687
35.88
78
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/heads/mocov3_head.py
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn from mmcv.runner import BaseModule from mmselfsup.utils import concat_all_gather from ..builder import HEADS, build_neck @HEADS.register_module() class MoCoV3Head(BaseModule): """Head for MoCo v3 algorithms. This head builds ...
2,024
32.196721
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/models/heads/latent_pred_head.py
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn from mmcv.runner import BaseModule, get_dist_info from ..builder import HEADS, build_neck @HEADS.register_module() class LatentPredictHead(BaseModule): """Head for latent feature prediction. This head builds a predictor, whic...
4,301
31.590909
78
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/datasets/base.py
# Copyright (c) OpenMMLab. All rights reserved. import warnings from abc import ABCMeta, abstractmethod from mmcv.utils import build_from_cfg from torch.utils.data import Dataset from torchvision.transforms import Compose from .builder import PIPELINES, build_datasource class BaseDataset(Dataset, metaclass=ABCMeta)...
1,698
34.395833
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/datasets/rotation_pred.py
# Copyright (c) OpenMMLab. All rights reserved. import torch from .base import BaseDataset from .builder import DATASETS from .utils import to_numpy def rotate(img): """Rotate input image with 0, 90, 180, and 270 degrees. Args: img (Tensor): input image of shape (C, H, W). Returns: list...
1,716
29.660714
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/datasets/deepcluster.py
# Copyright (c) OpenMMLab. All rights reserved. import torch from .base import BaseDataset from .builder import DATASETS from .utils import to_numpy @DATASETS.register_module() class DeepClusterDataset(BaseDataset): """Dataset for DC and ODC. The dataset initializes clustering labels and assigns it during t...
1,623
35.088889
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/datasets/relative_loc.py
# Copyright (c) OpenMMLab. All rights reserved. import torch import torchvision.transforms.functional as TF from mmcv.utils import build_from_cfg from torchvision.transforms import Compose, RandomCrop from .base import BaseDataset from .builder import DATASETS, PIPELINES from .utils import to_numpy def image_to_patc...
3,110
35.174419
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/datasets/utils.py
# Copyright (c) OpenMMLab. All rights reserved. import gzip import hashlib import os import os.path as osp import shutil import tarfile import urllib.error import urllib.request import zipfile import numpy as np import torch def to_numpy(pil_img): np_img = np.array(pil_img, dtype=np.uint8) if np_img.ndim < 3...
6,307
28.476636
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/datasets/multi_view.py
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmcv.utils import build_from_cfg from torchvision.transforms import Compose from .base import BaseDataset from .builder import DATASETS, PIPELINES, build_datasource from .utils import to_numpy @DATASETS.register_module() class MultiViewDataset(BaseDat...
2,427
36.353846
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/datasets/single_view.py
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmcv.utils import print_log from .base import BaseDataset from .builder import DATASETS from .utils import to_numpy @DATASETS.register_module() class SingleViewDataset(BaseDataset): """The dataset outputs one view of an image, containing some othe...
2,631
38.878788
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/datasets/dataset_wrappers.py
# Copyright (c) OpenMMLab. All rights reserved. from torch.utils.data.dataset import ConcatDataset as _ConcatDataset from .builder import DATASETS @DATASETS.register_module() class ConcatDataset(_ConcatDataset): """A wrapper of concatenated dataset. Same as :obj:`torch.utils.data.dataset.ConcatDataset`, but...
1,368
26.938776
78
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/datasets/builder.py
# Copyright (c) OpenMMLab. All rights reserved. import platform import random import warnings from functools import partial import numpy as np import torch from mmcv.parallel import collate from mmcv.runner import get_dist_info from mmcv.utils import Registry, build_from_cfg, digit_version from torch.utils.data import...
6,330
35.385057
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/datasets/data_sources/cifar.py
# Copyright (c) OpenMMLab. All rights reserved. import os.path as osp import pickle import numpy as np import torch.distributed as dist from mmcv.runner import get_dist_info from ..builder import DATASOURCES from ..utils import check_integrity, download_and_extract_archive from .base import BaseDataSource @DATASOUR...
4,483
32.969697
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/datasets/data_sources/imagenet.py
# Copyright (c) OpenMMLab. All rights reserved. import os import os.path as osp import numpy as np from ..builder import DATASOURCES from .base import BaseDataSource def has_file_allowed_extension(filename, extensions): """Checks if a file is an allowed extension. Args: filename (string): path to a...
3,380
32.147059
82
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/datasets/samplers/group_sampler.py
# Copyright (c) OpenMMLab. All rights reserved. import math import numpy as np import torch from mmcv.runner import get_dist_info from torch.utils.data import Sampler class GroupSampler(Sampler): def __init__(self, dataset, samples_per_gpu=1): assert hasattr(dataset, 'flag') self.dataset = datas...
4,914
33.858156
78
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/datasets/samplers/distributed_sampler.py
# Copyright (c) OpenMMLab. All rights reserved. import numpy as np import torch from mmcv.runner import get_dist_info from torch.utils.data import DistributedSampler as _DistributedSampler from torch.utils.data import Sampler from mmselfsup.utils import sync_random_seed class DistributedSampler(_DistributedSampler):...
6,637
34.881081
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/datasets/pipelines/transforms.py
# Copyright (c) OpenMMLab. All rights reserved. import inspect import math import random import warnings from typing import Optional, Sequence, Tuple, Union import numpy as np import torch import torchvision.transforms.functional as F from mmcv.utils import build_from_cfg from PIL import Image, ImageFilter from timm.d...
21,246
34.709244
89
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/utils/collect.py
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import numpy as np import torch from .gather import gather_tensors_batch def nondist_forward_collect(func, data_loader, length): """Forward and collect network outputs. This function performs forward propagation and collects outputs. It can be ...
3,043
33.988506
78
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/utils/dist_utils.py
# Copyright (c) OpenMMLab. All rights reserved. import numpy as np import torch import torch.distributed as dist from mmcv.runner import get_dist_info def sync_random_seed(seed=None, device='cuda'): """Make sure different ranks share the same seed. All workers must call this function, otherwise it will deadlo...
1,587
34.288889
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/utils/setup_env.py
# Copyright (c) OpenMMLab. All rights reserved. import os import platform import warnings import cv2 import torch.multiprocessing as mp def setup_multi_processes(cfg): """Setup multi-processing environment variables.""" # set multi-process start method as `fork` to speed up the training if platform.syste...
2,219
45.25
112
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/utils/alias_multinomial.py
# Copyright (c) OpenMMLab. All rights reserved. import torch class AliasMethod(object): """The alias method for sampling. From: https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/ Args: probs (Tensor): Sampling probabilities. """ # ...
2,195
27.894737
120
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/utils/distributed_sinkhorn.py
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # This file is modified from # https://github.com/facebookresearch/swav/blob/main/main_swav.py import torch import torch.distributed as dist @torch.no_grad() def distributed_sinkhorn(out, sinkhorn_iterations, world_size, epsilon): """Apply the ...
1,390
30.613636
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/utils/gather.py
# Copyright (c) OpenMMLab. All rights reserved. import numpy as np import torch import torch.distributed as dist def gather_tensors(input_array): """Gather tensor from all GPUs.""" world_size = dist.get_world_size() # gather shapes first myshape = input_array.shape mycount = input_array.size s...
3,019
34.529412
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/utils/clustering.py
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # This file is modified from # https://github.com/facebookresearch/deepcluster/blob/master/clustering.py import time try: import faiss except ImportError: faiss = None import numpy as np import torch from scipy.sparse import csr_matrix __al...
8,732
27.821782
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/utils/extractor.py
# Copyright (c) OpenMMLab. All rights reserved. import torch.nn as nn from torch.utils.data import Dataset from mmselfsup.utils import dist_forward_collect, nondist_forward_collect class Extractor(object): """Feature extractor. Args: dataset (Dataset | dict): A PyTorch dataset or dict that indicates...
2,881
37.426667
79
py
mmselfsup-0.x
mmselfsup-0.x/mmselfsup/utils/batch_shuffle.py
# Copyright (c) OpenMMLab. All rights reserved. import torch from .gather import concat_all_gather @torch.no_grad() def batch_shuffle_ddp(x): """Batch shuffle, for making use of BatchNorm. *** Only support DistributedDataParallel (DDP) model. *** """ # gather from all gpus batch_size_this = x.sh...
1,381
24.592593
61
py
mmselfsup-0.x
mmselfsup-0.x/configs/benchmarks/mmdetection/_base_/models/mask_rcnn_r50_fpn.py
# model settings model = dict( type='MaskRCNN', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=True, style='pytorch', init_cfg=dict(ty...
4,054
32.512397
79
py
mmselfsup-0.x
mmselfsup-0.x/configs/benchmarks/mmdetection/_base_/models/mask_rcnn_r50_c4.py
# model settings norm_cfg = dict(type='BN', requires_grad=False) model = dict( type='MaskRCNN', backbone=dict( type='ResNet', depth=50, num_stages=3, strides=(1, 2, 2), dilations=(1, 1, 1), out_indices=(2, ), frozen_stages=1, norm_cfg=norm_cfg, ...
4,024
31.459677
79
py
mmselfsup-0.x
mmselfsup-0.x/configs/benchmarks/mmdetection/_base_/models/faster_rcnn_r50_c4.py
# model settings norm_cfg = dict(type='BN', requires_grad=False) model = dict( type='FasterRCNN', backbone=dict( type='ResNet', depth=50, num_stages=3, strides=(1, 2, 2), dilations=(1, 1, 1), out_indices=(2, ), frozen_stages=1, norm_cfg=norm_cfg, ...
3,657
31.371681
79
py
mmselfsup-0.x
mmselfsup-0.x/configs/benchmarks/mmsegmentation/_base_/models/fcn_r50-d8.py
# model settings norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( type='EncoderDecoder', backbone=dict( type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), dilations=(1, 1, 2, 4), strides=(1, 2, 1, 1), norm_cfg=norm_cfg, ...
1,317
27.652174
79
py
mmselfsup-0.x
mmselfsup-0.x/docs/en/conf.py
# Copyright (c) OpenMMLab. All rights reserved. # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -----------------------...
4,244
32.425197
134
py
mmselfsup-0.x
mmselfsup-0.x/docs/zh_cn/conf.py
# Copyright (c) OpenMMLab. All rights reserved. # Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -----------------------...
4,100
31.039063
90
py
unlimiformer
unlimiformer-main/src/inference-example.py
from unlimiformer import Unlimiformer from random_training_unlimiformer import RandomTrainingUnlimiformer from usage import UnlimiformerArguments, training_addin from transformers import BartForConditionalGeneration, AutoTokenizer from datasets import load_dataset import torch device = torch.device('cuda' if torch.cu...
2,317
38.965517
115
py
unlimiformer
unlimiformer-main/src/random_training_unlimiformer.py
import contextlib import numpy as np import torch from torch import nn from enum import Enum, auto from unlimiformer import Unlimiformer, ModelType, UnlimiformerBART, UnlimiformerT5, UnlimiformerLED from transformers import BartModel, BartForConditionalGeneration, \ T5Model, T5ForConditionalGeneration, \ LEDMod...
11,565
50.633929
139
py
unlimiformer
unlimiformer-main/src/unlimiformer.py
import logging import numpy as np import torch from torch import nn from enum import Enum, auto from transformers import BartModel, BartForConditionalGeneration, \ T5Model, T5ForConditionalGeneration, \ LEDModel, LEDForConditionalGeneration, \ AutoModelForSeq2SeqLM from typing import TypeVar, Generic from...
50,326
53.52546
178
py
unlimiformer
unlimiformer-main/src/run.py
#!/usr/bin/env python # coding=utf-8 # Copyright 2021 The HuggingFace Team. 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...
52,495
43.450466
171
py
unlimiformer
unlimiformer-main/src/index_building.py
import faiss import faiss.contrib.torch_utils import time import logging import torch import numpy as np code_size = 64 class DatastoreBatch(): def __init__(self, dim, batch_size, flat_index=False, gpu_index=False, verbose=False) -> None: self.indices = [] self.batch_size = batch_size for...
5,479
39
116
py
unlimiformer
unlimiformer-main/src/utils/override_training_args.py
import os import sys import torch.cuda from transformers.utils import logging sys.path.insert(0, os.getcwd()) from dataclasses import dataclass, field from transformers.trainer_utils import IntervalStrategy from transformers import Seq2SeqTrainingArguments logger = logging.get_logger('swed_logger') @dataclass cl...
5,685
52.140187
138
py
unlimiformer
unlimiformer-main/src/utils/custom_seq2seq_trainer.py
import json import math import os import time from collections import defaultdict from typing import Any, Dict, List, Optional, Tuple, Union import torch from datasets import Dataset from torch import nn from transformers.debug_utils import DebugOption from transformers.deepspeed import is_deepspeed_zero3_enabled from...
14,785
43.942249
158
py
hessian-eff-dim
hessian-eff-dim-master/setup.py
from setuptools import setup import os import sys _here = os.path.abspath(os.path.dirname(__file__)) if sys.version_info[0] < 3: with open(os.path.join(_here, 'README.rst')) as f: long_description = f.read() else: with open(os.path.join(_here, 'README.rst'), encoding='utf-8') as f: long_descri...
1,026
25.333333
72
py
hessian-eff-dim
hessian-eff-dim-master/hess/utils.py
import torch import time import numpy as np import hess from torch import nn import torch.nn.functional as F from torch.autograd import Variable from gpytorch.utils.lanczos import lanczos_tridiag, lanczos_tridiag_to_diag def unflatten_like(vector, likeTensorList): # Takes a flat torch.tensor and unflattens it to ...
9,414
36.066929
94
py
hessian-eff-dim
hessian-eff-dim-master/hess/net_utils.py
import torch import time import numpy as np #import hess from .nets import SubLayerLinear, GetSubnet, MaskedLinear from torch import nn def freeze_model_weights(model): print("=> Freezing model weights") for n, m in model.named_modules(): if hasattr(m, "weight") and m.weight is not None: p...
2,720
31.011765
72
py
hessian-eff-dim
hessian-eff-dim-master/hess/loss_surfaces/dataloader_loss_surface.py
import math import torch import numpy as np from .. import utils from .loss_surfaces import get_plane def dataloader_loss_surface(basis, model, dataloader, loss=torch.nn.MSELoss(), rng=0.1, n_pts=25, **kwargs): start_pars = model.state_dict() ## get ...
1,191
31.216216
75
py
hessian-eff-dim
hessian-eff-dim-master/hess/loss_surfaces/loss_surfaces.py
import math import torch import numpy as np from .. import utils def get_loss_surface(basis, model, train_x, train_y, loss, rng=0.1, n_pts=25, use_cuda=False, **kwargs): """ note that loss should be a lambda function that just take...
1,846
27.859375
76
py
hessian-eff-dim
hessian-eff-dim-master/hess/nets/linear_subnet_layers.py
import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import math from .conv_type import GetSubnet class SubLayerLinear(nn.Linear): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.scores = nn.Parameter(torch.Tensor(self.we...
1,291
29.046512
87
py
hessian-eff-dim
hessian-eff-dim-master/hess/nets/moon_net.py
import torch import math from torch import nn class MoonNet(nn.Module): """docstring for SimpleNet.""" def __init__(self, x, y, hidden_size=10, n_hidden=2, activation=torch.nn.ReLU(), bias=False): super(MoonNet, self).__init__() self.x = x #inputs in G space self.y = y #...
1,203
31.540541
73
py
hessian-eff-dim
hessian-eff-dim-master/hess/nets/simple_net.py
import torch import math from torch import nn class SimpleNet(nn.Module): """docstring for SimpleNet.""" def __init__(self, in_dim, out_dim, hidden_size=10, n_hidden=2, activation=torch.nn.ReLU(), bias=False): super(SimpleNet, self).__init__() ## initialize the network ## ...
772
29.92
73
py
hessian-eff-dim
hessian-eff-dim-master/hess/nets/masked_layer.py
import math import torch import torch.nn as nn from torch.nn import Module, init, Linear, Conv2d from torch.nn.parameter import Parameter import torch.nn.functional as F from torch.nn.modules.utils import _pair class MaskedLinear(Linear): #__constants__ = ['bias', 'in_features', 'out_features'] def __init__(s...
3,241
45.314286
110
py
hessian-eff-dim
hessian-eff-dim-master/hess/nets/preresnet.py
""" PreResNet model definition ported from https://github.com/bearpaw/pytorch-classification/blob/master/models/cifar/preresnet.py """ import torch.nn as nn import torchvision.transforms as transforms import math from .masked_layer import MaskedConv2d, MaskedLinear __all__ = ["PreResNet110", "PreResNet56", "...
9,014
29.150502
106
py
hessian-eff-dim
hessian-eff-dim-master/hess/nets/conv_type.py
import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import math DenseConv = nn.Conv2d class GetSubnet(autograd.Function): @staticmethod def forward(ctx, scores, k): # Get the subnetwork by sorting the scores and using the top k% out = scores.c...
4,184
25.826923
82
py
hessian-eff-dim
hessian-eff-dim-master/hess/nets/resnet.py
## ResNet18 for CIFAR ## Based on: https://github.com/kuangliu/pytorch-cifar/blob/master/models/preact_resnet.py import torch.nn as nn import torch.nn.functional as F from torchvision import transforms __all__ = ["ResNet18"] class PreActBlock(nn.Module): '''Pre-activation version of the BasicBlock.''' expan...
3,536
35.84375
92
py
hessian-eff-dim
hessian-eff-dim-master/hess/nets/linear_subnets.py
import torch from torch import nn from .linear_subnet_layers import SubLayerLinear from .masked_layer import MaskedLinear class SubNetLinear(nn.Module): """ Small MLP """ def __init__(self, in_dim, out_dim, k=16, n_layers=5, activation=nn.ReLU(), bias=True): sup...
1,712
27.55
60
py
hessian-eff-dim
hessian-eff-dim-master/hess/nets/vgg.py
""" VGG model definition ported from https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py """ import math import torch.nn as nn import torchvision.transforms as transforms from .masked_layer import MaskedLinear, MaskedConv2d __all__ = ["VGG16", "VGG16BN", "VGG19", "VGG19BN"] def make_laye...
3,610
22.448052
110
py
hessian-eff-dim
hessian-eff-dim-master/hess/nets/cifar_net.py
import torch import torch.nn as nn import torch.nn.functional as F def ConvBNrelu(in_channels,out_channels,stride=1): return nn.Sequential( nn.Conv2d(in_channels,out_channels,3,padding=1,stride=stride), nn.BatchNorm2d(out_channels), nn.ReLU() ) class cifar_net(nn.Module): """ Ve...
1,252
26.844444
70
py
hessian-eff-dim
hessian-eff-dim-master/hess/nets/wide_resnet.py
""" WideResNet model definition ported from https://github.com/meliketoy/wide-resnet.pytorch/blob/master/networks/wide_resnet.py """ import torchvision.transforms as transforms import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F import math from .masked_layer import MaskedConv2d...
3,816
31.07563
100
py
hessian-eff-dim
hessian-eff-dim-master/hess/nets/transformer.py
import math import torch from torch import nn from .simple_net import SimpleNet class Transformer(nn.Module): """docstring for Transformer.""" def __init__(self, x, y, net=SimpleNet, **kwargs): super(Transformer, self).__init__() self.x = x self.y = y self.net = net(x, y, **kwa...
855
24.176471
71
py
hessian-eff-dim
hessian-eff-dim-master/hess/nets/simple_lstm.py
import torch import math from torch import nn class LSTM(nn.Module): def __init__(self, train_x, train_y, n_hidden=2, hidden_size=10, input_dim=1, output_dim=1, batch_size=1): super(LSTM, self).__init__() self.input_dim = 1 self.hidden_dim = hidden_size ...
686
26.48
77
py
hessian-eff-dim
hessian-eff-dim-master/hess/nets/convnet.py
## 5-Layer CNN for CIFAR ## Based on https://myrtle.ai/learn/how-to-train-your-resnet-4-architecture/ # based on https://gitlab.com/harvard-machine-learning/double-descent/blob/master/models/mcnn.py from torchvision import transforms import torch.nn as nn def block(input, output): # Layer i list = [nn.Conv2d...
4,293
32.286822
96
py
hessian-eff-dim
hessian-eff-dim-master/hess/nets/masked_net.py
import torch import math from torch import nn from .masked_layer import MaskedLinear class MaskedNet(nn.Module): """docstring for SimpleNet.""" def __init__(self, x, y, hidden_size=10, n_hidden=2, activation=torch.nn.ReLU(), bias=False, pct_keep=0.6): super(MaskedNet, self).__init__() ...
1,350
32.775
75
py
hessian-eff-dim
hessian-eff-dim-master/hess/plotting/decision_boundary.py
import math import torch import numpy as np import matplotlib.pyplot as plt def plot_decision_boundary(train_x, train_y, classifier, use_cuda=False, buffer=0.5, h=0.1): x_min, x_max = train_x[:, 0].min() - buffer, train_x[:, 0].max() + buffer y_min, y_max = train_x[:, 1].min() - buff...
852
39.619048
100
py
hessian-eff-dim
hessian-eff-dim-master/hess/runners/cifar10_runner.py
import math import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import torch.optim as optim import argparse import sys from hess.nets.cifar_net import cifar_net def parse(): parser = argparse.ArgumentParser() parser.add_argument('--epochs', help="number of epochs",...
2,768
32.768293
82
py
hessian-eff-dim
hessian-eff-dim-master/hess/data/data.py
import numpy as np import torch import torchvision import os from .fake import FakeData __all__ = ['loaders'] c10_classes = np.array([[0, 1, 2, 8, 9], [3, 4, 5, 6, 7]], dtype=np.int32) def svhn_loaders( path, batch_size, num_workers, transform_train, transform_test, use_validation, val_s...
5,916
29.34359
87
py
hessian-eff-dim
hessian-eff-dim-master/hess/data/fake.py
import torch from torchvision.datasets.vision import VisionDataset from torchvision import transforms class FakeData(VisionDataset): """A fake dataset that returns randomly generated images and returns them as PIL images Args: size (int, optional): Size of the dataset. Default: 1000 images ima...
2,405
39.1
91
py
hessian-eff-dim
hessian-eff-dim-master/hess/eigs/fisher_vec_prod.py
""" compute hessian vector products as well as eigenvalues of the hessian # copied from https://github.com/tomgoldstein/loss-landscape/blob/master/hess_vec_prod.py # code re-written to use gpu by default and then to use gpytorch """ import torch import time # import numpy as np # from torch import nn # fr...
6,396
33.208556
112
py
hessian-eff-dim
hessian-eff-dim-master/hess/eigs/hess_vec_prod.py
""" compute hessian vector products as well as eigenvalues of the hessian # copied from https://github.com/tomgoldstein/loss-landscape/blob/master/hess_vec_prod.py # code re-written to use gpu by default and then to use gpytorch """ import torch import time import numpy as np from torch import nn from torc...
6,027
35.533333
108
py
hessian-eff-dim
hessian-eff-dim-master/hess/eigs/obsfisher_vec_prod.py
""" compute hessian vector products as well as eigenvalues of the hessian # copied from https://github.com/tomgoldstein/loss-landscape/blob/master/hess_vec_prod.py # code re-written to use gpu by default and then to use gpytorch """ import torch import time # import numpy as np # from torch import nn # fr...
5,670
36.556291
136
py
hessian-eff-dim
hessian-eff-dim-master/hess/eigs/hessian_eigenpairs.py
import torch import time import numpy as np from torch import nn from torch.autograd import Variable from gpytorch.utils.lanczos import lanczos_tridiag, lanczos_tridiag_to_diag from hess.utils import flatten, unflatten_like, gradtensor_to_tensor from hess.utils import eval_hess_vec_prod def hessian_eigenpairs(net, cri...
1,524
32.152174
77
py
hessian-eff-dim
hessian-eff-dim-master/hess/eigs/run_hess_eigs.py
""" script to compute maximum and minimum eigenvalues of the hessian """ import argparse import torch # import torch.nn.functional as F import numpy as np # import os # import tqdm from swag import models, data from hess_vec_prod import min_max_hessian_eigs from fisher_vec_prod import min_max_fisher_eigs from o...
3,984
25.744966
89
py
hessian-eff-dim
hessian-eff-dim-master/hess/losses/trace_loss.py
import torch import torch.nn.functional as F import copy from ..utils import flatten, unflatten_like def fisher_trace(inputs, targets, diag_pars, model, base_loss = F.cross_entropy, beta = 0.01, samples = 1, nugget=1e-5): model_state_dict = copy.deepcopy(model.state_dict()) param_vec = flatten(model.parameter...
1,150
33.878788
120
py
hessian-eff-dim
hessian-eff-dim-master/experiments/test_subnets_cifar.py
import math import torch import hess import hess.utils as utils import hess.nets import numpy as np import pickle import argparse import os, sys import time import tabulate import swag.utils as training_utils import swag from hess import data import hess.nets as models from parser import parser columns = ["ep", "lr",...
5,889
32.089888
103
py
hessian-eff-dim
hessian-eff-dim-master/experiments/test_subnets_spirals.py
import math import torch import hess import hess.utils as utils import hess.nets import numpy as np import pickle def twospirals(n_points, noise=.5, random_state=920): """ Returns the two spirals dataset. """ n = np.sqrt(np.random.rand(n_points,1)) * 600 * (2*np.pi)/360 d1x = -1.5*np.cos(n)*n + np...
3,461
30.761468
82
py
hessian-eff-dim
hessian-eff-dim-master/experiments/gen-bounds/compute_sigma_norm.py
import math import torch import torchvision import hess from hess.nets import ConvNetDepth import torchvision from torchvision import transforms from norms import perturb_model, compute_accuracy, sharpness_sigma def main(): use_cuda = torch.cuda.is_available() ## load in a loader just for sizing ## tra...
2,225
30.352113
85
py
hessian-eff-dim
hessian-eff-dim-master/experiments/gen-bounds/model_checker.py
import math import torch import torchvision import hess from hess.nets import ConvNetDepth import torchvision from torchvision import transforms ## model sizes ## depths = torch.arange(9) widths = torch.arange(4, 65, 4) num_classes = 100 use_cuda = torch.cuda.is_available() for d_ind, dpth in enumerate(depths): ...
848
26.387097
79
py
hessian-eff-dim
hessian-eff-dim-master/experiments/gen-bounds/norms.py
import torch import math import copy import warnings import torch.nn as nn import numpy as np from hess import utils # This function calculates path-norm introduced in Neyshabur et al. 2015 def lp_path_norm(model, device, p=2, input_size=[3, 32, 32]): tmp_model = copy.deepcopy(model) tmp_model.eval() for ...
2,782
31.360465
91
py
hessian-eff-dim
hessian-eff-dim-master/experiments/gen-bounds/compute_sigma_norm_resnets.py
import math import torch import torchvision import hess from hess.nets import PreActBlock, PreActResNet import torchvision from torchvision import transforms from norms import sharpness_sigma def main(): use_cuda = torch.cuda.is_available() print("use cuda = ", use_cuda) ## load in a loader just for si...
2,052
29.641791
85
py
hessian-eff-dim
hessian-eff-dim-master/experiments/gen-bounds/compute_pac_bayes.py
import math import torch import torchvision import hess from hess.nets import PreActBlock, PreActResNet import torchvision from torchvision import transforms from norms import lp_path_norm from hess import utils def main(): use_cuda = torch.cuda.is_available() ## load in a loader just for sizing ## tra...
1,734
26.983871
85
py
hessian-eff-dim
hessian-eff-dim-master/experiments/gen-bounds/compute_path_norm_resenets.py
import math import torch import torchvision import hess from hess.nets import PreActResNet, PreActBlock import torchvision from torchvision import transforms from norms import lp_path_norm def main(): ## load in a loader just for sizing ## transform = transforms.Compose( [ transforms.Resiz...
1,799
29.508475
93
py