An implementation of Efficient Multi-head Attention of Segformer. This module is modified from MultiheadAttention which is a module from mmcv.cnn.bricks.transformer. Args: embed_dims (int): The embedding dimension. num_heads (int): Parallel attention heads. attn
| 89 | |
| 90 | |
| 91 | class EfficientMultiheadAttention(MultiheadAttention): |
| 92 | """An implementation of Efficient Multi-head Attention of Segformer. |
| 93 | |
| 94 | This module is modified from MultiheadAttention which is a module from |
| 95 | mmcv.cnn.bricks.transformer. |
| 96 | |
| 97 | Args: |
| 98 | embed_dims (int): The embedding dimension. |
| 99 | num_heads (int): Parallel attention heads. |
| 100 | attn_drop (float): A Dropout layer on attn_output_weights. |
| 101 | Default: 0.0. |
| 102 | proj_drop (float): A Dropout layer after `nn.MultiheadAttention`. |
| 103 | Default: 0.0. |
| 104 | dropout_layer (obj:`ConfigDict`): The dropout_layer used |
| 105 | when adding the shortcut. Default: None. |
| 106 | init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization. |
| 107 | Default: None. |
| 108 | batch_first (bool): Key, Query and Value are shape of |
| 109 | (batch, n, embed_dim) |
| 110 | or (n, batch, embed_dim). Default: False. |
| 111 | qkv_bias (bool): enable bias for qkv if True. Default True. |
| 112 | norm_cfg (dict): Config dict for normalization layer. |
| 113 | Default: dict(type='LN'). |
| 114 | sr_ratio (int): The ratio of spatial reduction of Efficient Multi-head |
| 115 | Attention of Segformer. Default: 1. |
| 116 | """ |
| 117 | |
| 118 | def __init__(self, |
| 119 | embed_dims, |
| 120 | num_heads, |
| 121 | attn_drop=0., |
| 122 | proj_drop=0., |
| 123 | dropout_layer=None, |
| 124 | init_cfg=None, |
| 125 | batch_first=True, |
| 126 | qkv_bias=False, |
| 127 | norm_cfg=dict(type='LN'), |
| 128 | sr_ratio=1): |
| 129 | super().__init__( |
| 130 | embed_dims, |
| 131 | num_heads, |
| 132 | attn_drop, |
| 133 | proj_drop, |
| 134 | dropout_layer=dropout_layer, |
| 135 | init_cfg=init_cfg, |
| 136 | batch_first=batch_first, |
| 137 | bias=qkv_bias) |
| 138 | |
| 139 | self.sr_ratio = sr_ratio |
| 140 | if sr_ratio > 1: |
| 141 | self.sr = Conv2d( |
| 142 | in_channels=embed_dims, |
| 143 | out_channels=embed_dims, |
| 144 | kernel_size=sr_ratio, |
| 145 | stride=sr_ratio) |
| 146 | # The ret[0] of build_norm_layer is norm name. |
| 147 | self.norm = build_norm_layer(norm_cfg, embed_dims)[1] |
| 148 |