Ascend-SACT/MapFormer-NPU
模型介绍文件和版本Pull Requests讨论分析
下载使用量0

MapFormer 模型使用指导

1. 模型概述及应用场景

开源模型MapFormer (https://github.com/mxbh/mapformer)是一种基于 Transformer 的遥感变化检测模型,主要应用于双时相高分辨率遥感影像变化检测(Binary Change Detection, BCD)场景。 MapFormer以 HRSCD(High-Resolution Semantic Change Detection)数据集为训练与评估对象,基于 PyTorch + MMSegmentation + OpenCD框架实现。 本文介绍MapFormer迁移适配昇腾平台训练及性能优化指导。

说明:本文对 MapFormer 的模型定位、任务定义、数据集使用方式, 均严格基于官方 GitHub 仓库 README 与论文说明, 未对模型能力、适用场景进行扩展或假设性描述。

本文档介绍 MapFormer 模型从 GPU(CUDA)平台迁移至昇腾 Ascend NPU 平台 的完整流程,包括:

  • 环境与依赖准备
  • 数据集预处理
  • NPU 运行指导与训练适配
  • 常见问题与解决方案
  • 性能优化手段与效果评估

2. 准备运行环境

2.1 软件环境

组件版本
Python3.11
PyTorch2.1.0
torch_npu2.1.0
MMCV1.7.2

2.2 硬件环境

设备型号NPU 配置
Atlas 900 A3单卡 / 多卡(0~7)

2.3 准备镜像

根据环境选择对应的镜像,mapformer选用对应A3环境的Pytorch2.1容器镜像

机型镜像名称镜像地址
910BPytorch2.1容器镜像swr.cn-southwest-2.myhuaweicloud.com/atelier/pytorch_2_1_ascend:pytorch_2.1.0-cann_8.2.rc1-py_3.11-hce_2.0.2503-aarch64-snt9b23-20250729103313-3a25129

2.4 创建容器

#!/bin/bash
cname=mapformer
docker stop "${cname}" && docker rm "${cname}" || true
image=swr.cn-southwest-2.myhuaweicloud.com/atelier/pytorch_2_1_ascend:pytorch_2.1.0-cann_8.2.rc1-py_3.11-hce_2.0.2503-aarch64-snt9b23-20250729103313-3a25129
docker run -itd -u root\
   --privileged=true \
   --cap-add=SYS_PTRACE \
   --device=/dev/davinci_manager \
   --device=/dev/devmm_svm \
   --device=/dev/hisi_hdc \
   -v /usr/local/Ascend/driver:/usr/local/Ascend/driver \
   -v /usr/local/dcmi:/usr/local/dcmi \
   -v /usr/local/sbin/npu-smi:/usr/local/sbin/npu-smi \
   -v /etc/ascend_install.info:/etc/ascend_install.info \
   -v /sys/fs/cgroup:/sys/fs/cgroup:ro \
   -v /usr/bin/hccn_tool:/usr/bin/hccn_tool \
   -v /etc/hccn.conf:/etc/hccn.conf \
   -v /mnt:/mnt \
   --shm-size 1024g \
   --net=host \
   --ipc=host \
   --hostname "${cname,,}" \
   --name "${cname}" \
   "${image}" \
   /bin/bash

2.5 容器内配置环境

docker exec -it mapformer bash -i
conda create -n mapformer --clone PyTorch-2.1.0
conda activate mapformer

可以更改容器默认激活环境为mapformer并且保留容器内命令行历史记录

vim ~/.bashrc 修改为:

conda activate mapformer
HISTSIZE=1000
HISTFILESIZE=1000

然后运行source ~/.bashrc让配置生效

2.6 Pip 源配置(强烈建议)

为避免依赖下载失败或速度过慢,建议统一使用 华为内部 PyPI 镜像源:

pip config --user set global.index https://mirrors.huaweicloud.com/repository/pypi
pip config --user set global.index-url https://mirrors.huaweicloud.com/repository/pypi/simple
pip config --user set global.trusted-host mirrors.huaweicloud.com

3. 数据集准备

mapformer在迁移准备数据集的过程中,遇到了一些问题,所以单独在本章节进行介绍。 HRSCD 数据集在 MapFormer 中的使用流程概况如下:

  1. 下载原始影像与标签压缩包
  2. 按年份与类型解压到 images / labels 目录
  3. 使用官方脚本生成 tiles(500 / 2000)
  4. 修复 GeoTIFF 读取问题(tifffile)
  5. 跳过损坏影像
  6. 修正目录命名以匹配配置文件

3.1 下载HRSCD数据集

https://ieee-dataport.org/open-access/hrscd-high-resolution-semantic-change-detection-dataset

3.2 数据集组织

在源码目录下 cd data/HRSCD 创建 image labels文件夹

  • 把 images_2006.zip、images_2012.zip 解压到image下
  • 把 labels_change.zip 、labels_land_cover_2006.zip 、labels_land_cover_2012.zip 解压到labels下

3.3 创建 Tiles(HRSCD)

由于 HRSCD 数据集中的原始遥感影像分辨率较高、尺寸较大,直接使用整幅影像进行训练将导致显存占用过高、训练效率低下,同时不利于模型对局部变化区域的学习。

因此,MapFormer 官方提供了 Tile 化预处理脚本,将原始大尺寸影像裁剪为固定大小的小块(Tiles),以作为模型训练与验证的输入。

在本项目中,分别生成 500×500 和 2000×2000 两种尺度的 Tiles,用于不同配置下的训练与评估。

3.3.1 500 × 500 Tiles

python ./tools/convert_datasets/create_hrscd_tiles.py \
  --data_dir=./data/HRSCD/ \
  --out_dir=./data/HRSCD/preprocessed/tiles500 \
  --tile_size=500

3.3.2 2000 × 2000 Tiles

python ./tools/convert_datasets/create_hrscd_tiles.py \
  --data_dir=./data/HRSCD/ \
  --out_dir=./data/HRSCD/preprocessed/tiles2000 \
  --tile_size=2000

3.4 问题 1:PIL 无法读取 GeoTIFF 图像

报错信息:

OSError: -2
PIL/Pillow cannot load TIFF image

原因分析:

  • HRSCD 数据集中的 TIFF 为 GeoTIFF
  • 包含多波段、压缩、地理信息
  • PIL/Pillow 无法正确解析

解决方案:

  1. 安装替代库:
pip install tifffile imagecodecs
  1. 修改 create_hrscd_tiles.py:
# 修改前
Image.open(path)

# 修改后
import tifffile
img = tifffile.imread(path)

3.5 问题 2:存在损坏或空的 TIFF 文件

报错信息:

Error: Empty input file

解决方案:

在脚本中增加异常捕获,跳过损坏文件:

try:
    img = tifffile.imread(file_path)
except Exception as e:
    print(f"[Warning] Skipping broken file: {file_path}. Reason: {e}")
    continue

4.运行指导

4.1 下载源码

git clone https://github.com/mxbh/mapformer.git

4.2 下载数据集

本节内容在第三章数据集准备中有详细介绍。

4.3 下载预训练权重

从 https://github.com/NVlabs/SegFormer#training 代码库下载 MiT-b2 权重:mit_b2_20220624-66e8bf70.pth。模型代码根目录下创建目录model_ckpt,并将权重文件放入其中。

4.4 安装依赖包

pip install -r requirement.txt 

该命令用于一次性安裝 requirements.txt 文件中列出的所有 Python 依赖套件及版本。

4.5 从源码安装mmcv:

pip uninstall mmcv
git clone -b 1.x https://github.com/open-mmlab/mmcv.git
cd mmcv
MMCV_WITH_OPS=1 FORCE_NPU=1 python setup.py develop
pip list | grep mmcv
# 安装成功应显示mmcv-full  1.7.2

4.6 安装DrivingSDK:

git clone https://gitcode.com/Ascend/DrivingSDK.git
cd DrivingSDK
bash ci/build.sh --python=3.11
cd dist/
pip install mx_driving-1.0.0+gitfa7952d-cp311-cp311-linux_aarch64.whl

4.7 添加自动适配代码

在/tools/train.py添加如下代码,用于在昇腾NPU自动迁移。


import torch_npu
from torch_npu.contrib import transfer_to_npu
from mx_driving.patcher import default_patcher_builder

if __name__ == '__main__':
    with default_patcher_builder.build() as patcher:
        main()

4.8 设置环境变量

export ASCEND_RT_VISIBLE_DEVICES=2
export WORLD_SIZE=1

4.9 启动训练

python tools/train.py \
  ./configs/bitemporal_bcd/hrscd/changeformer.yaml \
  --work-dir=./runs/bitemporal_bcd/hrscd/changeformer

5. 常见问题

5.1 MMSegmentation 与 MMCV 不匹配

报错信息:

AssertionError: MMCV==1.7.2 is used but incompatible

解决方案:

修改文件:mapformer/mmseg/init.py

将:

# 修改前
MMCV_MAX = '1.5.0'
# 修改后:
MMCV_MAX = '1.7.2'

5.2 OpenCD 与 MMCV 不匹配

报错信息:

AssertionError: MMCV==1.7.2 is used but incompatible

解决方案:

修改文件:mapformer/opencd/init.py

# 修改前
MMCV_MAX = '1.5.0'
# 修改后:
MMCV_MAX = '1.7.2'

注意:该修改仅用于解决当前 MapFormer 代码与 MMCV 1.7.2 的版本检查冲突, 不代表官方支持该版本组合。 若后续升级 MMSegmentation / OpenCD,需重新评估版本兼容性。 该替换方式为 MMSegmentation 在昇腾 NPU 上的通用适配方式,

适用于大多数基于 mmcv 的训练脚本。

5.3 Tiles 目录命名问题(数据路径不一致)

5.3.1 目录缺失问题

报错信息:

FileNotFoundError: ... -0M50-E080

原因:

  • 原始数据目录名缺少 -0M50-E080 后缀
  • 配置文件中路径与实际目录不一致

5.3.2 批量重命名命令

在对应目录下执行:

find . -maxdepth 1 -type d ! -name "." \
  -exec sh -c 'mv "$1" "${1}-0M50-E080"' _ {} \;

适用于:

  • tiles500/images/2006
  • tiles2000/images/2006

5.4 WandB 相关问题

5.4.1 缺少 wandb 包

ModuleNotFoundError: No module named 'wandb'

解决方案:

pip install wandb

5.4.2 运行时 WandB 交互提示

wandb: (1) Create a W&B account

禁用方式:

wandb offline
wandb disabled

5.5 NPU 设备适配问题

5.5.1 CUDA DataParallel 与 NPU 不兼容

报错信息:

RuntimeError: module must have its parameters on device cuda:0 but found npu:0

解决方案:

修改文件:

mmseg/apis/train.py

修改前:

from mmcv.parallel import MMDataParallel, MMDistributedDataParallel

model = MMDataParallel(model.cuda(cfg.gpu_ids[0]), device_ids=cfg.gpu_ids)

model = MMDistributedDataParallel(
            model.cuda(),)

修改后:

from mmcv.device.npu import NPUDataParallel, NPUDistributedDataParallel

model = NPUDataParallel(model.npu(cfg.gpu_ids[0]), device_ids=cfg.gpu_ids)

model = NPUDistributedDataParallel(
            model.npu(),)

原因说明: MMDataParallel 内部依赖 CUDA 设备语义(cuda:0),在 NPU 环境下会导致参数与 buffer 分布不一致。NPUDataParallel 是 mmcv 针对 Ascend 设备的适配实现,用于正确处理 NPU 设备上的模型并行。


6. 性能优化实践与效果

6.1 优化一:替换融合优化器

# 修改前
type: AdamW

# 修改后
type: NpuFusedAdamW

效果:

  • 0.3077 s → 0.2912 s
  • 提升 5.3%

6.2 优化二:开启虚拟内存

export PYTORCH_NPU_ALLOC_CONF=expandable_segments:True

效果:

  • 0.2912 s → 0.2892 s
  • 提升 0.68%

6.3 优化三:一级流水优化

export TASK_QUEUE_ENABLE=2

效果:

  • 0.2892 s → 0.2885 s
  • 提升 0.07%

6.4 性能优化综合效果

阶段平均 step 时间
初始0.3077 s
最终0.2885 s
总提升6.24%

7. 总结

本次 MapFormer 模型 NPU 迁移过程涉及:

  • 遥感 GeoTIFF 数据适配
  • MMCV / MMSeg / OpenCD 版本约束放宽
  • NPU DataParallel 替换
  • WandB 行为控制
  • 融合优化器与内存优化

最终实现 模型可训练、可收敛、性能可优化 的稳定 NPU 运行方案。