Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

create the block of eca in Dev 1.x #737

Open
wants to merge 99 commits into
base: main
Choose a base branch
from
Open

create the block of eca in Dev 1.x #737

wants to merge 99 commits into from

Conversation

wqe123321
Copy link

Thanks for your contribution and we appreciate it a lot. The following instructions would make your pull request more healthy and more easily get feedback. If you do not understand some items, don't worry, just make the pull request and seek help from maintainers.

Motivation

I want to add an attention module to the Neck part, in order to enhance the attention to features.

Modification

code is following:

import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule
from mmcv.runner import BaseModule, auto_fp16

from ..builder import NECKS

from mmrotate.models.builder import ROTATED_NECKS

class eca_layer(nn.Module):#eca注意力
def init(self, channel, k_size=3):
super(eca_layer, self).init() # super类的作用是继承的时候,调用含super的哥哥的基类__init__函数。
self.avg_pool = nn.AdaptiveAvgPool2d(1) # 全局平均池化
self.max_pool = nn.AdaptiveMaxPool2d(1)
self.conv = nn.Conv1d(1, 1, kernel_size=k_size,
padding=(k_size - 1) // 2, bias=False) # 基于1*1卷积学习通道之间的信息
self.sigmoid = nn.Sigmoid() # 激活函数

def forward(self, x):
    # x: input features with shape [b, c, h, w]
    b, c, h, w = x.size()  # b代表b个样本,c为通道数,h为高度,w为宽度
    # feature descriptor on the global spatial information
    y = self.avg_pool(x)
    # Two different branches of ECA module
    # torch.squeeze()这个函数主要对数据的维度进行压缩,torch.unsqueeze()这个函数 主要是对数据维度进行扩充
    y = self.conv(y.squeeze(-1).transpose(-1, -2)).transpose(-1, -2).unsqueeze(-1)
    # Multi-scale information fusion多尺度信息融合
    y = self.sigmoid(y)
    # 原网络中克罗内克积,也叫张量积,为两个任意大小矩阵间的运算
    return x * y.expand_as(x)

@ROTATED_NECKS.register_module()
class ECA(BaseModule): #eca注意力
def init(self,
in_channels,
out_channels,
num_outs,
start_level=0,
end_level=-1,
add_extra_convs=False,
relu_before_extra_convs=False,
no_norm_on_lateral=False,
conv_cfg=None,
norm_cfg=None,
act_cfg=None,
upsample_cfg=dict(mode='nearest'),
init_cfg=dict(
type='Xavier', layer='Conv2d', distribution='uniform')):
super(FPN_eca, self).init(init_cfg)
assert isinstance(in_channels, list)
self.in_channels = in_channels
self.out_channels = out_channels
self.num_ins = len(in_channels)
self.num_outs = num_outs
self.relu_before_extra_convs = relu_before_extra_convs
self.no_norm_on_lateral = no_norm_on_lateral
self.fp16_enabled = False
self.upsample_cfg = upsample_cfg.copy()

    if end_level == -1 or end_level == self.num_ins - 1:
        self.backbone_end_level = self.num_ins
        assert num_outs >= self.num_ins - start_level
    else:
        # if end_level is not the last level, no extra level is allowed
        self.backbone_end_level = end_level + 1
        assert end_level < self.num_ins
        assert num_outs == end_level - start_level + 1
    self.start_level = start_level
    self.end_level = end_level
    self.add_extra_convs = add_extra_convs
    assert isinstance(add_extra_convs, (str, bool))
    if isinstance(add_extra_convs, str):
        # Extra_convs_source choices: 'on_input', 'on_lateral', 'on_output'
        assert add_extra_convs in ('on_input', 'on_lateral', 'on_output')
    elif add_extra_convs:  # True
        self.add_extra_convs = 'on_input'

    self.lateral_convs = nn.ModuleList()
    self.fpn_convs = nn.ModuleList()
    self.fpn_att = nn.ModuleList()#ModeleList,可以存放很多函数,调用的时候类似数组用下标调用,比如fpn_att[i]


    for i in range(self.start_level, self.backbone_end_level):#遍历特征图,为了获取特征图通道数
        l_conv = ConvModule(
            in_channels[i],  # 输入通道数
            out_channels,#输出通道数
            1,
            conv_cfg=conv_cfg,
            norm_cfg=norm_cfg if not self.no_norm_on_lateral else None,
            act_cfg=act_cfg,
            inplace=False)
        fpn_conv = ConvModule(
            out_channels,
            out_channels,
            3,
            padding=1,
            conv_cfg=conv_cfg,
            norm_cfg=norm_cfg,
            act_cfg=act_cfg,
            inplace=False)
        s_layer = eca_layer(out_channels)

        self.lateral_convs.append(l_conv)
        self.fpn_convs.append(fpn_conv)
        self.fpn_att.append(s_layer)#容器fpn_att存放了每一层特征图的注意力函数,因为每层注意力输入通道数不一样

#包含了每一个特征图的操作
# add extra conv layers (e.g., RetinaNet)
extra_levels = num_outs - self.backbone_end_level + self.start_level
if self.add_extra_convs and extra_levels >= 1:
for i in range(extra_levels):
if i == 0 and self.add_extra_convs == 'on_input':
in_channels = self.in_channels[self.backbone_end_level - 1]
else:
in_channels = out_channels
extra_fpn_conv = ConvModule(
in_channels,
out_channels,
3,
stride=2,
padding=1,
conv_cfg=conv_cfg,
norm_cfg=norm_cfg,
act_cfg=act_cfg,
inplace=False)
self.fpn_convs.append(extra_fpn_conv)

@auto_fp16()
def forward(self, inputs):
    """Forward function."""
    assert len(inputs) == len(self.in_channels)

    # build laterals
    laterals = [#backbone输出特征图
        lateral_conv(inputs[i + self.start_level])
        for i, lateral_conv in enumerate(self.lateral_convs)
    ]
    laterals[0] = self.fpn_att[0](laterals[0])#将原始特征图经过注意力操作后,覆盖原始特征图,得到新的laterals[0]
    laterals[1] = self.fpn_att[1](laterals[1])
    laterals[2] = self.fpn_att[2](laterals[2])
    laterals[3] = self.fpn_att[3](laterals[3])
        #这里才是对特征图进行操作!!!!!!!!!!!!!!!!!!!!
    # build top-down path
    used_backbone_levels = len(laterals)
    for i in range(used_backbone_levels - 1, 0, -1):
        # In some cases, fixing `scale factor` (e.g. 2) is preferred, but
        #  it cannot co-exist with `size` in `F.interpolate`.
        if 'scale_factor' in self.upsample_cfg:
            # fix runtime error of "+=" inplace operation in PyTorch 1.10
            laterals[i - 1] = laterals[i - 1] + F.interpolate(
                laterals[i], **self.upsample_cfg)
        else:
            prev_shape = laterals[i - 1].shape[2:]
            laterals[i - 1] = laterals[i - 1] + F.interpolate(
                laterals[i], size=prev_shape, **self.upsample_cfg)

    # build outputs
    # part 1: from original levels
    outs = [
        self.fpn_convs[i](laterals[i]) for i in range(used_backbone_levels)
    ]
    # part 2: add extra levels
    if self.num_outs > len(outs):
        # use max pool to get more levels on top of outputs
        # (e.g., Faster R-CNN, Mask R-CNN)
        if not self.add_extra_convs:
            for i in range(self.num_outs - used_backbone_levels):
                outs.append(F.max_pool2d(outs[-1], 1, stride=2))
        # add conv layers on top of original feature maps (RetinaNet)
        else:
            if self.add_extra_convs == 'on_input':
                extra_source = inputs[self.backbone_end_level - 1]
            elif self.add_extra_convs == 'on_lateral':
                extra_source = laterals[-1]
            elif self.add_extra_convs == 'on_output':
                extra_source = outs[-1]
            else:
                raise NotImplementedError
            outs.append(self.fpn_convs[used_backbone_levels](extra_source))
            for i in range(used_backbone_levels + 1, self.num_outs):
                if self.relu_before_extra_convs:
                    outs.append(self.fpn_convs[i](F.relu(outs[-1])))
                else:
                    outs.append(self.fpn_convs[i](outs[-1]))
    return tuple(outs)

zytx121 and others added 30 commits August 2, 2022 11:06
* init

* delete github action

* test

* Update version.py

* Update version.py
* delete UT

* revert

* update

* Update test.yml
* update

* fix lint

* update ut

* fix

* Update dota.py

* Update dota.py

* Update anchor_generator.py

* Update dota.py

* Update registry.py

* update metric

* add format ut

* add merge_patches in DOTAMetric

* Update dota_metric.py

* Update mmrotate/datasets/dota.py

Co-authored-by: RangiLyu <[email protected]>

* Update mmrotate/evaluation/metrics/dota_metric.py

Co-authored-by: RangiLyu <[email protected]>

* Update dota_metric.py

Co-authored-by: RangiLyu <[email protected]>
* init

* Update default_runtime.py
#450)

* Initialize RotatedBoxes and QuadriBoxes

* Move all box modes into Structures, Add docstring

* Update docstring

* Upload UT

* Fix comments

* Update inplace operations

* Update

* Update

* Update

* Update

* Updata rotate and project UT

* Update

* Update

* Update

* Update

* update

* Update from_instance_masks
* add

* add

* Update dota_metric.py

* update

* fix lint

* remove hrsc metric

* fix typo

* Update dota_metric.py

* Update mmrotate/datasets/hrsc.py

Co-authored-by: RangiLyu <[email protected]>

* Update mmrotate/datasets/hrsc.py

Co-authored-by: RangiLyu <[email protected]>

* Update hrsc.py

* Update hrsc.py

Co-authored-by: RangiLyu <[email protected]>
* init

* fix lint

* update

* add  UT

* fix lint

* update coder

* Update mmrotate/core/bbox/iou_calculators/rotate_iou2d_calculator.py

Co-authored-by: RangiLyu <[email protected]>

* fix docstring

Co-authored-by: RangiLyu <[email protected]>
* init

* fix lint

* update

* update coder

* init

* fix lint

* fix bug in DOTA metric

* Update delta_xywht_hbbox_coder.py

* support tensor input when coder.decode.

In two stage detectors and refine single stage detectors, the bboxes can be Tensor.

* Update rotated_retinanet_obb_r50_fpn_1x_dota_le90.py

* support use_box_type in coder

* fix bug

* fix
* init

* fix lint

* update

* update coder

* init

* update

* update ut

* fix lint

* Update delta_xywht_hbbox_coder.py

* Update delta_xywht_hbbox_coder.py

* update ut

* fix docstring

* fix

* update

* fix

* add UT

* Create cascade_s2anet_r50_fpn_1x_dota_le135.py

* Update refine_single_stage.py

* Update refine_single_stage.py

* fix bug when run demo image

* Update refine_single_stage.py

* fix bug

* Update refine_single_stage.py

* fix docstring
* update

* Update test_two_stage.py

* Update s2anet_r50_fpn_fp16_1x_dota_le135.py

* add UT

* Update test_delta_midpointoffset_rbbox_coder.py

* update

* Update oriented_rcnn_r50_fpn_fp16_1x_dota_le90.py
* Refactor oriented rcnn (#515)

* update

* Update test_two_stage.py

* Update s2anet_r50_fpn_fp16_1x_dota_le135.py

* add UT

* Update test_delta_midpointoffset_rbbox_coder.py

* update

* Update oriented_rcnn_r50_fpn_fp16_1x_dota_le90.py

* update

* update

* fix lint

* Update re_resnet.py

* Update re_resnet.py
* init

* add UT

* fix lint

* Update rotated_reppoints_head.py

* Update rotated_reppoints_r50_fpn_1x_dota_qbox.py

* fix
* init

* fix bug

* add UT

* fix lint

* fix docstring

* update

* fix
* add UT

* fix lint

* init

* fix

* Update oriented_reppoints_head.py

* update

* Update test_oriented_reppoints.py

* fix error when train

* fix UT

* update docstring

* Update mmrotate/models/dense_heads/oriented_reppoints_head.py

Co-authored-by: RangiLyu <[email protected]>

* Update mmrotate/models/dense_heads/oriented_reppoints_head.py

Co-authored-by: RangiLyu <[email protected]>

* Update mmrotate/models/dense_heads/oriented_reppoints_head.py

Co-authored-by: RangiLyu <[email protected]>

* Update oriented_reppoints_head.py

* upgrade pre-commit-hook

Co-authored-by: RangiLyu <[email protected]>
* add UT

* fix lint

* update

* Update test_oriented_reppoints.py

* fix UT

* init

* Update angle_branch_retina_head.py

* add ut

* Update test_angle_coder.py

* add UT

* Update test_angle_branch_retina_head.py

* fix

* fix
ABCs were moved from collections to collections.abc in 3.3.
Since 3.10, ABCs cannot be imported directly from collections.
1. Removed invalid `score_threshold` arg  in `nms_rotated` call
2. Passed `--color-theme` to `plot_confusion_matrix`
* fcos for 1.x

* update config

* add test

* fix config

* fix

* fix

* fix

* remove useless class
* add UT

* fix lint

* update

* Update test_oriented_reppoints.py

* fix UT

* init

* fix

* add UT

* fix lint

* update

* fix
* Update s2anet_r50_fpn_fp16_1x_dota_le135.py

* add UT

* Update test_delta_midpointoffset_rbbox_coder.py

* update

* fix lint

* update

* update

* add rbox version

* fix

* add UT

* fix lint
* old version

* delete fake atss

* add ut

* Update UT

* update docstring
* delete 0.x docs

* init new en/docs

* fix lint

* fix docs error

* Update changelog_v0.x.md

* update get_started.py

* Update get_started.md

* Update docs/en/conf.py

Co-authored-by: RangiLyu <[email protected]>

* update en

* update zh_CN

* Update conf.py

* fix

Co-authored-by: RangiLyu <[email protected]>
* update

* fix lint

* update

* update

* fix ut

* Update test_angle_coder.py

* fix

* Update __init__.py

* fix

* fix ut bugs
* update

* update

* fix lint

* update

* update

* Update gliding-vertex-rbox_r50_fpn_1x_dota.py

* update ms configs

* update hrsc configs

* fix lint

* Update configs/redet/README.md

Co-authored-by: RangiLyu <[email protected]>

Co-authored-by: RangiLyu <[email protected]>
* Add Rotated COCO Metric

* Fix

Co-authored-by: Yue Zhou <[email protected]>
* update issue template

* Update .github/ISSUE_TEMPLATE/1-bug-report.yml

Co-authored-by: RangiLyu <[email protected]>

Co-authored-by: RangiLyu <[email protected]>
* update

* update citation

* update

* update

* update

* update
zytx121 and others added 11 commits February 27, 2023 13:57
* update

* Update README.md
…#731)

* init headet

* feat: add train and test

* feat:update readme

* feat: add h180

* docs: update readme

* feat: update readme

* feat: add datatsets

* docs: update h180 comments

* feat: add configs-ic19-obb-obb configs

* feat: update metric

* feat: update metric

* feat: delete unnecessary

* feat: init rtmdet

* feat: update datasets

* feat: update local_visualizer comments

* feat: add benchmark.py

* docs: update

* docs: update

* feat: update angle h180 in rtmdet

* feat: add roi_trans

* feat: add 180

* docs: update RotatedBoxes

* feat: add r_l1_loss

* feat: add rl1 loss config

* feat: update checkpoint hook

* feat: change the weight

* feat: update the loss weight 5

* fix: reletive import

* feat: fix the APH metric

* fix: fix the regularize_boxes

* fix: fix the edge_swap=False

* feat: init the tests in headet

* feat: strict the loss

* update interval

* feat: update logger config

* feat: support rtmdet 360

* feat: delete unnecessery comment

* feat: init the ic19 datasets

* feat: init ic19 datasets

* feat: add rotated_rtmdet_x3

* feat: add rotated_rtmdet_x3_r

* feat: update rtmdet

* feat: add a1l1 loss

* docs: update readme

* rename headet to RR360 Det

* feat: refactor the config

* docs: update readme

* fix: headet to RR360

* fix: delete unuse

* add test script

* feat: update readme

* fdocs: update script

* docs: update

* docs: update

* docs: update

* docs: update

* docs: update

* remove the configs180

* docs: update

* delete the unuse

* delete the unuse

* delete the unuse

* feat: delete the unuse

* docs: delete the unuse

* delete unuse

* delete the unuse

* delete the unuse

* fix: replace h180 with r360

* feat: delete the Unnecessary Comments

* feat: add rotated_retinanet

* fix: DOTAHeadMetric to DOTAR360Metric

* fix: hangle_thr to angle_thr

* fix: ORLocalVisualizer to RR360LocalVisualizer

* fix: delete the mmcls.models

* fix: delete the benckmark

* fix: pre-commit

* fix: delete unuse

* fix: dota_head_metric to dota_r360_metric

* fix: AP(T<xxxx)

* [Fix]: mAPH to mAP

* docs: update readme

* docs: update

* fix: ICDAR2019_MTD_HOQ to TRR360D

* fix: delete the unuse a l1 loss

* fix: delete the unuse model import

* docs: update

* fix: disable wandb

* feat: add without l1_loss

* docs: update en docs

* docs: update the datasets link

* docs: add todo
* Update hrsid.py

* Update configs/_base_/datasets/hrsid.py

Co-authored-by: RangiLyu <[email protected]>

---------

Co-authored-by: RangiLyu <[email protected]>
* LSKNet implementation

* passed by pre-commit

* update configs

* Update lsknet.py

* Update projects/LSKNet/README.md

Co-authored-by: Yue Zhou <[email protected]>

* Update projects/LSKNet/README.md

Co-authored-by: Yue Zhou <[email protected]>

* Update projects/LSKNet/README.md

Co-authored-by: Yue Zhou <[email protected]>

* Update projects/LSKNet/README.md

Co-authored-by: Yue Zhou <[email protected]>

* Update projects/LSKNet/README.md

Co-authored-by: Yue Zhou <[email protected]>

* update

* update ckpt download link

* update ckpt links

* update pretrained weight link

* update pretrained weight link

* update pretrained weight link

* update pretrained weight link

* pre-commit checked

---------

Co-authored-by: Yue Zhou <[email protected]>
* update

* Update dota_coco.py

* update

* fix
* [doc]:add more social network links

* [doc]:add more social network links
@OpenMMLab-Assistant001
Copy link

Hi @wqe123321 !We are grateful for your efforts in helping improve this open-source project during your personal time.

Welcome to join OpenMMLab Special Interest Group (SIG) private channel on Discord, where you can share your experiences, ideas, and build connections with like-minded peers. To join the SIG channel, simply message moderator— OpenMMLab on Discord or briefly share your open-source contributions in the #introductions channel and we will assist you. Look forward to seeing you there! Join us :https://discord.gg/UjgXkPWNqA
If you have a WeChat account,welcome to join our community on WeChat. You can add our assistant :openmmlabwx. Please add "mmsig + Github ID" as a remark when adding friends:)

Thank you again for your contribution❤

yuyi1005 and others added 18 commits April 18, 2023 10:25
* Support H2RBox-v2

* Update README

* Add figure in README

* Update figure in README

* Fix README lint problem
* [doc]:add more social network links

* [doc]:add more social network links

* [Feature] support semi-automatic annotation base Label-Studio

* [fix] change the name and url to mmrotate

* [fix] resolve conflict
* fix lsknet

* fix some comment
* fix confusion_matrix

* fix opencv error
There seems to be a lack of indentation, resulting in an assignment bug when square classes are not processed.
* [Fix] Fix nan loss in RotatedIoULoss when using AmpOptimizer

* Fix lint
* update version in __init__.py

* update version in mminstall.txt

* update version in en faq.md

* update version in zh_cn faq.md
Update NIPS information of h2rbox-v2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.