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 |
|---|---|---|---|---|---|---|
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/roi_heads/shared_heads/res_layer.py | import torch.nn as nn
from mmcv.cnn import constant_init, kaiming_init
from mmcv.runner import load_checkpoint
from mmdet.core import auto_fp16
from mmdet.models.backbones import ResNet
from mmdet.models.builder import SHARED_HEADS
from mmdet.models.utils import ResLayer as _ResLayer
from mmdet.utils import get_root_l... | 2,475 | 30.341772 | 74 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/roi_heads/mask_heads/grid_head.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, kaiming_init, normal_init
from mmdet.models.builder import HEADS, build_loss
@HEADS.register_module()
class GridHead(nn.Module):
def __init__(self,
grid_points=9,
... | 15,432 | 41.869444 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/roi_heads/mask_heads/coarse_mask_head.py | import torch.nn as nn
from mmcv.cnn import ConvModule, constant_init, xavier_init
from mmdet.core import auto_fp16
from mmdet.models.builder import HEADS
from .fcn_mask_head import FCNMaskHead
@HEADS.register_module
class CoarseMaskHead(FCNMaskHead):
"""Coarse mask head used in PointRend.
Compared with stan... | 3,228 | 34.097826 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/roi_heads/mask_heads/maskiou_head.py | import numpy as np
import torch
import torch.nn as nn
from mmcv.cnn import kaiming_init, normal_init
from torch.nn.modules.utils import _pair
from mmdet.core import force_fp32
from mmdet.models.builder import HEADS, build_loss
from mmdet.ops import Conv2d, Linear, MaxPool2d
@HEADS.register_module()
class MaskIoUHead... | 7,351 | 38.106383 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/roi_heads/mask_heads/fcn_mask_head.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, build_upsample_layer
from torch.nn.modules.utils import _pair
from mmdet.core import auto_fp16, force_fp32, mask_target
from mmdet.models.builder import HEADS, build_loss
from mmdet.ops import Conv2d
... | 12,056 | 38.019417 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/roi_heads/mask_heads/fused_semantic_head.py | import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, kaiming_init
from mmdet.core import auto_fp16, force_fp32
from mmdet.models.builder import HEADS
@HEADS.register_module()
class FusedSemanticHead(nn.Module):
r"""Multi-level fused semantic segmentation head.
.. code-block... | 3,609 | 32.425926 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/roi_heads/mask_heads/mask_point_head.py | # Modified from https://github.com/facebookresearch/detectron2/tree/master/projects/PointRend/point_head/point_head.py # noqa
import torch
import torch.nn as nn
from mmcv.cnn import ConvModule, normal_init
from mmdet.models.builder import HEADS, build_loss
from mmdet.ops import point_sample, rel_roi_point_to_rel_img... | 13,192 | 42.830565 | 126 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/losses/ghm_loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
def _expand_onehot_labels(labels, label_weights, label_channels):
bin_labels = labels.new_full((labels.size(0), label_channels), 0)
inds = torch.nonzero(
(labels >= 0) & (labels < label_channels), as_tuple... | 6,358 | 35.757225 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/losses/mse_loss.py | import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import weighted_loss
@weighted_loss
def mse_loss(pred, target):
"""Warpper of mse loss"""
return F.mse_loss(pred, target, reduction='none')
@LOSSES.register_module()
class MSELoss(nn.Module):
"""MSELoss
... | 1,460 | 28.22 | 78 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/losses/pisa_loss.py | import torch
from mmdet.core import bbox_overlaps
def isr_p(cls_score,
bbox_pred,
bbox_targets,
rois,
sampling_results,
loss_cls,
bbox_coder,
k=2,
bias=0,
num_class=80):
"""Importance-based Sample Reweighting (ISR_P), posit... | 7,076 | 38.099448 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/losses/balanced_l1_loss.py | import numpy as np
import torch
import torch.nn as nn
from ..builder import LOSSES
from .utils import weighted_loss
@weighted_loss
def balanced_l1_loss(pred,
target,
beta=1.0,
alpha=0.5,
gamma=1.5,
reduction='mea... | 4,114 | 33.291667 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/losses/iou_loss.py | import torch
import torch.nn as nn
from mmdet.core import bbox_overlaps
from ..builder import LOSSES
from .utils import weighted_loss
@weighted_loss
def iou_loss(pred, target, eps=1e-6):
"""IoU loss.
Computing the IoU loss between a set of predicted bboxes and target bboxes.
The loss is calculated as ne... | 8,184 | 32.004032 | 89 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/losses/smooth_l1_loss.py | import torch
import torch.nn as nn
from ..builder import LOSSES
from .utils import weighted_loss
@weighted_loss
def smooth_l1_loss(pred, target, beta=1.0):
"""Smooth L1 loss
Args:
pred (torch.Tensor): The prediction.
target (torch.Tensor): The learning target of the prediction.
beta ... | 4,417 | 31.248175 | 78 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/losses/utils.py | import functools
import torch.nn.functional as F
def reduce_loss(loss, reduction):
"""Reduce loss as specified.
Args:
loss (Tensor): Elementwise loss tensor.
reduction (str): Options are "none", "mean" and "sum".
Return:
Tensor: Reduced loss tensor.
"""
reduction_enum = ... | 3,003 | 29.343434 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/losses/ae_loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
def ae_loss_per_image(tl_preds, br_preds, match):
"""Associative Embedding Loss in one image.
Associative Embedding Loss including two parts: pull loss and push loss.
Pull loss makes embedding vectors from sa... | 3,710 | 36.484848 | 143 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/losses/accuracy.py | import torch.nn as nn
def accuracy(pred, target, topk=1):
"""Calculate accuracy according to the prediction and target
Args:
pred (torch.Tensor): The model prediction.
target (torch.Tensor): The target of each prediction
topk (int | tuple[int], optional): If the predictions in ``topk`... | 1,975 | 30.365079 | 73 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/losses/focal_loss.py | import torch.nn as nn
import torch.nn.functional as F
from mmdet.ops import sigmoid_focal_loss as _sigmoid_focal_loss
from ..builder import LOSSES
from .utils import weight_reduce_loss
# This method is only for debugging
def py_sigmoid_focal_loss(pred,
target,
weig... | 6,357 | 39.496815 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/losses/cross_entropy_loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import weight_reduce_loss
def cross_entropy(pred,
label,
weight=None,
reduction='mean',
avg_factor=None,
class_weight=N... | 7,480 | 36.218905 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/losses/gaussian_focal_loss.py | import torch.nn as nn
from ..builder import LOSSES
from .utils import weighted_loss
@weighted_loss
def gaussian_focal_loss(pred, gaussian_target, alpha=2.0, gamma=4.0):
"""`Focal Loss <https://arxiv.org/abs/1708.02002>`_ for targets in
gaussian distribution.
Args:
pred (torch.Tensor): The predic... | 3,210 | 34.677778 | 108 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/backbones/hrnet.py | import torch.nn as nn
from mmcv.cnn import (build_conv_layer, build_norm_layer, constant_init,
kaiming_init)
from mmcv.runner import load_checkpoint
from torch.nn.modules.batchnorm import _BatchNorm
from mmdet.utils import get_root_logger
from ..builder import BACKBONES
from .resnet import BasicB... | 20,351 | 36.970149 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/backbones/regnet.py | import numpy as np
import torch.nn as nn
from mmcv.cnn import build_conv_layer, build_norm_layer
from ..builder import BACKBONES
from .resnet import ResNet
from .resnext import Bottleneck
@BACKBONES.register_module()
class RegNet(ResNet):
"""RegNet backbone.
More details can be found in `paper <https://arxi... | 12,074 | 36.616822 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/backbones/resnet.py | import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import (build_conv_layer, build_norm_layer, constant_init,
kaiming_init)
from mmcv.runner import load_checkpoint
from torch.nn.modules.batchnorm import _BatchNorm
from mmdet.ops import build_plugin_layer
from mmdet.utils impo... | 23,143 | 33.960725 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/backbones/ssd_vgg.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import VGG, constant_init, kaiming_init, normal_init, xavier_init
from mmcv.runner import load_checkpoint
from mmdet.utils import get_root_logger
from ..builder import BACKBONES
@BACKBONES.register_module()
class SSDVGG(VGG):
"""VGG... | 5,877 | 33.576471 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/backbones/resnext.py | import math
from mmcv.cnn import build_conv_layer, build_norm_layer
from ..builder import BACKBONES
from ..utils import ResLayer
from .resnet import Bottleneck as _Bottleneck
from .resnet import ResNet
class Bottleneck(_Bottleneck):
expansion = 4
def __init__(self,
inplanes,
... | 4,730 | 34.840909 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/backbones/hourglass.py | import torch.nn as nn
from mmcv.cnn import ConvModule
from ..builder import BACKBONES
from ..utils import ResLayer
from .resnet import BasicBlock
class HourglassModule(nn.Module):
"""Hourglass Module for HourglassNet backbone.
Generate module recursively and use BasicBlock as the base unit.
Args:
... | 6,256 | 31.252577 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/models/backbones/res2net.py | import math
import torch
import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import build_conv_layer, build_norm_layer
from ..builder import BACKBONES
from .resnet import Bottleneck as _Bottleneck
from .resnet import ResNet
class Bottle2neck(_Bottleneck):
expansion = 4
def __init__(self... | 11,207 | 34.580952 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/datasets/custom.py | import os.path as osp
import mmcv
import numpy as np
from torch.utils.data import Dataset
from mmdet.core import eval_map, eval_recalls
from .builder import DATASETS
from .pipelines import Compose
@DATASETS.register_module()
class CustomDataset(Dataset):
"""Custom dataset for detection.
The annotation form... | 11,187 | 33.9625 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/datasets/dataset_wrappers.py | import bisect
import math
from collections import defaultdict
import numpy as np
from torch.utils.data.dataset import ConcatDataset as _ConcatDataset
from .builder import DATASETS
@DATASETS.register_module()
class ConcatDataset(_ConcatDataset):
"""A wrapper of concatenated dataset.
Same as :obj:`torch.util... | 7,091 | 34.638191 | 167 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/datasets/builder.py | import copy
import platform
import random
from functools import partial
import numpy as np
from mmcv.parallel import collate
from mmcv.runner import get_dist_info
from mmcv.utils import Registry, build_from_cfg
from torch.utils.data import DataLoader
from .samplers import DistributedGroupSampler, DistributedSampler, ... | 4,875 | 34.852941 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/datasets/samplers/group_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 Sampler
class GroupSampler(Sampler):
def __init__(self, dataset, samples_per_gpu=1):
assert hasattr(dataset, 'flag')
self.dataset = dataset
self.... | 4,898 | 33.744681 | 78 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/datasets/samplers/distributed_sampler.py | import torch
from torch.utils.data import DistributedSampler as _DistributedSampler
class DistributedSampler(_DistributedSampler):
def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True):
super().__init__(dataset, num_replicas=num_replicas, rank=rank)
self.shuffle = shuffle
d... | 978 | 32.758621 | 77 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/datasets/pipelines/formating.py | from collections.abc import Sequence
import mmcv
import numpy as np
import torch
from mmcv.parallel import DataContainer as DC
from ..builder import PIPELINES
def to_tensor(data):
"""Convert objects of various python types to :obj:`torch.Tensor`.
Supported types are: :class:`numpy.ndarray`, :class:`torch.T... | 11,016 | 31.594675 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/utils/contextmanagers.py | 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='',
name='',
... | 4,089 | 31.460317 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/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,289 | 30.463415 | 68 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/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 mmdet
def collect_env():
"""Collect the information of the running environments."""
env_info = {}
env_info['sys.platform'] = sys.platform
env_info['Pyt... | 2,016 | 30.030769 | 74 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/non_local.py | import torch
import torch.nn as nn
from mmcv.cnn import ConvModule, constant_init, normal_init
class NonLocal2D(nn.Module):
"""Non-local module.
See https://arxiv.org/abs/1711.07971 for details.
Args:
in_channels (int): Channels of the input feature map.
reduction (int): Channel reductio... | 3,568 | 33.317308 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/point_sample.py | # Modified from https://github.com/facebookresearch/detectron2/tree/master/projects/PointRend # noqa
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import _pair
def normalize(grid):
"""Normalize input grid from [-1, 1] to [0, 1]
Args:
grid (Tensor): T... | 7,581 | 33.621005 | 101 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/conv_ws.py | import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import CONV_LAYERS
def conv_ws_2d(input,
weight,
bias=None,
stride=1,
padding=0,
dilation=1,
groups=1,
eps=1e-5):
c_in = weight.size(0)
w... | 1,407 | 27.734694 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/context_block.py | import torch
from mmcv.cnn import constant_init, kaiming_init
from torch import nn
def last_zero_init(m):
if isinstance(m, nn.Sequential):
constant_init(m[-1], val=0)
else:
constant_init(m, val=0)
class ContextBlock(nn.Module):
"""ContextBlock module in GCNet.
See 'GCNet: Non-local ... | 4,303 | 35.786325 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/wrappers.py | """
Modified from https://github.com/facebookresearch/detectron2/blob/master
/detectron2/layers/wrappers.py
Wrap some nn modules to support empty tensor input.
Currently, these wrappers are mainly used in mask heads like fcn_mask_head
and maskiou_heads since mask heads are trained on only positive RoIs.
"""
import math... | 3,539 | 34.049505 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/generalized_attention.py | import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import kaiming_init
class GeneralizedAttention(nn.Module):
"""GeneralizedAttention module.
See 'An Empirical Study of Spatial Attention Mechanisms in Deep Networks'
(https://arxiv.org/abs/1711... | 15,077 | 38.163636 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/merge_cells.py | from abc import abstractmethod
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule
class BaseMergeCell(nn.Module):
"""The basic class for cells used in NAS-FPN and NAS-FCOS.
BaseMergeCell takes 2 inputs. After applying concolution
on them, they are resized ... | 5,358 | 34.966443 | 78 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/dcn/deform_pool.py | import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import deform_pool_ext
class DeformRoIPoolingFunction(Function):
@staticmethod
def forward(ctx,
data,
... | 10,481 | 39.471042 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/dcn/deform_conv.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import CONV_LAYERS
from mmcv.utils import print_log
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair, _single
from . import deform_conv_ext
... | 18,071 | 38.286957 | 80 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/carafe/grad_check.py | import os.path as osp
import sys
import mmcv
import torch
from torch.autograd import gradcheck
sys.path.append(osp.abspath(osp.join(__file__, '../../')))
from mmdet.ops.carafe import CARAFE, CARAFENaive # noqa: E402, isort:skip
from mmdet.ops.carafe import carafe, carafe_naive # noqa: E402, isort:skip
feat = torch... | 2,158 | 33.269841 | 77 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/carafe/setup.py | from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
NVCC_ARGS = [
'-D__CUDA_NO_HALF_OPERATORS__',
'-D__CUDA_NO_HALF_CONVERSIONS__',
'-D__CUDA_NO_HALF2_OPERATORS__',
]
setup(
name='carafe',
ext_modules=[
CUDAExtension(
'carafe_ext', ... | 1,041 | 27.162162 | 77 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/carafe/carafe.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import UPSAMPLE_LAYERS, normal_init, xavier_init
from torch.autograd import Function
from torch.nn.modules.module import Module
from . import carafe_ext, carafe_naive_ext
class CARAFENaiveFunction(Function):
@staticmethod
def f... | 8,829 | 36.10084 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/masked_conv/masked_conv.py | import math
import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import masked_conv2d_ext
class MaskedConv2dFunction(Function):
@staticmethod
def forward(ctx, features, mask, weight, bi... | 3,383 | 36.6 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/sigmoid_focal_loss/sigmoid_focal_loss.py | import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from . import sigmoid_focal_loss_ext
class SigmoidFocalLossFunction(Function):
@staticmethod
def forward(ctx, input, target, gamma=2.0, alpha=0.25):
ctx.save_for_backward(input, target)
... | 1,625 | 28.563636 | 76 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/roi_align/roi_align.py | from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import roi_align_ext
class RoIAlignFunction(Function):
@staticmethod
def forward(ctx,
features,
rois,
... | 6,183 | 38.896774 | 79 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/roi_align/gradcheck.py | import os.path as osp
import sys
import numpy as np
import torch
from torch.autograd import gradcheck
sys.path.append(osp.abspath(osp.join(__file__, '../../')))
from roi_align import RoIAlign # noqa: E402, isort:skip
feat_size = 15
spatial_scale = 1.0 / 8
img_size = feat_size / spatial_scale
num_imgs = 2
num_rois =... | 879 | 27.387097 | 76 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/corner_pool/corner_pool.py | from torch import nn
from torch.autograd import Function
from . import corner_pool_ext
class TopPoolFunction(Function):
@staticmethod
def forward(ctx, input):
output = corner_pool_ext.top_pool_forward(input)
ctx.save_for_backward(input)
return output
@staticmethod
def backwa... | 2,665 | 25.137255 | 73 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/roi_pool/roi_pool.py | import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from . import roi_pool_ext
class RoIPoolFunction(Function):
@staticmethod
def forward(ctx, features, rois, out_size, spatial_scale):
... | 2,534 | 32.355263 | 78 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/roi_pool/gradcheck.py | import os.path as osp
import sys
import torch
from torch.autograd import gradcheck
sys.path.append(osp.abspath(osp.join(__file__, '../../')))
from roi_pool import RoIPool # noqa: E402, isort:skip
feat = torch.randn(4, 16, 15, 15, requires_grad=True).cuda()
rois = torch.Tensor([[0, 0, 0, 50, 50], [0, 10, 30, 43, 55]... | 513 | 29.235294 | 66 | py |
Mask-aware-IoU | Mask-aware-IoU-master/mmdet/ops/nms/nms_wrapper.py | import numpy as np
import torch
from . import nms_ext
def nms(dets, iou_thr, device_id=None):
"""Dispatch to either CPU or GPU NMS implementations.
The input can be either a torch tensor or numpy array. GPU NMS will be used
if the input is a gpu tensor or device_id is specified, otherwise CPU NMS
wi... | 7,224 | 36.827225 | 79 | py |
Sparse-Sharpness-Aware-Minimization | Sparse-Sharpness-Aware-Minimization-main/train.py | import os
import time
import datetime
import torch
from models.build import build_model
from data.build import build_dataset, build_train_dataloader, build_val_dataloader
from solver.build import build_optimizer, build_lr_scheduler
from utils.logger import Logger
from utils.dist import init_distributed_model, is_mai... | 4,290 | 34.172131 | 124 | py |
Sparse-Sharpness-Aware-Minimization | Sparse-Sharpness-Aware-Minimization-main/solver/lr_scheduler.py | import math
from typing import List
import torch
import torch.optim as optim
from utils.configurable import configurable
from solver.build import LR_SCHEDULER_REGISTRY
class LRscheduler:
def __init__(self, optimizer: optim.Optimizer, resume: bool = False):
self.optimizer = optimizer
i... | 4,152 | 31.700787 | 138 | py |
Sparse-Sharpness-Aware-Minimization | Sparse-Sharpness-Aware-Minimization-main/solver/sam.py | import math
import torch
import torch.optim
from utils.configurable import configurable
from solver.build import OPTIMIZER_REGISTRY
@OPTIMIZER_REGISTRY.register()
class SAM(torch.optim.Optimizer):
@configurable()
def __init__(self, params, base_optimizer, rho) -> None:
assert isinstance(base_optimiz... | 15,172 | 39.140212 | 132 | py |
Sparse-Sharpness-Aware-Minimization | Sparse-Sharpness-Aware-Minimization-main/solver/build.py | import torch.optim as optim
from utils.register import Registry
OPTIMIZER_REGISTRY = Registry("Optimizer")
LR_SCHEDULER_REGISTRY = Registry("LRscheduler")
def build_base_optimizer(args, parameters):
opt_kwargs = dict(
lr=args.lr,
weight_decay=args.weight_decay,
nesterov=args.nesterov,
... | 1,761 | 33.54902 | 128 | py |
Sparse-Sharpness-Aware-Minimization | Sparse-Sharpness-Aware-Minimization-main/models/resnet.py | '''ResNet in PyTorch.
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from utils.configurable import configurable
from models.build import MODEL... | 5,553 | 34.602564 | 83 | py |
Sparse-Sharpness-Aware-Minimization | Sparse-Sharpness-Aware-Minimization-main/models/vgg.py | """vgg in pytorch
[1] Karen Simonyan, Andrew Zisserman
Very Deep Convolutional Networks for Large-Scale Image Recognition.
https://arxiv.org/abs/1409.1556v6
"""
'''VGG11/13/16/19 in Pytorch.'''
import torch
import torch.nn as nn
from utils.configurable import configurable
from models.build import MODELS_REGIST... | 2,618 | 29.453488 | 114 | py |
Sparse-Sharpness-Aware-Minimization | Sparse-Sharpness-Aware-Minimization-main/models/wideresnet.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.configurable import configurable
from models.build import MODELS_REGISTRY
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, dropRate=0.0):
super(BasicBlock, self).__init__()
self... | 4,324 | 36.938596 | 116 | py |
Sparse-Sharpness-Aware-Minimization | Sparse-Sharpness-Aware-Minimization-main/utils/engine.py | import time
from collections import defaultdict
from typing import Iterable
import torch
import torch.distributed as dist
from utils.dist import is_dist_avail_and_initialized
def train_one_epoch(
model: torch.nn.Module,
train_loader : Iterable,
criterion, optimizer, epoch, logger, log_freq, use_closure
):... | 5,201 | 31.716981 | 125 | py |
Sparse-Sharpness-Aware-Minimization | Sparse-Sharpness-Aware-Minimization-main/utils/seed.py | import torch
import numpy as np
import random
from utils.dist import get_rank
def setup_seed(args):
if args.seed is None: return
seed = args.seed + get_rank()
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.cuda.manual_seed(seed)
np.random.seed(seed)
random.seed(seed) | 313 | 21.428571 | 36 | py |
Sparse-Sharpness-Aware-Minimization | Sparse-Sharpness-Aware-Minimization-main/utils/dist.py | import os
import functools
import torch
import torch.distributed as dist
def is_dist_avail_and_initialized():
if not dist.is_available():
return False
if not dist.is_initialized():
return False
return True
def get_world_size():
if not is_dist_avail_and_initialized():
return 1
... | 1,945 | 28.044776 | 94 | py |
Sparse-Sharpness-Aware-Minimization | Sparse-Sharpness-Aware-Minimization-main/data/dataset.py | import torch
import torchvision.datasets
import torchvision.transforms
import numpy as np
from utils.configurable import configurable
from data.build import DATASET_REGISTRY
@DATASET_REGISTRY.register()
class CIFAR10_base:
@configurable
def __init__(self, datadir) -> None:
self.datadir = datadir
... | 6,050 | 32.994382 | 131 | py |
Sparse-Sharpness-Aware-Minimization | Sparse-Sharpness-Aware-Minimization-main/data/build.py |
import torch
from torch.utils.data import RandomSampler, DistributedSampler, SequentialSampler
from utils.configurable import configurable
from utils.register import Registry
from utils.dist import get_world_size, get_rank
DATASET_REGISTRY = Registry("Datasets")
def build_dataset(args):
dataset = DATASET_REGIST... | 2,866 | 26.567308 | 115 | py |
melodyExtraction_SSL | melodyExtraction_SSL-master/model.py | import keras.backend as KK
import math
from keras import backend as K
from keras.regularizers import l2
from keras.layers.advanced_activations import LeakyReLU, ReLU
from keras.models import model_from_json, Model, Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers import Con... | 2,648 | 35.791667 | 98 | py |
X-FNC | X-FNC-main/train_xfnc.py | import networkx as nx
import numpy as np
import random
import torch
import numpy as np
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from sklearn.model_selection import StratifiedKFold
import sys
import scipy
import sklearn
import json
from collections import defaultdict
import torch.optim as optim
... | 23,998 | 34.240822 | 150 | py |
X-FNC | X-FNC-main/model.py | import networkx as nx
import numpy as np
import random
import torch
import numpy as np
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from sklearn.model_selection import StratifiedKFold
import sys
import scipy
import sklearn
import json
from collections import defaultdict
import torch.optim as optim
... | 3,677 | 29.396694 | 117 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/tools/test.py | import argparse
import os
import mmcv
import torch
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import get_dist_info, init_dist, load_checkpoint
from mmcv.utils import DictAction
from mmseg.apis import multi_gpu_test, single_gpu_test
from mmseg.datasets import build_dataloader,... | 5,611 | 35.441558 | 79 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/tools/benchmark.py | import argparse
import time
import torch
from mmcv import Config
from mmcv.parallel import MMDataParallel
from mmcv.runner import load_checkpoint
from mmseg.datasets import build_dataloader, build_dataset
from mmseg.models import build_segmentor
def parse_args():
parser = argparse.ArgumentParser(description='MM... | 2,394 | 27.855422 | 75 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/tools/publish_model.py | import argparse
import subprocess
import torch
def parse_args():
parser = argparse.ArgumentParser(
description='Process a checkpoint to be published')
parser.add_argument('in_file', help='input checkpoint filename')
parser.add_argument('out_file', help='output checkpoint filename')
args = par... | 1,028 | 27.583333 | 77 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/tools/pytorch2onnx.py | import argparse
from functools import partial
import mmcv
import numpy as np
import onnxruntime as rt
import torch
import torch._C
import torch.serialization
from mmcv.onnx import register_extra_symbolics
from mmcv.runner import load_checkpoint
from torch import nn
from mmseg.models import build_segmentor
torch.manu... | 6,795 | 32.810945 | 79 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/tools/train.py | import argparse
import copy
import os
import os.path as osp
import time
import mmcv
import torch
from mmcv.runner import init_dist
from mmcv.utils import Config, DictAction, get_git_hash
from mmseg import __version__
from mmseg.apis import set_random_seed, train_segmentor
from mmseg.datasets import build_dataset
from... | 5,706 | 33.79878 | 79 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/apis/inference.py | import matplotlib.pyplot as plt
import mmcv
import torch
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from mmseg.datasets.pipelines import Compose
from mmseg.models import build_segmentor
def init_segmentor(config, checkpoint=None, device='cuda:0'):
"""Initialize a segmentor... | 4,296 | 32.570313 | 79 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/apis/test.py | import os.path as osp
import pickle
import shutil
import tempfile
import mmcv
import numpy as np
import torch
import torch.distributed as dist
from mmcv.image import tensor2imgs
from mmcv.runner import get_dist_info
def np2tmp(array, temp_file_name=None):
"""Save ndarray to local numpy file.
Args:
a... | 8,231 | 33.443515 | 79 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/apis/train.py | import random
import warnings
import numpy as np
import torch
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import build_optimizer, build_runner
from mmseg.core import DistEvalHook, EvalHook
from mmseg.datasets import build_dataloader, build_dataset
from mmseg.utils import get_r... | 3,919 | 32.504274 | 78 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/core/evaluation/eval_hooks.py | import os.path as osp
from mmcv.runner import Hook
from torch.utils.data import DataLoader
class EvalHook(Hook):
"""Evaluation hook.
Attributes:
dataloader (DataLoader): A PyTorch dataloader.
interval (int): Evaluation interval (by epochs). Default: 1.
"""
def __init__(self, dataloa... | 3,858 | 34.731481 | 79 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/core/evaluation/metrics.py | import mmcv
import numpy as np
import torch
def intersect_and_union(pred_label,
label,
num_classes,
ignore_index,
label_map=dict(),
reduce_zero_label=False):
"""Calculate intersection and Union.... | 9,896 | 39.561475 | 79 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/core/seg/sampler/ohem_pixel_sampler.py | import torch
import torch.nn.functional as F
from ..builder import PIXEL_SAMPLERS
from .base_pixel_sampler import BasePixelSampler
@PIXEL_SAMPLERS.register_module()
class OHEMPixelSampler(BasePixelSampler):
"""Online Hard Example Mining Sampler for segmentation.
Args:
context (nn.Module): The contex... | 3,155 | 39.987013 | 103 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/builder.py | import warnings
from mmcv.utils import Registry, build_from_cfg
from torch import nn
BACKBONES = Registry('backbone')
NECKS = Registry('neck')
HEADS = Registry('head')
LOSSES = Registry('loss')
SEGMENTORS = Registry('segmentor')
def build(cfg, registry, default_args=None):
"""Build a module.
Args:
... | 1,822 | 26.208955 | 79 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/necks/fpn.py | import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, xavier_init
from ..builder import NECKS
@NECKS.register_module()
class FPN(nn.Module):
"""Feature Pyramid Network.
This is an implementation of - Feature Pyramid Networks for Object
Detection (https://arxiv.org/abs/16... | 9,139 | 41.910798 | 79 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/fcn_head.py | import torch
import torch.nn as nn
from mmcv.cnn import ConvModule
from ..builder import HEADS
from .decode_head import BaseDecodeHead
@HEADS.register_module()
class FCNHead(BaseDecodeHead):
"""Fully Convolution Networks for Semantic Segmentation.
This head is implemented of `FCNNet <https://arxiv.org/abs/1... | 2,797 | 33.121951 | 77 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/sep_aspp_head.py | import torch
import torch.nn as nn
from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule
from mmseg.ops import resize
from ..builder import HEADS
from .aspp_head import ASPPHead, ASPPModule
class DepthwiseSeparableASPPModule(ASPPModule):
"""Atrous Spatial Pyramid Pooling (ASPP) Module with depthwise sepa... | 3,487 | 33.196078 | 76 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/ann_head.py | import torch
import torch.nn as nn
from mmcv.cnn import ConvModule
from ..builder import HEADS
from ..utils import SelfAttentionBlock as _SelfAttentionBlock
from .decode_head import BaseDecodeHead
class PPMConcat(nn.ModuleList):
"""Pyramid Pooling Module that only concat the features of each layer.
Args:
... | 9,174 | 36.296748 | 77 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/apc_head.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule
from mmseg.ops import resize
from ..builder import HEADS
from .decode_head import BaseDecodeHead
class ACM(nn.Module):
"""Adaptive Context Module used in APCNet.
Args:
pool_scale (int): Pooling scale u... | 5,532 | 33.798742 | 76 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/ocr_head.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule
from mmseg.ops import resize
from ..builder import HEADS
from ..utils import SelfAttentionBlock as _SelfAttentionBlock
from .cascade_decode_head import BaseCascadeDecodeHead
class SpatialGatherModule(nn.Module):
""... | 4,279 | 32.4375 | 76 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/dm_head.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, build_activation_layer, build_norm_layer
from ..builder import HEADS
from .decode_head import BaseDecodeHead
class DCM(nn.Module):
"""Dynamic Convolutional Module used in DMNet.
Args:
filter_size (int... | 4,984 | 34.35461 | 79 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/ema_head.py | import math
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule
from ..builder import HEADS
from .decode_head import BaseDecodeHead
def reduce_mean(tensor):
"""Reduce mean when distributed training."""
if not (dist.is_available(... | 5,776 | 33.183432 | 77 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/da_head.py | import torch
import torch.nn.functional as F
from mmcv.cnn import ConvModule, Scale
from torch import nn
from mmseg.core import add_prefix
from ..builder import HEADS
from ..utils import SelfAttentionBlock as _SelfAttentionBlock
from .decode_head import BaseDecodeHead
class PAM(_SelfAttentionBlock):
"""Position ... | 5,545 | 29.98324 | 77 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/psp_head.py | import torch
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmseg.ops import resize
from ..builder import HEADS
from .decode_head import BaseDecodeHead
class PPM(nn.ModuleList):
"""Pooling Pyramid Module used in PSPNet.
Args:
pool_scales (tuple[int]): Pooling scales used in Pooling Pyram... | 3,312 | 31.480392 | 78 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/cc_head.py | import torch
from ..builder import HEADS
from .fcn_head import FCNHead
try:
from mmcv.ops import CrissCrossAttention
except ModuleNotFoundError:
CrissCrossAttention = None
@HEADS.register_module()
class CCHead(FCNHead):
"""CCNet: Criss-Cross Attention for Semantic Segmentation.
This head is the imp... | 1,283 | 28.860465 | 71 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/enc_head.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, build_norm_layer
from mmseg.ops import Encoding, resize
from ..builder import HEADS, build_loss
from .decode_head import BaseDecodeHead
class EncModule(nn.Module):
"""Encoding Module used in EncNet.
Args:
... | 6,744 | 34.87766 | 78 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/fpn_head.py | import numpy as np
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmseg.ops import resize
from ..builder import HEADS
from .decode_head import BaseDecodeHead
@HEADS.register_module()
class FPNHead(BaseDecodeHead):
"""Panoptic Feature Pyramid Networks.
This head is the implementation of `Semantic... | 2,382 | 33.536232 | 79 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/nl_head.py | import torch
from mmcv.cnn import NonLocal2d
from ..builder import HEADS
from .fcn_head import FCNHead
@HEADS.register_module()
class NLHead(FCNHead):
"""Non-local Neural Networks.
This head is the implementation of `NLNet
<https://arxiv.org/abs/1711.07971>`_.
Args:
reduction (int): Reducti... | 1,557 | 30.16 | 78 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/dnl_head.py | import torch
from mmcv.cnn import NonLocal2d
from torch import nn
from ..builder import HEADS
from .fcn_head import FCNHead
class DisentangledNonLocal2d(NonLocal2d):
"""Disentangled Non-Local Blocks.
Args:
temperature (float): Temperature to adjust attention. Default: 0.05
"""
def __init__(... | 4,571 | 33.636364 | 78 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/decode_head.py | from abc import ABCMeta, abstractmethod
import torch
import torch.nn as nn
from mmcv.cnn import normal_init
from mmcv.runner import auto_fp16, force_fp32
from mmseg.core import build_pixel_sampler
from mmseg.ops import resize
from ..builder import build_loss
from ..losses import accuracy
class BaseDecodeHead(nn.Mod... | 9,160 | 37.982979 | 78 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/lraspp_head.py | import torch
import torch.nn as nn
from mmcv import is_tuple_of
from mmcv.cnn import ConvModule
from mmseg.ops import resize
from ..builder import HEADS
from .decode_head import BaseDecodeHead
@HEADS.register_module()
class LRASPPHead(BaseDecodeHead):
"""Lite R-ASPP (LRASPP) head is proposed in Searching for Mob... | 3,038 | 32.395604 | 77 | py |
Swin-Transformer-Semantic-Segmentation-mmseg | Swin-Transformer-Semantic-Segmentation-mmseg-master/mmseg/models/decode_heads/uper_head.py | import torch
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmseg.ops import resize
from ..builder import HEADS
from .decode_head import BaseDecodeHead
from .psp_head import PPM
@HEADS.register_module()
class UPerHead(BaseDecodeHead):
"""Unified Perceptual Parsing for Scene Understanding.
This h... | 3,972 | 30.283465 | 72 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.