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
Few-shot-WSI
Few-shot-WSI-master/openselfsup/datasets/byol.py
import torch from torch.utils.data import Dataset from openselfsup.utils import build_from_cfg from torchvision.transforms import Compose from .registry import DATASETS, PIPELINES from .builder import build_datasource from .utils import to_numpy @DATASETS.register_module class BYOLDataset(Dataset): """Dataset ...
1,284
29.595238
74
py
Few-shot-WSI
Few-shot-WSI-master/openselfsup/datasets/contrastive.py
import torch from PIL import Image from .registry import DATASETS from .base import BaseDataset from .utils import to_numpy @DATASETS.register_module class ContrastiveDataset(BaseDataset): """Dataset for contrastive learning methods that forward two views of the image at a time (MoCo, SimCLR). """ ...
1,210
34.617647
81
py
Few-shot-WSI
Few-shot-WSI-master/openselfsup/datasets/data_sources/cifar.py
from abc import ABCMeta, abstractmethod from PIL import Image from torchvision.datasets import CIFAR10, CIFAR100 from ..registry import DATASOURCES class Cifar(metaclass=ABCMeta): CLASSES = None def __init__(self, root, split, return_label=True): assert split in ['train', 'test'] self.root...
1,990
26.273973
76
py
Few-shot-WSI
Few-shot-WSI-master/openselfsup/datasets/loader/sampler.py
from __future__ import division import math 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 class DistributedSampler(_DistributedSampler): def __init__(self, dataset...
10,628
34.079208
92
py
Few-shot-WSI
Few-shot-WSI-master/openselfsup/datasets/loader/build_loader.py
import platform import random import torch from functools import partial import numpy as np from mmcv.parallel import collate from mmcv.runner import get_dist_info from torch.utils.data import DataLoader #from .sampler import DistributedGroupSampler, DistributedSampler, GroupSampler from .sampler import DistributedSa...
4,179
30.428571
92
py
Few-shot-WSI
Few-shot-WSI-master/openselfsup/datasets/pipelines/transforms.py
import cv2 import inspect import numpy as np from PIL import Image, ImageFilter import torch from torchvision import transforms as _transforms from openselfsup.utils import build_from_cfg from ..registry import PIPELINES # register all existing transforms in torchvision _EXCLUDED_TRANSFORMS = ['GaussianBlur'] for ...
3,142
26.330435
80
py
Few-shot-WSI
Few-shot-WSI-master/openselfsup/hooks/extractor.py
import torch.nn as nn from torch.utils.data import Dataset from openselfsup.utils import nondist_forward_collect, dist_forward_collect class Extractor(object): """Feature extractor. Args: dataset (Dataset | dict): A PyTorch dataset or dict that indicates the dataset. imgs_per_gpu...
2,196
34.435484
77
py
Few-shot-WSI
Few-shot-WSI-master/openselfsup/hooks/validate_hook.py
from mmcv.runner import Hook import torch from torch.utils.data import Dataset from openselfsup.utils import nondist_forward_collect, dist_forward_collect from .registry import HOOKS @HOOKS.register_module class ValidateHook(Hook): """Validation hook. Args: dataset (Dataset | dict): A PyTorch datas...
3,003
33.528736
77
py
Few-shot-WSI
Few-shot-WSI-master/openselfsup/hooks/deepcluster_hook.py
import numpy as np from mmcv.runner import Hook import torch import torch.distributed as dist from openselfsup.third_party import clustering as _clustering from openselfsup.utils import print_log from .registry import HOOKS from .extractor import Extractor @HOOKS.register_module class DeepClusterHook(Hook): ""...
4,637
36.104
79
py
Few-shot-WSI
Few-shot-WSI-master/openselfsup/utils/contextmanagers.py
# coding: utf-8 import asyncio import contextlib import logging import os import time from typing import List import torch logger = logging.getLogger(__name__) DEBUG_COMPLETED_TIME = bool(os.environ.get('DEBUG_COMPLETED_TIME', False)) @contextlib.asynccontextmanager async def completed(trace_name='', ...
4,103
32.365854
79
py
Few-shot-WSI
Few-shot-WSI-master/openselfsup/utils/optimizers.py
import torch from torch.optim.optimizer import Optimizer, required from torch.optim import * class LARS(Optimizer): r"""Implements layer-wise adaptive rate scaling for SGD. Args: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float): b...
4,327
35.991453
88
py
Few-shot-WSI
Few-shot-WSI-master/openselfsup/utils/profiling.py
import contextlib import sys import time import torch if sys.version_info >= (3, 7): @contextlib.contextmanager def profile_time(trace_name, name, enabled=True, stream=None, end_stream=None): """Print time spent by CP...
1,363
32.268293
74
py
Few-shot-WSI
Few-shot-WSI-master/openselfsup/utils/collect.py
import numpy as np import mmcv 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 used to collect results, features, losses, etc....
2,773
32.02381
78
py
Few-shot-WSI
Few-shot-WSI-master/openselfsup/utils/alias_multinomial.py
import torch import numpy as np 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. """ def __init__(self, probs): ...
2,132
27.065789
120
py
Few-shot-WSI
Few-shot-WSI-master/openselfsup/utils/gather.py
import numpy as np import torch import torch.distributed as dist def gather_tensors(input_array): world_size = dist.get_world_size() ## gather shapes first myshape = input_array.shape mycount = input_array.size shape_tensor = torch.Tensor(np.array(myshape)).cuda() all_shape = [ torch....
2,629
36.571429
100
py
Few-shot-WSI
Few-shot-WSI-master/openselfsup/utils/collect_env.py
import os.path as osp import subprocess import sys from collections import defaultdict import cv2 import mmcv import torch import torchvision import openselfsup def collect_env(): """Collect the information of the running environments.""" env_info = {} env_info['sys.platform'] = sys.platform env_inf...
2,055
30.630769
81
py
Few-shot-WSI
Few-shot-WSI-master/openselfsup/utils/flops_counter.py
# Modified from flops-counter.pytorch by Vladislav Sovrasov # original repo: https://github.com/sovrasov/flops-counter.pytorch # MIT License # Copyright (c) 2018 Vladislav Sovrasov # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (th...
14,304
31.146067
79
py
rivuletpy
rivuletpy-master/filtering/riveal.py
import numpy as np import math import skfmm from tqdm import tqdm from scipy.ndimage.morphology import binary_dilation from keras.models import Sequential from keras.layers import Dense, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D from keras.layers.noise import GaussianDropout, GaussianNois...
8,673
32.233716
78
py
Mr.Right
Mr.Right-main/main.py
import yaml import os import utils import warnings from argparse import ArgumentParser from torch import nn from pytorch_lightning import Trainer,seed_everything from pytorch_lightning import loggers as pl_loggers from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.callbacks import ModelCheckpoint,...
5,871
42.496296
150
py
Mr.Right
Mr.Right-main/pltrainer.py
import pdb import utils import json import pickle import torch import os import torch.nn.functional as F import torch.distributed as dist import pytorch_lightning as pl from metric import score from scheduler import CosineLRScheduler from tqdm import tqdm class TextToMultiTrainer(pl.LightningModule): def __init__(...
43,280
57.095302
126
py
Mr.Right
Mr.Right-main/metric.py
import numpy as np import torch import pdb from torchmetrics.functional import retrieval_recall,retrieval_reciprocal_rank @torch.no_grad() def score(scores_t2m, query_doc_id): """ scores_t2m: (q_size, d_size) query_doc_id: (q_size) """ ids = query_doc_id.unsqueeze(1) top1_i = torch.topk(scores...
1,097
30.371429
103
py
Mr.Right
Mr.Right-main/scheduler/cosine_lr.py
""" Cosine Scheduler Cosine LR schedule with warmup, cycle/restarts, noise. Hacked together by / Copyright 2020 Ross Wightman """ import logging import math import numpy as np import torch from .scheduler import Scheduler from pdb import set_trace as breakpoint _logger = logging.getLogger(__name__) class CosineL...
4,027
33.135593
121
py
Mr.Right
Mr.Right-main/scheduler/scheduler.py
from typing import Dict, Any import torch class Scheduler: """ Parameter Scheduler Base Class A scheduler base class that can be used to schedule any optimizer parameter groups. Unlike the builtin PyTorch schedulers, this is intended to be consistently called * At the END of each epoch, before incre...
4,750
43.820755
112
py
Mr.Right
Mr.Right-main/models/matching.py
import torch import torch.nn as nn import torch.nn.functional as F class MatchingModel(nn.Module): def __init__(self, args, config, text_width, n_layers): super().__init__() self.config = config from models.ALBEF.models.xbert import BertModel self.config.num_hidden_layers =...
1,817
29.3
89
py
Mr.Right
Mr.Right-main/models/model.py
import pdb import torch import torch.nn.functional as F from torch import nn from models.ALBEF.models.model_retrieval import ALBEF from models.ALBEF.models.vit import interpolate_pos_embed from models.ALBEF.models.xbert import BertOnlyMLMHead,BertConfig from models.ViLT.vilt.modules import ViLTransformerSS from models....
21,799
50.294118
151
py
Mr.Right
Mr.Right-main/models/METER/azure_distributed_run.py
import os import copy import pytorch_lightning as pl import os os.environ["NCCL_DEBUG"] = "INFO" from meter.config import ex from meter.modules import METERTransformerSS from meter.datamodules.multitask_datamodule import MTDataModule import resource rlimit = resource.getrlimit(resource.RLIMIT_NOFILE) resource.setrlim...
4,388
31.272059
97
py
Mr.Right
Mr.Right-main/models/METER/setup.py
from setuptools import setup, find_packages setup( name="meter", packages=find_packages( exclude=[".dfc", ".vscode", "dataset", "notebooks", "result", "scripts"] ), version="0.1.0", license="MIT", description="METER: Multimodal End-to-end TransformER", author="Microsoft Corporation"...
511
29.117647
80
py
Mr.Right
Mr.Right-main/models/METER/run.py
import os import copy import pytorch_lightning as pl import os os.environ["NCCL_DEBUG"] = "INFO" from meter.config import ex from meter.modules import METERTransformerSS from meter.datamodules.multitask_datamodule import MTDataModule import resource rlimit = resource.getrlimit(resource.RLIMIT_NOFILE) resource.setrlim...
2,373
29.050633
97
py
Mr.Right
Mr.Right-main/models/METER/meter/modules/clip_model.py
from collections import OrderedDict from typing import Tuple, Union import numpy as np import torch import torch.nn.functional as F from torch import nn class LayerNorm(nn.LayerNorm): """Subclass torch's LayerNorm to handle fp16.""" def forward(self, x: torch.Tensor): orig_type = x.dtype ret...
11,209
39.179211
142
py
Mr.Right
Mr.Right-main/models/METER/meter/modules/meter_utils.py
import torch import random from transformers.optimization import AdamW from transformers import ( get_polynomial_decay_schedule_with_warmup, get_cosine_schedule_with_warmup, ) from .dist_utils import all_gather from .objectives import compute_irtr_recall from ..gadgets.my_metrics import Accuracy, VQAScore, Sca...
11,926
38.363036
100
py
Mr.Right
Mr.Right-main/models/METER/meter/modules/swin_transformer.py
""" Swin Transformer A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` - https://arxiv.org/pdf/2103.14030 Code/weights from https://github.com/microsoft/Swin-Transformer, original copyright/license info below """ # -------------------------------------------------------- ...
27,086
41.191589
125
py
Mr.Right
Mr.Right-main/models/METER/meter/modules/bert_model.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a cop...
76,774
41.915036
213
py
Mr.Right
Mr.Right-main/models/METER/meter/modules/meter_module.py
import torch import torch.nn as nn import pytorch_lightning as pl import numpy as np import pdb from transformers.models.bert.modeling_bert import BertConfig, BertEmbeddings, BertModel, BertEncoder, BertLayer from .bert_model import BertCrossLayer, BertAttention from . import swin_transformer as swin from . import head...
15,962
40.141753
134
py
Mr.Right
Mr.Right-main/models/METER/meter/modules/dist_utils.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ This file contains primitives for multi-gpu communication. This is useful when doing distributed training. """ import functools import logging import numpy as np import pickle import torch import torch.distributed as dist import torch _LOCAL_...
7,814
27.837638
100
py
Mr.Right
Mr.Right-main/models/METER/meter/modules/objectives.py
import torch import torch.nn as nn import torch.nn.functional as F import os import glob import json import tqdm import functools from torch.utils.data.distributed import DistributedSampler from einops import rearrange from .dist_utils import all_gather def compute_mlm(pl_module, batch): infer = pl_module.infer...
17,360
33.514911
88
py
Mr.Right
Mr.Right-main/models/METER/meter/modules/swin_helpers.py
""" Model creation / weight loading / state_dict helpers Hacked together by / Copyright 2020 Ross Wightman """ import logging import os import math from collections import OrderedDict from copy import deepcopy from typing import Any, Callable, Optional, Tuple import torch import torch.nn as nn from timm.models.featu...
23,550
43.519849
153
py
Mr.Right
Mr.Right-main/models/METER/meter/modules/heads.py
import torch import torch.nn as nn import torch.nn.functional as F from transformers.models.bert.modeling_bert import BertPredictionHeadTransform class Pooler(nn.Module): def __init__(self, hidden_size): super().__init__() self.dense = nn.Linear(hidden_size, hidden_size) self.activation =...
1,257
27.590909
83
py
Mr.Right
Mr.Right-main/models/METER/meter/transforms/transform.py
from .utils import ( inception_normalize, imagenet_normalize, MinMaxResize, ) from PIL import Image from torchvision import transforms from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize from .randaug import RandAugment def pixelbert_transform(size=800): longer = int((1...
2,733
26.34
93
py
Mr.Right
Mr.Right-main/models/METER/meter/transforms/utils.py
from torchvision import transforms from PIL import Image class MinMaxResize: def __init__(self, shorter=800, longer=1333): self.min = shorter self.max = longer def __call__(self, x): w, h = x.size scale = self.min / min(w, h) if h < w: newh, neww = self.min...
1,792
27.919355
98
py
Mr.Right
Mr.Right-main/models/METER/meter/transforms/randaug.py
# code in this file is adpated from rpmcruz/autoaugment # https://github.com/rpmcruz/autoaugment/blob/master/transformations.py import random import PIL, PIL.ImageOps, PIL.ImageEnhance, PIL.ImageDraw import numpy as np import torch from PIL import Image def ShearX(img, v): # [-0.3, 0.3] assert -0.3 <= v <= 0.3 ...
6,990
24.892593
134
py
Mr.Right
Mr.Right-main/models/ALBEF/models/xbert.py
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a cop...
82,187
41.873239
213
py
Mr.Right
Mr.Right-main/models/ALBEF/models/vit.py
import torch import torch.nn as nn import torch.nn.functional as F from functools import partial from timm.models.vision_transformer import _cfg, PatchEmbed from timm.models.registry import register_model from timm.models.layers import trunc_normal_, DropPath class Mlp(nn.Module): """ MLP as used in Vision Trans...
8,558
41.162562
118
py
Mr.Right
Mr.Right-main/models/ALBEF/models/model_retrieval.py
from functools import partial from models.ALBEF.models.vit import VisionTransformer from models.ALBEF.models.xbert import BertConfig, BertModel import torch from torch import nn import torch.nn.functional as F class ALBEF(nn.Module): def __init__(self, text_encoder = None, ...
3,499
45.666667
129
py
Mr.Right
Mr.Right-main/models/ViLT/vilt/modules/vilt_utils.py
import torch import random from transformers.optimization import AdamW from transformers import ( get_polynomial_decay_schedule_with_warmup, get_cosine_schedule_with_warmup, ) from models.ViLT.vilt.modules.dist_utils import all_gather from models.ViLT.vilt.modules.objectives import compute_irtr_recall from mod...
10,650
37.451264
88
py
Mr.Right
Mr.Right-main/models/ViLT/vilt/modules/dist_utils.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ This file contains primitives for multi-gpu communication. This is useful when doing distributed training. """ import functools import logging import numpy as np import pickle import torch import torch.distributed as dist import torch _LOCAL_...
7,814
27.837638
100
py
Mr.Right
Mr.Right-main/models/ViLT/vilt/modules/objectives.py
import torch import torch.nn as nn import torch.nn.functional as F import os import glob import json import tqdm import functools from torch.utils.data.distributed import DistributedSampler from einops import rearrange from models.ViLT.vilt.modules.dist_utils import all_gather def cost_matrix_cosine(x, y, eps=1e-5)...
22,098
32.842266
88
py
Mr.Right
Mr.Right-main/models/ViLT/vilt/modules/vilt_module.py
import torch torch.autograd.set_detect_anomaly(True) import torch.nn as nn import pytorch_lightning as pl import models.ViLT.vilt.modules.vision_transformer as vit import pdb from transformers.models.bert.modeling_bert import BertConfig, BertEmbeddings from models.ViLT.vilt.modules import heads, objectives # from model...
10,172
28.148997
119
py
Mr.Right
Mr.Right-main/models/ViLT/vilt/modules/vision_transformer.py
""" Vision Transformer (ViT) in PyTorch A PyTorch implement of Vision Transformers as described in 'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929 The official jax code is released and available at https://github.com/google-research/vision_transformer ...
49,034
34.558376
155
py
Mr.Right
Mr.Right-main/models/ViLT/vilt/modules/heads.py
import torch import torch.nn as nn import torch.nn.functional as F from transformers.models.bert.modeling_bert import BertPredictionHeadTransform class Pooler(nn.Module): def __init__(self, hidden_size): super().__init__() self.dense = nn.Linear(hidden_size, hidden_size) self.activation =...
1,569
27.035714
83
py
Mr.Right
Mr.Right-main/models/ViLT/vilt/transforms/utils.py
from torchvision import transforms from PIL import Image class MinMaxResize: def __init__(self, shorter=800, longer=1333): self.min = shorter self.max = longer def __call__(self, x): w, h = x.size scale = self.min / min(w, h) if h < w: newh, neww = self.min...
1,645
27.877193
98
py
Mr.Right
Mr.Right-main/models/ViLT/vilt/transforms/randaug.py
# code in this file is adpated from rpmcruz/autoaugment # https://github.com/rpmcruz/autoaugment/blob/master/transformations.py import random import PIL, PIL.ImageOps, PIL.ImageEnhance, PIL.ImageDraw import numpy as np import torch from PIL import Image def ShearX(img, v): # [-0.3, 0.3] assert -0.3 <= v <= 0.3 ...
6,990
24.892593
134
py
Mr.Right
Mr.Right-main/models/ViLT/vilt/transforms/pixelbert.py
from .utils import ( inception_normalize, MinMaxResize, ) from torchvision import transforms from .randaug import RandAugment def pixelbert_transform(size=800): longer = int((1333 / 800) * size) return transforms.Compose( [ MinMaxResize(shorter=size, longer=longer), tra...
714
22.064516
54
py
Mr.Right
Mr.Right-main/data/data_module.py
import random import torch import os import json import pickle from torch.utils.data import Dataset, DataLoader from torchvision.transforms import Compose, ToTensor, Normalize, Resize, RandomResizedCrop, RandomHorizontalFlip from pytorch_lightning import LightningDataModule from data.utils import pre_caption, RandomAug...
13,856
44.136808
176
py
NORPPA
NORPPA-main/config.py
import os import sys from pathlib import Path import cv2 import numpy as np file_folder = Path(__file__).resolve().parent sys.path.append(str(file_folder / "reidentification/hesaff_pytorch")) from HessianAffinePatches import init_affnet, init_orinet, init_hardnet from segmentation.detectron_segment import create_pre...
4,039
41.526316
123
py
NORPPA
NORPPA-main/datasets.py
import os from pathlib import Path from tools import read_image import csv import numpy as np from torch.utils.data import Dataset import os class DatasetSlice(Dataset): def __init__(self, dataset, slice=None): self.dataset = dataset self.slice = (0, len(self.dataset)) if slice is None else slice ...
8,014
29.708812
106
py
NORPPA
NORPPA-main/vis_new_pattern.py
import os # import sys # sys.path.append('/ekaterina/work/src/NORPPA/repository/NORPPA') os.environ["CUDA_VISIBLE_DEVICES"]="1" from config_whaleshark import config import matplotlib.pyplot as plt from pathlib import Path import numpy as np import zipfile import tensorflow as tf import wget import pickle physical_dev...
3,022
34.564706
136
py
NORPPA
NORPPA-main/config_whaleshark.py
import sys from pathlib import Path import cv2 import numpy as np file_folder = Path(__file__).resolve().parent sys.path.append(str(file_folder / "reidentification/hesaff_pytorch")) from HessianAffinePatches import init_affnet, init_orinet, init_hardnet from segmentation.detectron_segment import create_predicto...
4,166
41.520408
131
py
NORPPA
NORPPA-main/codebooks_whaleshark.py
import os # import sys # sys.path.append('/ekaterina/work/src/NORPPA/repository/NORPPA') os.environ["CUDA_VISIBLE_DEVICES"]="1" from config_whaleshark import config import matplotlib.pyplot as plt from pathlib import Path import numpy as np import zipfile import tensorflow as tf import wget import pickle physical_dev...
1,668
30.490566
111
py
NORPPA
NORPPA-main/reidentification/geometric.py
from skimage.measure import label from sklearn.decomposition import KernelPCA from skimage.morphology import convex_hull_image, skeletonize from cyvlfeat.fisher import fisher from PIL import Image import math from sql import * import torch from torchvision import transforms import pickle from reidentification.encodi...
4,128
32.298387
111
py
NORPPA
NORPPA-main/reidentification/identify.py
from skimage.measure import label from sklearn.decomposition import KernelPCA from skimage.morphology import convex_hull_image, skeletonize from cyvlfeat.fisher import fisher from PIL import Image import math from sql import * import torch from torchvision import transforms import pickle from reidentification.encodi...
16,717
33.328542
155
py
NORPPA
NORPPA-main/reidentification/hesaff_pytorch/HandCraftedModules.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import math import numpy as np from Utils import GaussianBlur, CircularGaussKernel from LAF import abc2A,rectifyAffineTransformationUpIsUp, sc_y_x2LAFs from Utils import generate_2dgrid, generate_2dgrid, generate_3dg...
13,280
43.27
145
py
NORPPA
NORPPA-main/reidentification/hesaff_pytorch/HardNet.py
import sys import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import torch.backends.cudnn as cudnn import time import os import math import numpy as np class L2Norm(nn.Module): def __init__(self): super(L2Norm,self).__init__() self.eps = 1e-8 ...
3,589
34.544554
155
py
NORPPA
NORPPA-main/reidentification/hesaff_pytorch/HessianAffinePatches.py
import torch import torch.nn as nn import numpy as np from torch.autograd import Variable from SparseImgRepresenter import ScaleSpaceAffinePatchExtractor from LAF import denormalizeLAFs, LAFs2ell from Utils import line_prepender from architectures import AffNetFast, OriNetFast from skimage.filters import unsharp_mask...
3,848
36.735294
111
py
NORPPA
NORPPA-main/reidentification/hesaff_pytorch/LAF.py
import numpy as np import matplotlib.pyplot as plt from copy import deepcopy from scipy.spatial.distance import cdist from numpy.linalg import inv from scipy.linalg import schur, sqrtm import torch from torch.autograd import Variable import torch.nn.functional as F ##########numpy def invSqrt(a,b,c): eps = 1e-...
17,704
36.352321
142
py
NORPPA
NORPPA-main/reidentification/hesaff_pytorch/SparseImgRepresenter.py
import torch import torch.nn as nn import numpy as np import math import torch.nn.functional as F from torch.autograd import Variable from copy import deepcopy from Utils import GaussianBlur, batch_eig2x2, line_prepender, batched_forward from LAF import LAFs2ell,abc2A, angles2A, generate_patch_grid_from_normalized_LAFs...
10,911
49.753488
231
py
NORPPA
NORPPA-main/reidentification/hesaff_pytorch/ReprojectonStuff.py
import torch from torch.autograd import Variable import numpy as np from LAF import rectifyAffineTransformationUpIsUp from Utils import zeros_like def distance_matrix_vector(anchor, positive): """Given batch of anchor descriptors and positive descriptors calculate distance matrix""" d1_sq = torch.sum(anchor * ...
6,844
45.25
177
py
NORPPA
NORPPA-main/reidentification/hesaff_pytorch/Utils.py
import torch import torch.nn.init import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import cv2 import numpy as np # resize image to size 32x32 cv2_scale = lambda x: cv2.resize(x, dsize=(32, 32), interpolation=cv2.INTER_LINEAR) # reshape image np_...
6,244
33.125683
144
py
NORPPA
NORPPA-main/reidentification/hesaff_pytorch/architectures.py
from __future__ import division, print_function import os import errno import numpy as np import sys from copy import deepcopy import math import torch import torch.nn.init import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torchvision.transforms as transforms from torch.autograd i...
36,272
45.32567
223
py
NORPPA
NORPPA-main/reidentification/hesaff_pytorch/extract_features_oxaff.py
import torch import torch.nn as nn import numpy as np import sys import time from PIL import Image from torch.autograd import Variable from SparseImgRepresenter import ScaleSpaceAffinePatchExtractor from LAF import denormalizeLAFs, LAFs2ell from Utils import line_prepender USE_CUDA = False try: input_img_fname =...
1,140
27.525
107
py
NORPPA
NORPPA-main/reidentification/hesaff_pytorch/pytorch_sift.py
import torch import math import torch.nn.init import torch.nn as nn from torch.autograd import Variable import torch.backends.cudnn as cudnn import numpy as np class L2Norm(nn.Module): def __init__(self): super(L2Norm,self).__init__() self.eps = 1e-10 def forward(self, x): norm = torch....
4,815
42.781818
129
py
NORPPA
NORPPA-main/pattern_extraction/model.py
import numpy as np import os import skimage.io as io import skimage.transform as trans import numpy as np from tensorflow.keras.models import * from tensorflow.keras.layers import * from tensorflow.keras.optimizers import * from tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler from tensorflow.k...
3,797
56.545455
132
py
robust-transformers
robust-transformers-main/conftest.py
# Copyright 2020 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-2.0 # # Unless required by applicabl...
2,846
35.037975
107
py
robust-transformers
robust-transformers-main/setup.py
# 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-2.0 # # Unless required by applicabl...
14,253
33.019093
259
py
robust-transformers
robust-transformers-main/hubconf.py
# Copyright 2020 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-2.0 # # Unless required by applicabl...
8,496
51.450617
189
py
robust-transformers
robust-transformers-main/examples/research_projects/longform-qa/eli5_app.py
import datasets import numpy as np import streamlit as st import torch from elasticsearch import Elasticsearch import faiss import transformers from eli5_utils import ( embed_questions_for_retrieval, make_qa_s2s_model, qa_s2s_generate, query_es_index, query_qa_dense_index, ) from transformers impor...
13,474
37.28125
159
py
robust-transformers
robust-transformers-main/examples/research_projects/longform-qa/eli5_utils.py
import functools import math import os # noqa: F401 from random import choice, randint from time import time import datasets # noqa: F401 import numpy as np import pandas as pd import torch import torch.utils.checkpoint as checkpoint from elasticsearch import Elasticsearch # noqa: F401 from elasticsearch.helpers im...
28,299
40.07402
119
py
robust-transformers
robust-transformers-main/examples/research_projects/codeparrot/scripts/codeparrot_training.py
import logging from argparse import Namespace from pathlib import Path import datasets import torch from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from torch.utils.tensorboard import SummaryWriter import transformers import wandb from ...
9,194
37.153527
119
py
robust-transformers
robust-transformers-main/examples/research_projects/codeparrot/scripts/validation_loss.py
import logging import torch from datasets import load_dataset from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from accelerate import Accelerator from arguments import EvaluationArguments from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, set...
3,496
33.97
114
py
robust-transformers
robust-transformers-main/examples/research_projects/bertology/run_prune_gpt.py
#!/usr/bin/env python3 """ This script is adapted from the Bertology pruning code (https://github.com/huggingface/transformers/blob/783d7d2629e97c5f0c5f9ef01b8c66410275c204/examples/research_projects/bertology/run_bertology.py) to prune GPT-like models. The author is @altsoph. """ import argparse import logging import...
15,469
38.666667
204
py
robust-transformers
robust-transformers-main/examples/research_projects/bertology/run_bertology.py
#!/usr/bin/env python3 # Copyright 2018 CMU and The HuggingFace Inc. team. # # 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 requir...
18,572
40.181818
118
py
robust-transformers
robust-transformers-main/examples/research_projects/rag/use_own_knowledge_dataset.py
import logging import os from dataclasses import dataclass, field from functools import partial from pathlib import Path from tempfile import TemporaryDirectory from typing import List, Optional import torch from datasets import Features, Sequence, Value, load_dataset import faiss from transformers import ( DPRCo...
8,174
38.878049
152
py
robust-transformers
robust-transformers-main/examples/research_projects/rag/utils_rag.py
import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transfo...
8,114
32.122449
118
py
robust-transformers
robust-transformers-main/examples/research_projects/rag/finetune_rag.py
"""Finetuning script for RAG models. Adapted from examples.seq2seq.finetune.py""" import argparse import logging import os import sys import time from collections import defaultdict from pathlib import Path from typing import Any, Dict, List, Tuple import numpy as np import pytorch_lightning as pl import torch import...
25,623
40.462783
197
py
robust-transformers
robust-transformers-main/examples/research_projects/rag/distributed_pytorch_retriever.py
import logging import os from typing import List, Tuple import numpy as np import psutil import torch import torch.distributed as dist from transformers import RagRetriever logger = logging.getLogger(__name__) class RagPyTorchDistributedRetriever(RagRetriever): """ A distributed retriever built on top of ...
6,539
46.05036
155
py
robust-transformers
robust-transformers-main/examples/research_projects/rag/test_distributed_retriever.py
import json import os import shutil import sys import tempfile import unittest from unittest import TestCase from unittest.mock import patch import numpy as np from datasets import Dataset import faiss from transformers import BartConfig, BartTokenizer, DPRConfig, DPRQuestionEncoderTokenizer, RagConfig from transform...
13,794
39.693215
118
py
robust-transformers
robust-transformers-main/examples/research_projects/rag/eval_rag.py
""" Evaluation script for RAG models.""" import argparse import ast import logging import os import sys import pandas as pd import torch from tqdm import tqdm from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration from transformers import logging as trans...
11,101
34.469649
132
py
robust-transformers
robust-transformers-main/examples/research_projects/rag/lightning_base.py
import argparse import logging import os from pathlib import Path from typing import Any, Dict import pytorch_lightning as pl from pytorch_lightning.utilities import rank_zero_info from transformers import ( AdamW, AutoConfig, AutoModel, AutoModelForPreTraining, AutoModelForQuestionAnswering, ...
15,609
37.734491
124
py
robust-transformers
robust-transformers-main/examples/research_projects/rag/callbacks_rag.py
import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def count_trainable_parameters(model): model_parame...
4,428
36.854701
126
py
robust-transformers
robust-transformers-main/examples/research_projects/rag/_test_finetune_rag.py
import json import logging import os import sys from pathlib import Path import finetune_rag from transformers.file_utils import is_apex_available from transformers.testing_utils import ( TestCasePlus, execute_subprocess_async, require_ray, require_torch_gpu, require_torch_multi_gpu, ) logging.ba...
3,969
34.765766
85
py
robust-transformers
robust-transformers-main/examples/research_projects/pplm/run_pplm.py
#! /usr/bin/env python3 # coding=utf-8 # Copyright (c) 2019 Uber Technologies, Inc. # # 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 ...
29,044
34.078502
182
py
robust-transformers
robust-transformers-main/examples/research_projects/pplm/run_pplm_discrim_train.py
#! /usr/bin/env python3 # coding=utf-8 # Copyright (c) 2019 Uber Technologies, Inc. # # 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 ...
18,788
34.92543
117
py
robust-transformers
robust-transformers-main/examples/research_projects/pplm/pplm_classification_head.py
from torch import nn class ClassificationHead(nn.Module): """Classification Head for transformer encoders""" def __init__(self, class_size, embed_size): super().__init__() self.class_size = class_size self.embed_size = embed_size # self.mlp1 = nn.Linear(embed_size, embed_size...
651
31.6
68
py
robust-transformers
robust-transformers-main/examples/research_projects/deebert/test_glue_deebert.py
import argparse import logging import sys from unittest.mock import patch import run_glue_deebert from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger() def get_setup_file(): parser = argparse....
3,690
34.152381
109
py
robust-transformers
robust-transformers-main/examples/research_projects/deebert/run_glue_deebert.py
from __future__ import absolute_import, division, print_function import argparse import glob import logging import os import random import time import numpy as np import torch from torch import nn from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset from torch.utils.data.distribute...
31,693
42.297814
150
py
robust-transformers
robust-transformers-main/examples/research_projects/deebert/src/modeling_highway_bert.py
import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEmbeddings, BertLayer, ...
17,668
43.506297
172
py
robust-transformers
robust-transformers-main/examples/research_projects/deebert/src/modeling_highway_roberta.py
from __future__ import absolute_import, division, print_function, unicode_literals from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers import RobertaConfig from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.roberta...
6,791
42.261146
172
py
robust-transformers
robust-transformers-main/examples/research_projects/lxmert/modeling_frcnn.py
""" coding=utf-8 Copyright 2018, Antonio Mendoza Hao Tan, Mohit Bansal Adapted From Facebook Inc, Detectron2 && Huggingface Co. 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...
73,726
37.359521
152
py
robust-transformers
robust-transformers-main/examples/research_projects/lxmert/extracting_data.py
import getopt import json import os # import numpy as np import sys from collections import OrderedDict import datasets import numpy as np import torch from modeling_frcnn import GeneralizedRCNN from processing_image import Preprocess from utils import Config """ USAGE: ``python extracting_data.py -i <img_dir> -o ...
5,254
34.033333
109
py
robust-transformers
robust-transformers-main/examples/research_projects/lxmert/utils.py
""" coding=utf-8 Copyright 2018, Antonio Mendoza Hao Tan, Mohit Bansal, Huggingface team :) Adapted From Facebook Inc, Detectron2 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://w...
18,199
31.5
143
py
robust-transformers
robust-transformers-main/examples/research_projects/lxmert/visualizing_image.py
""" coding=utf-8 Copyright 2018, Antonio Mendoza Hao Tan, Mohit Bansal Adapted From Facebook Inc, Detectron2 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/license...
13,420
25.842
100
py