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 |
|---|---|---|---|---|---|---|
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/roi_extractors/base_roi_extractor.py | from abc import ABCMeta, abstractmethod
import torch
import torch.nn as nn
from mmdet import ops
class BaseRoIExtractor(nn.Module, metaclass=ABCMeta):
"""Base class for RoI extractor.
Args:
roi_layer (dict): Specify RoI layer type and arguments.
out_channels (int): Output channels of RoI la... | 2,763 | 31.517647 | 79 | py |
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/roi_extractors/single_level_roi_extractor.py | import torch
from mmdet.core import force_fp32
from mmdet.models.builder import ROI_EXTRACTORS
from .base_roi_extractor import BaseRoIExtractor
@ROI_EXTRACTORS.register_module()
class SingleRoIExtractor(BaseRoIExtractor):
"""Extract RoI features from a single level feature map.
If there are multiple input f... | 2,910 | 36.320513 | 79 | py |
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/roi_extractors/obb/hbb_select_level_roi_extractor.py | import torch
from mmdet.core import force_fp32, obb2hbb
from mmdet.models.builder import ROI_EXTRACTORS
from .obb_base_roi_extractor import OBBBaseRoIExtractor
@ROI_EXTRACTORS.register_module()
class HBBSelectLVLRoIExtractor(OBBBaseRoIExtractor):
"""Extract RoI features from a single level feature map.
If t... | 3,077 | 37 | 79 | py |
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/roi_extractors/obb/obb_base_roi_extractor.py | from abc import ABCMeta, abstractmethod
import torch
import torch.nn as nn
from torch.nn.modules.utils import _pair
from mmdet import ops
class OBBBaseRoIExtractor(nn.Module, metaclass=ABCMeta):
"""Base class for RoI extractor.
Args:
roi_layer (dict): Specify RoI layer type and arguments.
o... | 2,656 | 32.2125 | 79 | py |
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/roi_extractors/obb/obb_single_level_roi_extractor.py | import torch
from mmdet.core import force_fp32
from mmdet.models.builder import ROI_EXTRACTORS
from .obb_base_roi_extractor import OBBBaseRoIExtractor
@ROI_EXTRACTORS.register_module()
class OBBSingleRoIExtractor(OBBBaseRoIExtractor):
"""Extract RoI features from a single level feature map.
If there are mul... | 2,983 | 36.772152 | 79 | py |
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/obb/obb_base_roi_head.py | from abc import ABCMeta, abstractmethod
import torch.nn as nn
from mmdet.models.builder import build_shared_head
class OBBBaseRoIHead(nn.Module, metaclass=ABCMeta):
"""Base class for RoIHeads"""
def __init__(self,
bbox_roi_extractor=None,
bbox_head=None,
s... | 2,662 | 27.634409 | 78 | py |
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/obb/obb_test_mixins.py | import logging
import sys
import numpy as np
import torch
from mmdet.core import (arb2roi, arb_mapping, merge_rotate_aug_arb,
get_bbox_type, multiclass_arb_nms)
logger = logging.getLogger(__name__)
if sys.version_info >= (3, 7):
from mmdet.utils.contextmanagers import completed
class O... | 5,104 | 42.262712 | 91 | py |
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/obb/obb_standard_roi_head.py | import torch
from mmdet.core import arb2result, arb2roi, build_assigner, build_sampler
from mmdet.models.builder import HEADS, build_head, build_roi_extractor
from .obb_test_mixins import OBBoxTestMixin
from .obb_base_roi_head import OBBBaseRoIHead
@HEADS.register_module()
class OBBStandardRoIHead(OBBBaseRoIHead, O... | 8,907 | 41.218009 | 86 | py |
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/obb/gv_ratio_roi_head.py | import torch
import torch.nn as nn
import numpy as np
from .obb_standard_roi_head import OBBStandardRoIHead
from mmdet.core import (arb2roi, arb2result, arb_mapping, merge_rotate_aug_arb,
multiclass_arb_nms)
from mmdet.models.builder import HEADS
@HEADS.register_module()
class GVRatioRoIHead(... | 6,013 | 42.89781 | 91 | py |
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/obb/roitrans_roi_head.py | import torch
import torch.nn as nn
import numpy as np
from mmdet.core import (hbb_mapping, build_assigner,
build_sampler, merge_rotate_aug_arb,
multiclass_arb_nms)
from mmdet.core import arb2roi, arb2result
from mmdet.core import regular_obb, get_bbox_dim
from mmdet.mode... | 13,056 | 42.092409 | 93 | py |
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/bbox_heads/bbox_head.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import _pair
from mmdet.core import (auto_fp16, build_bbox_coder, force_fp32, multi_apply,
multiclass_nms)
from mmdet.models.builder import HEADS, build_loss
from mmdet.models.losses import accuracy
... | 13,618 | 39.653731 | 79 | py |
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/bbox_heads/convfc_bbox_head.py | import torch.nn as nn
from mmcv.cnn import ConvModule
from mmdet.models.builder import HEADS
from .bbox_head import BBoxHead
@HEADS.register_module()
class ConvFCBBoxHead(BBoxHead):
r"""More general bbox head, with shared conv and fc layers and two optional
separated branches.
.. code-block:: none
... | 7,435 | 35.097087 | 79 | py |
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/bbox_heads/double_bbox_head.py | import torch.nn as nn
from mmcv.cnn import ConvModule, normal_init, xavier_init
from mmdet.models.backbones.resnet import Bottleneck
from mmdet.models.builder import HEADS
from .bbox_head import BBoxHead
class BasicResBlock(nn.Module):
"""Basic residual block.
This block is a little different from the block... | 5,378 | 30.092486 | 78 | py |
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/bbox_heads/obb/gv_bbox_head.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import _pair
from mmdet.core import (auto_fp16, build_bbox_coder, force_fp32, multi_apply,
multiclass_arb_nms, hbb2poly, bbox2type)
from mmdet.models.builder import HEADS, build_loss
from mmdet.models... | 15,428 | 39.602632 | 87 | py |
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/bbox_heads/obb/obb_double_bbox_head.py | import torch.nn as nn
from mmcv.cnn import ConvModule, normal_init, xavier_init
from mmdet.models.backbones.resnet import Bottleneck
from mmdet.models.builder import HEADS
from .obbox_head import OBBoxHead
class BasicResBlock(nn.Module):
"""Basic residual block.
This block is a little different from the blo... | 5,427 | 30.195402 | 78 | py |
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/bbox_heads/obb/obbox_head.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.utils import _pair
from mmdet.core import (auto_fp16, build_bbox_coder, force_fp32, multi_apply,
multiclass_arb_nms, get_bbox_dim, bbox2type)
from mmdet.models.builder import HEADS, build_loss
from mmdet.mo... | 14,630 | 40.214085 | 86 | py |
RSP | RSP-main/Object Detection/mmdet/models/roi_heads/bbox_heads/obb/obb_convfc_bbox_head.py | import torch.nn as nn
from mmcv.cnn import ConvModule
from mmdet.models.builder import HEADS
from .obbox_head import OBBoxHead
@HEADS.register_module()
class OBBConvFCBBoxHead(OBBoxHead):
r"""More general bbox head, with shared conv and fc layers and two optional
separated branches.
.. code-block:: none... | 7,480 | 35.315534 | 79 | py |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 st... | 3,230 | 34.119565 | 79 | py |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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,055 | 38.016181 | 79 | py |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/mmdet/models/losses/gfocal_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 quality_focal_loss(pred, target, beta=2.0):
"""Quality Focal Loss (QFL) is from
Generalized Focal Loss: Learning Qualified and Distributed Bounding Boxes
for Dense Object... | 7,296 | 37.405263 | 79 | py |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/mmdet/models/losses/obb/poly_iou_loss.py | import torch
import torch.nn as nn
from mmdet.ops import convex_sort
from mmdet.core import bbox2type, get_bbox_areas
from mmdet.models.builder import LOSSES
from ..utils import weighted_loss
def shoelace(pts):
roll_pts = torch.roll(pts, 1, dims=-2)
xyxy = pts[..., 0] * roll_pts[..., 1] - \
roll_p... | 7,495 | 33.385321 | 91 | py |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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,174 | 36.693498 | 79 | py |
RSP | RSP-main/Object Detection/mmdet/models/backbones/detectors_resnext.py | import math
from mmcv.cnn import build_conv_layer, build_norm_layer
from ..builder import BACKBONES
from .detectors_resnet import Bottleneck as _Bottleneck
from .detectors_resnet import DetectoRS_ResNet
class Bottleneck(_Bottleneck):
expansion = 4
def __init__(self,
inplanes,
... | 3,871 | 30.737705 | 75 | py |
RSP | RSP-main/Object Detection/mmdet/models/backbones/swin_transformer.py | # --------------------------------------------------------
# Swin Transformer
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ze Liu, Yutong Lin, Yixuan Wei
# --------------------------------------------------------
import warnings
from collections import OrderedDi... | 25,850 | 37.873684 | 123 | py |
RSP | RSP-main/Object Detection/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 mmcv_custom import load_checkpoint
from torch.nn.modules.batchnorm import _BatchNorm
from mmdet.ops import... | 23,264 | 33.932432 | 79 | py |
RSP | RSP-main/Object Detection/mmdet/models/backbones/detectors_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
from ..builder import BACKBONES
from .resnet import Bottleneck as _Bottleneck
from .resnet import ResNet
class Bottleneck(_Bottleneck):
"""Bottleneck for the ResNet backbone in `Detect... | 10,513 | 33.359477 | 78 | py |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/mmdet/models/backbones/our_resnet.py | import math
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import os
import torchvision
torchvision.models.resnext50_32x4d()
from mmcv.cnn import (constant_init, kaiming_init)
#from ..backbones.custom_load import load_checkpoint
from mmdet.utils import get_root_logger
#from mmcv.utils.r... | 17,349 | 38.793578 | 110 | py |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/mmdet/models/backbones/ViTAE_Window_NoShift/base_model.py | from functools import partial
from pyexpat import model
import torch
import torch.nn as nn
from timm.models.layers import trunc_normal_
import numpy as np
from torch.nn.functional import instance_norm
from torch.nn.modules.batchnorm import BatchNorm2d
from .NormalCell import NormalCell
from .ReductionCell import Reduct... | 16,879 | 44.376344 | 199 | py |
RSP | RSP-main/Object Detection/mmdet/models/backbones/ViTAE_Window_NoShift/swin.py | # --------------------------------------------------------
# Swin Transformer
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ze Liu
# --------------------------------------------------------
import torch
import torch.nn as nn
import torch.utils.checkpoint as chec... | 24,644 | 40.559865 | 142 | py |
RSP | RSP-main/Object Detection/mmdet/models/backbones/ViTAE_Window_NoShift/ReductionCell.py | import math
from numpy.core.fromnumeric import resize, shape
import torch
import torch.nn as nn
import torch.nn.functional as F
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
import numpy as np
from .token_transformer import Token_transformer
from .token_performer import Token_performer
from .SELayer... | 11,032 | 46.761905 | 179 | py |
RSP | RSP-main/Object Detection/mmdet/models/backbones/ViTAE_Window_NoShift/NormalCell.py | # Copyright (c) [2012]-[2021] Shanghai Yitu Technology Co., Ltd.
#
# This source code is licensed under the Clear BSD License
# LICENSE file in the root directory of this file
# All rights reserved.
"""
Borrow from timm(https://github.com/rwightman/pytorch-image-models)
"""
import torch
import torch.nn as nn
import num... | 11,944 | 43.240741 | 177 | py |
RSP | RSP-main/Object Detection/mmdet/models/backbones/ViTAE_Window_NoShift/token_performer.py | """
Take Performer as T2T Transformer
"""
import math
import torch
import torch.nn as nn
import numpy as np
class Token_performer(nn.Module):
def __init__(self, dim, in_dim, head_cnt=1, kernel_ratio=0.5, dp1=0.1, dp2 = 0.1, gamma=False, init_values=1e-4):
super().__init__()
self.head_dim = in_dim ... | 3,147 | 35.604651 | 128 | py |
RSP | RSP-main/Object Detection/mmdet/models/backbones/ViTAE_Window_NoShift/SELayer.py | import torch
import torch.nn as nn
class SELayer(nn.Module):
def __init__(self, channel, reduction=16):
super(SELayer, self).__init__()
self.avg_pool = nn.AdaptiveAvgPool1d(1)
self.fc = nn.Sequential(
nn.Linear(channel, channel // reduction, bias=False),
nn.ReLU(inpl... | 726 | 32.045455 | 65 | py |
RSP | RSP-main/Object Detection/mmdet/models/backbones/ViTAE_Window_NoShift/token_transformer.py | # Copyright (c) [2012]-[2021] Shanghai Yitu Technology Co., Ltd.
#
# This source code is licensed under the Clear BSD License
# LICENSE file in the root directory of this file
# All rights reserved.
"""
Take the standard Transformer as T2T Transformer
"""
import torch
import torch.nn as nn
from timm.models.layers impor... | 2,703 | 39.358209 | 165 | py |
RSP | RSP-main/Object Detection/mmdet/models/backbones/ViTAE_Window_NoShift/models.py | # Copyright (c) [2012]-[2021] Shanghai Yitu Technology Co., Ltd.
#
# This source code is licensed under the Clear BSD License
# LICENSE file in the root directory of this file
# All rights reserved.
"""
T2T-ViT
"""
from math import gamma
import torch
import torch.nn as nn
from timm.models.helpers import load_pretraine... | 1,657 | 38.47619 | 269 | py |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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... | 12,040 | 31.989041 | 79 | py |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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,544 | 34.09901 | 79 | py |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/mmdet/ops/orn/functions/active_rotating_filter.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 .. import orn_cuda
#import _C
class _ActiveRotatingFilter(Function):
@s... | 2,736 | 27.510417 | 96 | py |
RSP | RSP-main/Object Detection/mmdet/ops/orn/functions/rotation_invariant_pooling.py | import torch
from torch import nn
from torch.nn import functional as F
class RotationInvariantPooling(nn.Module):
def __init__(self, nInputPlane, nOrientation=8):
super(RotationInvariantPooling, self).__init__()
self.nInputPlane = nInputPlane
self.nOrientation = nOrientation
# hiddent_dim = int... | 950 | 26.970588 | 76 | py |
RSP | RSP-main/Object Detection/mmdet/ops/orn/functions/__init__.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from .active_rotating_filter import active_rotating_filter
from .active_rotating_filter import ActiveRotatingFilter
from .rotation_invariant_encoding import rotation_invariant_encoding
from .rotation_invariant_encoding import RotationI... | 551 | 60.333333 | 148 | py |
RSP | RSP-main/Object Detection/mmdet/ops/orn/functions/rotation_invariant_encoding.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 .. import orn_cuda
class _RotationInvariantEncoding(Function):
@staticme... | 1,900 | 31.775862 | 106 | py |
RSP | RSP-main/Object Detection/mmdet/ops/orn/modules/ORConv.py | from __future__ import absolute_import
import math
import torch
from torch.nn.parameter import Parameter
import torch.nn.functional as F
from torch.nn.modules import Conv2d
from torch.nn.modules.utils import _pair
from ..functions import active_rotating_filter
class ORConv2d(Conv2d):
def __init__(self, in_channels,... | 3,732 | 35.960396 | 121 | py |
RSP | RSP-main/Object Detection/mmdet/ops/box_iou_rotated/box_iou_rotated_wrapper.py | import numpy as np
import torch
from . import box_iou_rotated_ext
from ..convex import convex_sort
def obb_overlaps(bboxes1, bboxes2, mode='iou', is_aligned=False, device_id=None):
assert mode in ['iou', 'iof']
assert type(bboxes1) is type(bboxes2)
if is_aligned:
assert bboxes1.shape[0] == bboxes... | 5,786 | 35.16875 | 91 | py |
RSP | RSP-main/Object Detection/mmdet/ops/convex/convex_wrapper.py | from torch.autograd import Function
from . import convex_ext
class ConvexSortFunction(Function):
@staticmethod
def forward(ctx, pts, masks, circular):
idx = convex_ext.convex_sort(pts, masks, circular)
ctx.mark_non_differentiable(idx)
return idx
@staticmethod
def backward(ctx... | 497 | 19.75 | 58 | py |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/mmdet/ops/nms_rotated/nms_rotated_wrapper.py | import BboxToolkit as bt
import numpy as np
import torch
from . import nms_rotated_ext
def obb2hbb(obboxes):
center, w, h, theta = torch.split(obboxes, [2, 1, 1, 1], dim=1)
Cos, Sin = torch.cos(theta), torch.sin(theta)
x_bias = torch.abs(w/2 * Cos) + torch.abs(h/2 * Sin)
y_bias = torch.abs(w/2 * Sin)... | 3,925 | 31.991597 | 76 | py |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/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 |
RSP | RSP-main/Object Detection/mmdet/ops/roi_align_rotated/roi_align_rotated.py | import numpy as np
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_rotated_ext
class RoIAlignRotatedFunction(Function):
@staticmethod
def forward(ctx,
features,
... | 2,770 | 31.22093 | 77 | py |
RSP | RSP-main/Object Detection/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 |
IMF-Pytorch | IMF-Pytorch-main/main.py | from models.model import *
from utils.data_util import load_data
from utils.data_loader import *
import numpy as np
import argparse
import torch
import time
def parse_args():
config_args = {
'lr': 0.0005,
'dropout_gat': 0.3,
'dropout': 0.3,
'cuda': 0,
'epochs_gat': 3000,
... | 8,810 | 36.653846 | 113 | py |
IMF-Pytorch | IMF-Pytorch-main/models/model.py | import numpy as np
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
from layers.layer import *
class BaseModel(nn.Module):
def __init__(self, args):
super(BaseModel, self).__init__()
self.device = args.device
@staticmethod
def format_metrics(metrics, split)... | 24,660 | 46.792636 | 152 | py |
IMF-Pytorch | IMF-Pytorch-main/layers/layer.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
CUDA = torch.cuda.is_available()
class ConvKBLayer(nn.Module):
def __init__(self, input_dim, input_seq_len, in_channels, out_channels, drop_prob, alpha_leaky):
super(ConvKBLayer, self).__init__()
self.conv_layer... | 9,476 | 34.36194 | 109 | py |
IMF-Pytorch | IMF-Pytorch-main/utils/data_loader.py | import torch
import numpy as np
class Corpus:
def __init__(self, args, train_data, val_data, test_data, entity2id, relation2id):
self.device = args.device
self.train_triples = train_data[0]
self.val_triples = val_data[0]
self.test_triples = test_data[0]
self.max_batch_num =... | 22,424 | 50.315789 | 150 | py |
IMF-Pytorch | IMF-Pytorch-main/utils/data_util.py | import h5py
import pickle
import torch
import numpy as np
# Get item2id and write into txt
def write_index_dict(datasets):
path = 'datasets/'+datasets+'/'
entities = set()
relations = set()
with open(path+datasets+'_EntityTriples.txt', 'r') as f:
for line in f:
instance = line.stri... | 4,735 | 31.662069 | 122 | py |
DCGAN-LSGAN-WGAN-GP-DRAGAN-Tensorflow-2 | DCGAN-LSGAN-WGAN-GP-DRAGAN-Tensorflow-2-master/module.py | import tensorflow as tf
import tensorflow_addons as tfa
import tensorflow.keras as keras
# ==============================================================================
# = networks =
# =================================================================... | 2,668 | 34.586667 | 92 | py |
DCGAN-LSGAN-WGAN-GP-DRAGAN-Tensorflow-2 | DCGAN-LSGAN-WGAN-GP-DRAGAN-Tensorflow-2-master/data.py | import tensorflow as tf
import tf2lib as tl
# ==============================================================================
# = datasets =
# ==============================================================================
def make_32x32_dataset(dataset... | 4,616 | 40.594595 | 118 | py |
DCGAN-LSGAN-WGAN-GP-DRAGAN-Tensorflow-2 | DCGAN-LSGAN-WGAN-GP-DRAGAN-Tensorflow-2-master/train.py | import functools
import imlib as im
import pylib as py
import tensorflow as tf
import tensorflow.keras as keras
import tf2lib as tl
import tf2gan as gan
import tqdm
import data
import module
# ==============================================================================
# = param ... | 7,845 | 38.23 | 142 | py |
PyAstronomy | PyAstronomy-master/src/doc/conf.py | # -*- coding: utf-8 -*-
import sys
sys.path.append("./..")
from PyA_Version import PyA_Version
import mock
MOCK_MODULES = ['scipy', 'scipy.stats', 'scipy.special', 'scipy.optimize', 'scipy.interpolate', 'scipy.integrate', 'scipy.misc',
'pymc', 'matplotlib', 'emcee',
'matplotlib.pylab',... | 8,420 | 31.513514 | 128 | py |
MILLI | MILLI-master/src/interpretability/tef_interpretability.py | from functools import partial
import torch
from data.tef_dataset import create_datasets, TEF_N_CLASSES
from interpretability import metrics as met
from interpretability.base_interpretability import Model, InterpretabilityStudy, Method, Metric
from interpretability.instance_attribution import independent_instance_attr... | 3,687 | 48.837838 | 117 | py |
MILLI | MILLI-master/src/interpretability/sival_interpretability.py | import numpy as np
import torch
from data.sival.sival_dataset import create_datasets, SIVAL_N_CLASSES
from interpretability.base_interpretability import Model, InterpretabilityStudy, Method
from interpretability.instance_attribution import independent_instance_attribution as indep
from interpretability.instance_attrib... | 3,831 | 50.783784 | 109 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.