MMCV核心组件知识整理

3.1 MMCV整体概述

提供了上层框架需要的 hook 机制以及可以直接使用的 runner

MMCV 提供了非常多的高性能 cuda 算子及其 python 接口

3.2 FileHandler

可参考https://zhuanlan.zhihu.com/p/336097883

fileio中的核心组件,设计文件读写。

mmcv提供了底层逻辑的读写handler,目前支持的有.json/.yaml/.yml/.pickle/.pkl文件

# 具体用法
import mmcv

# load data from a file
data = mmcv.load('test.json')
data = mmcv.load('test.yaml')
data = mmcv.load('test.pkl')

mmcv.dump(data, 'out.pkl')

mmcv支持自定义拓展的文件格式(即需要的文件格式不在上述列表),链接中给了.npy的例子。

3.3 FileClient

其作用是对外提供统一的文件内容获取 API,主要用于训练过程中数据的后端读取,通过用户选择默认或者自定义不同的 FileClient 后端,可以轻松实现文件缓存、文件加速读取等等功能

https://zhuanlan.zhihu.com/p/339190576

FileClinet用法示例,其实际调用在 mmseg/datasets/pipelines/loading.py/LoadImageFromFile 类中

class LoadImageFromFile(object): # 加载图片到内存中
    """Load an image from file.

    Required keys are "img_prefix" and "img_info" (a dict that must contain the
    key "filename"). Added or updated keys are "filename", "img", "img_shape",
    "ori_shape" (same as `img_shape`), "pad_shape" (same as `img_shape`),
    "scale_factor" (1.0) and "img_norm_cfg" (means=0 and stds=1).

    Args:
        to_float32 (bool): Whether to convert the loaded image to a float32
            numpy array. If set to False, the loaded image is an uint8 array.
            Defaults to False.
        color_type (str): The flag argument for :func:`mmcv.imfrombytes`.
            Defaults to 'color'.
        file_client_args (dict): Arguments to instantiate a FileClient.
            See :class:`mmcv.fileio.FileClient` for details.
            Defaults to ``dict(backend='disk')``.
        imdecode_backend (str): Backend for :func:`mmcv.imdecode`. Default:
            'cv2'
    """

    def __init__(self,
                 to_float32=False,
                 color_type='color',
                 file_client_args=dict(backend='disk'),
                 imdecode_backend='cv2'):
        self.to_float32 = to_float32
        self.color_type = color_type
        # 默认是disk后端
        self.file_client_args = file_client_args.copy()
        self.file_client = None
        self.imdecode_backend = imdecode_backend

    def __call__(self, results):
        """Call functions to load image and get image meta information.

        Args:
            results (dict): Result dict from :obj:`mmseg.CustomDataset`.

        Returns:
            dict: The dict contains loaded image and meta information.
        """

        if self.file_client is None:
            self.file_client = mmcv.FileClient(**self.file_client_args)

        if results.get('img_prefix') is not None:
            filename = osp.join(results['img_prefix'],
                                results['img_info']['filename'])
        else:
            filename = results['img_info']['filename']
        # 读取图片字节内容
        img_bytes = self.file_client.get(filename)
        # 对字节内容进行解码
        img = mmcv.imfrombytes(
            img_bytes, flag=self.color_type, backend=self.imdecode_backend)
        if self.to_float32:
            img = img.astype(np.float32)

        results['filename'] = filename
        results['ori_filename'] = results['img_info']['filename']
        results['img'] = img
        results['img_shape'] = img.shape
        results['ori_shape'] = img.shape
        # Set initial values for default meta_keys
        results['pad_shape'] = img.shape
        results['scale_factor'] = 1.0
        num_channels = 1 if len(img.shape) < 3 else img.shape[2]
        results['img_norm_cfg'] = dict(
            mean=np.zeros(num_channels, dtype=np.float32),
            std=np.ones(num_channels, dtype=np.float32),
            to_rgb=False)
        return results

    def __repr__(self):
        repr_str = self.__class__.__name__
        repr_str += f'(to_float32={self.to_float32},'
        repr_str += f"color_type='{self.color_type}',"
        repr_str += f"imdecode_backend='{self.imdecode_backend}')"
        return repr_str

