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
w2ot
w2ot-main/w2ot/external/benchmark/icnn.py
# This file is from # https://github.com/iamalexkorotin/Wasserstein1Benchmark/commit/647a1acc85f88e207733d087cbe87987cc0dea06 # and remains under the original licensing. import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F from .unet import UNet from .resnet2 import Res...
12,359
37.504673
116
py
w2ot
w2ot-main/w2ot/external/benchmark/unet.py
# This file is from # https://github.com/iamalexkorotin/Wasserstein1Benchmark/commit/647a1acc85f88e207733d087cbe87987cc0dea06 # and remains under the original licensing. import torch import torch.nn as nn import torch.nn.functional as F import functools class DoubleConv(nn.Module): """(convolution => [BN] => ...
4,065
34.666667
122
py
w2ot
w2ot-main/w2ot/external/benchmark/metrics.py
# This file is from # https://github.com/iamalexkorotin/Wasserstein1Benchmark/commit/647a1acc85f88e207733d087cbe87987cc0dea06 # and remains under the original licensing. import torch import numpy as np import jax.numpy as jnp from .tools import freeze import gc def score_fitted_maps(benchmark, D, D_conj, size=4096...
3,293
41.230769
116
py
w2ot
w2ot-main/w2ot/external/benchmark/map_benchmark.py
# This file is from # https://github.com/iamalexkorotin/Wasserstein1Benchmark/commit/647a1acc85f88e207733d087cbe87987cc0dea06 # and remains under the original licensing. import torch import torch.nn as nn import numpy as np from scipy.linalg import sqrtm from . import potentials from . import distributions from .ic...
8,579
33.736842
128
py
w2ot
w2ot-main/w2ot/external/benchmark/fid_score.py
#!/usr/bin/env python3 # This file is from # https://github.com/iamalexkorotin/Wasserstein1Benchmark/commit/647a1acc85f88e207733d087cbe87987cc0dea06 # and remains under the original licensing. """Calculates the Frechet Inception Distance (FID) to evalulate GANs The FID metric calculates the distance between two distr...
9,926
36.041045
105
py
w2ot
w2ot-main/w2ot/models/init_nn.py
# Copyright (c) Meta Platforms, Inc. and affiliates. from functools import partial import numpy as np import jax import jax.numpy as jnp from jax import dtypes from jax.random import PRNGKey from flax import linen as nn from flax.linen.linear import default_kernel_init, \ _conv_dimension_numbers from dataclass...
1,059
22.043478
66
py
w2ot
w2ot-main/w2ot/models/potential_nn.py
# Copyright (c) Meta Platforms, Inc. and affiliates. from functools import partial import numpy as np import jax import jax.numpy as jnp from jax import dtypes from jax.random import PRNGKey from flax import linen as nn from typing import Any, Optional, Callable, Sequence, Tuple, Union from w2ot import utils clas...
1,154
22.571429
71
py
w2ot
w2ot-main/w2ot/models/potential_conv.py
# Copyright (c) Meta Platforms, Inc. and affiliates. from functools import partial import numpy as np import jax import jax.numpy as jnp from jax import dtypes from jax.random import PRNGKey from flax import linen as nn from typing import Any, Optional, Callable, Sequence, Tuple, Union from w2ot import utils clas...
1,794
24.642857
67
py
mganprior
mganprior-master/inpainting.py
import os import argparse import math, time import torch import cv2 from utils.file_utils import image_files, load_as_tensor, Tensor2PIL, split_to_batches from utils.image_precossing import _sigmoid_to_tanh, _tanh_to_sigmoid, _add_batch_one from derivable_models.derivable_generator import get_derivable_generator from ...
6,547
51.384
162
py
mganprior
mganprior-master/face_semantic_editing.py
import os import argparse import torch import cv2 from utils.manipulate import convert_array_to_images, get_interpolated_wp, get_boundary, BOUNDARY_DIR from utils.file_utils import image_files, load_as_tensor from utils.image_precossing import _sigmoid_to_tanh, _add_batch_one from derivable_models.derivable_generator ...
7,017
49.128571
123
py
mganprior
mganprior-master/multi_code_inversion.py
import os import argparse import torch import cv2 from utils.file_utils import image_files, load_as_tensor, Tensor2PIL, split_to_batches from utils.image_precossing import _sigmoid_to_tanh, _tanh_to_sigmoid, _add_batch_one from derivable_models.derivable_generator import get_derivable_generator from inversion.inversio...
5,683
49.300885
129
py
mganprior
mganprior-master/colorization.py
import os import argparse import numpy as np import torch from PIL import Image import math, time import cv2 from utils.file_utils import image_files, load_as_tensor, Tensor2PIL, split_to_batches from utils.image_precossing import _sigmoid_to_tanh, _tanh_to_sigmoid, _add_batch_one from derivable_models.derivable_gener...
6,673
51.140625
140
py
mganprior
mganprior-master/super_resolution.py
import os import argparse import torch import cv2 from utils.file_utils import image_files, load_as_tensor, Tensor2PIL, split_to_batches from utils.image_precossing import _sigmoid_to_tanh, _tanh_to_sigmoid, _add_batch_one from derivable_models.derivable_generator import get_derivable_generator from utils.manipulate i...
6,432
49.257813
129
py
mganprior
mganprior-master/inversion/losses.py
import torch import torch.nn as nn import torch.nn.functional as F from torchvision.models.vgg import vgg16, vgg19 def get_loss(loss_name, args): if loss_name == 'VGG': return VGGLoss(args.vgg_layer, args) elif loss_name == 'L1': return nn.L1Loss(reduction='mean') elif loss_name == 'L2': ...
4,260
39.580952
120
py
mganprior
mganprior-master/inversion/inversion_methods.py
from tqdm import tqdm import copy import torch import torch.nn as nn import torch.optim as optim def get_inversion(inversion_type, args): if inversion_type == 'GD': return GradientDescent(args.iterations, args.lr, optimizer=optim.SGD, args=args) elif inversion_type == 'Adam': return GradientD...
2,004
35.454545
94
py
mganprior
mganprior-master/models/model_settings.py
# python 3.7 """Contains basic configurations for models used in this project. Please download the public released models from the following repositories OR train your own models, and then put them into the folder `pretrain/tensorflow`. PGGAN: https://github.com/tkarras/progressive_growing_of_gans StyleGAN: https://g...
26,659
42.633388
114
py
mganprior
mganprior-master/models/stylegan2_generator.py
# python 3.7 """Contains the generator class of StyleGAN2. This class is derived from the `BaseGenerator` class defined in `base_generator.py`. """ import numpy as np import torch from . import model_settings from .base_generator import BaseGenerator from .stylegan2_generator_network import StyleGAN2GeneratorNet _...
11,859
39.477816
80
py
mganprior
mganprior-master/models/pggan_generator.py
# python 3.7 """Contains the generator class of PGGAN. This class is derived from the `BaseGenerator` class defined in `base_generator.py`. """ import numpy as np import torch from .base_generator import BaseGenerator from .pggan_generator_network import PGGANGeneratorNet __all__ = ['PGGANGenerator'] class PGGAN...
5,314
36.167832
80
py
mganprior
mganprior-master/models/base_generator.py
# python 3.7 """Contains the base class for generator in a GAN model.""" import os.path import sys import logging import numpy as np import torch from . import model_settings __all__ = ['BaseGenerator'] def get_temp_logger(logger_name='logger'): """Gets a temporary logger. This logger will print all levels o...
11,057
33.664577
80
py
mganprior
mganprior-master/models/stylegan_generator_network.py
# python 3.7 """Contains the implementation of generator described in StyleGAN. Different from the official tensorflow version in folder `stylegan_tf_official`, this is a simple pytorch version which only contains the generator part. This class is specially used for inference. For more details, please check the origi...
30,448
37.494311
104
py
mganprior
mganprior-master/models/pggan_generator_network.py
# python 3.7 """Contains the implementation of generator described in PGGAN. Different from the official tensorflow version in folder `pggan_tf_official`, this is a simple pytorch version which only contains the generator part. This class is specially used for inference. For more details, please check the original pa...
11,276
35.97377
80
py
mganprior
mganprior-master/models/stylegan_generator.py
# python 3.7 """Contains the generator class of StyleGAN. This class is derived from the `BaseGenerator` class defined in `base_generator.py`. """ import numpy as np import torch from . import model_settings from .base_generator import BaseGenerator from .stylegan_generator_network import StyleGANGeneratorNet __al...
12,441
40.062706
80
py
mganprior
mganprior-master/models/stylegan2_generator_network.py
# python 3.7 """Contains the implementation of generator described in StyleGAN2. Different from the official tensorflow version in folder `stylegan2_tf_official`, this is a simple pytorch version which only contains the generator part. This class is specially used for inference. NOTE: Compared to that of StyleGAN, th...
31,291
37.395092
83
py
mganprior
mganprior-master/derivable_models/gan_utils.py
import numpy as np import os import torch import torch.nn as nn from models.helper import build_generator PGGAN_Inter_Output_Layer_256 = [-1, 17, 14, 11, 8, 5, 2] PGGAN_Inter_Output_Layer_1024 = [-1, 23, 20, 17, 14, 11, 8, 5, 2] def standard_z_sample(size, depth, device=None): ''' Generate a standard set o...
1,393
29.304348
120
py
mganprior
mganprior-master/derivable_models/derivable_generator.py
import torch import torch.nn as nn import torch.nn.functional as F from .gan_utils import get_gan_model PGGAN_LATENT_1024 = [(512, 1, 1), (512, 4, 4), (512, 4, 4), (512, 8, 8), (512, 8, 8), (512, 16, 16), (512, 16, 16), (512, 32, 32), (512, 32, 32), ...
4,875
34.852941
145
py
mganprior
mganprior-master/utils/manipulate.py
import numpy as np import cv2 from math import sqrt, ceil from PIL import Image import torch import torch.nn.functional as F from .file_utils import Tensor2PIL, PIL2Tensor from .image_precossing import _add_batch_one BOUNDARY_DIR = './boundaries' LEVEL = { # for style mixing 'coarse': (0, 4), 'middle': (4, ...
7,697
31.897436
103
py
mganprior
mganprior-master/utils/file_utils.py
import os from PIL import Image import torchvision IMG_EXTENSIONS = ['jpg', 'jpeg', 'png', 'ppm', 'bmp', 'pgm'] def mkdir(path): if not os.path.exists(path): os.makedirs(path) def pil_loader(path, mode='RGB'): """ open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pil...
2,146
27.25
126
py
GLIP
GLIP-main/setup.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. #!/usr/bin/env python import glob import os import torch from setuptools import find_packages from setuptools import setup from torch.utils.cpp_extension import CUDA_HOME from torch.utils.cpp_extension import CppExtension from torch.utils.cpp_ext...
1,967
28.373134
99
py
GLIP
GLIP-main/tools/visualize_grounding_net.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # Set up custom environment before nearly anything else is imported # NOTE: this should be the first import (no not reorder) from maskrcnn_benchmark.utils.env import setup_environment # noqa F401 isort:skip import argparse import os import matplo...
12,352
37.009231
124
py
GLIP
GLIP-main/tools/test_net.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # Set up custom environment before nearly anything else is imported # NOTE: this should be the first import (no not reorder) from maskrcnn_benchmark.utils.env import setup_environment # noqa F401 isort:skip import argparse import os import torch...
4,839
36.230769
114
py
GLIP
GLIP-main/tools/eval_all.py
"""Script to evaluate all checkpoints for the trained model. OUTPUT_DIR has to contain trained checkpoints. MODEL.WEIGHT parameter will be ignored. """ # NOTE: this should be the first import (no not reorder) from maskrcnn_benchmark.utils.env import setup_environment # noqa F401 isort:skip import argparse import os ...
5,201
34.148649
82
py
GLIP
GLIP-main/tools/finetune.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. r""" Basic training script for PyTorch """ # Set up custom environment before nearly anything else is imported # NOTE: this should be the first import (no not reorder) from maskrcnn_benchmark.utils.env import setup_environment # noqa F401 isort:s...
18,331
38.508621
232
py
GLIP
GLIP-main/tools/test_grounding_net.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # Set up custom environment before nearly anything else is imported # NOTE: this should be the first import (no not reorder) from maskrcnn_benchmark.utils.env import setup_environment # noqa F401 isort:skip import argparse import os import torch...
8,649
37.789238
128
py
GLIP
GLIP-main/tools/train_net.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. r""" Basic training script for PyTorch """ # Set up custom environment before nearly anything else is imported # NOTE: this should be the first import (no not reorder) from maskrcnn_benchmark.utils.env import setup_environment # noqa F401 isort:s...
8,349
31.617188
102
py
GLIP
GLIP-main/maskrcnn_benchmark/solver/lr_scheduler.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. from bisect import bisect_right import math import torch # FIXME ideally this would be achieved with a CombinedLRScheduler, # separating MultiStepLR with WarmupLR # but the current LRScheduler design doesn't allow it class WarmupMultiStepLR(torc...
5,800
34.371951
144
py
GLIP
GLIP-main/maskrcnn_benchmark/solver/build.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch import itertools from .lr_scheduler import WarmupMultiStepLR, WarmupCosineAnnealingLR, WarmupReduceLROnPlateau def make_optimizer(cfg, model): def maybe_add_full_model_gradient_clipping(optim): # optim: the optimizer class ...
4,457
37.102564
117
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/nms.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. from maskrcnn_benchmark import _C try: import torchvision from torchvision.ops import nms except: nms = _C.nms ml_nms = _C.ml_nms soft_nms = _C.soft_nms # nms.__doc__ = """ # This function performs Non-maximum suppresion"""
311
19.8
71
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/batch_norm.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from torch import nn import torch.distributed as dist import maskrcnn_benchmark.utils.comm as comm from torch.autograd.function import Function class FrozenBatchNorm2d(nn.Module): """ BatchNorm2d where the batch statistics an...
4,925
41.102564
99
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/deform_pool.py
import torch import torch.nn as nn import torch.nn.functional as F from .deform_conv import DeformConv2d def add_conv(in_ch, out_ch, ksize, stride, leaky=True): """ Add a conv2d / batchnorm / leaky ReLU block. Args: in_ch (int): number of input channels of the convolution layer. out_ch (in...
17,079
39.283019
122
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/deform_conv.py
import torch import math from torch import nn from torch.nn import init from torch.nn.modules.utils import _pair from torch.autograd import Function from torch.autograd.function import once_differentiable from maskrcnn_benchmark.utils.amp import custom_fwd, custom_bwd from maskrcnn_benchmark import _C class DeformCon...
14,204
31.505721
83
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/iou_loss.py
import torch from torch import nn class IOULoss(nn.Module): def __init__(self, loss_type="iou"): super(IOULoss, self).__init__() self.loss_type = loss_type def forward(self, pred, target, weight=None): pred_left = pred[:, 0] pred_top = pred[:, 1] pred_right = pred[:, 2...
2,849
33.337349
95
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/roi_pool.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from torch import nn from torch.autograd import Function from torch.autograd.function import once_differentiable from torch.nn.modules.utils import _pair from maskrcnn_benchmark import _C class _ROIPool(Function): @staticmethod ...
1,855
28
74
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/roi_align.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from torch import nn from torch.autograd import Function from torch.autograd.function import once_differentiable from torch.nn.modules.utils import _pair from maskrcnn_benchmark import _C class _ROIAlign(Function): @staticmethod ...
2,944
31.722222
96
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/dropblock.py
import torch import torch.nn.functional as F from torch import nn class DropBlock2D(nn.Module): r"""Randomly zeroes 2D spatial blocks of the input tensor. As described in the paper `DropBlock: A regularization method for convolutional networks`_ , dropping whole blocks of feature map allows to remove...
4,439
29.410959
98
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/smooth_l1_loss.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch # TODO maybe push this to nn? def smooth_l1_loss(input, target, beta=1. / 9, size_average=True): """ very similar to the smooth_l1_loss from pytorch, but with the extra beta parameter """ n = torch.abs(input - tar...
481
27.352941
71
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/sigmoid_focal_loss.py
import torch from torch import nn import torch.nn.functional as F from torch.autograd import Function from torch.autograd.function import once_differentiable from maskrcnn_benchmark import _C # TODO: Use JIT to replace CUDA implementation in the future. class _SigmoidFocalLoss(Function): @staticmethod def fo...
7,335
36.050505
120
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/evonorm.py
import torch import torch.nn as nn class EvoNorm2d(nn.Module): __constants__ = ['num_features', 'eps', 'nonlinearity'] def __init__(self, num_features, eps=1e-5, nonlinearity=True, group=32): super(EvoNorm2d, self).__init__() self.num_features = num_features self.eps = eps se...
1,305
31.65
80
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/set_loss.py
import torch import torch.nn.functional as F import torch.distributed as dist from torch import nn from scipy.optimize import linear_sum_assignment from torch.cuda.amp import custom_fwd, custom_bwd def box_area(boxes): return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) # modified from torchvision...
16,542
43.47043
130
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/misc.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. """ helper class that supports empty tensors on some nn functions. Ideally, add support directly in PyTorch to empty tensors in those functions. This can be removed once https://github.com/pytorch/pytorch/issues/12013 is implemented """ import m...
6,666
31.364078
88
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/dyrelu.py
import torch import torch.nn as nn import torch.nn.functional as F def _make_divisible(v, divisor, min_value=None): if min_value is None: min_value = divisor new_v = max(min_value, int(v + divisor / 2) // divisor * divisor) # Make sure that round down does not go down by more than 10%. if new_v...
3,836
30.710744
102
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from .batch_norm import FrozenBatchNorm2d, NaiveSyncBatchNorm2d from .misc import Conv2d, _NewEmptyTensorOp from .misc import ConvTranspose2d from .misc import DFConv2d from .misc import interpolate from .misc import Scale from .nms i...
1,510
42.171429
111
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/dyhead.py
import torch import torch.nn.functional as F from torch import nn from .deform_conv import ModulatedDeformConv from .dyrelu import h_sigmoid, DYReLU class Conv3x3Norm(torch.nn.Module): def __init__(self, in_channels, out_channels, stride, deform...
5,055
32.483444
111
py
GLIP
GLIP-main/maskrcnn_benchmark/layers/se.py
from torch import nn class SELayer(nn.Module): def __init__(self, channel, reduction=16): super(SELayer, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential( nn.Linear(channel, channel // reduction, bias=False), nn.ReLU(inplace=True), ...
1,770
33.057692
99
py
GLIP
GLIP-main/maskrcnn_benchmark/engine/inference.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import datetime import logging import time import os import re import torch from tqdm import tqdm from collections import defaultdict from maskrcnn_benchmark.data.datasets.evaluation import evaluate, im_detect_bbox_aug from ..utils.comm import is...
24,835
38.801282
194
py
GLIP
GLIP-main/maskrcnn_benchmark/engine/stage_trainer.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import datetime import logging import time import torch import torch.distributed as dist from maskrcnn_benchmark.utils.comm import get_world_size from maskrcnn_benchmark.utils.metric_logger import MetricLogger def reduce_loss_dict(all_loss_dict...
7,270
38.302703
106
py
GLIP
GLIP-main/maskrcnn_benchmark/engine/evolution.py
import time import pickle import logging import os import numpy as np import torch import torch.nn as nn from collections import OrderedDict from yaml import safe_dump from yacs.config import load_cfg, CfgNode#, _to_dict from maskrcnn_benchmark.config import cfg from maskrcnn_benchmark.engine.inference import _accum...
12,687
34.441341
136
py
GLIP
GLIP-main/maskrcnn_benchmark/engine/singlepath_trainer.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import datetime import logging import time import random import torch import torch.distributed as dist from maskrcnn_benchmark.utils.comm import get_world_size, synchronize, broadcast_data from maskrcnn_benchmark.utils.metric_logger import MetricLo...
4,935
33.760563
145
py
GLIP
GLIP-main/maskrcnn_benchmark/engine/predictor.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import cv2 import torch import numpy as np from torchvision import transforms as T from maskrcnn_benchmark.modeling.detector import build_detection_model from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer from maskrcnn_benchmark...
20,346
34.822183
107
py
GLIP
GLIP-main/maskrcnn_benchmark/engine/predictor_glip.py
import cv2 import torch import re import numpy as np from typing import List, Union import nltk import inflect from transformers import AutoTokenizer from torchvision import transforms as T import pdb from maskrcnn_benchmark.modeling.detector import build_detection_model from maskrcnn_benchmark.utils.checkpoint import ...
18,662
38.624204
183
py
GLIP
GLIP-main/maskrcnn_benchmark/engine/alter_trainer.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import datetime import logging import time import torch import torch.distributed as dist from maskrcnn_benchmark.utils.comm import get_world_size from maskrcnn_benchmark.utils.metric_logger import MetricLogger def reduce_loss_dict(all_loss_dict...
4,431
33.625
93
py
GLIP
GLIP-main/maskrcnn_benchmark/engine/trainer.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import datetime import logging import sys import os import math import time import torch import torch.distributed as dist from maskrcnn_benchmark.utils.comm import get_world_size, all_gather, is_main_process, broadcast_data, get_rank from maskrcn...
15,719
42.545706
130
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/c2_model_loading.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import logging import pickle from collections import OrderedDict import torch from maskrcnn_benchmark.utils.model_serialization import load_state_dict from maskrcnn_benchmark.utils.registry import Registry def _rename_basic_resnet_weights(layer...
8,396
39.370192
129
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/metric_logger.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. from collections import defaultdict from collections import deque import torch import time from datetime import datetime from .comm import is_main_process class SmoothedValue(object): """Track a series of values and provide access to smoothe...
3,687
27.152672
86
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/checkpoint.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import logging import os import torch from maskrcnn_benchmark.utils.model_serialization import load_state_dict from maskrcnn_benchmark.utils.c2_model_loading import load_c2_format from maskrcnn_benchmark.utils.big_model_loading import load_big_fo...
6,117
36.304878
98
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/fuse_helper.py
import torch import torch.nn as nn import torch.nn.functional as F import pdb import math from maskrcnn_benchmark.modeling.utils import cat, concat_box_prediction_layers, permute_and_flatten from timm.models.layers import DropPath from transformers.activations import ACT2FN class BertPredictionHeadTransform(nn.Module)...
26,691
42.829228
153
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/flops.py
import argparse import logging import torch import torch.nn as nn import timeit from maskrcnn_benchmark.layers import * from maskrcnn_benchmark.modeling.backbone.resnet_big import StdConv2d from maskrcnn_benchmark.modeling.backbone.fpn import * from maskrcnn_benchmark.modeling.rpn.inference import * from maskrcnn_benc...
7,203
27.931727
109
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/comm.py
""" This file contains primitives for multi-gpu communication. This is useful when doing distributed training. """ import pickle import time import functools import logging import torch import torch.distributed as dist import numpy as np def get_world_size(): if not dist.is_available(): return 1 if n...
4,423
27.178344
84
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/stats.py
''' Copyright (C) 2019 Sovrasov V. - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license. * You should have received a copy of the MIT license with * this file. If not visit https://opensource.org/licenses/MIT ''' import sys from functools import partial import ...
17,622
33.554902
90
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/pretrain_model_loading.py
import numpy as np import torch import torch.nn as nn from collections import OrderedDict def _remove_bn_statics(state_dict): layer_keys = sorted(state_dict.keys()) remove_list = [] for key in layer_keys: if 'running_mean' in key or 'running_var' in key or 'num_batches_tracked' in key: ...
1,647
31.96
89
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/model_zoo.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import os import sys try: from torch.hub import _download_url_to_file from torch.hub import urlparse from torch.hub import HASH_REGEX except ImportError: from torch.utils.model_zoo import _download_url_to_file from torch.utils....
3,041
48.064516
135
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/mdetr_dist.py
# Copyright (c) Aishwarya Kamath & Nicolas Carion. Licensed under the Apache License 2.0. All Rights Reserved # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Utilities related to distributed mode. By default, the reduce of metrics and such are done on GPU, since it's more straightforward (we...
6,818
28.647826
119
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/big_model_loading.py
import numpy as np import torch import torch.nn as nn from collections import OrderedDict def tf2th(conv_weights): """Possibly convert HWIO to OIHW.""" if conv_weights.ndim == 4: conv_weights = conv_weights.transpose([3, 2, 0, 1]) return torch.from_numpy(conv_weights) def _rename_conv_weights_f...
3,188
38.37037
104
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/collect_env.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import PIL from torch.utils.collect_env import get_pretty_env_info def get_pil_version(): return "\n Pillow ({})".format(PIL.__version__) def collect_env_info(): env_str = get_pretty_env_info() env_str += get_pil_version() ...
338
21.6
71
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/model_serialization.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. from collections import OrderedDict, defaultdict import logging import math import torch from maskrcnn_benchmark.utils.imports import import_file def resize_2d(posemb, shape_new): # Rescale the grid of position embeddings when loading from st...
7,256
45.22293
132
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/shallow_contrastive_loss_helper.py
import torch import maskrcnn_benchmark.utils.dist as dist def normalized_positive_map(positive_map): positive_map = positive_map.float() positive_map_num_pos = positive_map.sum(2) positive_map_num_pos[positive_map_num_pos == 0] = 1e-6 positive_map = positive_map / positive_map_num_pos.unsqueeze(-1) ...
2,101
35.241379
99
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/amp.py
from contextlib import contextmanager @contextmanager def nullcontext(enter_result=None, **kwargs): yield enter_result try: from torch.cuda.amp import autocast, GradScaler, custom_fwd, custom_bwd except: print('[Warning] Library for automatic mixed precision is not found, AMP is disabled!!') GradScale...
420
29.071429
92
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/dist.py
# Copyright (c) Aishwarya Kamath & Nicolas Carion. Licensed under the Apache License 2.0. All Rights Reserved # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ Utilities related to distributed mode. By default, the reduce of metrics and such are done on GPU, since it's more straightforward (we...
6,744
28.454148
119
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/ema.py
from copy import deepcopy from collections import OrderedDict import torch class ModelEma: def __init__(self, model, decay=0.9999, device=''): self.ema = deepcopy(model) self.ema.eval() self.decay = decay self.device = device if device: self.ema.to(device=device...
1,644
34
84
py
GLIP
GLIP-main/maskrcnn_benchmark/utils/imports.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch if torch._six.PY37: import importlib import importlib.util import sys # from https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path?utm_medium=organic&utm_source=google_rich_qa&utm_campa...
844
34.208333
168
py
GLIP
GLIP-main/maskrcnn_benchmark/data/collate_batch.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from maskrcnn_benchmark.structures.image_list import to_image_list import pdb class BatchCollator(object): """ From a list of samples from the dataset, returns the batched images and targets. This should be passed to t...
3,860
40.074468
111
py
GLIP
GLIP-main/maskrcnn_benchmark/data/build.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import bisect import copy import logging import os import torch.utils.data import torch.distributed as dist from maskrcnn_benchmark.utils.comm import get_world_size from maskrcnn_benchmark.utils.imports import import_file from . import datasets a...
22,626
45.177551
182
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/modulated_coco.py
import logging import os import os.path import math from PIL import Image, ImageDraw import random import numpy as np import torch import torchvision import torch.utils.data as data from pycocotools import mask as coco_mask from maskrcnn_benchmark.structures.bounding_box import BoxList from maskrcnn_benchmark.struct...
26,513
39.479389
182
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/caption.py
import torch import torch.distributed as dist import time from torchvision.ops import nms import random import numpy as np from PIL import Image, ImageDraw import pdb from maskrcnn_benchmark.structures.bounding_box import BoxList from .modulated_coco import ConvertCocoPolysToMask from .tsv import ODTSVDataset, TSVYamlD...
13,112
45.832143
861
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/voc.py
import os import torch import torch.utils.data from PIL import Image import sys if sys.version_info[0] == 2: import xml.etree.cElementTree as ET else: import xml.etree.ElementTree as ET from maskrcnn_benchmark.structures.bounding_box import BoxList class PascalVOCDataset(torch.utils.data.Dataset): CL...
4,121
29.533333
118
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/object365.py
import torch import torchvision import torch.utils.data as data from maskrcnn_benchmark.data.datasets.coco_dt import CocoDetectionTSV class Object365DetectionTSV(CocoDetectionTSV): pass
192
20.444444
69
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/vg.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import collections import json import os.path as op import numpy as np import torch from .tsv import TSVYamlDataset, find_file_path_in_yaml from .box_label_loader import BoxLabelLoader from maskrcnn_benchmark.data.datasets.coco_dt import CocoDete...
10,744
39.093284
112
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/refexp.py
import copy from collections import defaultdict from pathlib import Path import torch import torch.utils.data import maskrcnn_benchmark.utils.dist as dist from maskrcnn_benchmark.layers.set_loss import generalized_box_iou from .modulated_coco import ModulatedDataset class RefExpDataset(ModulatedDataset): pass ...
3,270
35.752809
101
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/custom_distributed_sampler.py
import math from typing import TypeVar, Optional, Iterator import torch from torch.utils.data import Sampler, Dataset import torch.distributed as dist import random import numpy as np import torch class DistributedSamplerChunkByNode(torch.utils.data.Sampler): def __init__(self, dataset, ...
7,776
40.811828
146
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/concat_dataset.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import bisect from torch.utils.data.dataset import ConcatDataset as _ConcatDataset class ConcatDataset(_ConcatDataset): """ Same as torch.utils.data.dataset.ConcatDataset, but exposes an extra method for querying the sizes of the ima...
766
30.958333
72
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/box_label_loader.py
import torch import numpy as np import math import base64 import collections import pycocotools.mask as mask_utils from maskrcnn_benchmark.structures.bounding_box import BoxList from maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask class LabelLoader(object): def __init__(self, labelmap, ex...
11,214
43.503968
118
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/mixup.py
"""Mixup detection dataset wrapper.""" from __future__ import absolute_import import numpy as np import torch import torch.utils.data as data class MixupDetection(data.Dataset): """Detection dataset wrapper that performs mixup for normal dataset. Parameters ---------- dataset : mx.gluon.data.Dataset ...
4,884
38.08
92
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/background.py
import os import os.path import json from PIL import Image import torch import torchvision import torch.utils.data as data from maskrcnn_benchmark.structures.bounding_box import BoxList class Background(data.Dataset): """ Background Args: root (string): Root directory where images are downloaded to. ...
1,577
28.773585
96
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/coco_dt.py
""" COCO dataset which returns image_id for evaluation. Mostly copy-paste from https://github.com/pytorch/vision/blob/13b35ff/references/detection/coco_utils.py """ import torch import json from PIL import Image, ImageDraw from .modulated_coco import ConvertCocoPolysToMask from .tsv import ODTSVDataset from pycocoto...
6,130
38.554839
176
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/flickr.py
import torch import torchvision import torch.utils.data as data from maskrcnn_benchmark.data.datasets.modulated_coco import ModulatedDataset class FlickrDataset(ModulatedDataset): pass
191
20.333333
76
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/mixed.py
import os import os.path from pathlib import Path from typing import Any, Callable, Optional, Tuple import torch from maskrcnn_benchmark.structures.bounding_box import BoxList from PIL import Image, ImageDraw from torchvision.datasets.vision import VisionDataset from .modulated_coco import ConvertCocoPolysToMask, ha...
5,286
35.212329
124
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/lvis.py
# Copyright (c) Aishwarya Kamath & Nicolas Carion. Licensed under the Apache License 2.0. All Rights Reserved # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import json import os import time from collections import defaultdict import pycocotools.mask as mask_utils import torchvision from PIL im...
8,869
32.097015
116
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/pseudo_data.py
import torch import torch.distributed as dist import time from torchvision.ops import nms import random import numpy as np from PIL import Image, ImageDraw import pdb from maskrcnn_benchmark.structures.bounding_box import BoxList from .modulated_coco import ConvertCocoPolysToMask from .tsv import ODTSVDataset, TSVYamlD...
9,133
38.886463
117
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/gqa.py
import json from pathlib import Path import torch import torchvision from .modulated_coco import ConvertCocoPolysToMask, ModulatedDataset class GQADataset(ModulatedDataset): pass class GQAQuestionAnswering(torchvision.datasets.CocoDetection): def __init__(self, img_folder, ann_file, transforms, return_mas...
3,662
38.815217
111
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/imagenet.py
import os import os.path import json from PIL import Image import torch.utils.data as data def pil_loader(path): # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835) with open(path, 'rb') as f: img = Image.open(f) return img.convert('RGB') class Im...
1,965
30.206349
118
py
GLIP
GLIP-main/maskrcnn_benchmark/data/datasets/phrasecut.py
import torch import torchvision import torch.utils.data as data from maskrcnn_benchmark.data.datasets.modulated_coco import ModulatedDataset class PhrasecutDetection(ModulatedDataset): pass
196
20.888889
76
py