repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
Few-shot-WSI | Few-shot-WSI-master/openselfsup/hooks/__init__.py | from .builder import build_hook
from .byol_hook import BYOLHook
from .deepcluster_hook import DeepClusterHook
from .odc_hook import ODCHook
from .optimizer_hook import DistOptimizerHook
from .extractor import Extractor
from .validate_hook import ValidateHook
from .registry import HOOKS
| 287 | 31 | 45 | py |
Few-shot-WSI | Few-shot-WSI-master/openselfsup/hooks/builder.py | from openselfsup.utils import build_from_cfg
from .registry import HOOKS
def build_hook(cfg, default_args=None):
return build_from_cfg(cfg, HOOKS, default_args)
| 168 | 20.125 | 51 | 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/registry.py | import inspect
from functools import partial
import mmcv
class Registry(object):
def __init__(self, name):
self._name = name
self._module_dict = dict()
def __repr__(self):
format_str = self.__class__.__name__ + '(name={}, items={})'.format(
self._name, list(self._module_... | 2,478 | 29.9875 | 78 | 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/misc.py | from functools import partial
import mmcv
import numpy as np
from six.moves import map, zip
def tensor2imgs(tensor, mean=(0, 0, 0), std=(1, 1, 1), to_rgb=True):
num_imgs = tensor.size(0)
mean = np.array(mean, dtype=np.float32)
std = np.array(std, dtype=np.float32)
imgs = []
for img_id in range(nu... | 1,107 | 28.157895 | 74 | py |
Few-shot-WSI | Few-shot-WSI-master/openselfsup/utils/logger.py | import logging
from mmcv.runner import get_dist_info
def get_root_logger(log_file=None, log_level=logging.INFO):
"""Get the root logger.
The logger will be initialized if it has not been initialized. By default a
StreamHandler will be added. If `log_file` is specified, a FileHandler will
also be add... | 2,424 | 35.19403 | 79 | 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 |
Few-shot-WSI | Few-shot-WSI-master/openselfsup/utils/__init__.py | from .alias_multinomial import AliasMethod
from .collect import nondist_forward_collect, dist_forward_collect
from .collect_env import collect_env
from .config_tools import traverse_replace
from .flops_counter import get_model_complexity_info
from .logger import get_root_logger, print_log
from .registry import Registry... | 362 | 39.333333 | 66 | py |
Few-shot-WSI | Few-shot-WSI-master/openselfsup/utils/config_tools.py | from mmcv import Config
def traverse_replace(d, key, value):
if isinstance(d, (dict, Config)):
for k, v in d.items():
if k == key:
d[k] = value
else:
traverse_replace(v, key, value)
elif isinstance(d, (list, tuple, set)):
for v in d:
... | 359 | 26.692308 | 47 | py |
rivuletpy | rivuletpy-master/build.py | """
Build C extensions.
Adapted from: https://github.com/zoj613/htnorm/blob/main/build.py
"""
import os
from distutils.core import Extension
import numpy as np
source_files = [
"rivuletpy/msfm/msfmmodule.c",
"rivuletpy/msfm/_msfm.c",
]
# get environmental variables to determine the flow of the build process... | 1,216 | 24.354167 | 76 | py |
rivuletpy | rivuletpy-master/tests/test_riveal.py | from filtering.riveal import riveal
from rivuletpy.utils.io import *
from filtering.thresholding import rescale
img = loadimg('tests/data/test.tif')
dtype = img.dtype
swc = loadswc('tests/data/test.swc')
img = riveal(img, swc, nsample=5e4, epoch=30)
img = rescale(img)
try:
from skimage import filters
except Import... | 585 | 26.904762 | 45 | py |
rivuletpy | rivuletpy-master/tests/testbgrsp.py | from filtering.anisotropic import *
from rivuletpy.utils.io import *
import matplotlib.pyplot as plt
from scipy import io as sio
try:
from skimage import filters
except ImportError:
from skimage import filter as filters
from scipy.ndimage.filters import gaussian_filter
mat = sio.loadmat('tests/data/very-smal... | 2,448 | 20.866071 | 74 | py |
rivuletpy | rivuletpy-master/tests/testmsfm.py | import msfm
from rivuletpy.utils.io import *
import skfmm
import os
from matplotlib import pyplot as plt
dir_path = os.path.dirname(os.path.realpath(__file__))
img = loadimg(os.path.join(dir_path, 'data/test.tif'))
dt = skfmm.distance(img > 0, dx=1) # Boundary DT
somaradius = dt.max()
somapos = np.asarray(np.unravel_... | 592 | 30.210526 | 76 | py |
rivuletpy | rivuletpy-master/tests/test_fuzzy_threshold.py | from os import path
from rivuletpy.utils.io import *
from filtering.thresholding import fuzzy
import matplotlib.pyplot as plt
img = loadimg(path.join('tests', 'data', 'test.tif'))
thr = fuzzy(img, render=True)
| 213 | 22.777778 | 53 | py |
rivuletpy | rivuletpy-master/tests/testssm.py | from filtering.morphology import ssm
from rivuletpy.utils.io import *
import matplotlib.pyplot as plt
import skfmm
ITER = 30
img = loadimg('/home/siqi/ncidata/rivuletpy/tests/data/test-crop.tif')
bimg = (img > 0).astype('int')
dt = skfmm.distance(bimg, dx=1)
sdt = ssm(dt, anisotropic=True, iterations=ITER)
try:
... | 624 | 20.551724 | 70 | py |
rivuletpy | rivuletpy-master/tests/testmetrics.py | from rivuletpy.utils.metrics import *
from rivuletpy.utils.io import *
from os.path import join
datapath = 'tests/data'
swc1 = loadswc(join(datapath, 'test-output.swc'))
swc2 = loadswc(join(datapath, 'test-expected.swc'))
prf, swc_compare = precision_recall(swc1, swc2)
print('Precision: %.2f\tRecall: %.2f\tF1: %.2f\t... | 700 | 27.04 | 62 | py |
rivuletpy | rivuletpy-master/tests/testoof.py | from filtering.anisotropic import *
from rivuletpy.utils.io import *
import matplotlib.pyplot as plt
from scipy import io as sio
try:
from skimage import filters
except ImportError:
from skimage import filter as filters
mat = sio.loadmat('tests/data/very-small-oof.mat', )
img = mat['img']
ostu_img = filters... | 2,584 | 23.619048 | 108 | py |
rivuletpy | rivuletpy-master/tests/test_node_push.py | # Load swc
import SimpleITK as sitk
from rivuletpy.utils.io import loadswc, loadimg
from rivuletpy.swc import SWC
from rivuletpy.utils.io import swc2world, swc2vtk
swc_mat = loadswc(
'/home/z003s24h/Desktop/zhoubing_vessel_example/mask/Anonymous EJRH_16.r2.swc')
s = SWC()
s._data = swc_mat
# Load image and binar... | 974 | 28.545455 | 99 | py |
rivuletpy | rivuletpy-master/tests/testbg.py | from filtering.anisotropic import *
from rivuletpy.utils.io import *
import matplotlib.pyplot as plt
from scipy import io as sio
try:
from skimage import filters
except ImportError:
from skimage import filter as filters
# plot the gaussian kernel
nsig = 5
nmu = 5
kerlen = 101
kr = (kerlen - 1) / 2
X, Y, Z =... | 1,287 | 24.76 | 59 | py |
rivuletpy | rivuletpy-master/tests/test_viewer.py | from rivuletpy.utils.io import loadswc
from rivuletpy.swc import SWC
swc_mat = loadswc('test_data/test.tif.r2.swc')
s = SWC()
s._data = swc_mat
s.view()
input("Press any key to continue...") | 191 | 23 | 46 | py |
rivuletpy | rivuletpy-master/rivuletpy/soma.py | # -*- coding: utf-8 -*-
"""
somasnakes
===========
Original package is adjusted for soma detection by donghaozhang and siqiliu.
This soma submodule can be used for soma detection only, but this submodule is
currently embedded in rivuletpy. The soma mask can be generate by setting
its corresponding argument. Soma detec... | 24,107 | 34.040698 | 86 | py |
rivuletpy | rivuletpy-master/rivuletpy/__init__.py | 0 | 0 | 0 | py | |
rivuletpy | rivuletpy-master/rivuletpy/trace.py | import math
from tqdm import tqdm
import numpy as np
import skfmm
import msfm
from scipy.interpolate import RegularGridInterpolator
from scipy.ndimage.morphology import binary_dilation
from skimage.morphology import skeletonize_3d
from .soma import Soma
from .swc import SWC
class Tracer(object):
def __init__(sel... | 16,754 | 33.054878 | 96 | py |
rivuletpy | rivuletpy-master/rivuletpy/swc.py | import math
import numpy as np
from .utils.io import saveswc
from collections import Counter
from random import gauss
from random import random
from random import randrange
from scipy.spatial.distance import cdist
class SWC(object):
def __init__(self, soma=None):
self._data = np.zeros((1, 8))
if ... | 13,630 | 30.407834 | 101 | py |
rivuletpy | rivuletpy-master/rivuletpy/utils/rendering3.py | import os
import numpy as np
import math
# from gym.envs.classic_control.rendering import *
from .rendering import *
from PIL import Image # PIL library is required
import pyglet
from pyglet.gl import glu
from .io import *
# colors
black = (0, 0, 0, 1)
gray = (0.5, 0.5, 0.5)
red = (1, 0, 0)
def _add_attrs(geom, att... | 6,644 | 33.252577 | 95 | py |
rivuletpy | rivuletpy-master/rivuletpy/utils/metrics.py | from collections import deque
import numpy as np
from scipy.spatial.distance import cdist
def precision_recall(swc1, swc2, dist1=4, dist2=4):
'''
Calculate the precision, recall and F1 score between swc1 and swc2 (ground truth)
It generates a new swc file with node types indicating the agreement between tw... | 9,515 | 31.367347 | 116 | py |
rivuletpy | rivuletpy-master/rivuletpy/utils/__init__.py | 0 | 0 | 0 | py | |
rivuletpy | rivuletpy-master/rivuletpy/utils/io.py | import os
import numpy as np
from scipy import io as sio
import SimpleITK as sitk
def loadimg(file, target_resolution):
if file.endswith('.mat'):
filecont = sio.loadmat(file)
img = filecont['img']
for z in range(img.shape[-1]): # Flip the image upside down
img[:, :, z] = np.fl... | 5,620 | 29.22043 | 92 | py |
rivuletpy | rivuletpy-master/rivuletpy/utils/rendering.py | """
2D rendering framework
"""
from __future__ import division
import os
import six
import sys
import pyglet
from pyglet.gl import *
import math
import numpy as np
RAD2DEG = 57.29577951308232
def get_display(spec):
"""Convert a display specification (such as :0) into an actual Display
object.
Pyglet o... | 9,508 | 24.980874 | 98 | py |
rivuletpy | rivuletpy-master/filtering/thresholding.py | import numpy as np
def fuzzy(img, level=128, p=2):
'''
Image auto thresholding with measure of fuzziness using the Yager's measure
Implemented the algorithm following Eq.(11) in
L. K. Huang and M. J. J. Wang, “Image thresholding by minimizing the
measures of fuzziness,” Pattern Recognit., vol. 28,... | 2,224 | 31.720588 | 79 | py |
rivuletpy | rivuletpy-master/filtering/anisotropic.py | import numpy as np
from scipy.special import jv # Bessel Function of the first kind
from scipy.linalg import eig
from scipy.fftpack import fftn, ifftn, ifft
# import progressbar
from tqdm import tqdm
from scipy.ndimage import filters as fi
import math
# An implementation of the Optimally Oriented
# M.W.K. Law and A.C... | 15,197 | 34.180556 | 217 | 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 |
rivuletpy | rivuletpy-master/filtering/__init__.py | 0 | 0 | 0 | py | |
rivuletpy | rivuletpy-master/filtering/morphology.py | import numpy as np
from scipy.ndimage import gaussian_filter1d
from scipy.ndimage.filters import laplace
try:
from skimage import filters
except ImportError:
from skimage import filter as filters
from tqdm import tqdm
from functools import reduce
from scipy.interpolate import RegularGridInterpolator
import skfm... | 7,344 | 30.122881 | 110 | 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/compute_pickle.py | import pickle
import os
from argparse import ArgumentParser
from metric import score
def main(args):
print("Load pickle...")
path = args.pickle_intput
multi_doc_path = os.path.join(path,'multimodal_documents.pickle')
img_embd_path = os.path.join(path,'img_query.pickle')
txt_embd_path = os.path.joi... | 1,894 | 34.754717 | 69 | py |
Mr.Right | Mr.Right-main/utils.py | import json
def prepare_pretrain_data(files):
print("\nReading json files")
image_text_pairs = []
for f in files:
print(f"File: {f}",end="\r")
image_text_pairs += json.load(open(f,'r'))
return image_text_pairs
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init_... | 367 | 25.285714 | 55 | 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/scheduler/__init__.py | from .cosine_lr import CosineLRScheduler
| 41 | 20 | 40 | 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/config.py | from sacred import Experiment
ex = Experiment("METER")
def _loss_names(d):
ret = {
"itm": 0,
"mlm": 0,
"mpp": 0,
"vqa": 0,
"vcr": 0,
"vcr_qar": 0,
"nlvr2": 0,
"irtr": 0,
"contras": 0,
"snli": 0,
}
ret.update(d)
return ret... | 7,425 | 23.671096 | 123 | py |
Mr.Right | Mr.Right-main/models/METER/meter/__init__.py | 0 | 0 | 0 | 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/modules/__init__.py | from .meter_module import METERTransformerSS
| 45 | 22 | 44 | py |
Mr.Right | Mr.Right-main/models/METER/meter/utils/write_vg.py | import json
import pandas as pd
import pyarrow as pa
import random
import os
from tqdm import tqdm
from glob import glob
from collections import defaultdict
def path2rest(path, iid2captions):
name = path.split("/")[-1]
iid = int(name[:-4])
with open(path, "rb") as fp:
binary = fp.read()
cdi... | 1,928 | 25.424658 | 82 | py |
Mr.Right | Mr.Right-main/models/METER/meter/utils/glossary.py | import re
contractions = {
"aint": "ain't",
"arent": "aren't",
"cant": "can't",
"couldve": "could've",
"couldnt": "couldn't",
"couldn'tve": "couldn't've",
"couldnt've": "couldn't've",
"didnt": "didn't",
"doesnt": "doesn't",
"dont": "don't",
"hadnt": "hadn't",
"hadnt've":... | 4,435 | 22.225131 | 54 | py |
Mr.Right | Mr.Right-main/models/METER/meter/utils/write_vqa.py | import json
import pandas as pd
import pyarrow as pa
import random
import os
from tqdm import tqdm
from glob import glob
from collections import defaultdict, Counter
from .glossary import normalize_word
def get_score(occurences):
if occurences == 0:
return 0.0
elif occurences == 1:
return 0.3... | 6,523 | 30.669903 | 88 | py |
Mr.Right | Mr.Right-main/models/METER/meter/utils/write_conceptual_caption.py | import json
import pandas as pd
import pyarrow as pa
import gc
import random
import os
from tqdm import tqdm
from glob import glob
def path2rest(path, iid2captions):
split, _, name = path.split("/")[-3:]
split = split.split("_")[-1]
iid = name
with open(path, "rb") as fp:
binary = fp.read()
... | 2,037 | 27.305556 | 87 | py |
Mr.Right | Mr.Right-main/models/METER/meter/utils/write_nlvr2.py | import json
import pandas as pd
import pyarrow as pa
import os
from tqdm import tqdm
from collections import defaultdict
def process(root, iden, row):
texts = [r["sentence"] for r in row]
labels = [r["label"] for r in row]
split = iden.split("-")[0]
if iden.startswith("train"):
directory = ... | 2,818 | 25.101852 | 86 | py |
Mr.Right | Mr.Right-main/models/METER/meter/utils/write_sbu.py | import json
import pandas as pd
import pyarrow as pa
import gc
import random
import os
from tqdm import tqdm
from glob import glob
def path2rest(path, iid2captions):
split, _, name = path.split("/")[-3:]
split = split.split("_")[-1]
iid = name
with open(path, "rb") as fp:
binary = fp.read()
... | 1,785 | 25.656716 | 88 | py |
Mr.Right | Mr.Right-main/models/METER/meter/utils/write_f30k_karpathy.py | import json
import pandas as pd
import pyarrow as pa
import random
import os
from tqdm import tqdm
from glob import glob
from collections import defaultdict
def path2rest(path, iid2captions, iid2split):
name = path.split("/")[-1]
with open(path, "rb") as fp:
binary = fp.read()
captions = iid2ca... | 1,871 | 26.529412 | 83 | py |
Mr.Right | Mr.Right-main/models/METER/meter/utils/write_snli.py | import json
import pandas as pd
import pyarrow as pa
import os
from tqdm import tqdm
from collections import defaultdict
label2id = {'contradiction': 0, 'neutral': 1, 'entailment': 2}
def process(root, imgid, ann):
with open(f"{root}/Flickr30K/images/{imgid}.jpg", "rb") as fp:
img = fp.read()
senten... | 2,006 | 26.493151 | 94 | py |
Mr.Right | Mr.Right-main/models/METER/meter/utils/__init__.py | 0 | 0 | 0 | py | |
Mr.Right | Mr.Right-main/models/METER/meter/utils/write_coco_karpathy.py | import json
import os
import pandas as pd
import pyarrow as pa
import random
from tqdm import tqdm
from glob import glob
from collections import defaultdict
def path2rest(path, iid2captions, iid2split):
name = path.split("/")[-1]
with open(path, "rb") as fp:
binary = fp.read()
captions = iid2capt... | 1,904 | 28.765625 | 87 | 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/METER/meter/transforms/__init__.py | from .transform import (
pixelbert_transform,
pixelbert_transform_randaug,
vit_transform,
vit_transform_randaug,
imagenet_transform,
imagenet_transform_randaug,
clip_transform,
clip_transform_randaug,
)
_transforms = {
"pixelbert": pixelbert_transform,
"pixelbert_randaug": pixel... | 678 | 26.16 | 56 | 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/modules/__init__.py | from .vilt_module import ViLTransformerSS
| 42 | 20.5 | 41 | 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/models/ViLT/vilt/transforms/__init__.py | from .pixelbert import (
pixelbert_transform,
pixelbert_transform_randaug,
)
_transforms = {
"pixelbert": pixelbert_transform,
"pixelbert_randaug": pixelbert_transform_randaug,
}
def keys_to_transforms(keys: list, size=224):
return [_transforms[key](size=size) for key in keys]
| 301 | 20.571429 | 56 | py |
Mr.Right | Mr.Right-main/data/utils.py | import re
import cv2
import numpy as np
# ref: https://github.com/salesforce/ALBEF
def pre_caption(caption,max_words):
caption = re.sub(
r"([,.'!?\"()*#:;~])",
'',
caption.lower(),
).replace('-', ' ').replace('/', ' ').replace('<person>', 'person')
caption = re.sub(
r"\s{2,}... | 10,271 | 27.773109 | 99 | py |
Mr.Right | Mr.Right-main/data/extract_multimodal_val.py | import os
import json
import pdb
import random
from argparse import ArgumentParser
random.seed(42)
def main(args):
document = json.load(open(args.mul_doc,'r'))
val_query = json.load(open(args.mul_val,'r'))
document_dict = dict()
for doc in document:
document_dict[doc['id']] = doc
val_document = []
for idx,... | 1,298 | 24.470588 | 75 | 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/sql.py | import sqlite3
import numpy as np
from datetime import datetime
def create_connection(path="/app/mount/tasks.db"):
""" create a database connection to the SQLite database
"""
conn = None
try:
conn = sqlite3.connect(path, check_same_thread=False)
except sqlite3.Error as e:
print(e)
... | 6,354 | 29.552885 | 212 | py |
NORPPA | NORPPA-main/tools.py |
from datetime import datetime
import random
import string
import os
import sys
import shutil
from zipfile import ZipFile
from skimage import color
import numpy as np
from datetime import datetime
from six.moves import urllib
from pattern_extraction.utils import thickness_resize
from pattern_extraction.extract_pattern ... | 10,545 | 29.391931 | 101 | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.