扩展开发示例提供了img文件和annotations 文件不在同一个地方的例子。

3.4 Config

Config 主要是提供各种格式的配置文件解析功能,包括 py、json、ymal 和 yml,是一个非常基础常用类

https://zhuanlan.zhihu.com/p/346203167

3.4.1 Config用法汇总

3.4.1.1 通过 dict 生成 config

mmseg/configs目录下的很多文件是用这个方法定义的

cfg = Config(dict(a=1, b=dict(b1=[0, 1])))

# 可以通过 .属性方式访问,比较方便
cfg.b.b1 # [0, 1]
3.4.1.2 通过 配置文件 生成 config

该功能最为常用,配置文件可以是 py、yaml、yml 和 json 格式。

cfg = Config.fromfile('tests/data/config/a.py')

cfg.filename
cfg.item4 # 'test'
cfg # 打印 config path,和字典内容...
3.4.1.3 自动替换预定义变量

假设h.py文件里面存储的内容是:

cfg_dict = dict(
        item1='{
   
   {fileBasename}}',
        item2='{
   
   {fileDirname}}',
        item3='abc_{
   
   {fileBasenameNoExtension }}')

则可以通过参数 use_predefined_variables 实现自动替换预定义变量功能

# cfg_file 文件名是 h.py
cfg = Config.fromfile(cfg_file, use_predefined_variables=True)
print(cfg.pretty_text)

# 输出
item1 = 'h.py'
item2 = 'config 文件路径'
item3 = 'abc_h'

该参数主要用途是自动替换 Config 类中已经预定义好的变量模板为真实值,在某些场合有用,目前支持 4 个变量:fileDirname、fileBasename、fileBasenameNoExtension 和 fileExtname,预定义变量参考自 VS Code

如果 use_predefined_variables=False( 默认为 True ),则不会进行任何替换。

3.4.1.4 导入自定义模块

Config.fromfile 函数除了有 filenameuse_predefined_variables 参数外,还有 import_custom_modules,默认是 True,即当 cfg中存在 custom_imports 键时候会对里面的内容进行自动导入,其输入格式要么是 str 要么是 list[str],表示待导入的模块路径,一个典型用法是:

在mmseg/datasets目录下新建greenscreen.py时,需要在__init__里面加入

from .greenscreen import GreenScreenDataset

但是上述做法在某些场景下会比较麻烦。例如该模块处于非常深的层级,那么就需要逐层修改 __init__.py,有了本参数,便可以采用如下做法:

# .py 文件里面存储如下内容
custom_imports = dict(
    imports=['mmdet.models.backbones.mobilenet'],
    allow_failed_imports=False)

# 自动导入 mmdet.models.backbones.mobilenet
Config.fromfile(cfg_file, import_custom_modules=True)
3.4.1.5 合并多个配置文件

(1) 从 base 文件中合并 Config 支持基于单个 base 配置文件,然后合并其余配置,最终得到一个汇总配置,该功能在各大上层框架中使用非常频繁,可以极大的增加配置复用性。一个典型用法是:

# base.py 内容

item1 = [1, 2]
item2 = {
   
   'a': 0}
item3 = True
item4 = 'test'

# d.py 内容
_base_ = './base.py'
item1 = [2, 3]
item2 = {
   
   'a': 1}
item3 = False
item4 = 'test_base'

# 用法
cfg = Config.fromfile('d.py'
sPS F:\SegFormer> python demo/image_demo.py demo/demo.png local_configs/segformer/B5/segformer.b5.640x640.ade.160k.py pretrained/segformer.b5.640x640.ade.160k.pth --device cuda:0 --palette ade D:\Anaconda\envs\segformer\lib\site-packages\mmcv\__init__.py:20: UserWarning: On January 1, 2023, MMCV will release v2.0.0, in which it will remove components related to the training process and add a data transformation module. In addition, it will rename the package names mmcv to mmcv-lite and mmcv-full to mmcv. See https://github.com/open-mmlab/mmcv/blob/master/docs/en/compatibility.md for more details. warnings.warn( load checkpoint from local path: pretrained/segformer.b5.640x640.ade.160k.pth f:\segformer\mmseg\models\segmentors\base.py:268: UserWarning: show==False and out_file is not specified, only result image will be returned warnings.warn('show==False and out_file is not specified, only ' OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized. OMP: Hint This means that multiple copies of the OpenMP runtime have been linked into the program. That is dangerous, since it can degrade performance or cause incorrect results. The best thing to do is to ensure that only a single OpenMP runtime is linked into the process, e.g. by avoiding static linking of the OpenMP runtime in any library. As an unsafe, unsupported, undocumented workaround you can set the environment variable KMP_DUPLICATE_LIB_OK=TRUE to allow the program to continue to execute, but that may cause crashes or silently produce incorrect results. For more information, please see http://www.intel.com/software/products/support/.
06-07
### mmcv 中的知识蒸馏实现与用法 #### 1. 知识蒸馏简介 知识蒸馏是一种有效的模型压缩技术,通过让较小的学生模型模仿较大的教师模型来提高其性能。这种方法不仅能够减少计算成本,还能保持较高的准确性[^3]。 #### 2. mmcv中的知识蒸馏模块概述 `mmcv` 是一个基础库,支持多个计算机视觉任务的高效开发。为了方便研究人员和开发者实施知识蒸馏策略,`mmcv` 提供了一系列工具和支持函数。这些功能使得在各种下游任务中应用知识蒸馏变得更加容易,特别是对于目标检测等复杂场景下的优化[^4]。 #### 3. 基于logits的目标蒸馏 最简单的形式之一就是基于logits(即未经过softmax层之前的输出)来进行软标签训练。这种方式下,学生模型不仅要最小化自身的预测误差,还要尽可能接近教师模型给出的概率分布。这可以通过调整损失函数来完成: ```python import torch.nn.functional as F def soft_cross_entropy_loss(student_logits, teacher_logits, temperature=4): """Compute the knowledge-distillation (KD) loss given outputs, labels. "Hyperparameters": temperature should be adjusted so that logits usually lie between [-10, 10]. Args: student_logits: Softmax input from student model. teacher_logits: Softmax input from teacher model. temperature (float): Temperature scaling factor for softmax function. Returns: Loss tensor according to arg size. """ p_s = F.log_softmax(student_logits / temperature, dim=1) p_t = F.softmax(teacher_logits / temperature, dim=1) KD_loss = F.kl_div(p_s, p_t.detach(), reduction='batchmean') * (temperature ** 2) return KD_loss ``` 此代码片段展示了如何定义并计算soft-cross entropy损失项,这是执行基于logits的知识蒸馏的核心部分[^2]。 #### 4. 特征层面的知识蒸馏 除了直接利用最终分类得分外,还可以考虑在网络内部层次间传递有用的信息。例如,在目标检测任务中,考虑到前景和背景区域的重要性不同,可以设计专门针对特定位置或通道的关注机制。如下所示的是Focal and Global Distillation(FGD),该方法特别适用于解决此类问题: ```python from mmdet.models.builder import LOSSES from mmdet.core.bbox.assigners.atss_assigner import ATSSAssigner from .utils import weighted_loss @LOSSES.register_module() class FGDLoss(nn.Module): def __init__(self, focal_weight=1., global_weight=1., feat_channels=(512,), num_classes=80, strides=[8, 16, 32], eps=1e-7): super().__init__() self.focal_weight = focal_weight self.global_weight = global_weight # ... 初始化其他参数 ... @weighted_loss def forward(self, pred_student_feats, target_teacher_feats, gt_bboxes_list=None, img_metas=None): # 计算focal distillation 和global distillation 的loss... total_loss = self.focal_weight * focal_distill_loss + \ self.global_weight * global_distill_loss return total_loss ``` 上述代码实现了FGD损失类,允许用户自定义权重比例以及其他超参数设置。这种做法有助于更好地捕捉到局部细节的同时也不忽视整体结构信息。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值