diff --git a/testbed/open-mmlab__mmengine/.gitignore b/testbed/open-mmlab__mmengine/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..5a48f3447317d2ef0e8e8ae259076d4541d627b6
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.gitignore
@@ -0,0 +1,123 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+.hypothesis/
+.pytest_cache/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/en/_build/
+docs/en/api/generated/
+docs/zh_cn/_build/
+docs/zh_cn/api/generated/
+src/
+
+# PyBuilder
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# pyenv
+.python-version
+
+# celery beat schedule file
+celerybeat-schedule
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+
+.vscode
+.idea
+.DS_Store
+
+# custom
+*.pkl
+*.pkl.json
+*.log.json
+docs/modelzoo_statistics.md
+work_dirs/
+
+# Pytorch
+*.pth
+*.py~
+*.sh~
diff --git a/testbed/open-mmlab__mmengine/.owners.yml b/testbed/open-mmlab__mmengine/.owners.yml
new file mode 100644
index 0000000000000000000000000000000000000000..377054ce1f7a9650b093346f93b60f188d70bdcc
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.owners.yml
@@ -0,0 +1,12 @@
+assign:
+ strategy:
+ # random
+ daily-shift-based
+ scedule:
+ '*/1 * * * *'
+ assignees:
+ - HAOCHENYE
+ - zhouzaida
+ - C1rN09
+ - ice-tong
+ - HAOCHENYE
diff --git a/testbed/open-mmlab__mmengine/.pre-commit-config-zh-cn.yaml b/testbed/open-mmlab__mmengine/.pre-commit-config-zh-cn.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..7869ff0a6e8df7d3193a1c3bdba33f8f68557787
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.pre-commit-config-zh-cn.yaml
@@ -0,0 +1,61 @@
+exclude: ^tests/data/
+repos:
+ - repo: https://gitee.com/openmmlab/mirrors-flake8
+ rev: 5.0.4
+ hooks:
+ - id: flake8
+ - repo: https://gitee.com/openmmlab/mirrors-isort
+ rev: 5.10.1
+ hooks:
+ - id: isort
+ - repo: https://gitee.com/openmmlab/mirrors-yapf
+ rev: v0.32.0
+ hooks:
+ - id: yapf
+ - repo: https://gitee.com/openmmlab/mirrors-pre-commit-hooks
+ rev: v4.3.0
+ hooks:
+ - id: trailing-whitespace
+ - id: check-yaml
+ - id: end-of-file-fixer
+ - id: requirements-txt-fixer
+ - id: double-quote-string-fixer
+ - id: check-merge-conflict
+ - id: fix-encoding-pragma
+ args: ["--remove"]
+ - id: mixed-line-ending
+ args: ["--fix=lf"]
+ - repo: https://gitee.com/openmmlab/mirrors-mdformat
+ rev: 0.7.9
+ hooks:
+ - id: mdformat
+ args: ["--number"]
+ additional_dependencies:
+ - mdformat-openmmlab
+ - mdformat_frontmatter
+ - linkify-it-py
+ - repo: https://gitee.com/openmmlab/mirrors-codespell
+ rev: v2.2.1
+ hooks:
+ - id: codespell
+ - repo: https://gitee.com/openmmlab/mirrors-docformatter
+ rev: v1.3.1
+ hooks:
+ - id: docformatter
+ args: ["--in-place", "--wrap-descriptions", "79"]
+ - repo: https://gitee.com/openmmlab/mirrors-pyupgrade
+ rev: v3.0.0
+ hooks:
+ - id: pyupgrade
+ args: ["--py36-plus"]
+ - repo: https://gitee.com/openmmlab/pre-commit-hooks
+ rev: v0.4.0
+ hooks:
+ - id: check-copyright
+ args: ["mmengine", "tests"]
+ - id: remove-improper-eol-in-cn-docs
+ - repo: https://gitee.com/openmmlab/mirrors-mypy
+ rev: v0.812
+ hooks:
+ - id: mypy
+ exclude: "docs"
diff --git a/testbed/open-mmlab__mmengine/.pre-commit-config.yaml b/testbed/open-mmlab__mmengine/.pre-commit-config.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..e4bf75e6827117ba980190d129bd9980fa3e7e87
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.pre-commit-config.yaml
@@ -0,0 +1,61 @@
+exclude: ^tests/data/
+repos:
+ - repo: https://github.com/PyCQA/flake8
+ rev: 5.0.4
+ hooks:
+ - id: flake8
+ - repo: https://github.com/PyCQA/isort
+ rev: 5.10.1
+ hooks:
+ - id: isort
+ - repo: https://github.com/pre-commit/mirrors-yapf
+ rev: v0.32.0
+ hooks:
+ - id: yapf
+ - repo: https://github.com/pre-commit/pre-commit-hooks
+ rev: v4.3.0
+ hooks:
+ - id: trailing-whitespace
+ - id: check-yaml
+ - id: end-of-file-fixer
+ - id: requirements-txt-fixer
+ - id: double-quote-string-fixer
+ - id: check-merge-conflict
+ - id: fix-encoding-pragma
+ args: ["--remove"]
+ - id: mixed-line-ending
+ args: ["--fix=lf"]
+ - repo: https://github.com/executablebooks/mdformat
+ rev: 0.7.9
+ hooks:
+ - id: mdformat
+ args: ["--number"]
+ additional_dependencies:
+ - mdformat-openmmlab
+ - mdformat_frontmatter
+ - linkify-it-py
+ - repo: https://github.com/codespell-project/codespell
+ rev: v2.2.1
+ hooks:
+ - id: codespell
+ - repo: https://github.com/myint/docformatter
+ rev: v1.3.1
+ hooks:
+ - id: docformatter
+ args: ["--in-place", "--wrap-descriptions", "79"]
+ - repo: https://github.com/asottile/pyupgrade
+ rev: v3.0.0
+ hooks:
+ - id: pyupgrade
+ args: ["--py36-plus"]
+ - repo: https://github.com/open-mmlab/pre-commit-hooks
+ rev: v0.4.0
+ hooks:
+ - id: check-copyright
+ args: ["mmengine", "tests"]
+ - id: remove-improper-eol-in-cn-docs
+ - repo: https://github.com/pre-commit/mirrors-mypy
+ rev: v0.812
+ hooks:
+ - id: mypy
+ exclude: "docs"
diff --git a/testbed/open-mmlab__mmengine/.readthedocs.yml b/testbed/open-mmlab__mmengine/.readthedocs.yml
new file mode 100644
index 0000000000000000000000000000000000000000..7d5f1c2060a64e5cf9c2bec433cd24532a283164
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/.readthedocs.yml
@@ -0,0 +1,9 @@
+version: 2
+
+formats: all
+
+python:
+ version: 3.7
+ install:
+ - requirements: requirements/runtime.txt
+ - requirements: requirements/docs.txt
diff --git a/testbed/open-mmlab__mmengine/CODEOWNERS b/testbed/open-mmlab__mmengine/CODEOWNERS
new file mode 100644
index 0000000000000000000000000000000000000000..9baba4044ce19b7a006388226e107814f11c65ea
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/CODEOWNERS
@@ -0,0 +1,84 @@
+# IMPORTANT:
+# This file is ONLY used to subscribe for notifications for PRs
+# related to a specific file path, and each line is a file pattern followed by
+# one or more owners.
+
+# Order is important; the last matching pattern takes the most
+# precedence.
+
+# These owners will be the default owners for everything in
+# the repo. Unless a later match takes precedence,
+# @global-owner1 and @global-owner2 will be requested for
+# review when someone opens a pull request.
+* @zhouzaida @HAOCHENYE
+
+# Docs
+/docs/ @C1rN09
+*.rst @zhouzaida @HAOCHENYE
+
+# mmengine file
+# config
+/mmengine/config/ @HAOCHENYE
+
+# dataset
+/mmengine/dataset/ @HAOCHENYE
+
+# device
+/mmengine/device/ @zhouzaida
+
+# dist
+/mmengine/dist/ @zhouzaida @C1rN09
+
+# evaluator
+/mmengine/evaluator/ @RangiLyu @ice-tong
+
+# fileio
+/mmengine/fileio/ @zhouzaida
+
+# hooks
+/mmengine/hooks/ @zhouzaida @HAOCHENYE
+/mmengine/hooks/ema_hook.py @RangiLyu
+
+# hub
+/mmengine/hub/ @HAOCHENYE @zhouzaida
+
+# logging
+/mmengine/logging/ @HAOCHENYE
+
+# model
+/mmengine/model/ @HAOCHENYE @C1rN09
+/mmengine/model/averaged_model.py @RangiLyu
+/mmengine/model/wrappers/fully_sharded_distributed.py @C1rN09
+
+# optim
+/mmengine/optim/ @HAOCHENYE
+/mmengine/optim/scheduler/ @RangiLyu
+
+# registry
+/mmengine/registry/ @C1rN09 @HAOCHENYE
+
+# runner
+/mmengine/runner/ @zhouzaida @RangiLyu @HAOCHENYE
+/mmengine/runner/amp.py @HAOCHENYE
+/mmengine/runner/log_processor.py @HAOCHENYE
+/mmengine/runner/checkpoint.py @zhouzaida @C1rN09
+/mmengine/runner/priority.py @zhouzaida
+/mmengine/runner/utils.py @zhouzaida @HAOCHENYE
+
+# structure
+/mmengine/structures/ @Harold-lkk @HAOCHENYE
+
+# testing
+/mmengine/testing/ @zhouzaida
+
+# utils
+/mmengine/utils/ @HAOCHENYE @zhouzaida
+
+# visualization
+/mmengine/visualization/ @Harold-lkk @HAOCHENYE
+
+# version
+/mmengine/__version__.py @zhouzaida
+
+# unit test
+/tests/ @zhouzaida @HAOCHENYE
diff --git a/testbed/open-mmlab__mmengine/CONTRIBUTING.md b/testbed/open-mmlab__mmengine/CONTRIBUTING.md
new file mode 100644
index 0000000000000000000000000000000000000000..6b09f4f7f63c751f78b95999dbf6f19ad0f4b44b
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/CONTRIBUTING.md
@@ -0,0 +1,240 @@
+## Contributing to OpenMMLab
+
+Welcome to the MMEngine community, we are committed to building a cutting-edge computer vision foundational library and all kinds of contributions are welcomed, including but not limited to
+
+**Fix bug**
+
+You can directly post a Pull Request to fix typo in code or documents
+
+The steps to fix the bug of code implementation are as follows.
+
+1. If the modification involve significant changes, you should create an issue first and describe the error information and how to trigger the bug. Other developers will discuss with you and propose an proper solution.
+
+2. Posting a pull request after fixing the bug and adding corresponding unit test.
+
+**New Feature or Enhancement**
+
+1. If the modification involve significant changes, you should create an issue to discuss with our developers to propose an proper design.
+2. Post a Pull Request after implementing the new feature or enhancement and add corresponding unit test.
+
+**Document**
+
+You can directly post a pull request to fix documents. If you want to add a document, you should first create an issue to check if it is reasonable.
+
+### Pull Request Workflow
+
+If you're not familiar with Pull Request, don't worry! The following guidance will tell you how to create a Pull Request step by step. If you want to dive into the develop mode of Pull Request, you can refer to the [official documents](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-requests)
+
+#### 1. Fork and clone
+
+If you are posting a pull request for the first time, you should fork the OpenMMLab repositories by clicking the **Fork** button in the top right corner of the GitHub page, and the forked repositories will appear under your GitHub profile.
+
+
+
+Then, you can clone the repositories to local:
+
+```shell
+git clone git@github.com:{username}/mmengine.git
+```
+
+After that, you should ddd official repository as the upstream repository
+
+```bash
+git remote add upstream git@github.com:open-mmlab/mmengine
+```
+
+Check whether remote repository has been added successfully by `git remote -v`
+
+```bash
+origin git@github.com:{username}/mmengine.git (fetch)
+origin git@github.com:{username}/mmengine.git (push)
+upstream git@github.com:open-mmlab/mmengine (fetch)
+upstream git@github.com:open-mmlab/mmengine (push)
+```
+
+> Here's a brief introduction to origin and upstream. When we use "git clone", we create an "origin" remote by default, which points to the repository cloned from. As for "upstream", we add it ourselves to point to the target repository. Of course, if you don't like the name "upstream", you could name it as you wish. Usually, we'll push the code to "origin". If the pushed code conflicts with the latest code in official("upstream"), we should pull the latest code from upstream to resolve the conflicts, and then push to "origin" again. The posted Pull Request will be updated automatically.
+
+#### 2. Configure pre-commit
+
+You should configure [pre-commit](https://pre-commit.com/#intro) in the local development environment to make sure the code style matches that of OpenMMLab. **Note**: The following code should be executed under the mmengine directory.
+
+```shell
+pip install -U pre-commit
+pre-commit install
+```
+
+Check that pre-commit is configured successfully, and install the hooks defined in `.pre-commit-config.yaml`.
+
+```shell
+pre-commit run --all-files
+```
+
+
+
+
+
+If the installation process is interrupted, you can repeatedly run `pre-commit run ... ` to continue the installation.
+
+If the code does not conform to the code style specification, pre-commit will raise a warning and fixes some of the errors automatically.
+
+
+
+If we want to commit our code bypassing the pre-commit hook, we can use the `--no-verify` option(**only for temporarily commit**).
+
+```shell
+git commit -m "xxx" --no-verify
+```
+
+#### 3. Create a development branch
+
+After configuring the pre-commit, we should create a branch based on the master branch to develop the new feature or fix the bug. The proposed branch name is `username/pr_name`
+
+```shell
+git checkout -b yhc/refactor_contributing_doc
+```
+
+In subsequent development, if the master branch of the local repository is behind the master branch of "upstream", we need to pull the upstream for synchronization, and then execute the above command:
+
+```shell
+git pull upstream master
+```
+
+#### 4. Commit the code and pass the unit test
+
+- MMEngine introduces mypy to do static type checking to increase the robustness of the code. Therefore, we need to add Type Hints to our code and pass the mypy check. If you are not familiar with Type Hints, you can refer to [this tutorial](https://docs.python.org/3/library/typing.html).
+
+- The committed code should pass through the unit test
+
+ ```shell
+ # Pass all unit tests
+ pytest tests
+
+ # Pass the unit test of runner
+ pytest tests/test_runner/test_runner.py
+ ```
+
+ If the unit test fails for lack of dependencies, you can install the dependencies referring to the [guidance](#unit-test)
+
+- If the documents are modified/added, we should check the rendering result referring to [guidance](#document-rendering)
+
+#### 5. Push the code to remote
+
+We could push the local commits to remote after passing through the check of unit test and pre-commit. You can associate the local branch with remote branch by adding `-u` option.
+
+```shell
+git push -u origin {branch_name}
+```
+
+This will allow you to use the `git push` command to push code directly next time without specifying a branch or the remote repository.
+
+#### 6. Create a Pull Request
+
+(1) Create a pull request in GitHub's Pull request interface
+
+
+
+(2) Modify the PR description according to the guidelines so that other developers can better understand your changes
+
+
+
+Find more details about Pull Request description in [pull request guidelines](#pr-specs).
+
+**note**
+
+(a) The Pull Request description should contain the reason for the change, the content of the change, and the impact of the change, and be associated with the relevant Issue (see [documentation](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue)
+
+(b) If it is your first contribution, please sign the CLA
+
+
+
+(c) Check whether the Pull Request pass through the CI
+
+
+
+MMEngine will run unit test for the posted Pull Request on different platforms (Linux, Window, Mac), based on different versions of Python, PyTorch, CUDA to make sure the code is correct. We can see the specific test information by clicking `Details` in the above image so that we can modify the code.
+
+(3) If the Pull Request passes the CI, then you can wait for the review from other developers. You'll modify the code based on the reviewer's comments, and repeat the steps [4](#4-commit-the-code-and-pass-the-unit-test)-[5](#5-push-the-code-to-remote) until all reviewers approve it. Then, we will merge it ASAP.
+
+
+
+#### 7. Resolve conflicts
+
+If your local branch conflicts with the latest master branch of "upstream", you'll need to resolove them. There are two ways to do this:
+
+```shell
+git fetch --all --prune
+git rebase upstream/master
+```
+
+or
+
+```shell
+git fetch --all --prune
+git merge upstream/master
+```
+
+If you are very good at handling conflicts, then you can use rebase to resolve conflicts, as this will keep your commit logs tidy. If you are not familiar with `rebase`, then you can use `merge` to resolve conflicts.
+
+### Guidance
+
+#### Unit test
+
+We should also make sure the committed code will not decrease the coverage of unit test, we could run the following command to check the coverage of unit test:
+
+```shell
+python -m coverage run -m pytest /path/to/test_file
+python -m coverage html
+# check file in htmlcov/index.html
+```
+
+#### Document rendering
+
+If the documents are modified/added, we should check the rendering result. We could install the dependencies and run the following command to render the documents and check the results:
+
+```shell
+pip install -r requirements/docs.txt
+cd docs/zh_cn/
+# or docs/en
+make html
+# check file in ./docs/zh_cn/_build/html/index.html
+```
+
+### Python Code style
+
+We adopt [PEP8](https://www.python.org/dev/peps/pep-0008/) as the preferred code style.
+
+We use the following tools for linting and formatting:
+
+- [flake8](https://github.com/PyCQA/flake8): A wrapper around some linter tools.
+- [isort](https://github.com/timothycrosley/isort): A Python utility to sort imports.
+- [yapf](https://github.com/google/yapf): A formatter for Python files.
+- [codespell](https://github.com/codespell-project/codespell): A Python utility to fix common misspellings in text files.
+- [mdformat](https://github.com/executablebooks/mdformat): Mdformat is an opinionated Markdown formatter that can be used to enforce a consistent style in Markdown files.
+- [docformatter](https://github.com/myint/docformatter): A formatter to format docstring.
+
+Style configurations of yapf and isort can be found in [setup.cfg](./setup.cfg).
+
+We use [pre-commit hook](https://pre-commit.com/) that checks and formats for `flake8`, `yapf`, `isort`, `trailing whitespaces`, `markdown files`,
+fixes `end-of-files`, `double-quoted-strings`, `python-encoding-pragma`, `mixed-line-ending`, sorts `requirments.txt` automatically on every commit.
+The config for a pre-commit hook is stored in [.pre-commit-config](./.pre-commit-config.yaml).
+
+### PR Specs
+
+1. Use [pre-commit](https://pre-commit.com) hook to avoid issues of code style
+
+2. One short-time branch should be matched with only one PR
+
+3. Accomplish a detailed change in one PR. Avoid large PR
+
+ - Bad: Support Faster R-CNN
+ - Acceptable: Add a box head to Faster R-CNN
+ - Good: Add a parameter to box head to support custom conv-layer number
+
+4. Provide clear and significant commit message
+
+5. Provide clear and meaningful PR description
+
+ - Task name should be clarified in title. The general format is: \[Prefix\] Short description of the PR (Suffix)
+ - Prefix: add new feature \[Feature\], fix bug \[Fix\], related to documents \[Docs\], in developing \[WIP\] (which will not be reviewed temporarily)
+ - Introduce main changes, results and influences on other modules in short description
+ - Associate related issues and pull requests with a milestone
diff --git a/testbed/open-mmlab__mmengine/CONTRIBUTING_zh-CN.md b/testbed/open-mmlab__mmengine/CONTRIBUTING_zh-CN.md
new file mode 100644
index 0000000000000000000000000000000000000000..357c02d4c6da0a4552708d715e02c7946a0c7844
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/CONTRIBUTING_zh-CN.md
@@ -0,0 +1,255 @@
+## 贡献代码
+
+欢迎加入 MMEngine 社区,我们致力于打造最前沿的深度学习模型训练的基础库,我们欢迎任何类型的贡献,包括但不限于
+
+**修复错误**
+
+修复代码实现错误的步骤如下:
+
+1. 如果提交的代码改动较大,建议先提交 issue,并正确描述 issue 的现象、原因和复现方式,讨论后确认修复方案。
+2. 修复错误并补充相应的单元测试,提交拉取请求。
+
+**新增功能或组件**
+
+1. 如果新功能或模块涉及较大的代码改动,建议先提交 issue,确认功能的必要性。
+2. 实现新增功能并添单元测试,提交拉取请求。
+
+**文档补充**
+
+修复文档可以直接提交拉取请求
+
+添加文档或将文档翻译成其他语言步骤如下
+
+1. 提交 issue,确认添加文档的必要性。
+2. 添加文档,提交拉取请求。
+
+### 拉取请求工作流
+
+如果你对拉取请求不了解,没关系,接下来的内容将会从零开始,一步一步地指引你如何创建一个拉取请求。如果你想深入了解拉取请求的开发模式,可以参考 github [官方文档](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-requests)
+
+#### 1. 复刻仓库
+
+当你第一次提交拉取请求时,先复刻 OpenMMLab 原代码库,点击 GitHub 页面右上角的 **Fork** 按钮,复刻后的代码库将会出现在你的 GitHub 个人主页下。
+
+
+
+将代码克隆到本地
+
+```shell
+git clone git@github.com:{username}/mmengine.git
+```
+
+添加原代码库为上游代码库
+
+```bash
+git remote add upstream git@github.com:open-mmlab/mmengine
+```
+
+检查 remote 是否添加成功,在终端输入 `git remote -v`
+
+```bash
+origin git@github.com:{username}/mmengine.git (fetch)
+origin git@github.com:{username}/mmengine.git (push)
+upstream git@github.com:open-mmlab/mmengine (fetch)
+upstream git@github.com:open-mmlab/mmengine (push)
+```
+
+> 这里对 origin 和 upstream 进行一个简单的介绍,当我们使用 git clone 来克隆代码时,会默认创建一个 origin 的 remote,它指向我们克隆的代码库地址,而 upstream 则是我们自己添加的,用来指向原始代码库地址。当然如果你不喜欢他叫 upstream,也可以自己修改,比如叫 open-mmlab。我们通常向 origin 提交代码(即 fork 下来的远程仓库),然后向 upstream 提交一个 pull request。如果提交的代码和最新的代码发生冲突,再从 upstream 拉取最新的代码,和本地分支解决冲突,再提交到 origin。
+
+#### 2. 配置 pre-commit
+
+在本地开发环境中,我们使用 [pre-commit](https://pre-commit.com/#intro) 来检查代码风格,以确保代码风格的统一。在提交代码,需要先安装 pre-commit(需要在 mmengine 目录下执行):
+
+```shell
+pip install -U pre-commit
+pre-commit install
+```
+
+检查 pre-commit 是否配置成功,并安装 `.pre-commit-config.yaml` 中的钩子:
+
+```shell
+pre-commit run --all-files
+```
+
+
+
+
+
+> 如果你是中国用户,由于网络原因,可能会出现安装失败的情况,这时可以使用国内源
+
+> pre-commit install -c .pre-commit-config-zh-cn.yaml
+
+> pre-commit run --all-files -c .pre-commit-config-zh-cn.yaml
+
+如果安装过程被中断,可以重复执行 `pre-commit run ...` 继续安装。
+
+如果提交的代码不符合代码风格规范,pre-commit 会发出警告,并自动修复部分错误。
+
+
+
+如果我们想临时绕开 pre-commit 的检查提交一次代码,可以在 `git commit` 时加上 `--no-verify`(需要保证最后推送至远程仓库的代码能够通过 pre-commit 检查)。
+
+```shell
+git commit -m "xxx" --no-verify
+```
+
+#### 3. 创建开发分支
+
+安装完 pre-commit 之后,我们需要基于 master 创建开发分支,建议的分支命名规则为 `username/pr_name`。
+
+```shell
+git checkout -b yhc/refactor_contributing_doc
+```
+
+在后续的开发中,如果本地仓库的 master 分支落后于 upstream 的 master 分支,我们需要先拉取 upstream 的代码进行同步,再执行上面的命令
+
+```shell
+git pull upstream master
+```
+
+#### 4. 提交代码并在本地通过单元测试
+
+- MMEngine 引入了 mypy 来做静态类型检查,以增加代码的鲁棒性。因此我们在提交代码时,需要补充 Type Hints。具体规则可以参考[教程](https://zhuanlan.zhihu.com/p/519335398)。
+
+- 提交的代码同样需要通过单元测试
+
+ ```shell
+ # 通过全量单元测试
+ pytest tests
+
+ # 我们需要保证提交的代码能够通过修改模块的单元测试,以 runner 为例
+ pytest tests/test_runner/test_runner.py
+ ```
+
+ 如果你由于缺少依赖无法运行修改模块的单元测试,可以参考[指引-单元测试](#单元测试)
+
+- 如果修改/添加了文档,参考[指引](#文档渲染)确认文档渲染正常。
+
+#### 5. 推送代码到远程
+
+代码通过单元测试和 pre-commit 检查后,将代码推送到远程仓库,如果是第一次推送,可以在 `git push` 后加上 `-u` 参数以关联远程分支
+
+```shell
+git push -u origin {branch_name}
+```
+
+这样下次就可以直接使用 `git push` 命令推送代码了,而无需指定分支和远程仓库。
+
+#### 6. 提交拉取请求(PR)
+
+(1) 在 GitHub 的 Pull request 界面创建拉取请求
+
+
+(2) 根据指引修改 PR 描述,以便于其他开发者更好地理解你的修改
+
+
+
+描述规范详见[拉取请求规范](#拉取请求规范)
+
+
+
+**注意事项**
+
+(a) PR 描述应该包含修改理由、修改内容以及修改后带来的影响,并关联相关 Issue(具体方式见[文档](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue))
+
+(b) 如果是第一次为 OpenMMLab 做贡献,需要签署 CLA
+
+
+
+(c) 检查提交的 PR 是否通过 CI(集成测试)
+
+
+
+MMEngine 会在不同的平台(Linux、Window、Mac),基于不同版本的 Python、PyTorch、CUDA 对提交的代码进行单元测试,以保证代码的正确性,如果有任何一个没有通过,我们可点击上图中的 `Details` 来查看具体的测试信息,以便于我们修改代码。
+
+(3) 如果 PR 通过了 CI,那么就可以等待其他开发者的 review,并根据 reviewer 的意见,修改代码,并重复 [4](#4-提交代码并本地通过单元测试)-[5](#5-推送代码到远程) 步骤,直到 reviewer 同意合入 PR。
+
+
+
+所有 reviewer 同意合入 PR 后,我们会尽快将 PR 合并到主分支。
+
+#### 7. 解决冲突
+
+随着时间的推移,我们的代码库会不断更新,这时候,如果你的 PR 与主分支存在冲突,你需要解决冲突,解决冲突的方式有两种:
+
+```shell
+git fetch --all --prune
+git rebase upstream/master
+```
+
+或者
+
+```shell
+git fetch --all --prune
+git merge upstream/master
+```
+
+如果你非常善于处理冲突,那么可以使用 rebase 的方式来解决冲突,因为这能够保证你的 commit log 的整洁。如果你不太熟悉 `rebase` 的使用,那么可以使用 `merge` 的方式来解决冲突。
+
+### 指引
+
+#### 单元测试
+
+在提交修复代码错误或新增特性的拉取请求时,我们应该尽可能的让单元测试覆盖所有提交的代码,计算单元测试覆盖率的方法如下
+
+```shell
+python -m coverage run -m pytest /path/to/test_file
+python -m coverage html
+# check file in htmlcov/index.html
+```
+
+#### 文档渲染
+
+在提交修复代码错误或新增特性的拉取请求时,可能会需要修改/新增模块的 docstring。我们需要确认渲染后的文档样式是正确的。
+本地生成渲染后的文档的方法如下
+
+```shell
+pip install -r requirements/docs.txt
+cd docs/zh_cn/
+# or docs/en
+make html
+# check file in ./docs/zh_cn/_build/html/index.html
+```
+
+### Python 代码风格
+
+[PEP8](https://www.python.org/dev/peps/pep-0008/) 作为 OpenMMLab 算法库首选的代码规范,我们使用以下工具检查和格式化代码
+
+- [flake8](https://github.com/PyCQA/flake8): Python 官方发布的代码规范检查工具,是多个检查工具的封装
+- [isort](https://github.com/timothycrosley/isort): 自动调整模块导入顺序的工具
+- [yapf](https://github.com/google/yapf): Google 发布的代码规范检查工具
+- [codespell](https://github.com/codespell-project/codespell): 检查单词拼写是否有误
+- [mdformat](https://github.com/executablebooks/mdformat): 检查 markdown 文件的工具
+- [docformatter](https://github.com/myint/docformatter): 格式化 docstring 的工具
+
+yapf 和 isort 的配置可以在 [setup.cfg](./setup.cfg) 找到
+
+通过配置 [pre-commit hook](https://pre-commit.com/) ,我们可以在提交代码时自动检查和格式化 `flake8`、`yapf`、`isort`、`trailing whitespaces`、`markdown files`,修复 `end-of-files`、`double-quoted-strings`、`python-encoding-pragma`、`mixed-line-ending`,调整 `requirments.txt` 的包顺序。
+pre-commit 钩子的配置可以在 [.pre-commit-config](./.pre-commit-config.yaml) 找到。
+
+pre-commit 具体的安装使用方式见[拉取请求](#2-配置-pre-commit)。
+
+更具体的规范请参考 [OpenMMLab 代码规范](code_style.md)。
+
+### 拉取请求规范
+
+1. 使用 [pre-commit hook](https://pre-commit.com),尽量减少代码风格相关问题
+
+2. 一个`拉取请求`对应一个短期分支
+
+3. 粒度要细,一个`拉取请求`只做一件事情,避免超大的`拉取请求`
+
+ - Bad:实现 Faster R-CNN
+ - Acceptable:给 Faster R-CNN 添加一个 box head
+ - Good:给 box head 增加一个参数来支持自定义的 conv 层数
+
+4. 每次 Commit 时需要提供清晰且有意义 commit 信息
+
+5. 提供清晰且有意义的`拉取请求`描述
+
+ - 标题写明白任务名称,一般格式:\[Prefix\] Short description of the pull request (Suffix)
+ - prefix: 新增功能 \[Feature\], 修 bug \[Fix\], 文档相关 \[Docs\], 开发中 \[WIP\] (暂时不会被review)
+ - 描述里介绍`拉取请求`的主要修改内容,结果,以及对其他部分的影响, 参考`拉取请求`模板
+ - 关联相关的`议题` (issue) 和其他`拉取请求`
+
+6. 如果引入了其他三方库,或借鉴了三方库的代码,请确认他们的许可证和 MMEngine 兼容,并在借鉴的代码上补充 `This code is inspired from http://`
diff --git a/testbed/open-mmlab__mmengine/LICENSE b/testbed/open-mmlab__mmengine/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..1bfc23e48f92245b229cdd57c77e79bc10a1cc27
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/LICENSE
@@ -0,0 +1,203 @@
+Copyright 2018-2023 OpenMMLab. All rights reserved.
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2018-2023 OpenMMLab.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/testbed/open-mmlab__mmengine/MANIFEST.in b/testbed/open-mmlab__mmengine/MANIFEST.in
new file mode 100644
index 0000000000000000000000000000000000000000..8bf078a7572fb583af011ac5d714895694f279cf
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/MANIFEST.in
@@ -0,0 +1 @@
+include mmengine/hub/openmmlab.json mmengine/hub/deprecated.json mmengine/hub/mmcls.json mmengine/hub/torchvision_0.12.json
diff --git a/testbed/open-mmlab__mmengine/README.md b/testbed/open-mmlab__mmengine/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..c0bb49df1cb9d83af4ac2c53d8529eaceaba9561
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/README.md
@@ -0,0 +1,306 @@
+
+
+
+
+
+
+[](https://pypi.org/project/mmengine/)
+[](https://pypi.org/project/mmengine)
+[](https://github.com/open-mmlab/mmengine/blob/main/LICENSE)
+[](https://github.com/open-mmlab/mmengine/issues)
+[](https://github.com/open-mmlab/mmengine/issues)
+
+[🤔Reporting Issues](https://github.com/open-mmlab/mmengine/issues/new/choose)
+
+
+
+
+
+English | [简体中文](README_zh-CN.md)
+
+
+
+## Introduction
+
+MMEngine is a foundational library for training deep learning models based on PyTorch. It provides a solid engineering foundation and frees developers from writing redundant codes on workflows. It serves as the training engine of all OpenMMLab codebases, which support hundreds of algorithms in various research areas. Moreover, MMEngine is also generic to be applied to non-OpenMMLab projects.
+
+Major features:
+
+1. **A universal and powerful runner**:
+
+ - Supports training different tasks with a small amount of code, e.g., ImageNet can be trained with only 80 lines of code (400 lines of the original PyTorch example)
+ - Easily compatible with models from popular algorithm libraries such as TIMM, TorchVision, and Detectron2
+
+2. **Open architecture with unified interfaces**:
+
+ - Handles different algorithm tasks with unified APIs, e.g., implement a method and apply it to all compatible models.
+ - Provides a unified abstraction for upper-level algorithm libraries, which supports various back-end devices such as Nvidia CUDA, Mac MPS, AMD, MLU, and more for model training.
+
+3. **Customizable training process**:
+
+ - Defines the training process just like playing with Legos.
+ - Provides rich components and strategies.
+ - Complete controls on the training process with different levels of APIs.
+
+## What's New
+
+v0.3.2 was released in 2022-11-24.
+
+Read [Changelog](./docs/en/notes/changelog.md#v032-11242022) for more details.
+
+## Installation
+
+Before installing MMEngine, please ensure that PyTorch has been successfully installed following the [official guide](https://pytorch.org/get-started/locally/).
+
+Install MMEngine
+
+```bash
+pip install -U openmim
+mim install mmengine
+```
+
+Verify the installation
+
+```bash
+python -c 'from mmengine.utils.dl_utils import collect_env;print(collect_env())'
+```
+
+## Get Started
+
+Taking the training of a ResNet-50 model on the CIFAR-10 dataset as an example, we will use MMEngine to build a complete, configurable training and validation process in less than 80 lines of code.
+
+
+Build Models
+
+First, we need to define a **model** which 1) inherits from `BaseModel` and 2) accepts an additional argument `mode` in the `forward` method, in addition to those arguments related to the dataset.
+
+- During training, the value of `mode` is "loss," and the `forward` method should return a `dict` containing the key "loss".
+- During validation, the value of `mode` is "predict", and the forward method should return results containing both predictions and labels.
+
+```python
+import torch.nn.functional as F
+import torchvision
+from mmengine.model import BaseModel
+
+class MMResNet50(BaseModel):
+ def __init__(self):
+ super().__init__()
+ self.resnet = torchvision.models.resnet50()
+
+ def forward(self, imgs, labels, mode):
+ x = self.resnet(imgs)
+ if mode == 'loss':
+ return {'loss': F.cross_entropy(x, labels)}
+ elif mode == 'predict':
+ return x, labels
+```
+
+
+
+
+Build Datasets
+
+Next, we need to create **Dataset**s and **DataLoader**s for training and validation.
+In this case, we simply use built-in datasets supported in TorchVision.
+
+```python
+import torchvision.transforms as transforms
+from torch.utils.data import DataLoader
+
+norm_cfg = dict(mean=[0.491, 0.482, 0.447], std=[0.202, 0.199, 0.201])
+train_dataloader = DataLoader(batch_size=32,
+ shuffle=True,
+ dataset=torchvision.datasets.CIFAR10(
+ 'data/cifar10',
+ train=True,
+ download=True,
+ transform=transforms.Compose([
+ transforms.RandomCrop(32, padding=4),
+ transforms.RandomHorizontalFlip(),
+ transforms.ToTensor(),
+ transforms.Normalize(**norm_cfg)
+ ])))
+val_dataloader = DataLoader(batch_size=32,
+ shuffle=False,
+ dataset=torchvision.datasets.CIFAR10(
+ 'data/cifar10',
+ train=False,
+ download=True,
+ transform=transforms.Compose([
+ transforms.ToTensor(),
+ transforms.Normalize(**norm_cfg)
+ ])))
+```
+
+
+
+
+Build Metrics
+
+To validate and test the model, we need to define a **Metric** called accuracy to evaluate the model. This metric needs to inherit from `BaseMetric` and implements the `process` and `compute_metrics` methods.
+
+```python
+from mmengine.evaluator import BaseMetric
+
+class Accuracy(BaseMetric):
+ def process(self, data_batch, data_samples):
+ score, gt = data_samples
+ # Save the results of a batch to `self.results`
+ self.results.append({
+ 'batch_size': len(gt),
+ 'correct': (score.argmax(dim=1) == gt).sum().cpu(),
+ })
+ def compute_metrics(self, results):
+ total_correct = sum(item['correct'] for item in results)
+ total_size = sum(item['batch_size'] for item in results)
+ # Returns a dictionary with the results of the evaluated metrics,
+ # where the key is the name of the metric
+ return dict(accuracy=100 * total_correct / total_size)
+```
+
+
+
+
+Build a Runner
+
+Finally, we can construct a **Runner** with previously defined `Model`, `DataLoader`, and `Metrics`, with some other configs, as shown below.
+
+```python
+from torch.optim import SGD
+from mmengine.runner import Runner
+
+runner = Runner(
+ model=MMResNet50(),
+ work_dir='./work_dir',
+ train_dataloader=train_dataloader,
+ # a wapper to execute back propagation and gradient update, etc.
+ optim_wrapper=dict(optimizer=dict(type=SGD, lr=0.001, momentum=0.9)),
+ # set some training configs like epochs
+ train_cfg=dict(by_epoch=True, max_epochs=5, val_interval=1),
+ val_dataloader=val_dataloader,
+ val_cfg=dict(),
+ val_evaluator=dict(type=Accuracy),
+)
+```
+
+
+
+
+Launch Training
+
+```python
+runner.train()
+```
+
+
+
+## Learn More
+
+
+Tutorials
+
+- [Runner](https://mmengine.readthedocs.io/en/latest/tutorials/runner.html)
+- [Dataset and DataLoader](https://mmengine.readthedocs.io/en/latest/tutorials/dataset.html)
+- [Model](https://mmengine.readthedocs.io/en/latest/tutorials/model.html)
+- [Evaluation](https://mmengine.readthedocs.io/en/latest/tutorials/evaluation.html)
+- [OptimWrapper](https://mmengine.readthedocs.io/en/latest/tutorials/optim_wrapper.html)
+- [Parameter Scheduler](https://mmengine.readthedocs.io/en/latest/tutorials/param_scheduler.html)
+- [Hook](https://mmengine.readthedocs.io/en/latest/tutorials/hook.html)
+
+
+
+
+Advanced tutorials
+
+- [Registry](https://mmengine.readthedocs.io/en/latest/tutorials/registry.html)
+- [Config](https://mmengine.readthedocs.io/en/latest/tutorials/config.html)
+- [BaseDataset](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/basedataset.html)
+- [Data Transform](https://mmengine.readthedocs.io/en/latest/tutorials/data_transform.html)
+- [Initialization](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/initialize.html)
+- [Visualization](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/visualization.html)
+- [Abstract Data Element](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/data_element.html)
+- [Distribution Communication](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/distributed.html)
+- [Logging](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/logging.html)
+- [File IO](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/fileio.html)
+- [Global manager (ManagerMixin)](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/manager_mixin.html)
+- [Use modules from other libraries](https://mmengine.readthedocs.io/en/latest/advanced_tutorials/cross_library.html)
+
+
+
+
+Examples
+
+- [Resume Training](https://mmengine.readthedocs.io/en/latest/examples/resume_training.html)
+- [Speed up Training](https://mmengine.readthedocs.io/en/latest/examples/speed_up_training.html)
+- [Save Memory on GPU](https://mmengine.readthedocs.io/en/latest/examples/save_gpu_memory.html)
+- [Train a GAN](https://mmengine.readthedocs.io/en/latest/examples/train_a_gan.html)
+
+
+
+
+Design
+
+- [Hook](https://mmengine.readthedocs.io/en/latest/design/hook.html)
+- [Runner](https://mmengine.readthedocs.io/en/latest/design/runner.html)
+- [Evaluation](https://mmengine.readthedocs.io/en/latest/design/evaluation.html)
+- [Visualization](https://mmengine.readthedocs.io/en/latest/design/visualization.html)
+- [Logging](https://mmengine.readthedocs.io/en/latest/design/logging.html)
+
+
+
+
+Migration guide
+
+- [Migrate Runner from MMCV to MMEngine](https://mmengine.readthedocs.io/en/latest/migration/runner.html)
+- [Migrate Hook from MMCV to MMEngine](https://mmengine.readthedocs.io/en/latest/migration/hook.html)
+- [Migrate Model from MMCV to MMEngine](https://mmengine.readthedocs.io/en/latest/migration/model.html)
+- [Migrate Parameter Scheduler from MMCV to MMEngine](https://mmengine.readthedocs.io/en/latest/migration/param_scheduler.html)
+- [Migrate Data Transform to OpenMMLab 2.0](https://mmengine.readthedocs.io/en/latest/migration/transform.html)
+
+
+
+## Contributing
+
+We appreciate all contributions to improve MMEngine. Please refer to [CONTRIBUTING.md](CONTRIBUTING.md) for the contributing guideline.
+
+## License
+
+This project is released under the [Apache 2.0 license](LICENSE).
+
+## Projects in OpenMMLab
+
+- [MIM](https://github.com/open-mmlab/mim): MIM installs OpenMMLab packages.
+- [MMCV](https://github.com/open-mmlab/mmcv): OpenMMLab foundational library for computer vision.
+- [MMEval](https://github.com/open-mmlab/mmeval): A unified evaluation library for multiple machine learning libraries.
+- [MMClassification](https://github.com/open-mmlab/mmclassification): OpenMMLab image classification toolbox and benchmark.
+- [MMDetection](https://github.com/open-mmlab/mmdetection): OpenMMLab detection toolbox and benchmark.
+- [MMDetection3D](https://github.com/open-mmlab/mmdetection3d): OpenMMLab's next-generation platform for general 3D object detection.
+- [MMRotate](https://github.com/open-mmlab/mmrotate): OpenMMLab rotated object detection toolbox and benchmark.
+- [MMYOLO](https://github.com/open-mmlab/mmyolo): OpenMMLab YOLO series toolbox and benchmark.
+- [MMSegmentation](https://github.com/open-mmlab/mmsegmentation): OpenMMLab semantic segmentation toolbox and benchmark.
+- [MMOCR](https://github.com/open-mmlab/mmocr): OpenMMLab text detection, recognition, and understanding toolbox.
+- [MMPose](https://github.com/open-mmlab/mmpose): OpenMMLab pose estimation toolbox and benchmark.
+- [MMHuman3D](https://github.com/open-mmlab/mmhuman3d): OpenMMLab 3D human parametric model toolbox and benchmark.
+- [MMSelfSup](https://github.com/open-mmlab/mmselfsup): OpenMMLab self-supervised learning toolbox and benchmark.
+- [MMRazor](https://github.com/open-mmlab/mmrazor): OpenMMLab model compression toolbox and benchmark.
+- [MMFewShot](https://github.com/open-mmlab/mmfewshot): OpenMMLab fewshot learning toolbox and benchmark.
+- [MMAction2](https://github.com/open-mmlab/mmaction2): OpenMMLab's next-generation action understanding toolbox and benchmark.
+- [MMTracking](https://github.com/open-mmlab/mmtracking): OpenMMLab video perception toolbox and benchmark.
+- [MMFlow](https://github.com/open-mmlab/mmflow): OpenMMLab optical flow toolbox and benchmark.
+- [MMEditing](https://github.com/open-mmlab/mmediting): OpenMMLab image and video editing toolbox.
+- [MMGeneration](https://github.com/open-mmlab/mmgeneration): OpenMMLab image and video generative models toolbox.
+- [MMDeploy](https://github.com/open-mmlab/mmdeploy): OpenMMLab model deployment framework.
diff --git a/testbed/open-mmlab__mmengine/README_zh-CN.md b/testbed/open-mmlab__mmengine/README_zh-CN.md
new file mode 100644
index 0000000000000000000000000000000000000000..7cea0830d87513f20e72b0e95eaba909978d7170
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/README_zh-CN.md
@@ -0,0 +1,333 @@
+
+
+
+
+
+
+[](https://pypi.org/project/mmengine/)
+[](https://pypi.org/project/mmengine)
+[](https://github.com/open-mmlab/mmengine/blob/main/LICENSE)
+[](https://github.com/open-mmlab/mmengine/issues)
+[](https://github.com/open-mmlab/mmengine/issues)
+
+[📘使用文档](https://mmengine.readthedocs.io/zh_CN/latest/) |
+[🛠️安装教程](https://mmengine.readthedocs.io/zh_CN/latest/get_started/installation.html) |
+[🤔报告问题](https://github.com/open-mmlab/mmengine/issues/new/choose)
+
+
+
+
+
+[English](README.md) | 简体中文
+
+
+
+## 简介
+
+MMEngine 是一个基于 PyTorch 用于深度学习模型训练的基础库,支持在 Linux、Windows、macOS 上运行。它具有如下三个亮点:
+
+1. 通用:MMEngine 实现了一个高级的通用训练器,它能够:
+
+ - 支持用少量代码训练不同的任务,例如仅使用 80 行代码就可以训练 imagenet(原始pytorch example 400 行)
+ - 轻松兼容流行的算法库 (如 TIMM、TorchVision 和 Detectron2 ) 中的模型
+
+2. 统一:MMEngine 设计了一个接口统一的开放架构,使得:
+
+ - 用户可以仅依赖一份代码实现所有任务的轻量化,例如 MMRazor 1.x 相比 MMRazor 0.x 优化了 40% 的代码量
+ - 上下游的对接更加统一便捷,在为上层算法库提供统一抽象的同时,支持多种后端设备。目前 MMEngine 支持 Nvidia CUDA、Mac MPS、AMD、MLU 等设备进行模型训练。
+
+3. 灵活:MMEngine 实现了“乐高”式的训练流程,支持了:
+
+ - 根据迭代数、 loss 和评测结果等动态调整的训练流程、优化策略和数据增强策略,例如早停(early stopping)机制等
+ - 任意形式的模型权重平均,如 Exponential Momentum Average (EMA) 和 Stochastic Weight Averaging (SWA)
+ - 训练过程中针对任意数据和任意节点的灵活可视化和日志控制
+ - 对神经网络模型中各个层的优化配置进行细粒度调整
+ - 混合精度训练的灵活控制
+
+## 最近进展
+
+最新版本 v0.3.2 在 2022.11.24 发布。
+
+如果想了解更多版本更新细节和历史信息,请阅读[更新日志](./docs/en/notes/changelog.md#v032-11242022)
+
+## 安装
+
+在安装 MMengine 之前,请确保 PyTorch 已成功安装在环境中,可以参考 [PyTorch 官方安装文档](https://pytorch.org/get-started/locally/)。
+
+安装 MMEngine
+
+```bash
+pip install -U openmim
+mim install mmengine
+```
+
+验证是否安装成功
+
+```bash
+python -c 'from mmengine.utils.dl_utils import collect_env;print(collect_env())'
+```
+
+更多安装方式请阅读[安装文档](https://mmengine.readthedocs.io/zh_CN/latest/get_started/installation.html)
+
+## 快速上手
+
+以在 CIFAR-10 数据集上训练一个 ResNet-50 模型为例,我们将使用 80 行以内的代码,利用 MMEngine 构建一个完整的、可配置的训练和验证流程。
+
+
+构建模型
+
+首先,我们需要构建一个**模型**,在 MMEngine 中,我们约定这个模型应当继承 `BaseModel`,并且其 `forward` 方法除了接受来自数据集的若干参数外,还需要接受额外的参数 `mode`:对于训练,我们需要 `mode` 接受字符串 "loss",并返回一个包含 "loss" 字段的字典;对于验证,我们需要 `mode` 接受字符串 "predict",并返回同时包含预测信息和真实信息的结果。
+
+```python
+import torch.nn.functional as F
+import torchvision
+from mmengine.model import BaseModel
+
+class MMResNet50(BaseModel):
+ def __init__(self):
+ super().__init__()
+ self.resnet = torchvision.models.resnet50()
+
+ def forward(self, imgs, labels, mode):
+ x = self.resnet(imgs)
+ if mode == 'loss':
+ return {'loss': F.cross_entropy(x, labels)}
+ elif mode == 'predict':
+ return x, labels
+```
+
+
+
+
+构建数据集
+
+其次,我们需要构建训练和验证所需要的**数据集 (Dataset)**和**数据加载器 (DataLoader)**。
+对于基础的训练和验证功能,我们可以直接使用符合 PyTorch 标准的数据加载器和数据集。
+
+```python
+import torchvision.transforms as transforms
+from torch.utils.data import DataLoader
+
+norm_cfg = dict(mean=[0.491, 0.482, 0.447], std=[0.202, 0.199, 0.201])
+train_dataloader = DataLoader(batch_size=32,
+ shuffle=True,
+ dataset=torchvision.datasets.CIFAR10(
+ 'data/cifar10',
+ train=True,
+ download=True,
+ transform=transforms.Compose([
+ transforms.RandomCrop(32, padding=4),
+ transforms.RandomHorizontalFlip(),
+ transforms.ToTensor(),
+ transforms.Normalize(**norm_cfg)
+ ])))
+val_dataloader = DataLoader(batch_size=32,
+ shuffle=False,
+ dataset=torchvision.datasets.CIFAR10(
+ 'data/cifar10',
+ train=False,
+ download=True,
+ transform=transforms.Compose([
+ transforms.ToTensor(),
+ transforms.Normalize(**norm_cfg)
+ ])))
+```
+
+
+
+
+构建评测指标
+
+为了进行验证和测试,我们需要定义模型推理结果的**评测指标**。我们约定这一评测指标需要继承 `BaseMetric`,并实现 `process` 和 `compute_metrics` 方法。
+
+```python
+from mmengine.evaluator import BaseMetric
+
+class Accuracy(BaseMetric):
+ def process(self, data_batch, data_samples):
+ score, gt = data_samples
+ # 将一个批次的中间结果保存至 `self.results`
+ self.results.append({
+ 'batch_size': len(gt),
+ 'correct': (score.argmax(dim=1) == gt).sum().cpu(),
+ })
+ def compute_metrics(self, results):
+ total_correct = sum(item['correct'] for item in results)
+ total_size = sum(item['batch_size'] for item in results)
+ # 返回保存有评测指标结果的字典,其中键为指标名称
+ return dict(accuracy=100 * total_correct / total_size)
+```
+
+
+
+
+构建执行器
+
+最后,我们利用构建好的**模型**,**数据加载器**,**评测指标**构建一个**执行器 (Runner)**,同时在其中配置
+**优化器**、**工作路径**、**训练与验证配置**等选项
+
+```python
+from torch.optim import SGD
+from mmengine.runner import Runner
+
+runner = Runner(
+ # 用以训练和验证的模型,需要满足特定的接口需求
+ model=MMResNet50(),
+ # 工作路径,用以保存训练日志、权重文件信息
+ work_dir='./work_dir',
+ # 训练数据加载器,需要满足 PyTorch 数据加载器协议
+ train_dataloader=train_dataloader,
+ # 优化器包装,用于模型优化,并提供 AMP、梯度累积等附加功能
+ optim_wrapper=dict(optimizer=dict(type=SGD, lr=0.001, momentum=0.9)),
+ # 训练配置,用于指定训练周期、验证间隔等信息
+ train_cfg=dict(by_epoch=True, max_epochs=5, val_interval=1),
+ # 验证数据加载器,需要满足 PyTorch 数据加载器协议
+ val_dataloader=val_dataloader,
+ # 验证配置,用于指定验证所需要的额外参数
+ val_cfg=dict(),
+ # 用于验证的评测器,这里使用默认评测器,并评测指标
+ val_evaluator=dict(type=Accuracy),
+)
+```
+
+
+
+
+开始训练
+
+```python
+runner.train()
+```
+
+
+
+## 了解更多
+
+
+入门教程
+
+- [注册器](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/registry.html)
+- [配置](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/config.html)
+- [执行器](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/runner.html)
+- [钩子](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/hook.html)
+- [数据集与数据加载器](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/dataset.html)
+- [模型](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/model.html)
+- [评测指标和评测器](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/evaluation.html)
+- [优化器](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/optim_wrapper.html)
+- [优化器参数调整策略](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/param_scheduler.html)
+- [数据变换](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/data_transform.html)
+- [钩子](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/hook.html)
+
+
+
+
+进阶教程
+
+- [注册器](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/registry.html)
+- [配置](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/config.html)
+- [数据集基类](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/basedataset.html)
+- [抽象数据接口](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/data_element.html)
+- [可视化](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/visualization.html)
+- [数据变换](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/data_transform.html)
+- [初始化](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/initialize.html)
+- [可视化](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/visualization.html)
+- [抽象数据接口](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/data_element.html)
+- [分布式通信原语](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/distributed.html)
+- [记录日志](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/logging.html)
+- [文件读写](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/fileio.html)
+- [辅助类](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/utils.html)
+- [全局管理器](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/manager_mixin.html)
+- [跨库调用模块](https://mmengine.readthedocs.io/zh_CN/latest/advanced_tutorials/cross_library.html)
+
+
+
+
+示例
+- [恢复训练](https://mmengine.readthedocs.io/zh_CN/latest/examples/resume_training.html)
+- [加速训练](https://mmengine.readthedocs.io/zh_CN/latest/examples/speed_up_training.html)
+- [节省显存](https://mmengine.readthedocs.io/zh_CN/latest/examples/save_gpu_memory.html)
+- [跨库调用模块](https://mmengine.readthedocs.io/zh_CN/latest/examples/cross_library.html)
+- [训练生成对抗网络](https://mmengine.readthedocs.io/zh_CN/latest/examples/train_a_gan.html)
+
+
+
+架构设计
+- [钩子的设计](https://mmengine.readthedocs.io/zh_CN/latest/design/hook.html)
+- [执行器的设计](https://mmengine.readthedocs.io/zh_CN/latest/design/runner.html)
+- [模型精度评测的设计](https://mmengine.readthedocs.io/zh_CN/latest/design/evaluation.html)
+- [可视化的设计](https://mmengine.readthedocs.io/zh_CN/latest/design/visualization.html)
+- [日志系统的设计](https://mmengine.readthedocs.io/zh_CN/latest/design/logging.html)
+
+
+迁移指南
+- [迁移 MMCV 执行器到 MMEngine](https://mmengine.readthedocs.io/zh_CN/latest/migration/runner.html)
+- [迁移 MMCV 钩子到 MMEngine](https://mmengine.readthedocs.io/zh_CN/latest/migration/hook.html)
+- [迁移 MMCV 模型到 MMEngine](https://mmengine.readthedocs.io/zh_CN/latest/migration/model.html)
+- [迁移 MMCV 参数调度器到 MMEngine](https://mmengine.readthedocs.io/zh_CN/latest/migration/param_scheduler.html)
+- [数据变换类的迁移](https://mmengine.readthedocs.io/zh_CN/latest/migration/transform.html)
+
+
+## 贡献指南
+
+我们感谢所有的贡献者为改进和提升 MMEngine 所作出的努力。请参考[贡献指南](CONTRIBUTING_zh-CN.md)来了解参与项目贡献的相关指引。
+
+## 开源许可证
+
+该项目采用 [Apache 2.0 license](LICENSE) 开源许可证。
+
+## OpenMMLab 的其他项目
+
+- [MIM](https://github.com/open-mmlab/mim): MIM 是 OpenMMLab 项目、算法、模型的统一入口
+- [MMCV](https://github.com/open-mmlab/mmcv/tree/dev-2.x): OpenMMLab 计算机视觉基础库
+- [MMEval](https://github.com/open-mmlab/mmeval): 统一开放的跨框架算法评测库
+- [MMClassification](https://github.com/open-mmlab/mmclassification/tree/dev-1.x): OpenMMLab 图像分类工具箱
+- [MMDetection](https://github.com/open-mmlab/mmdetection/tree/dev-3.x): OpenMMLab 目标检测工具箱
+- [MMDetection3D](https://github.com/open-mmlab/mmdetection3d/tree/dev-1.x): OpenMMLab 新一代通用 3D 目标检测平台
+- [MMRotate](https://github.com/open-mmlab/mmrotate/tree/dev-1.x): OpenMMLab 旋转框检测工具箱与测试基准
+- [MMYOLO](https://github.com/open-mmlab/mmyolo): OpenMMLab YOLO 系列工具箱与测试基准
+- [MMSegmentation](https://github.com/open-mmlab/mmsegmentation/tree/dev-1.x): OpenMMLab 语义分割工具箱
+- [MMOCR](https://github.com/open-mmlab/mmocr/tree/dev-1.x): OpenMMLab 全流程文字检测识别理解工具包
+- [MMPose](https://github.com/open-mmlab/mmpose/tree/dev-1.x): OpenMMLab 姿态估计工具箱
+- [MMHuman3D](https://github.com/open-mmlab/mmhuman3d): OpenMMLab 人体参数化模型工具箱与测试基准
+- [MMSelfSup](https://github.com/open-mmlab/mmselfsup/tree/dev-1.x): OpenMMLab 自监督学习工具箱与测试基准
+- [MMRazor](https://github.com/open-mmlab/mmrazor/tree/dev-1.x): OpenMMLab 模型压缩工具箱与测试基准
+- [MMFewShot](https://github.com/open-mmlab/mmfewshot): OpenMMLab 少样本学习工具箱与测试基准
+- [MMAction2](https://github.com/open-mmlab/mmaction2/tree/dev-1.x): OpenMMLab 新一代视频理解工具箱
+- [MMTracking](https://github.com/open-mmlab/mmtracking/tree/dev-1.x): OpenMMLab 一体化视频目标感知平台
+- [MMFlow](https://github.com/open-mmlab/mmflow/tree/dev-1.x): OpenMMLab 光流估计工具箱与测试基准
+- [MMEditing](https://github.com/open-mmlab/mmediting/tree/dev-1.x): OpenMMLab 图像视频编辑工具箱
+- [MMGeneration](https://github.com/open-mmlab/mmgeneration/tree/dev-1.x): OpenMMLab 图片视频生成模型工具箱
+- [MMDeploy](https://github.com/open-mmlab/mmdeploy): OpenMMLab 模型部署框架
+
+## 欢迎加入 OpenMMLab 社区
+
+扫描下方的二维码可关注 OpenMMLab 团队的 [知乎官方账号](https://www.zhihu.com/people/openmmlab),加入 OpenMMLab 团队的 [官方交流 QQ 群](https://jq.qq.com/?_wv=1027&k=K0QI8ByU),或通过添加微信“Open小喵Lab”加入官方交流微信群。
+
+
+
+我们会在 OpenMMLab 社区为大家
+
+- 📢 分享 AI 框架的前沿核心技术
+- 💻 解读 PyTorch 常用模块源码
+- 📰 发布 OpenMMLab 的相关新闻
+- 🚀 介绍 OpenMMLab 开发的前沿算法
+- 🏃 获取更高效的问题答疑和意见反馈
+- 🔥 提供与各行各业开发者充分交流的平台
+
+干货满满 📘,等你来撩 💗,OpenMMLab 社区期待您的加入 👬
diff --git a/testbed/open-mmlab__mmengine/docs/README.md b/testbed/open-mmlab__mmengine/docs/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..548ffd7ffed2a3b147a0a2806b3ff28eba19af2d
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/README.md
@@ -0,0 +1,28 @@
+## Build Documentation
+
+1. Clone MMEngine
+
+ ```bash
+ git clone https://github.com/open-mmlab/mmengine.git
+ cd mmengine
+ ```
+
+2. Install the building dependencies of documentation
+
+ ```bash
+ pip install -r requirements/docs.txt
+ ```
+
+3. Change directory to `docs/en` or `docs/zh_cn`
+
+ ```bash
+ cd docs/en # or docs/zh_cn
+ ```
+
+4. Build documentation
+
+ ```bash
+ make html
+ ```
+
+5. Open `_build/html/index.html` with browser
diff --git a/testbed/open-mmlab__mmengine/docs/en/Makefile b/testbed/open-mmlab__mmengine/docs/en/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..d4bb2cbb9eddb1bb1b4f366623044af8e4830919
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/en/Makefile
@@ -0,0 +1,20 @@
+# Minimal makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line, and also
+# from the environment for the first two.
+SPHINXOPTS ?=
+SPHINXBUILD ?= sphinx-build
+SOURCEDIR = .
+BUILDDIR = _build
+
+# Put it first so that "make" without argument is like "make help".
+help:
+ @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
+
+.PHONY: help Makefile
+
+# Catch-all target: route all unknown targets to Sphinx using the new
+# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
+%: Makefile
+ @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
diff --git a/testbed/open-mmlab__mmengine/docs/en/conf.py b/testbed/open-mmlab__mmengine/docs/en/conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea3aee32995ef3ed288961153eaff1ae92d1de90
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/en/conf.py
@@ -0,0 +1,100 @@
+# Configuration file for the Sphinx documentation builder.
+#
+# This file only contains a selection of the most common options. For a full
+# list see the documentation:
+# https://www.sphinx-doc.org/en/master/usage/configuration.html
+
+# -- Path setup --------------------------------------------------------------
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#
+import os
+import sys
+
+import pytorch_sphinx_theme
+
+sys.path.insert(0, os.path.abspath('../..'))
+
+# -- Project information -----------------------------------------------------
+
+project = 'mmengine'
+copyright = '2022, mmengine contributors'
+author = 'mmengine contributors'
+
+version_file = '../../mmengine/version.py'
+with open(version_file) as f:
+ exec(compile(f.read(), version_file, 'exec'))
+__version__ = locals()['__version__']
+# The short X.Y version
+version = __version__
+# The full version, including alpha/beta/rc tags
+release = __version__
+
+# -- General configuration ---------------------------------------------------
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
+# ones.
+
+extensions = [
+ 'sphinx.ext.autodoc',
+ 'sphinx.ext.autosummary',
+ 'sphinx.ext.intersphinx',
+ 'sphinx.ext.napoleon',
+ 'sphinx.ext.viewcode',
+ 'sphinx.ext.autosectionlabel',
+ 'myst_parser',
+ 'sphinx_copybutton',
+ 'sphinx.ext.autodoc.typehints',
+] # yapf: disable
+autodoc_typehints = 'description'
+myst_heading_anchors = 4
+myst_enable_extensions = ['colon_fence']
+
+# Configuration for intersphinx
+intersphinx_mapping = {
+ 'python': ('https://docs.python.org/3', None),
+ 'numpy': ('https://numpy.org/doc/stable', None),
+ 'torch': ('https://pytorch.org/docs/stable/', None),
+ 'mmcv': ('https://mmcv.readthedocs.io/en/2.x/', None),
+}
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+# This pattern also affects html_static_path and html_extra_path.
+exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
+
+# -- Options for HTML output -------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+#
+html_theme = 'pytorch_sphinx_theme'
+html_theme_path = [pytorch_sphinx_theme.get_html_theme_path()]
+
+html_theme_options = {
+ 'menu': [
+ {
+ 'name': 'GitHub',
+ 'url': 'https://github.com/open-mmlab/mmengine'
+ },
+ ],
+ # Specify the language of shared menu
+ 'menu_lang': 'en',
+}
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+html_css_files = ['css/readthedocs.css']
+
+# -- Extension configuration -------------------------------------------------
+# Ignore >>> when copying code
+copybutton_prompt_text = r'>>> |\.\.\. '
+copybutton_prompt_is_regexp = True
diff --git a/testbed/open-mmlab__mmengine/docs/en/docutils.conf b/testbed/open-mmlab__mmengine/docs/en/docutils.conf
new file mode 100644
index 0000000000000000000000000000000000000000..0c00c84688701117f231fd0c8ec295fb747b7d8f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/en/docutils.conf
@@ -0,0 +1,2 @@
+[html writers]
+table_style: colwidths-auto
diff --git a/testbed/open-mmlab__mmengine/docs/en/get_started/installation.md b/testbed/open-mmlab__mmengine/docs/en/get_started/installation.md
new file mode 100644
index 0000000000000000000000000000000000000000..cb9fbf08b26012f3591599f54628ca8f6fbd6ad2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/en/get_started/installation.md
@@ -0,0 +1,75 @@
+# Installation
+
+## Prerequisites
+
+- Python 3.6+
+- PyTorch 1.6+
+- CUDA 9.2+
+- GCC 5.4+
+
+## Prepare the Environment
+
+1. Use conda and activate the environment:
+
+ ```bash
+ conda create -n open-mmlab python=3.7 -y
+ conda activate open-mmlab
+ ```
+
+2. Install PyTorch
+
+ Before installing `MMEngine`, please make sure that PyTorch has been successfully installed in the environment. You can refer to [PyTorch official installation documentation](https://pytorch.org/get-started/locally/#start-locally). Verify the installation with the following command:
+
+ ```bash
+ python -c 'import torch;print(torch.__version__)'
+ ```
+
+## Install MMEngine
+
+### Install with mim
+
+[mim](https://github.com/open-mmlab/mim) is a package management tool for OpenMMLab projects, which can be used to install the OpenMMLab project easily.
+
+```bash
+pip install -U openmim
+mim install mmengine
+```
+
+### Install with pip
+
+```bash
+pip install mmengine
+```
+
+### Use docker images
+
+1. Build the image
+
+ ```bash
+ docker build -t mmengine https://github.com/open-mmlab/mmengine.git#main:docker/release
+ ```
+
+ More information can be referred from [mmengine/docker](https://github.com/open-mmlab/mmengine/tree/main/docker).
+
+2. Run the image
+
+ ```bash
+ docker run --gpus all --shm-size=8g -it mmengine
+ ```
+
+#### Build from source
+
+```bash
+# if cloning speed is too slow, you can switch the source to https://gitee.com/open-mmlab/mmengine.git
+git clone https://github.com/open-mmlab/mmengine.git
+cd mmengine
+pip install -e . -v
+```
+
+### Verify the Installation
+
+To verify if `MMEngine` and the necessary environment are successfully installed, we can run this command:
+
+```bash
+python -c 'import mmengine;print(mmengine.__version__)'
+```
diff --git a/testbed/open-mmlab__mmengine/docs/en/index.rst b/testbed/open-mmlab__mmengine/docs/en/index.rst
new file mode 100644
index 0000000000000000000000000000000000000000..fdab224e0a87bc0e3a3f8f8720042abb1f12ae7a
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/en/index.rst
@@ -0,0 +1,110 @@
+Welcome to MMEngine's documentation!
+=========================================
+You can switch between Chinese and English documents in the lower-left corner of the layout.
+
+.. toctree::
+ :maxdepth: 1
+ :caption: Get Started
+
+ get_started/introduction.md
+ get_started/installation.md
+ get_started/15_minutes.md
+
+.. toctree::
+ :maxdepth: 1
+ :caption: Common Usage
+
+ examples/resume_training.md
+ examples/speed_up_training.md
+ examples/save_gpu_memory.md
+ examples/train_a_gan.md
+
+.. toctree::
+ :maxdepth: 3
+ :caption: Tutorials
+
+ tutorials/runner.md
+ tutorials/dataset.md
+ tutorials/model.md
+ tutorials/evaluation.md
+ tutorials/optim_wrapper.md
+ tutorials/param_scheduler.md
+ tutorials/hook.md
+
+.. toctree::
+ :maxdepth: 1
+ :caption: Advanced tutorials
+
+ advanced_tutorials/registry.md
+ advanced_tutorials/config.md
+ advanced_tutorials/basedataset.md
+ advanced_tutorials/data_transform.md
+ advanced_tutorials/initialize.md
+ advanced_tutorials/visualization.md
+ advanced_tutorials/data_element.md
+ advanced_tutorials/distributed.md
+ advanced_tutorials/logging.md
+ advanced_tutorials/fileio.md
+ advanced_tutorials/manager_mixin.md
+ advanced_tutorials/cross_library.md
+
+.. toctree::
+ :maxdepth: 1
+ :caption: Design
+
+ design/hook.md
+ design/runner.md
+ design/evaluation.md
+ design/visualization.md
+ design/logging.md
+
+.. toctree::
+ :maxdepth: 1
+ :caption: Migration guide
+
+ migration/runner.md
+ migration/hook.md
+ migration/model.md
+ migration/param_scheduler.md
+ migration/transform.md
+
+.. toctree::
+ :maxdepth: 2
+ :caption: API Reference
+
+ mmengine.registry
+ mmengine.config
+ mmengine.runner
+ mmengine.hooks
+ mmengine.model
+ mmengine.optim
+ mmengine.evaluator
+ mmengine.structures
+ mmengine.dataset
+ mmengine.device
+ mmengine.hub
+ mmengine.logging
+ mmengine.visualization
+ mmengine.fileio
+ mmengine.dist
+ mmengine.utils
+ mmengine.utils.dl_utils
+
+.. toctree::
+ :maxdepth: 2
+ :caption: Notes
+
+ notes/changelog.md
+ notes/contributing.md
+
+.. toctree::
+ :caption: Switch Language
+
+ switch_language.md
+
+Indices and tables
+==================
+
+* :ref:`genindex`
+* :ref:`modindex`
+* :ref:`search`
diff --git a/testbed/open-mmlab__mmengine/docs/en/make.bat b/testbed/open-mmlab__mmengine/docs/en/make.bat
new file mode 100644
index 0000000000000000000000000000000000000000..922152e96a04a242e6fc40f124261d74890617d8
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/en/make.bat
@@ -0,0 +1,35 @@
+@ECHO OFF
+
+pushd %~dp0
+
+REM Command file for Sphinx documentation
+
+if "%SPHINXBUILD%" == "" (
+ set SPHINXBUILD=sphinx-build
+)
+set SOURCEDIR=.
+set BUILDDIR=_build
+
+if "%1" == "" goto help
+
+%SPHINXBUILD% >NUL 2>NUL
+if errorlevel 9009 (
+ echo.
+ echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
+ echo.installed, then set the SPHINXBUILD environment variable to point
+ echo.to the full path of the 'sphinx-build' executable. Alternatively you
+ echo.may add the Sphinx directory to PATH.
+ echo.
+ echo.If you don't have Sphinx installed, grab it from
+ echo.http://sphinx-doc.org/
+ exit /b 1
+)
+
+%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
+goto end
+
+:help
+%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
+
+:end
+popd
diff --git a/testbed/open-mmlab__mmengine/docs/en/migration/hook.md b/testbed/open-mmlab__mmengine/docs/en/migration/hook.md
new file mode 100644
index 0000000000000000000000000000000000000000..daabe338ca78a5be0248ce3cab4c16e97c526437
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/en/migration/hook.md
@@ -0,0 +1,3 @@
+# Migrate Hook from MMCV to MMEngine
+
+Coming soon. Please refer to [chinese documentation](https://mmengine.readthedocs.io/zh_CN/latest/migration/hook.html).
diff --git a/testbed/open-mmlab__mmengine/docs/en/notes/contributing.md b/testbed/open-mmlab__mmengine/docs/en/notes/contributing.md
new file mode 100644
index 0000000000000000000000000000000000000000..912f2c9041d97fd02b7f9b89792ece7c8aba4b11
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/en/notes/contributing.md
@@ -0,0 +1,242 @@
+## Contributing to OpenMMLab
+
+Welcome to the MMEngine community, we are committed to building a cutting-edge computer vision foundational library and all kinds of contributions are welcomed, including but not limited to
+
+**Fix bug**
+
+You can directly post a Pull Request to fix typos in code or documents
+
+The steps to fix the bug of code implementation are as follows.
+
+1. If the modification involves significant changes, you should create an issue first and describe the error information and how to trigger the bug. Other developers will discuss it with you and propose a proper solution.
+
+2. Posting a pull request after fixing the bug and adding the corresponding unit test.
+
+**New Feature or Enhancement**
+
+1. If the modification involves significant changes, you should create an issue to discuss with our developers to propose a proper design.
+2. Post a Pull Request after implementing the new feature or enhancement and add the corresponding unit test.
+
+**Document**
+
+You can directly post a pull request to fix documents. If you want to add a document, you should first create an issue to check if it is reasonable.
+
+### Pull Request Workflow
+
+If you're not familiar with Pull Request, don't worry! The following guidance will tell you how to create a Pull Request step by step. If you want to dive into the development mode of Pull Request, you can refer to the [official documents](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-requests).
+
+#### 1. Fork and clone
+
+If you are posting a pull request for the first time, you should fork the OpenMMLab repositories by clicking the **Fork** button in the top right corner of the GitHub page, and the forked repositories will appear under your GitHub profile.
+
+
+
+Then, you can clone the repositories to local:
+
+```shell
+git clone git@github.com:{username}/mmengine.git
+```
+
+After that, you should add the official repository as the upstream repository.
+
+```bash
+git remote add upstream git@github.com:open-mmlab/mmengine
+```
+
+Check whether the remote repository has been added successfully by `git remote -v`.
+
+```bash
+origin git@github.com:{username}/mmengine.git (fetch)
+origin git@github.com:{username}/mmengine.git (push)
+upstream git@github.com:open-mmlab/mmengine (fetch)
+upstream git@github.com:open-mmlab/mmengine (push)
+```
+
+```{note}
+Here's a brief introduction to origin and upstream. When we use "git clone", we create an "origin" remote by default, which points to the repository cloned from. As for "upstream", we add it ourselves to point to the target repository. Of course, if you don't like the name "upstream", you could name it as you wish. Usually, we'll push the code to "origin". If the pushed code conflicts with the latest code in official("upstream"), we should pull the latest code from upstream to resolve the conflicts, and then push to "origin" again. The posted Pull Request will be updated automatically.
+```
+
+#### 2. Configure pre-commit
+
+You should configure [pre-commit](https://pre-commit.com/#intro) in the local development environment to make sure the code style matches that of OpenMMLab. **Note**: The following code should be executed under the mmengine directory.
+
+```shell
+pip install -U pre-commit
+pre-commit install
+```
+
+Check that pre-commit is configured successfully, and install the hooks defined in `.pre-commit-config.yaml`.
+
+```shell
+pre-commit run --all-files
+```
+
+
+
+
+
+If the installation process is interrupted, you can repeatedly run `pre-commit run ... ` to continue the installation.
+
+If the code does not conform to the code style specification, pre-commit will raise a warning and fixes some of the errors automatically.
+
+
+
+If we want to commit our code bypassing the pre-commit hook, we can use the `--no-verify` option(**only for temporary committing**).
+
+```shell
+git commit -m "xxx" --no-verify
+```
+
+#### 3. Create a development branch
+
+After configuring the pre-commit, we should create a branch based on the master branch to develop the new feature or fix the bug. The proposed branch name is `username/pr_name`
+
+```shell
+git checkout -b yhc/refactor_contributing_doc
+```
+
+In subsequent development, if the master branch of the local repository is behind the master branch of "upstream", we need to pull the upstream for synchronization, and then execute the above command:
+
+```shell
+git pull upstream master
+```
+
+#### 4. Commit the code and pass the unit test
+
+- MMEngine introduces mypy to do static type checking to increase the robustness of the code. Therefore, we need to add Type Hints to our code and pass the mypy check. If you are not familiar with Type Hints, you can refer to [this tutorial](https://docs.python.org/3/library/typing.html).
+
+- The committed code should pass through the unit test
+
+ ```shell
+ # Pass all unit tests
+ pytest tests
+
+ # Pass the unit test of runner
+ pytest tests/test_runner/test_runner.py
+ ```
+
+ If the unit test fails for lack of dependencies, you can install the dependencies referring to the [guidance](#unit-test)
+
+- If the documents are modified/added, we should check the rendering result referring to [guidance](#document-rendering)
+
+#### 5. Push the code to remote
+
+We could push the local commits to remote after passing through the check of unit test and pre-commit. You can associate the local branch with remote branch by adding `-u` option.
+
+```shell
+git push -u origin {branch_name}
+```
+
+This will allow you to use the `git push` command to push code directly next time, without having to specify a branch or the remote repository.
+
+#### 6. Create a Pull Request
+
+(1) Create a pull request in GitHub's Pull request interface
+
+
+
+(2) Modify the PR description according to the guidelines so that other developers can better understand your changes
+
+
+
+Find more details about Pull Request description in [pull request guidelines](#pr-specs).
+
+**note**
+
+(a) The Pull Request description should contain the reason for the change, the content of the change, and the impact of the change, and be associated with the relevant Issue (see [documentation](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue)
+
+(b) If it is your first contribution, please sign the CLA
+
+
+
+(c) Check whether the Pull Request pass through the CI
+
+
+
+MMEngine will run unit test for the posted Pull Request on different platforms (Linux, Window, Mac), based on different versions of Python, PyTorch, CUDA to make sure the code is correct. We can see the specific test information by clicking `Details` in the above image so that we can modify the code.
+
+(3) If the Pull Request passes the CI, then you can wait for the review from other developers. You'll modify the code based on the reviewer's comments, and repeat the steps [4](#4-commit-the-code-and-pass-the-unit-test)-[5](#5-push-the-code-to-remote) until all reviewers approve it. Then, we will merge it ASAP.
+
+
+
+#### 7. Resolve conflicts
+
+If your local branch conflicts with the latest master branch of "upstream", you'll need to resolove them. There are two ways to do this:
+
+```shell
+git fetch --all --prune
+git rebase upstream/master
+```
+
+or
+
+```shell
+git fetch --all --prune
+git merge upstream/master
+```
+
+If you are very good at handling conflicts, then you can use rebase to resolve conflicts, as this will keep your commit logs tidy. If you are not familiar with `rebase`, then you can use `merge` to resolve conflicts.
+
+### Guidance
+
+#### Unit test
+
+We should also make sure the committed code will not decrease the coverage of unit test, we could run the following command to check the coverage of unit test:
+
+```shell
+python -m coverage run -m pytest /path/to/test_file
+python -m coverage html
+# check file in htmlcov/index.html
+```
+
+#### Document rendering
+
+If the documents are modified/added, we should check the rendering result. We could install the dependencies and run the following command to render the documents and check the results:
+
+```shell
+pip install -r requirements/docs.txt
+cd docs/zh_cn/
+# or docs/en
+make html
+# check file in ./docs/zh_cn/_build/html/index.html
+```
+
+### Python Code style
+
+We adopt [PEP8](https://www.python.org/dev/peps/pep-0008/) as the preferred code style.
+
+We use the following tools for linting and formatting:
+
+- [flake8](https://github.com/PyCQA/flake8): A wrapper around some linter tools.
+- [isort](https://github.com/timothycrosley/isort): A Python utility to sort imports.
+- [yapf](https://github.com/google/yapf): A formatter for Python files.
+- [codespell](https://github.com/codespell-project/codespell): A Python utility to fix common misspellings in text files.
+- [mdformat](https://github.com/executablebooks/mdformat): Mdformat is an opinionated Markdown formatter that can be used to enforce a consistent style in Markdown files.
+- [docformatter](https://github.com/myint/docformatter): A formatter to format docstring.
+
+Style configurations of yapf and isort can be found in [setup.cfg](./setup.cfg).
+
+We use [pre-commit hook](https://pre-commit.com/) that checks and formats for `flake8`, `yapf`, `isort`, `trailing whitespaces`, `markdown files`,
+fixes `end-of-files`, `double-quoted-strings`, `python-encoding-pragma`, `mixed-line-ending`, sorts `requirments.txt` automatically on every commit.
+The config for a pre-commit hook is stored in [.pre-commit-config](./.pre-commit-config.yaml).
+
+### PR Specs
+
+1. Use [pre-commit](https://pre-commit.com) hook to avoid issues of code style
+
+2. One short-time branch should be matched with only one PR
+
+3. Accomplish a detailed change in one PR. Avoid large PR
+
+ - Bad: Support Faster R-CNN
+ - Acceptable: Add a box head to Faster R-CNN
+ - Good: Add a parameter to box head to support custom conv-layer number
+
+4. Provide clear and significant commit message
+
+5. Provide clear and meaningful PR description
+
+ - Task name should be clarified in title. The general format is: \[Prefix\] Short description of the PR (Suffix)
+ - Prefix: add new feature \[Feature\], fix bug \[Fix\], related to documents \[Docs\], in developing \[WIP\] (which will not be reviewed temporarily)
+ - Introduce main changes, results and influences on other modules in short description
+ - Associate related issues and pull requests with a milestone
diff --git a/testbed/open-mmlab__mmengine/docs/en/switch_language.md b/testbed/open-mmlab__mmengine/docs/en/switch_language.md
new file mode 100644
index 0000000000000000000000000000000000000000..e47b751e33928f59c4bf1aea94110493214754ea
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/en/switch_language.md
@@ -0,0 +1,3 @@
+## English
+
+## 简体中文
diff --git a/testbed/open-mmlab__mmengine/docs/en/tutorials/dataset.md b/testbed/open-mmlab__mmengine/docs/en/tutorials/dataset.md
new file mode 100644
index 0000000000000000000000000000000000000000..b1a1c8ff945b63e4212e23eb51b000c88ca69e5a
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/en/tutorials/dataset.md
@@ -0,0 +1,200 @@
+# Dataset and DataLoader
+
+```{hint}
+If you have never been exposed to PyTorch's Dataset and DataLoader classes, you are recommended to read through [PyTorch official tutorial](https://pytorch.org/tutorials/beginner/basics/data_tutorial.html) to get familiar with some basic concepts.
+```
+
+Datasets and DataLoaders are necessary components in MMEngine's training pipeline. They are conceptually derived from and consistent with PyTorch. Typically, a dataset defines the quantity, parsing, and pre-processing of the data, while a dataloader iteratively loads data according to settings such as `batch_size`, `shuffle`, `num_workers`, etc. Datasets are encapsulated with dataloaders and they together constitute the data source.
+
+In this tutorial, we will step through their usage in MMEngine runner from the outside (dataloader) to the inside (dataset) and give some practical examples. After reading through this tutorial, you will be able to:
+
+- Master the configuration of dataloaders in MMEngine
+- Learn to use existing datasets (e.g. those from `torchvision`) from config files
+- Know about building and using your own dataset
+
+## Details on dataloader
+
+Dataloaders can be configured in MMEngine's `Runner` with 3 arguments:
+
+- `train_dataloader`: Used in `Runner.train()` to provide training data for models
+- `val_dataloader`: Used in `Runner.val()` or in `Runner.train()` at regular intervals for model evaluation
+- `test_dataloader`: Used in `Runner.test()` for the final test
+
+MMEngine has full support for PyTorch native `DataLoader` objects. Therefore, you can simply pass your valid, already built dataloaders to the runner, as shown in [getting started in 15 minutes](../get_started/15_minutes.md). Meanwhile, thanks to the [Registry Mechanism](../advanced_tutorials/registry.md) of MMEngine, those arguments also accept `dict`s as inputs, as illustrated in the following example (referred to as example 1). The keys in the dictionary correspond to arguments in DataLoader's init function.
+
+```python
+runner = Runner(
+ train_dataloader=dict(
+ batch_size=32,
+ sampler=dict(
+ type='DefaultSampler',
+ shuffle=True),
+ dataset=torchvision.datasets.CIFAR10(...),
+ collate_fn=dict(type='default_collate')
+ )
+)
+```
+
+When passed to the runner in the form of a dict, the dataloader will be lazily built in the runner when actually needed.
+
+```{note}
+For more configurable arguments of the `DataLoader`, please refer to [PyTorch API documentation](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader)
+```
+
+```{note}
+If you are interested in the details of the building procedure, you may refer to [build_dataloader](mmengine.runner.Runner.build_dataloader)
+```
+
+You may find example 1 differs from that in [getting started in 15 minutes](../get_started/15_minutes.md) in some arguments. Indeed, due to some obscure conventions in MMEngine, you can't seamlessly switch it to a dict by simply replacing `DataLoader` with `dict`. We will discuss the differences between our convention and PyTorch's in the following sections, in case you run into trouble when using config files.
+
+### sampler and shuffle
+
+One obvious difference is that we add a `sampler` argument to the dict. This is because we **require `sampler` to be explicitly specified** when using a dict as a dataloader. Meanwhile, `shuffle` is also removed from `DataLoader` arguments, because it conflicts with `sampler` in PyTorch, as referred to in [PyTorch DataLoader API documentation](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader).
+
+```{note}
+In fact, `shuffle` is just a notation for convenience in PyTorch implementation. If `shuffle` is set to `True`, the dataloader will automatically switch to `RandomSampler`
+```
+
+With a `sampler` argument, codes in example 1 is **nearly** equivalent to code block below
+
+```python
+from mmengine.dataset import DefaultSampler
+
+dataset = torchvision.datasets.CIFAR10(...)
+sampler = DefaultSampler(dataset, shuffle=True)
+
+runner = Runner(
+ train_dataloader=DataLoader(
+ batch_size=32,
+ sampler=sampler,
+ dataset=dataset,
+ collate_fn=default_collate
+ )
+)
+```
+
+```{warning}
+The equivalence of the above codes holds only if: 1) you are training with a single process, and 2) no `randomness` argument is passed to the runner. This is due to the fact that `sampler` should be built after distributed environment setup to be correct. The runner will guarantee the correct order and proper random seed by applying lazy initialization techniques, which is only possible for dict inputs. Instead, when building a sampler manually, it requires extra work and is highly error-prone. Therefore, the code block above is just for illustration and definitely not recommended. We **strongly suggest passing `sampler` as a `dict`** to avoid potential problems.
+```
+
+### DefaultSampler
+
+The above example may make you wonder what a `DefaultSampler` is, why use it and whether there are other options. In fact, `DefaultSampler` is a built-in sampler in MMEngine which eliminates the gap between distributed and non-distributed training and thus enabling a seamless conversion between them. If you have the experience of using `DistributedDataParallel` in PyTorch, you may be impressed by having to change the `sampler` argument to make it correct. However, in MMEngine, you don't need to bother with this `DefaultSampler`.
+
+`DefaultSampler` accepts the following arguments:
+
+- `shuffle`: Set to `True` to load data in the dataset in random order
+- `seed`: Random seed used to shuffle the dataset. Typically it doesn't require manual configuration here because the runner will handle it with `randomness` configuration
+- `round_up`: When set this to `True`, this is the same behavior as setting `drop_last=False` in PyTorch `DataLoader`. You should take care of it when doing migration from PyTorch.
+
+```{note}
+For more details about `DefaultSampler`, please refer to [its API docs](mmengine.dataset.DefaultSampler)
+```
+
+`DefaultSampler` handles most of the cases. We ensure that error-prone details such as random seeds are handled properly when you are using it in a runner. This prevents you from getting into troubles with distributed training. Apart from `DefaultSampler`, you may also be interested in [InfiniteSampler](mmengine.dataset.InfiniteSampler) for iteration-based training pipelines. If you have more advanced demands, you may want to refer to the codes of these two built-in samplers to implement your own one and register it to `DATA_SAMPLERS` registry.
+
+```python
+@DATA_SAMPLERS.register_module()
+class MySampler(Sampler):
+ pass
+
+runner = Runner(
+ train_dataloader=dict(
+ sampler=dict(type='MySampler'),
+ ...
+ )
+)
+```
+
+### The obscure collate_fn
+
+Among the arguments of PyTorch `DataLoader`, `collate_fn` is often ignored by users, but in MMEngine you must pay special attention to it. When you pass the dataloader argument as a dict, MMEngine will use the built-in [pseudo_collate](mmengine.dataset.pseudo_collate) by default, which is significantly different from that, [default_collate](https://pytorch.org/docs/stable/data.html#torch.utils.data.default_collate), in PyTorch. Therefore, when doing a migration from PyTorch, you have to explicitly specify the `collate_fn` in config files to be consistent in behavior.
+
+```{note}
+MMEngine uses `pseudo_collate` as default value is mainly due to historical compatibility reasons. You don't have to look deeply into it. You can just know about it and avoid potential errors.
+```
+
+MMEngine provides 2 built-in `collate_fn`:
+
+- `pseudo_collate`: Default value in MMEngine. It won't concatenate data through `batch` index. Detailed explanations can be found in [pseudo_collate API doc](mmengine.dataset.pseudo_collate)
+- `default_collate`: It behaves almost identically to PyTorch's `default_collate`. It will transfer data into `Tensor` and concatenate them through `batch` index. More details and slight differences from PyTorch can be found in [default_collate API doc](mmengine.dataset.default_collate)
+
+If you want to use a custom `collate_fn`, you can register it to `COLLATE_FUNCTIONS` registry.
+
+```python
+@COLLATE_FUNCTIONS.register_module()
+def my_collate_func(data_batch: Sequence) -> Any:
+ pass
+
+runner = Runner(
+ train_dataloader=dict(
+ ...
+ collate_fn=dict(type='my_collate_func')
+ )
+)
+```
+
+## Details on dataset
+
+Typically, datasets define the quantity, parsing, and pre-processing of the data. It is encapsulated in dataloader, allowing the latter to load data in batches. Since we fully support PyTorch `DataLoader`, the dataset is also compatible. Meanwhile, thanks to the registry mechanism, when a dataloader is given as a dict, its `dataset` argument can also be given as a dict, which enables lazy initialization in the runner. This mechanism allows for writing config files.
+
+### Use torchvision datasets
+
+`torchvision` provides various open datasets. They can be directly used in MMEngine as shown in [getting started in 15 minutes](../get_started/15_minutes.md), where a `CIFAR10` dataset is used together with torchvision's built-in data transforms.
+
+However, if you want to use the dataset in config files, registration is needed. What's more, if you also require data transforms in torchvision, some more registrations are required. The following example illustrates how to do it.
+
+```python
+import torchvision.transforms as tvt
+from mmengine.registry import DATASETS, TRANSFORMS
+from mmengine.dataset.base_dataset import Compose
+
+# register CIFAR10 dataset in torchvision
+# data transforms should also be built here
+@DATASETS.register_module(name='Cifar10', force=False)
+def build_torchvision_cifar10(transform=None, **kwargs):
+ if isinstance(transform, dict):
+ transform = [transform]
+ if isinstance(transform, (list, tuple)):
+ transform = Compose(transform)
+ return torchvision.datasets.CIFAR10(**kwargs, transform=transform)
+
+# register data transforms in torchvision
+DATA_TRANSFORMS.register_module('RandomCrop', module=tvt.RandomCrop)
+DATA_TRANSFORMS.register_module('RandomHorizontalFlip', module=tvt.RandomHorizontalFlip)
+DATA_TRANSFORMS.register_module('ToTensor', module=tvt.ToTensor)
+DATA_TRANSFORMS.register_module('Normalize', module=tvt.Normalize)
+
+# specify in runner
+runner = Runner(
+ train_dataloader=dict(
+ batch_size=32,
+ sampler=dict(
+ type='DefaultSampler',
+ shuffle=True),
+ dataset=dict(type='Cifar10',
+ root='data/cifar10',
+ train=True,
+ download=True,
+ transform=[
+ dict(type='RandomCrop', size=32, padding=4),
+ dict(type='RandomHorizontalFlip'),
+ dict(type='ToTensor'),
+ dict(type='Normalize', **norm_cfg)])
+ )
+)
+```
+
+```{note}
+The above example makes extensive use of the registry mechanism and borrows the [Compose](mmengine.dataset.Compose) module from MMEngine. If you urge to use torchvision dataset in your config files, you can refer to it and make some slight modifications. However, we recommend you borrow datasets from downstream repos such as [MMDet](https://github.com/open-mmlab/mmdetection), [MMCls](https://github.com/open-mmlab/mmclassification), etc. This may give you a better experience.
+```
+
+### Customize your dataset
+
+You are free to customize your own datasets, as you would with PyTorch. You can also copy existing datasets from your previous PyTorch projects. If you want to learn how to customize your dataset, please refer to [PyTorch official tutorials](https://pytorch.org/tutorials/beginner/basics/data_tutorial.html#creating-a-custom-dataset-for-your-files)
+
+### Use MMEngine BaseDataset
+
+Apart from directly using PyTorch native `Dataset` class, you can also use MMEngine's built-in class `BaseDataset` to customize your own one, as referred to [BaseDataset tutorial](../advanced_tutorials/basedataset.md). It makes some conventions on the format of annotation files, which makes the data interface more unified and multi-task training more convenient. Meanwhile, `BaseDataset` can easily cooperate with built-in [data transforms](../advanced_tutorials/data_element.md) in MMEngine, which releases you from writing one from scratch.
+
+Currently, `BaseDataset` has been widely used in downstream repos of OpenMMLab 2.0 projects.
diff --git a/testbed/open-mmlab__mmengine/docs/en/tutorials/evaluation.md b/testbed/open-mmlab__mmengine/docs/en/tutorials/evaluation.md
new file mode 100644
index 0000000000000000000000000000000000000000..90f09e776ae7d36c6b3ce6831b00bd78ced5d026
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/en/tutorials/evaluation.md
@@ -0,0 +1,3 @@
+# Evaluation
+
+Coming soon. Please refer to [chinese documentation](https://mmengine.readthedocs.io/zh_CN/latest/tutorials/evaluation.html).
diff --git a/testbed/open-mmlab__mmengine/docs/en/tutorials/param_scheduler.md b/testbed/open-mmlab__mmengine/docs/en/tutorials/param_scheduler.md
new file mode 100644
index 0000000000000000000000000000000000000000..06dc047a95e3f0015338572443296b94caf3ddb8
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/en/tutorials/param_scheduler.md
@@ -0,0 +1,229 @@
+# Parameter Scheduler
+
+During neural network training, optimization hyperparameters (e.g. learning rate) are usually adjusted along with the training process.
+One of the simplest and most common learning rate adjustment strategies is multi-step learning rate decay, which reduces the learning rate to a fraction at regular intervals.
+PyTorch provides LRScheduler to implement various learning rate adjustment strategies. In MMEngine, we have extended it and implemented a more general [ParamScheduler](mmengine.optim._ParamScheduler).
+It can adjust optimization hyperparameters such as learning rate and momentum. It also supports the combination of multiple schedulers to create more complex scheduling strategies.
+
+## Usage
+
+We first introduce how to use PyTorch's `torch.optim.lr_scheduler` to adjust learning rate.
+
+
+How to use PyTorch's builtin learning rate scheduler?
+
+Here is an example which refers from [PyTorch official documentation](https://pytorch.org/docs/stable/optim.html):
+
+Initialize an ExponentialLR object, and call the `step` method after each training epoch.
+
+```python
+import torch
+from torch.optim import SGD
+from torch.optim.lr_scheduler import ExponentialLR
+
+model = torch.nn.Linear(1, 1)
+dataset = [torch.randn((1, 1, 1)) for _ in range(20)]
+optimizer = SGD(model, 0.1)
+scheduler = ExponentialLR(optimizer, gamma=0.9)
+
+for epoch in range(10):
+ for data in dataset:
+ optimizer.zero_grad()
+ output = model(data)
+ loss = 1 - output
+ loss.backward()
+ optimizer.step()
+ scheduler.step()
+```
+
+
+
+`mmengine.optim.scheduler` supports most of PyTorch's learning rate schedulers such as `ExponentialLR`, `LinearLR`, `StepLR`, `MultiStepLR`, etc. Please refer to [parameter scheduler API documentation](https://mmengine.readthedocs.io/en/latest/api/optim.html#scheduler) for all of the supported schedulers.
+
+MMEngine also supports adjusting momentum with parameter schedulers. To use momentum schedulers, replace `LR` in the class name to `Momentum`, such as `ExponentialMomentum`,`LinearMomentum`. Further, we implement the general parameter scheduler ParamScheduler, which is used to adjust the specified hyperparameters in the optimizer, such as weight_decay, etc. This feature makes it easier to apply some complex hyperparameter tuning strategies.
+
+Different from the above example, MMEngine usually does not need to manually implement the training loop and call `optimizer.step()`. The runner will automatically manage the training progress and control the execution of the parameter scheduler through `ParamSchedulerHook`.
+
+### Use a single LRScheduler
+
+If only one scheduler needs to be used for the entire training process, there is no difference with PyTorch's learning rate scheduler.
+
+```python
+# build the scheduler manually
+from torch.optim import SGD
+from mmengine.runner import Runner
+from mmengine.optim.scheduler import MultiStepLR
+
+optimizer = SGD(model.parameters(), lr=0.01, momentum=0.9)
+param_scheduler = MultiStepLR(optimizer, milestones=[8, 11], gamma=0.1)
+
+runner = Runner(
+ model=model,
+ optim_wrapper=dict(
+ optimizer=optimizer),
+ param_scheduler=param_scheduler,
+ ...
+ )
+```
+
+
+
+If using the runner with the registry and config file, we can specify the scheduler by setting the `param_scheduler` field in the config. The runner will automatically build a parameter scheduler based on this field:
+
+```python
+# build the scheduler with config file
+param_scheduler = dict(type='MultiStepLR', by_epoch=True, milestones=[8, 11], gamma=0.1)
+```
+
+Note that the parameter `by_epoch` is added here, which controls the frequency of learning rate adjustment. When set to True, it means adjusting by epoch. When set to False, it means adjusting by iteration. The default value is True.
+
+In the above example, it means to adjust according to epochs. At this time, the unit of the parameters is epoch. For example, \[8, 11\] in `milestones` means that the learning rate will be multiplied by 0.1 at the end of the 8 and 11 epoch.
+
+When the frequency is modified, the meaning of the count-related settings of the scheduler will be changed accordingly. When `by_epoch=True`, the numbers in milestones indicate at which epoch the learning rate decay is performed, and when `by_epoch=False` it indicates at which iteration the learning rate decay is performed.
+
+Here is an example of adjusting by iterations: At the end of the 600th and 800th iterations, the learning rate will be multiplied by 0.1 times.
+
+```python
+param_scheduler = dict(type='MultiStepLR', by_epoch=False, milestones=[600, 800], gamma=0.1)
+```
+
+
+
+If users want to use the iteration-based frequency while filling the scheduler config settings by epoch, MMEngine's scheduler also provides an automatic conversion method. Users can call the `build_iter_from_epoch` method and provide the number of iterations for each training epoch to construct a scheduler object updated by iterations:
+
+```python
+epoch_length = len(train_dataloader)
+param_scheduler = MultiStepLR.build_iter_from_epoch(optimizer, milestones=[8, 11], gamma=0.1, epoch_length=epoch_length)
+```
+
+If using config to build a scheduler, just add `convert_to_iter_based=True` to the field. The runner will automatically call `build_iter_from_epoch` to convert the epoch-based config to an iteration-based scheduler object:
+
+```python
+param_scheduler = dict(type='MultiStepLR', by_epoch=True, milestones=[8, 11], gamma=0.1, convert_to_iter_based=True)
+```
+
+Below is a Cosine Annealing learning rate scheduler that is updated by epoch, where the learning rate is only modified after each epoch:
+
+```python
+param_scheduler = dict(type='CosineAnnealingLR', by_epoch=True, T_max=12)
+```
+
+
+
+After automatically conversion, the learning rate is updated by iteration. As you can see from the graph below, the learning rate changes more smoothly.
+
+```python
+param_scheduler = dict(type='CosineAnnealingLR', by_epoch=True, T_max=12, convert_to_iter_based=True)
+```
+
+
+
+### Combine multiple LRSchedulers (e.g. learning rate warm-up)
+
+In the training process of some algorithms, the learning rate is not adjusted according to a certain scheduling strategy from beginning to end. The most common example is learning rate warm-up.
+
+For example, in the first few iterations, a linear strategy is used to increase the learning rate from a small value to normal, and then another strategy is applied.
+
+MMEngine supports combining multiple schedulers together. Just modify the `param_scheduler` field in the config file to a list of scheduler config, and the ParamSchedulerHook can automatically process the scheduler list. The following example implements learning rate warm-up.
+
+```python
+param_scheduler = [
+ # Linear learning rate warm-up scheduler
+ dict(type='LinearLR',
+ start_factor=0.001,
+ by_epoch=False, # Updated by iterations
+ begin=0,
+ end=50), # Warm up for the first 50 iterations
+ # The main LRScheduler
+ dict(type='MultiStepLR',
+ by_epoch=True, # Updated by epochs
+ milestones=[8, 11],
+ gamma=0.1)
+]
+```
+
+
+
+Note that the `begin` and `end` parameters are added here. These two parameters specify the **valid interval** of the scheduler. The valid interval usually only needs to be set when multiple schedulers are combined, and can be ignored when using a single scheduler. When the `begin` and `end` parameters are specified, it means that the scheduler only takes effect in the \[begin, end) interval, and the unit is determined by the `by_epoch` parameter.
+
+In the above example, the `by_epoch` of `LinearLR` in the warm-up phase is False, which means that the scheduler only takes effect in the first 50 iterations. After more than 50 iterations, the scheduler will no longer take effect, and the second scheduler, which is `MultiStepLR`, will control the learning rate. When combining different schedulers, the `by_epoch` parameter does not have to be the same for each scheduler.
+
+Here is another example:
+
+```python
+param_scheduler = [
+ # Use a linear warm-up at [0, 100) iterations
+ dict(type='LinearLR',
+ start_factor=0.001,
+ by_epoch=False,
+ begin=0,
+ end=100),
+ # Use a cosine learning rate at [100, 900) iterations
+ dict(type='CosineAnnealingLR',
+ T_max=800,
+ by_epoch=False,
+ begin=100,
+ end=900)
+]
+```
+
+
+
+The above example uses a linear learning rate warm-up for the first 100 iterations, and then uses a cosine annealing learning rate scheduler with a period of 800 from the 100th to the 900th iteration.
+
+Users can combine any number of schedulers. If the valid intervals of two schedulers are not connected to each other which leads to an interval that is not covered, the learning rate of this interval remains unchanged. If the valid intervals of the two schedulers overlap, the adjustment of the learning rate will be triggered in the order of the scheduler config (similar with [`ChainedScheduler`](https://pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.ChainedScheduler.html#chainedscheduler)).
+
+We recommend using different learning rate scheduling strategies in different stages of training to avoid overlapping of the valid intervals. Be careful If you really need to stack two schedulers overlapped. We recommend using [learning rate visualization tool](TODO) to visualize the learning rate after stacking, to avoid the adjustment not as expected.
+
+## How to adjust other hyperparameters
+
+### Momentum
+
+Like learning rate, momentum is a schedulable hyperparameter in the optimizer's parameter group. The momentum scheduler is used in exactly the same way as the learning rate scheduler. Just add the momentum scheduler config to the list in the `param_scheduler` field.
+
+Example:
+
+```python
+param_scheduler = [
+ # the lr scheduler
+ dict(type='LinearLR', ...),
+ # the momentum scheduler
+ dict(type='LinearMomentum',
+ start_factor=0.001,
+ by_epoch=False,
+ begin=0,
+ end=1000)
+]
+```
+
+### Generic parameter scheduler
+
+MMEngine also provides a set of generic parameter schedulers for scheduling other hyperparameters in the `param_groups` of the optimizer. Change `LR` in the class name of the learning rate scheduler to `Param`, such as `LinearParamScheduler`. Users can schedule the specific hyperparameters by setting the `param_name` variable of the scheduler.
+
+Here is an example:
+
+```python
+param_scheduler = [
+ dict(type='LinearParamScheduler',
+ param_name='lr', # adjust the 'lr' in `optimizer.param_groups`
+ start_factor=0.001,
+ by_epoch=False,
+ begin=0,
+ end=1000)
+]
+```
+
+By setting the `param_name` to `'lr'`, this parameter scheduler is equivalent to `LinearLRScheduler`.
+
+In addition to learning rate and momentum, users can also schedule other parameters in `optimizer.param_groups`. The schedulable parameters depend on the optimizer used. For example, when using the SGD optimizer with `weight_decay`, the `weight_decay` can be adjusted as follows:
+
+```python
+param_scheduler = [
+ dict(type='LinearParamScheduler',
+ param_name='weight_decay', # adjust 'weight_decay' in `optimizer.param_groups`
+ start_factor=0.001,
+ by_epoch=False,
+ begin=0,
+ end=1000)
+]
+```
diff --git a/testbed/open-mmlab__mmengine/docs/en/tutorials/runner.md b/testbed/open-mmlab__mmengine/docs/en/tutorials/runner.md
new file mode 100644
index 0000000000000000000000000000000000000000..5ddb44ac581ea80c98e393cee5ff3ee01284534e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/en/tutorials/runner.md
@@ -0,0 +1,523 @@
+# Runner
+
+Welcome to the tutorial of runner, the core of MMEngine's user interface!
+
+The runner, as an "integrator" in MMEngine, covers all aspects of the framework and shoulders the responsibility of organizing and scheduling nearly all modules. Therefore, the code logic in it has to take into account various situations, making it relatively hard to understand. But **don't worry**! In this tutorial, we will leave out some messy details and have a quick overview of commonly used APIs, functionalities, and examples. Hopefully, this should provide you with a clear and easy-to-understand user interface. After reading through this tutorial, you will be able to:
+
+- Master the common usage and configuration of the runner
+- Learn the best practice - writing config files - of the runner
+- Know about the basic dataflow and execution order
+- Feel by yourself the advantages of using runner (perhaps)
+
+## Example codes of the runner
+
+To build your training pipeline with a runner, there are typically two ways to get started:
+
+- Refer to runner's [API documentation](mmengine.runner.Runner) for argument-by-argument configuration
+- Make your custom modifications based on some existing configurations, such as [Getting started in 15 minutes](../get_started/15_minutes.md) and downstream repositories like [MMDet](https://github.com/open-mmlab/mmdetection)
+
+Pros and cons lie in both approaches. For the former one, beginners may be lost in a vast number of configurable arguments. For the latter one, beginners may find it hard to get a good reference, since neither an over-simplified nor an over-detailed reference is conducive to them.
+
+We argue that the key to learning runner is using it as a memo. You should remember its most commonly used arguments and only focus on those less used when in need, since default values usually work fine. In the following, we will provide a beginner-friendly example to illustrate the most commonly used arguments of the runner, along with advanced guidelines for those less used.
+
+### A beginer-friendly example
+
+```{hint}
+In this tutorial, we hope you can focus more on overall architecture instead of implementation details. This "top-down" way of thinking is exactly what we advocate. Don't worry, you will definitely have plenty of opportunities and guidance afterward to focus on modules you want to improve.
+```
+
+
+Before running the actual example below, you should first run this piece of code for the preparation of the model, dataset, and metric. However, these implementations are not important in this tutorial and you can simply look through
+
+```python
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.utils.data import Dataset
+
+from mmengine.model import BaseModel
+from mmengine.evaluator import BaseMetric
+from mmengine.registry import MODELS, DATASETS, METRICS
+
+
+@MODELS.register_module()
+class MyAwesomeModel(BaseModel):
+ def __init__(self, layers=4, activation='relu') -> None:
+ super().__init__()
+ if activation == 'relu':
+ act_type = nn.ReLU
+ elif activation == 'silu':
+ act_type = nn.SiLU
+ elif activation == 'none':
+ act_type = nn.Identity
+ else:
+ raise NotImplementedError
+ sequence = [nn.Linear(2, 64), act_type()]
+ for _ in range(layers-1):
+ sequence.extend([nn.Linear(64, 64), act_type()])
+ self.mlp = nn.Sequential(*sequence)
+ self.classifier = nn.Linear(64, 2)
+
+ def forward(self, data, labels, mode):
+ x = self.mlp(data)
+ x = self.classifier(x)
+ if mode == 'tensor':
+ return x
+ elif mode == 'predict':
+ return F.softmax(x, dim=1), labels
+ elif mode == 'loss':
+ return {'loss': F.cross_entropy(x, labels)}
+
+
+@DATASETS.register_module()
+class MyDataset(Dataset):
+ def __init__(self, is_train, size):
+ self.is_train = is_train
+ if self.is_train:
+ torch.manual_seed(0)
+ self.labels = torch.randint(0, 2, (size,))
+ else:
+ torch.manual_seed(3407)
+ self.labels = torch.randint(0, 2, (size,))
+ r = 3 * (self.labels+1) + torch.randn(self.labels.shape)
+ theta = torch.rand(self.labels.shape) * 2 * torch.pi
+ self.data = torch.vstack([r*torch.cos(theta), r*torch.sin(theta)]).T
+
+ def __getitem__(self, index):
+ return self.data[index], self.labels[index]
+
+ def __len__(self):
+ return len(self.data)
+
+
+@METRICS.register_module()
+class Accuracy(BaseMetric):
+ def __init__(self):
+ super().__init__()
+
+ def process(self, data_batch, data_samples):
+ score, gt = data_samples
+ self.results.append({
+ 'batch_size': len(gt),
+ 'correct': (score.argmax(dim=1) == gt).sum().cpu(),
+ })
+
+ def compute_metrics(self, results):
+ total_correct = sum(r['correct'] for r in results)
+ total_size = sum(r['batch_size'] for r in results)
+ return dict(accuracy=100*total_correct/total_size)
+```
+
+
+
+
+Click to show a long example. Be well prepared
+
+```python
+from torch.utils.data import DataLoader, default_collate
+from torch.optim import Adam
+from mmengine.runner import Runner
+
+
+runner = Runner(
+ # your model
+ model=MyAwesomeModel(
+ layers=2,
+ activation='relu'),
+ # work directory for saving checkpoints and logs
+ work_dir='exp/my_awesome_model',
+
+ # training data
+ train_dataloader=DataLoader(
+ dataset=MyDataset(
+ is_train=True,
+ size=10000),
+ shuffle=True,
+ collate_fn=default_collate,
+ batch_size=64,
+ pin_memory=True,
+ num_workers=2),
+ # training configurations
+ train_cfg=dict(
+ by_epoch=True, # display in epoch number instead of iterations
+ max_epochs=10,
+ val_begin=2, # start validation from the 2nd epoch
+ val_interval=1), # do validation every 1 epoch
+
+ # OptimizerWrapper, new concept in MMEngine for richer optimization options
+ # Default value works fine for most cases. You may check our documentations
+ # for more details, e.g. 'AmpOptimWrapper' for enabling mixed precision
+ # training.
+ optim_wrapper=dict(
+ optimizer=dict(
+ type=Adam,
+ lr=0.001)),
+ # ParamScheduler to adjust learning rates or momentums during training
+ param_scheduler=dict(
+ type='MultiStepLR',
+ by_epoch=True,
+ milestones=[4, 8],
+ gamma=0.1),
+
+ # validation data
+ val_dataloader=DataLoader(
+ dataset=MyDataset(
+ is_train=False,
+ size=1000),
+ shuffle=False,
+ collate_fn=default_collate,
+ batch_size=1000,
+ pin_memory=True,
+ num_workers=2),
+ # validation configurations, usually leave it an empty dict
+ val_cfg=dict(),
+ # evaluation metrics and evaluator
+ val_evaluator=dict(type=Accuracy),
+
+ # following are advanced configurations, try to default when not in need
+ # hooks are advanced usage, try to default when not in need
+ default_hooks=dict(
+ # the most commonly used hook for modifying checkpoint saving interval
+ checkpoint=dict(type='CheckpointHook', interval=1)),
+
+ # `luancher` and `env_cfg` responsible for distributed environment
+ launcher='none',
+ env_cfg=dict(
+ cudnn_benchmark=False, # whether enable cudnn_benchmark
+ backend='nccl', # distributed communication backend
+ mp_cfg=dict(mp_start_method='fork')), # multiprocessing configs
+ log_level='INFO',
+
+ # load model weights from given path. None for no loading.
+ load_from=None
+ # resume training from the given path
+ resume=False
+)
+
+# start training your model
+runner.train()
+```
+
+
+
+### Explanations on example codes
+
+Really a long piece of code, isn't it! However, if you read through the above example, you may have already understood the training process in general even without knowing any implementation details, thanks to the compactness and readability of runner codes (probably). This is what MMEngine expects: a structured, modular, and standardized training process that allows for more reliable reproductions and clearer comparisons.
+
+The above example may lead you to the following confusion:
+
+
+There are too many arguments!
+
+Don't worry. As we mentioned before, **use runner as a memo**. The runner covers all aspects just to ensure you won't miss something important. You don't actually need to configure everything. The simple example in [15 minutes](../get_started/15_minutes.md) still works fine, and it can be even more simplified by removing `val_evaluator`, `val_dataloader`, and `val_cfg` without breaking down. All configurable arguments are driven by your demands. Those not in your focus usually work fine by default.
+
+
+
+
+Why are some arguments passed as dicts?
+
+Well, this is related to MMEngine's style. In MMEngine, we provide 2 different styles of runner construction: a) manual construction and b) construction via registry. If you are confused, the following example will give a good illustration:
+
+```python
+from mmengine.model import BaseModel
+from mmengine.runner import Runner
+from mmengine.registry import MODELS # root registry for your custom model
+
+@MODELS.register_module() # decorator for registration
+class MyAwesomeModel(BaseModel): # your custom model
+ def __init__(self, layers=18, activation='silu'):
+ ...
+
+# An example of manual construction
+runner = Runner(
+ model=dict(
+ type='MyAwesomeModel',
+ layers=50,
+ activation='relu'),
+ ...
+)
+
+# An example of construction via registry
+model = MyAwesomeModel(layers=18, activation='relu')
+runner = Runner(
+ model=model,
+ ...
+)
+```
+
+Similar to the above example, most arguments in the runner accept both 2 types of inputs. They are conceptually equivalent. The difference is, in the former style, the module (passed in as a `dict`) will be built **in the runner when actually needed**, while in the latter style, the module has been built before being passed to the runner. The following figure illustrates the core idea of registry: it maintains the mapping between a module's **build method** and its **registry name**. If you want to learn more about the full usage of the registry, you are recommended to read [Registry](../advanced_tutorials/registry.md) tutorial.
+
+
+
+You might still be confused after the explanation. Why should we let the Runner build modules from dicts? What are the benefits? If you have such questions, then we are proud to answer: "Absolutely - no benefits!" In fact, module construction via registry only works to its best advantage when combined with a configuration file. It is still far from the best practice to write as the above example. We provide it here just to make sure you can read and get used to this writing style, which may facilitate your understanding of the actual best practice we will soon talk about - the configuration file. Stay tuned!
+
+If you as a beginner do not immediately understand, it doesn't matter too much, because **manual construction** is still a good choice, especially for small-scale development and trial-and-error due to its being IDE friendly. However, you are still expected to read and get used to the writing style via registry, so that you can avoid being unnecessarily confused and puzzled in subsequent tutorials.
+
+
+
+
+Where can I find the possible configuration options for the xxx argument?
+
+You will find extensive instructions and examples in those tutorials of the corresponding modules. You can also find all possible arguments in [Runner's API documentation](mmengine.runner.Runner). If neither of the above resolves your query, you are always encouraged to start a topic in our [discussion forum](https://github.com/open-mmlab/mmengine/discussions). It also helps us improve documentations.
+
+
+
+
+I come from repositoried like MMDet/MMCls... Why does this example differ from what I've been exposed to?
+
+Downstream repositories in OpenMMLab have widely adopted the writing style of config files. In the following chapter, we will show the usage of config files, the best practice of the runner in MMEngine, based on the above example with a slight variation.
+
+
+
+## Best practice of the Runner - config files
+
+MMEngine provides a powerful config file system that supports Python syntax. You can **almost seamlessly** (which we will illustrate below) convert from the previous sample code to a config file. Here is an example:
+
+```python
+# Save the following codes in example_config.py
+# Almost copied from the above example, with some commas removed
+model = dict(type='MyAwesomeModel',
+ layers=2,
+ activation='relu')
+work_dir = 'exp/my_awesome_model'
+
+train_dataloader = dict(
+ dataset=dict(type='MyDataset',
+ is_train=True,
+ size=10000),
+ sampler=dict(
+ type='DefaultSampler',
+ shuffle=True),
+ collate_fn=dict(type='default_collate'),
+ batch_size=64,
+ pin_memory=True,
+ num_workers=2)
+train_cfg = dict(
+ by_epoch=True,
+ max_epochs=10,
+ val_begin=2,
+ val_interval=1)
+optim_wrapper = dict(
+ optimizer=dict(
+ type='Adam',
+ lr=0.001))
+param_scheduler = dict(
+ type='MultiStepLR',
+ by_epoch=True,
+ milestones=[4, 8],
+ gamma=0.1)
+
+val_dataloader = dict(
+ dataset=dict(type='MyDataset',
+ is_train=False,
+ size=1000),
+ sampler=dict(
+ type='DefaultSampler',
+ shuffle=False),
+ collate_fn=dict(type='default_collate'),
+ batch_size=1000,
+ pin_memory=True,
+ num_workers=2)
+val_cfg = dict()
+val_evaluator = dict(type='Accuracy')
+
+default_hooks = dict(
+ checkpoint=dict(type='CheckpointHook', interval=1))
+launcher = 'none'
+env_cfg = dict(
+ cudnn_benchmark=False,
+ backend='nccl',
+ mp_cfg=dict(mp_start_method='fork'))
+log_level = 'INFO'
+load_from = None
+resume = False
+```
+
+Given the above config file, we can simply load configurations and run the training pipeline in a few lines of codes as follows:
+
+```python
+from mmengine.config import Config
+from mmengine.runner import Runner
+config = Config.fromfile('example_config.py')
+runner = Runner.from_cfg(config)
+runner.train()
+```
+
+```{note}
+Although it supports Python syntax, a valid config file needs to meet the condition that all variables must be Python built-in types such as `str`, `dict` and `int`. Therefore, the config system is highly dependent on the registry mechanism to enable construction from built-in types to other types such as `nn.Module`.
+```
+
+```{note}
+When using config files, you typically don't need to manually register every module. For instance, all optimizers in `torch.optim` including `Adam` and `SGD` have already been registered in `mmengine.optim`. The rule of thumb is, try to directly access modules provided by PyTorch, and only start to register them manually after error occurs.
+```
+
+```{note}
+When using config files, the implementations of your custom modules may be stored in separate files and thus not registered properly, which will lead to errors in the build process. You may find solutions in [Registry tutorial](./registry.md) by searching for `custom_imports`.
+```
+
+```{warnings}
+Although sharing nearly the same codes, `from_cfg` and `__init__` differs in some default values like `env_cfg`.
+```
+
+Writing config files of the runner has been widely adopted in downstream repositories in OpenMMLab projects. It has been a de facto convention and best practice. The config files are far more featured than illustrated above. You can refer to [Config tutorial](../advanced_tutorials/config.md) for more advanced features including keywords inheriting and overriding.
+
+## Basic dataflow
+
+```{hint}
+In this chapter, we'll dive deeper into the runner to illustrate dataflow and data format convention between modules managed by the runner. It may be relatively abstract and dry if you haven't built a training pipeline with MMEngine. Therefore, you are free to skip for now and read it in conjunction with practice in the future when in need.
+```
+
+Now let's dive **slightly deeper** into the runner, and illustrate the dataflow and data format convention under the hood (or, under the engine)!
+
+
+
+The diagram above illustrates the **basic** dataflow of the runner, where the dashed border, gray filled shapes represent different data formats, while solid boxes represent modules/methods. Due to the great flexibility and extensibility of MMEngine, you can always inherit some key base classes and override their methods, so the above diagram doesn't always hold. It only holds when you are not customizing your own `Runner` or `TrainLoop`, and you are not overriding `train_step`, `val_step` or `test_step` method in your custom model. Actually, this is common for most tasks like detection and segmentation, as referred to [Model tutorial](./model.md).
+
+
+Can you state the exact type of each data item shown in the diagram?
+
+Unfortunately, this is not possible. Although we did heavy type annotations in MMEngine, Python is still a highly dynamic programming language, and deep learning as a data-centric system needs to be flexible enough to deal with a wide range of complex data sources. You always have full freedom to decide when you need (and sometimes must) break type conventions. Therefore, when you are customizing your module (e.g. `val_evaluator`), you need to make sure its input is compatible with upstream (e.g. `model`) output and its output can be parsed by downstream. MMEngine puts the flexibility of handling data in the hands of the user, and thus also requires the user to ensure compatibility of dataflow, which, in fact, is not that difficult once you get started.
+
+The uniformity of data formats has always been a problem in deep learning. We are trying to improve it in MMEngine in our own way. If you are interested, you can refer to [BaseDataset](../advanced_tutorials/basedataset.md) and [BaseDataElement](../advanced_tutorials/data_element.md) - but please note that they are mainly geared towards advanced users.
+
+
+
+
+What's the data format convention between dataloader, model and evaluator?
+
+For the basic dataflow shown in the diagram above, the data transfer between the above three modules can be represented by the following pseudo-code:
+
+```python
+# training
+for data_batch in train_dataloader:
+ data_batch = data_preprocessor(data_batch)
+ if isinstance(data_batch, dict):
+ losses = model.forward(**data_batch, mode='loss')
+ elif isinstance(data_batch, (list, tuple)):
+ losses = model.forward(*data_batch, mode='loss')
+ else:
+ raise TypeError()
+
+# validation
+for data_batch in val_dataloader:
+ data_batch = data_preprocessor(data_batch)
+ if isinstance(data_batch, dict):
+ outputs = model.forward(**data_batch, mode='predict')
+ elif isinstance(data_batch, (list, tuple)):
+ outputs = model.forward(**data_batch, mode='predict')
+ else:
+ raise TypeError()
+ evaluator.process(data_samples=outputs, data_batch=data_batch)
+metrics = evaluator.evaluate(len(val_dataloader.dataset))
+```
+
+The key points of the above pseudo-code is:
+
+- Outputs of data_preprocessor are passed to model **after unpacking**
+- The `data_samples` argument of the evaluator receives the prediction results of the model, while the `data_batch` argument receives the raw data coming from dataloader
+
+
+
+
+What is data_preprocessor? Can I do image pre-processing such as crop and resize in it?
+
+Though drawn separately in the diagram, data_preprocessor is a part of the model and thus can be found in [Model tutorial](./model.md) in DataPreprocessor chapter.
+
+In most cases, data_preprocessor needs no special attention or manual configuration. The default data_preprocessor will only do data transfer between host and GPU devices. However, if your model has incompatible inputs format with dataloader's output, you can also customize you own data_preprocessor for data formatting.
+
+Image pre-processing such as crop and resize is more recommended in [data transforms module](../advanced_tutorials/data_transform.md), but for batch-related data transforms (e.g. batch-resize), it can be implemented here.
+
+
+
+
+Why does module produce 3 different outputs? What is the meaning of "loss", "predict" and "tensor"?
+
+As described in [get started in 15 minutes](../get_started/15_minutes.md), you need to implement 3 data paths in your custom model's `forward` function to suit different pipelines for training, validation and testing. This is further discussed in [Model tutorial](./model.md).
+
+
+
+
+I can see that the red line is for training process and the blue line for validation/testing, but what is the green line?
+
+Currently model outputs in "tensor" mode has not been officially used in runner. The "tensor" mode can output some intermediate results and thus facilitating debugging process.
+
+
+
+
+What if I override methods such as train_step? Will the diagram totally fail?
+
+The behavior of default `train_step`, `val_step` and `test_step` covers the dataflow from data_preprocessor to model outputs and optim_wrapper. The rest of the diagram will not be spoiled.
+
+
+
+## Why use the runner? (Optional reading)
+
+```{hint}
+Contents in this chapter will not teach you how to use the runner and MMEngine. If you are being pushed by your employer/advisor/DDL to work out a result in a few hours, it may not help you and you can feel free to skip it. However, we highly recommend taking time to read through this chapter, since it will help you better understand the aim and style of MMEngine.
+```
+
+
+Relax, time for some philosophy
+
+Congratulations for reading through the runner tutorial, a long, long but kind of interesting (hope so) tutorial! Please believe that all of these - this tutorial, the runner, MMEngine - are intended to **make things easier for you**.
+
+The runner is the "manager" of all modules in MMEngine. In the runner, all the distinct modules - whether visible ones like model and dataset, or obscure ones like logging, distributed environment and random seed - are getting organized and scheduled. The runner deals with the complex relationship between different modules and provides you with a clear, easy-to-understand and configurable interface. The benefits of this design are:
+
+1. You can modify or add your codes without spoiling your whole codebase. For example, you may start with single GPU training and you can always add a few lines of configuration codes to enable multi GPUs or even multi nodes training.
+2. You can continuously benefit from new features without worrying about backward compatibility. Mixed precision training, visualization, state of the art distributed training methods, various device backends... We will continue to absorb the best suggestions and cutting-edge technologies from the community while ensuring backward compatibility, and provide them to you in a clear interface.
+3. You can focus on your own awesome ideas without being bothered by other annoying and irrelevant details. The default values will handle most cases.
+
+So, MMEngine and the runner will truly make things easier for you. With only a little effort on migration, your code and experiments will evolve with MMEngine. With a little more effort, the config file system allows you to manage your data, model, and experiments more efficiently. Convenience and reliability are the aims we strive for.
+
+The blue one, or the red one - are you prepared to use MMEngine?
+
+
+
+## Suggestions on next steps
+
+If you want to:
+
+
+Write your own model structure
+
+Refer to [Model tutorial](./model.md)
+
+
+
+
+Use your own datasets
+
+Refer to [Dataset and DataLoader tutorial](./dataset.md)
+
+
+
+
+Change evaluation metrics
+
+Refer to [Evaluation tutorial](./evaluation.md)
+
+
+
+
+Do something related to optimizers or mixed-precision training
+
+Refer to [OptimWrapper tutorial](./optim_wrapper.md)
+
+
+
+
+Schedule learning rates or other parameters during training
+
+Refer to [Parameter Scheduler tutorial](./param_scheduler.md)
+
+
+
+
+Something not mentioned above
+
+- "Common Usage" section to the left contains more example codes
+- "Advanced tutorials" to the left consists of more contents for experienced developers to make more flexible extensions to the training pipeline
+- [Hook](./hook.md) provides some flexible modifications without spoiling your codes
+- If none of the above solves your problem, you are always welcome to start a topic in our [discussion forum](https://github.com/open-mmlab/mmengine/discussions)!
+
+
diff --git a/testbed/open-mmlab__mmengine/docs/resources/config/cross_repo.py b/testbed/open-mmlab__mmengine/docs/resources/config/cross_repo.py
new file mode 100644
index 0000000000000000000000000000000000000000..947266895640192e34ca57c4c2d56f013428e00b
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/resources/config/cross_repo.py
@@ -0,0 +1,6 @@
+_base_ = [
+ 'mmdet::_base_/schedules/schedule_1x.py',
+ 'mmdet::_base_/datasets/coco_instance.py',
+ 'mmdet::_base_/default_runtime.py',
+ 'mmdet::_base_/models/faster-rcnn_r50_fpn.py',
+]
diff --git a/testbed/open-mmlab__mmengine/docs/resources/config/custom_imports.py b/testbed/open-mmlab__mmengine/docs/resources/config/custom_imports.py
new file mode 100644
index 0000000000000000000000000000000000000000..adb5d0489ae3884e5e17c02f3056103039856762
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/resources/config/custom_imports.py
@@ -0,0 +1,2 @@
+custom_imports = dict(imports=['my_module'], allow_failed_imports=False)
+optimizer = dict(type='CustomOptim')
diff --git a/testbed/open-mmlab__mmengine/docs/resources/config/demo_train.py b/testbed/open-mmlab__mmengine/docs/resources/config/demo_train.py
new file mode 100644
index 0000000000000000000000000000000000000000..411ef6a98d905ed9e6993a5782fe2b0c2b76d169
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/resources/config/demo_train.py
@@ -0,0 +1,33 @@
+import argparse
+
+from mmengine.config import Config, DictAction
+
+
+def parse_args():
+ parser = argparse.ArgumentParser(description='Train a model')
+ parser.add_argument('config', help='train config file path')
+ parser.add_argument(
+ '--cfg-options',
+ nargs='+',
+ action=DictAction,
+ help='override some settings in the used config, the key-value pair '
+ 'in xxx=yyy format will be merged into config file. If the value to '
+ 'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
+ 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
+ 'Note that the quotation marks are necessary and that no white space '
+ 'is allowed.')
+
+ args = parser.parse_args()
+ return args
+
+
+def main():
+ args = parse_args()
+ cfg = Config.fromfile(args.config)
+ if args.cfg_options is not None:
+ cfg.merge_from_dict(args.cfg_options)
+ print(cfg)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/testbed/open-mmlab__mmengine/docs/resources/config/example.py b/testbed/open-mmlab__mmengine/docs/resources/config/example.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3df48c6a6445b42c477c6d10790dea908ccfe2c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/resources/config/example.py
@@ -0,0 +1,2 @@
+model = dict(type='CustomModel', in_channels=[1, 2, 3])
+optimizer = dict(type='SGD', lr=0.01)
diff --git a/testbed/open-mmlab__mmengine/docs/resources/config/learn_read_config.py b/testbed/open-mmlab__mmengine/docs/resources/config/learn_read_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..822aa66257eb1428d1075699005e556a9875633f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/resources/config/learn_read_config.py
@@ -0,0 +1,3 @@
+test_int = 1
+test_list = [1, 2, 3]
+test_dict = dict(key1='value1', key2=0.1)
diff --git a/testbed/open-mmlab__mmengine/docs/resources/config/my_module.py b/testbed/open-mmlab__mmengine/docs/resources/config/my_module.py
new file mode 100644
index 0000000000000000000000000000000000000000..ddb9538b0e99aee86c3b9aa7e0d4c013be3f21fd
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/resources/config/my_module.py
@@ -0,0 +1,6 @@
+from mmengine.registry import OPTIMIZERS
+
+
+@OPTIMIZERS.register_module()
+class CustomOptim:
+ pass
diff --git a/testbed/open-mmlab__mmengine/docs/resources/config/optimizer_cfg.py b/testbed/open-mmlab__mmengine/docs/resources/config/optimizer_cfg.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6f55cd3c51fc955f7c70f658b082d381613a44e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/resources/config/optimizer_cfg.py
@@ -0,0 +1 @@
+optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)
diff --git a/testbed/open-mmlab__mmengine/docs/resources/config/predefined_var.py b/testbed/open-mmlab__mmengine/docs/resources/config/predefined_var.py
new file mode 100644
index 0000000000000000000000000000000000000000..f072068c05041eed3614d2c92819591f74118020
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/resources/config/predefined_var.py
@@ -0,0 +1 @@
+work_dir = './work_dir/{{fileBasenameNoExtension}}'
diff --git a/testbed/open-mmlab__mmengine/docs/resources/config/refer_base_var.py b/testbed/open-mmlab__mmengine/docs/resources/config/refer_base_var.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e98a1ef08285877ad702252810b438369428ccf
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/resources/config/refer_base_var.py
@@ -0,0 +1,2 @@
+_base_ = ['resnet50.py']
+a = {{_base_.model}}
diff --git a/testbed/open-mmlab__mmengine/docs/resources/config/resnet50.py b/testbed/open-mmlab__mmengine/docs/resources/config/resnet50.py
new file mode 100644
index 0000000000000000000000000000000000000000..43f0187d9aebb91c74ec1c33c2d9593dfd943017
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/resources/config/resnet50.py
@@ -0,0 +1,2 @@
+_base_ = ['optimizer_cfg.py']
+model = dict(type='ResNet', depth=50)
diff --git a/testbed/open-mmlab__mmengine/docs/resources/config/resnet50_delete_key.py b/testbed/open-mmlab__mmengine/docs/resources/config/resnet50_delete_key.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7ada136a775170f65a4d4c141a079e1dc189edd
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/resources/config/resnet50_delete_key.py
@@ -0,0 +1,3 @@
+_base_ = ['optimizer_cfg.py', 'runtime_cfg.py']
+model = dict(type='ResNet', depth=50)
+optimizer = dict(_delete_=True, type='SGD', lr=0.01)
diff --git a/testbed/open-mmlab__mmengine/docs/resources/config/resnet50_lr0.01.py b/testbed/open-mmlab__mmengine/docs/resources/config/resnet50_lr0.01.py
new file mode 100644
index 0000000000000000000000000000000000000000..47a83994b610d77277a6d17254c4c606e96b1f93
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/resources/config/resnet50_lr0.01.py
@@ -0,0 +1,3 @@
+_base_ = ['optimizer_cfg.py', 'runtime_cfg.py']
+model = dict(type='ResNet', depth=50)
+optimizer = dict(lr=0.01)
diff --git a/testbed/open-mmlab__mmengine/docs/resources/config/resnet50_runtime.py b/testbed/open-mmlab__mmengine/docs/resources/config/resnet50_runtime.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b7c8e1a43111dcdf14109ff19263ecdc283e7ab
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/resources/config/resnet50_runtime.py
@@ -0,0 +1,2 @@
+_base_ = ['optimizer_cfg.py', 'runtime_cfg.py']
+model = dict(type='ResNet', depth=50)
diff --git a/testbed/open-mmlab__mmengine/docs/resources/config/runtime_cfg.py b/testbed/open-mmlab__mmengine/docs/resources/config/runtime_cfg.py
new file mode 100644
index 0000000000000000000000000000000000000000..3286f6973610a171ba983af2de8602b3f2a0bc42
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/resources/config/runtime_cfg.py
@@ -0,0 +1 @@
+gpu_ids = [0, 1]
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/Makefile b/testbed/open-mmlab__mmengine/docs/zh_cn/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..d4bb2cbb9eddb1bb1b4f366623044af8e4830919
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/Makefile
@@ -0,0 +1,20 @@
+# Minimal makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line, and also
+# from the environment for the first two.
+SPHINXOPTS ?=
+SPHINXBUILD ?= sphinx-build
+SOURCEDIR = .
+BUILDDIR = _build
+
+# Put it first so that "make" without argument is like "make help".
+help:
+ @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
+
+.PHONY: help Makefile
+
+# Catch-all target: route all unknown targets to Sphinx using the new
+# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
+%: Makefile
+ @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/_static/css/readthedocs.css b/testbed/open-mmlab__mmengine/docs/zh_cn/_static/css/readthedocs.css
new file mode 100644
index 0000000000000000000000000000000000000000..7a2acaefa76bb4c9f74b0f625b562e5d17f58c61
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/_static/css/readthedocs.css
@@ -0,0 +1,20 @@
+table.colwidths-auto td {
+ width: 50%
+}
+
+.header-logo {
+ background-image: url("../image/mmengine-logo.png");
+ background-size: 130px 40px;
+ height: 40px;
+ width: 130px;
+}
+
+.two-column-table-wrapper {
+ width: 50%;
+ max-width: 300px;
+ overflow-x: auto;
+}
+
+.two-column-table-wrapper .highlight {
+ width: 1500px
+}
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/_templates/classtemplate.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/_templates/classtemplate.rst
new file mode 100644
index 0000000000000000000000000000000000000000..4f74842394ec9807fb1ae2d8f05a8a57e9a2e24c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/_templates/classtemplate.rst
@@ -0,0 +1,14 @@
+.. role:: hidden
+ :class: hidden-section
+.. currentmodule:: {{ module }}
+
+
+{{ name | underline}}
+
+.. autoclass:: {{ name }}
+ :members:
+
+
+..
+ autogenerated from source/_templates/classtemplate.rst
+ note it does not have :inherited-members:
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/basedataset.md b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/basedataset.md
new file mode 100644
index 0000000000000000000000000000000000000000..2fd9b80340d894c06b313eb4d3db0d9fc492522f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/basedataset.md
@@ -0,0 +1,505 @@
+# 数据集基类(BaseDataset)
+
+## 基本介绍
+
+算法库中的数据集类负责在训练/测试过程中为模型提供输入数据,OpenMMLab 下各个算法库中的数据集有一些共同的特点和需求,比如需要高效的内部数据存储格式,需要支持数据集拼接、数据集重复采样等功能。
+
+因此 **MMEngine** 实现了一个数据集基类(BaseDataset)并定义了一些基本接口,且基于这套接口实现了一些数据集包装(DatasetWrapper)。OpenMMLab 算法库中的大部分数据集都会满足这套数据集基类定义的接口,并使用统一的数据集包装。
+
+数据集基类的基本功能是加载数据集信息,这里我们将数据集信息分成两类,一种是元信息 (meta information),代表数据集自身相关的信息,有时需要被模型或其他外部组件获取,比如在图像分类任务中,数据集的元信息一般包含类别信息 `classes`,因为分类模型 `model` 一般需要记录数据集的类别信息;另一种为数据信息 (data information),在数据信息中,定义了具体样本的文件路径、对应标签等的信息。除此之外,数据集基类的另一个功能为不断地将数据送入数据流水线(data pipeline)中,进行数据预处理。
+
+### 数据标注文件规范
+
+为了统一不同任务的数据集接口,便于多任务的算法模型训练,OpenMMLab 制定了 **OpenMMLab 2.0 数据集格式规范**, 数据集标注文件需符合该规范,数据集基类基于该规范去读取与解析数据标注文件。如果用户提供的数据标注文件不符合规定格式,用户可以选择将其转化为规定格式,并使用 OpenMMLab 的算法库基于该数据标注文件进行算法训练和测试。
+
+OpenMMLab 2.0 数据集格式规范规定,标注文件必须为 `json` 或 `yaml`,`yml` 或 `pickle`,`pkl` 格式;标注文件中存储的字典必须包含 `metainfo` 和 `data_list` 两个字段。其中 `metainfo` 是一个字典,里面包含数据集的元信息;`data_list` 是一个列表,列表中每个元素是一个字典,该字典定义了一个原始数据(raw data),每个原始数据包含一个或若干个训练/测试样本。
+
+以下是一个 JSON 标注文件的例子(该例子中每个原始数据只包含一个训练/测试样本):
+
+```json
+
+{
+ 'metainfo':
+ {
+ 'classes': ('cat', 'dog'),
+ ...
+ },
+ 'data_list':
+ [
+ {
+ 'img_path': "xxx/xxx_0.jpg",
+ 'img_label': 0,
+ ...
+ },
+ {
+ 'img_path': "xxx/xxx_1.jpg",
+ 'img_label': 1,
+ ...
+ },
+ ...
+ ]
+}
+```
+
+同时假设数据存放路径如下:
+
+```text
+data
+├── annotations
+│ ├── train.json
+├── train
+│ ├── xxx/xxx_0.jpg
+│ ├── xxx/xxx_1.jpg
+│ ├── ...
+```
+
+### 数据集基类的初始化流程
+
+数据集基类的初始化流程如下图所示:
+
+
+
+
+
+1. `load metainfo`:获取数据集的元信息,元信息有三种来源,优先级从高到低为:
+
+- `__init__()` 方法中用户传入的 `metainfo` 字典;改动频率最高,因为用户可以在实例化数据集时,传入该参数;
+
+- 类属性 `BaseDataset.METAINFO` 字典;改动频率中等,因为用户可以改动自定义数据集类中的类属性 `BaseDataset.METAINFO`;
+
+- 标注文件中包含的 `metainfo` 字典;改动频率最低,因为标注文件一般不做改动。
+
+ 如果三种来源中有相同的字段,优先级最高的来源决定该字段的值,这些字段的优先级比较是:用户传入的 `metainfo` 字典里的字段 > `BaseDataset.METAINFO` 字典里的字段 > 标注文件中 `metainfo` 字典里的字段。
+
+2. `join path`:处理数据与标注文件的路径;
+
+3. `build pipeline`:构建数据流水线(data pipeline),用于数据预处理与数据准备;
+
+4. `full init`:完全初始化数据集类,该步骤主要包含以下操作:
+
+- `load data list`:读取与解析满足 OpenMMLab 2.0 数据集格式规范的标注文件,该步骤中会调用 `parse_data_info()` 方法,该方法负责解析标注文件里的每个原始数据;
+
+- `filter data` (可选):根据 `filter_cfg` 过滤无用数据,比如不包含标注的样本等;默认不做过滤操作,下游子类可以按自身所需对其进行重写;
+
+- `get subset` (可选):根据给定的索引或整数值采样数据,比如只取前 10 个样本参与训练/测试;默认不采样数据,即使用全部数据样本;
+
+- `serialize data` (可选):序列化全部样本,以达到节省内存的效果,详情请参考[节省内存](#节省内存);默认操作为序列化全部样本。
+
+数据集基类中包含的 `parse_data_info()` 方法用于将标注文件里的一个原始数据处理成一个或若干个训练/测试样本的方法。因此对于自定义数据集类,用户需要实现 `parse_data_info()` 方法。
+
+### 数据集基类提供的接口
+
+与 `torch.utils.data.Dataset` 类似,数据集初始化后,支持 `__getitem__` 方法,用来索引数据,以及 `__len__` 操作获取数据集大小,除此之外,OpenMMLab 的数据集基类主要提供了以下接口来访问具体信息:
+
+- `metainfo`:返回元信息,返回值为字典
+
+- `get_data_info(idx)`:返回指定 `idx` 的样本全量信息,返回值为字典
+
+- `__getitem__(idx)`:返回指定 `idx` 的样本经过 pipeline 之后的结果(也就是送入模型的数据),返回值为字典
+
+- `__len__()`:返回数据集长度,返回值为整数型
+
+- `get_subset_(indices)`:根据 `indices` 以 inplace 的方式**修改原数据集类**。如果 `indices` 为 `int`,则原数据集类只包含前若干个数据样本;如果 `indices` 为 `Sequence[int]`,则原数据集类包含根据 `Sequence[int]` 指定的数据样本。
+
+- `get_subset(indices)`:根据 `indices` 以**非** inplace 的方式**返回子数据集类**,即重新复制一份子数据集。如果 `indices` 为 `int`,则返回的子数据集类只包含前若干个数据样本;如果 `indices` 为 `Sequence[int]`,则返回的子数据集类包含根据 `Sequence[int]` 指定的数据样本。
+
+## 使用数据集基类自定义数据集类
+
+在了解了数据集基类的初始化流程与提供的接口之后,就可以基于数据集基类自定义数据集类。
+
+### 对于满足 OpenMMLab 2.0 数据集格式规范的标注文件
+
+如上所述,对于满足 OpenMMLab 2.0 数据集格式规范的标注文件,用户可以重载 `parse_data_info()` 来加载标签。以下是一个使用数据集基类来实现某一具体数据集的例子。
+
+```python
+import os.path as osp
+
+from mmengine.dataset import BaseDataset
+
+
+class ToyDataset(BaseDataset):
+
+ # 以上面标注文件为例,在这里 raw_data_info 代表 `data_list` 对应列表里的某个字典:
+ # {
+ # 'img_path': "xxx/xxx_0.jpg",
+ # 'img_label': 0,
+ # ...
+ # }
+ def parse_data_info(self, raw_data_info):
+ data_info = raw_data_info
+ img_prefix = self.data_prefix.get('img_path', None)
+ if img_prefix is not None:
+ data_info['img_path'] = osp.join(
+ img_prefix, data_info['img_path'])
+ return data_info
+
+```
+
+#### 使用自定义数据集类
+
+在定义了数据集类后,就可以通过如下配置实例化 `ToyDataset`:
+
+```python
+
+class LoadImage:
+
+ def __call__(self, results):
+ results['img'] = cv2.imread(results['img_path'])
+ return results
+
+class ParseImage:
+
+ def __call__(self, results):
+ results['img_shape'] = results['img'].shape
+ return results
+
+pipeline = [
+ LoadImage(),
+ ParseImage(),
+]
+
+toy_dataset = ToyDataset(
+ data_root='data/',
+ data_prefix=dict(img_path='train/'),
+ ann_file='annotations/train.json',
+ pipeline=pipeline)
+```
+
+同时可以使用数据集类提供的对外接口访问具体的样本信息:
+
+```python
+toy_dataset.metainfo
+# dict(classes=('cat', 'dog'))
+
+toy_dataset.get_data_info(0)
+# {
+# 'img_path': "data/train/xxx/xxx_0.jpg",
+# 'img_label': 0,
+# ...
+# }
+
+len(toy_dataset)
+# 2
+
+toy_dataset[0]
+# {
+# 'img_path': "data/train/xxx/xxx_0.jpg",
+# 'img_label': 0,
+# 'img': a ndarray with shape (H, W, 3), which denotes the value of the image,
+# 'img_shape': (H, W, 3) ,
+# ...
+# }
+
+# `get_subset` 接口不对原数据集类做修改,即完全复制一份新的
+sub_toy_dataset = toy_dataset.get_subset(1)
+len(toy_dataset), len(sub_toy_dataset)
+# 2, 1
+
+# `get_subset_` 接口会对原数据集类做修改,即 inplace 的方式
+toy_dataset.get_subset_(1)
+len(toy_dataset)
+# 1
+```
+
+经过以上步骤,可以了解基于数据集基类如何自定义新的数据集类,以及如何使用自定义数据集类。
+
+#### 自定义视频的数据集类
+
+在上面的例子中,标注文件的每个原始数据只包含一个训练/测试样本(通常是图像领域)。如果每个原始数据包含若干个训练/测试样本(通常是视频领域),则只需保证 `parse_data_info()` 的返回值为 `list[dict]` 即可:
+
+```python
+from mmengine.dataset import BaseDataset
+
+
+class ToyVideoDataset(BaseDataset):
+
+ # raw_data_info 仍为一个字典,但它包含了多个样本
+ def parse_data_info(self, raw_data_info):
+ data_list = []
+
+ ...
+
+ for ... :
+
+ data_info = dict()
+
+ ...
+
+ data_list.append(data_info)
+
+ return data_list
+
+```
+
+`ToyVideoDataset` 使用方法与 `ToyDataset` 类似,在此不做赘述。
+
+### 对于不满足 OpenMMLab 2.0 数据集格式规范的标注文件
+
+对于不满足 OpenMMLab 2.0 数据集格式规范的标注文件,有两种方式来使用数据集基类:
+
+1. 将不满足规范的标注文件转换成满足规范的标注文件,再通过上述方式使用数据集基类。
+
+2. 实现一个新的数据集类,继承自数据集基类,并且重载数据集基类的 `load_data_list(self):` 函数,处理不满足规范的标注文件,并保证返回值为 `list[dict]`,其中每个 `dict` 代表一个数据样本。
+
+## 数据集基类的其它特性
+
+数据集基类还包含以下特性:
+
+### 懒加载(lazy init)
+
+在数据集类实例化时,需要读取并解析标注文件,因此会消耗一定时间。然而在某些情况比如预测可视化时,往往只需要数据集类的元信息,可能并不需要读取与解析标注文件。为了节省这种情况下数据集类实例化的时间,数据集基类支持懒加载:
+
+```python
+pipeline = [
+ LoadImage(),
+ ParseImage(),
+]
+
+toy_dataset = ToyDataset(
+ data_root='data/',
+ data_prefix=dict(img_path='train/'),
+ ann_file='annotations/train.json',
+ pipeline=pipeline,
+ # 在这里传入 lazy_init 变量
+ lazy_init=True)
+```
+
+当 `lazy_init=True` 时,`ToyDataset` 的初始化方法只执行了[数据集基类的初始化流程](#数据集基类的初始化流程)中的 1、2、3 步骤,此时 `toy_dataset` 并未被完全初始化,因为 `toy_dataset` 并不会读取与解析标注文件,只会设置数据集类的元信息(`metainfo`)。
+
+自然的,如果之后需要访问具体的数据信息,可以手动调用 `toy_dataset.full_init()` 接口来执行完整的初始化过程,在这个过程中数据标注文件将被读取与解析。调用 `get_data_info(idx)`, `__len__()`, `__getitem__(idx)`,`get_subset_(indices)`, `get_subset(indices)` 接口也会自动地调用 `full_init()` 接口来执行完整的初始化过程(仅在第一次调用时,之后调用不会重复地调用 `full_init()` 接口):
+
+```python
+# 完整初始化
+toy_dataset.full_init()
+
+# 初始化完毕,现在可以访问具体数据
+len(toy_dataset)
+# 2
+toy_dataset[0]
+# {
+# 'img_path': "data/train/xxx/xxx_0.jpg",
+# 'img_label': 0,
+# 'img': a ndarray with shape (H, W, 3), which denotes the value the image,
+# 'img_shape': (H, W, 3) ,
+# ...
+# }
+```
+
+**注意:**
+
+通过直接调用 `__getitem__()` 接口来执行完整初始化会带来一定风险:如果一个数据集类首先通过设置 `lazy_init=True` 未进行完全初始化,然后直接送入数据加载器(dataloader)中,在后续读取数据的过程中,不同的 worker 会同时读取与解析标注文件,虽然这样可能可以正常运行,但是会消耗大量的时间与内存。**因此,建议在需要访问具体数据之前,提前手动调用 `full_init()` 接口来执行完整的初始化过程。**
+
+以上通过设置 `lazy_init=True` 未进行完全初始化,之后根据需求再进行完整初始化的方式,称为懒加载。
+
+### 节省内存
+
+在具体的读取数据过程中,数据加载器(dataloader)通常会起多个 worker 来预取数据,多个 worker 都拥有完整的数据集类备份,因此内存中会存在多份相同的 `data_list`,为了节省这部分内存消耗,数据集基类可以提前将 `data_list` 序列化存入内存中,使得多个 worker 可以共享同一份 `data_list`,以达到节省内存的目的。
+
+数据集基类默认是将 `data_list` 序列化存入内存,也可以通过 `serialize_data` 变量(默认为 `True`)来控制是否提前将 `data_list` 序列化存入内存中:
+
+```python
+pipeline = [
+ LoadImage(),
+ ParseImage(),
+]
+
+toy_dataset = ToyDataset(
+ data_root='data/',
+ data_prefix=dict(img_path='train/'),
+ ann_file='annotations/train.json',
+ pipeline=pipeline,
+ # 在这里传入 serialize_data 变量
+ serialize_data=False)
+```
+
+上面例子不会提前将 `data_list` 序列化存入内存中,因此不建议在使用数据加载器开多个 worker 加载数据的情况下,使用这种方式实例化数据集类。
+
+## 数据集基类包装
+
+除了数据集基类,MMEngine 也提供了若干个数据集基类包装:`ConcatDataset`, `RepeatDataset`, `ClassBalancedDataset`。这些数据集基类包装同样也支持懒加载与拥有节省内存的特性。
+
+### ConcatDataset
+
+MMEngine 提供了 `ConcatDataset` 包装来拼接多个数据集,使用方法如下:
+
+```python
+from mmengine.dataset import ConcatDataset
+
+pipeline = [
+ LoadImage(),
+ ParseImage(),
+]
+
+toy_dataset_1 = ToyDataset(
+ data_root='data/',
+ data_prefix=dict(img_path='train/'),
+ ann_file='annotations/train.json',
+ pipeline=pipeline)
+
+toy_dataset_2 = ToyDataset(
+ data_root='data/',
+ data_prefix=dict(img_path='val/'),
+ ann_file='annotations/val.json',
+ pipeline=pipeline)
+
+toy_dataset_12 = ConcatDataset(datasets=[toy_dataset_1, toy_dataset_2])
+
+```
+
+上述例子将数据集的 `train` 部分与 `val` 部分合成一个大的数据集。
+
+### RepeatDataset
+
+MMEngine 提供了 `RepeatDataset` 包装来重复采样某个数据集若干次,使用方法如下:
+
+```python
+from mmengine.dataset import RepeatDataset
+
+pipeline = [
+ LoadImage(),
+ ParseImage(),
+]
+
+toy_dataset = ToyDataset(
+ data_root='data/',
+ data_prefix=dict(img_path='train/'),
+ ann_file='annotations/train.json',
+ pipeline=pipeline)
+
+toy_dataset_repeat = RepeatDataset(dataset=toy_dataset, times=5)
+
+```
+
+上述例子将数据集的 `train` 部分重复采样了 5 次。
+
+### ClassBalancedDataset
+
+MMEngine 提供了 `ClassBalancedDataset` 包装,来基于数据集中类别出现频率,重复采样相应样本。
+
+**注意:**
+
+`ClassBalancedDataset` 包装假设了被包装的数据集类支持 `get_cat_ids(idx)` 方法,`get_cat_ids(idx)` 方法返回一个列表,该列表包含了 `idx` 指定的 `data_info` 包含的样本类别,使用方法如下:
+
+```python
+from mmengine.dataset import BaseDataset, ClassBalancedDataset
+
+class ToyDataset(BaseDataset):
+
+ def parse_data_info(self, raw_data_info):
+ data_info = raw_data_info
+ img_prefix = self.data_prefix.get('img_path', None)
+ if img_prefix is not None:
+ data_info['img_path'] = osp.join(
+ img_prefix, data_info['img_path'])
+ return data_info
+
+ # 必须支持的方法,需要返回样本的类别
+ def get_cat_ids(self, idx):
+ data_info = self.get_data_info(idx)
+ return [int(data_info['img_label'])]
+
+pipeline = [
+ LoadImage(),
+ ParseImage(),
+]
+
+toy_dataset = ToyDataset(
+ data_root='data/',
+ data_prefix=dict(img_path='train/'),
+ ann_file='annotations/train.json',
+ pipeline=pipeline)
+
+toy_dataset_repeat = ClassBalancedDataset(dataset=toy_dataset, oversample_thr=1e-3)
+
+```
+
+上述例子将数据集的 `train` 部分以 `oversample_thr=1e-3` 重新采样,具体地,对于数据集中出现频率低于 `1e-3` 的类别,会重复采样该类别对应的样本,否则不重复采样,具体采样策略请参考 `ClassBalancedDataset` API 文档。
+
+### 自定义数据集类包装
+
+由于数据集基类实现了懒加载的功能,因此在自定义数据集类包装时,需要遵循一些规则,下面以一个例子的方式来展示如何自定义数据集类包装:
+
+```python
+from mmengine.dataset import BaseDataset
+from mmengine.registry import DATASETS
+
+
+@DATASETS.register_module()
+class ExampleDatasetWrapper:
+
+ def __init__(self, dataset, lazy_init=False, ...):
+ # 构建原数据集(self.dataset)
+ if isinstance(dataset, dict):
+ self.dataset = DATASETS.build(dataset)
+ elif isinstance(dataset, BaseDataset):
+ self.dataset = dataset
+ else:
+ raise TypeError(
+ 'elements in datasets sequence should be config or '
+ f'`BaseDataset` instance, but got {type(dataset)}')
+ # 记录原数据集的元信息
+ self._metainfo = self.dataset.metainfo
+
+ '''
+ 1. 在这里实现一些代码,来记录用于包装数据集的一些超参。
+ '''
+
+ self._fully_initialized = False
+ if not lazy_init:
+ self.full_init()
+
+ def full_init(self):
+ if self._fully_initialized:
+ return
+
+ # 将原数据集完全初始化
+ self.dataset.full_init()
+
+ '''
+ 2. 在这里实现一些代码,来包装原数据集。
+ '''
+
+ self._fully_initialized = True
+
+ @force_full_init
+ def _get_ori_dataset_idx(self, idx: int):
+
+ '''
+ 3. 在这里实现一些代码,来将包装的索引 `idx` 映射到原数据集的索引 `ori_idx`。
+ '''
+ ori_idx = ...
+
+ return ori_idx
+
+ # 提供与 `self.dataset` 一样的对外接口。
+ @force_full_init
+ def get_data_info(self, idx):
+ sample_idx = self._get_ori_dataset_idx(idx)
+ return self.dataset.get_data_info(sample_idx)
+
+ # 提供与 `self.dataset` 一样的对外接口。
+ def __getitem__(self, idx):
+ if not self._fully_initialized:
+ warnings.warn('Please call `full_init` method manually to '
+ 'accelerate the speed.')
+ self.full_init()
+
+ sample_idx = self._get_ori_dataset_idx(idx)
+ return self.dataset[sample_idx]
+
+ # 提供与 `self.dataset` 一样的对外接口。
+ @force_full_init
+ def __len__(self):
+
+ '''
+ 4. 在这里实现一些代码,来计算包装数据集之后的长度。
+ '''
+ len_wrapper = ...
+
+ return len_wrapper
+
+ # 提供与 `self.dataset` 一样的对外接口。
+ @property
+ def metainfo(self)
+ return copy.deepcopy(self._metainfo)
+```
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/config.md b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/config.md
new file mode 100644
index 0000000000000000000000000000000000000000..5644987721a74c730278f692c5b4ab96139e056c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/config.md
@@ -0,0 +1,606 @@
+# 配置(Config)
+
+MMEngine 实现了抽象的配置类(Config),为用户提供统一的配置访问接口。配置类能够支持不同格式的配置文件,包括 `python`,`json`,`yaml`,用户可以根据需求选择自己偏好的格式。配置类提供了类似字典或者 Python 对象属性的访问接口,用户可以十分自然地进行配置字段的读取和修改。为了方便算法框架管理配置文件,配置类也实现了一些特性,例如配置文件的字段继承等。
+
+在开始教程之前,我们先将教程中需要用到的配置文件下载到本地(建议在临时目录下执行,方便后续删除示例配置文件):
+
+```bash
+wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/config_sgd.py
+wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/cross_repo.py
+wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/custom_imports.py
+wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/demo_train.py
+wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/example.py
+wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/learn_read_config.py
+wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/my_module.py
+wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/optimizer_cfg.py
+wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/predefined_var.py
+wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/refer_base_var.py
+wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/resnet50_delete_key.py
+wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/resnet50_lr0.01.py
+wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/resnet50_runtime.py
+wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/resnet50.py
+wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/runtime_cfg.py
+wget https://raw.githubusercontent.com/open-mmlab/mmengine/main/docs/resources/config/modify_base_var.py
+```
+
+## 配置文件读取
+
+配置类提供了统一的接口 `Config.fromfile()`,来读取和解析配置文件。
+
+合法的配置文件应该定义一系列键值对,这里举几个不同格式配置文件的例子。
+
+Python 格式:
+
+```Python
+test_int = 1
+test_list = [1, 2, 3]
+test_dict = dict(key1='value1', key2=0.1)
+```
+
+Json 格式:
+
+```json
+{
+ "test_int": 1,
+ "test_list": [1, 2, 3],
+ "test_dict": {"key1": "value1", "key2": 0.1}
+}
+```
+
+YAML 格式:
+
+```yaml
+test_int: 1
+test_list: [1, 2, 3]
+test_dict:
+ key1: "value1"
+ key2: 0.1
+```
+
+对于以上三种格式的文件,假设文件名分别为 `config.py`,`config.json`,`config.yml`,调用 `Config.fromfile('config.xxx')` 接口加载这三个文件都会得到相同的结果,构造了包含 3 个字段的配置对象。我们以 `config.py` 为例,我们先将示例配置文件下载到本地:
+
+然后通过配置类的 `fromfile` 接口读取配置文件:
+
+```python
+from mmengine.config import Config
+
+cfg = Config.fromfile('learn_read_config.py')
+print(cfg)
+```
+
+```
+Config (path: learn_read_config.py): {'test_int': 1, 'test_list': [1, 2, 3], 'test_dict': {'key1': 'value1', 'key2': 0.1}}
+```
+
+## 配置文件的使用
+
+通过读取配置文件来初始化配置对象后,就可以像使用普通字典或者 Python 类一样来使用这个变量了。我们提供了两种访问接口,即类似字典的接口 `cfg['key']` 或者类似 Python 对象属性的接口 `cfg.key`。这两种接口都支持读写。
+
+```python
+print(cfg.test_int)
+print(cfg.test_list)
+print(cfg.test_dict)
+cfg.test_int = 2
+
+print(cfg['test_int'])
+print(cfg['test_list'])
+print(cfg['test_dict'])
+cfg['test_list'][1] = 3
+print(cfg['test_list'])
+```
+
+```
+1
+[1, 2, 3]
+{'key1': 'value1', 'key2': 0.1}
+2
+[1, 2, 3]
+{'key1': 'value1', 'key2': 0.1}
+[1, 3, 3]
+```
+
+注意,配置文件中定义的嵌套字段(即类似字典的字段),在 Config 中会将其转化为 ConfigDict 类,该类继承了 Python 内置字典类型的全部接口,同时也支持以对象属性的方式访问数据。
+
+在算法库中,可以将配置与注册器结合起来使用,达到通过配置文件来控制模块构造的目的。这里举一个在配置文件中定义优化器的例子。
+
+假设我们已经定义了一个优化器的注册器 OPTIMIZERS,包括了各种优化器。那么首先写一个 `config_sgd.py`:
+
+```python
+optimizer = dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.0001)
+```
+
+然后在算法库中可以通过如下代码构造优化器对象。
+
+```python
+from mmengine import Config, optim
+from mmengine.registry import OPTIMIZERS
+
+import torch.nn as nn
+
+cfg = Config.fromfile('config_sgd.py')
+
+model = nn.Conv2d(1, 1, 1)
+cfg.optimizer.params = model.parameters()
+optimizer = OPTIMIZERS.build(cfg.optimizer)
+print(optimizer)
+```
+
+```
+SGD (
+Parameter Group 0
+ dampening: 0
+ foreach: None
+ lr: 0.1
+ maximize: False
+ momentum: 0.9
+ nesterov: False
+ weight_decay: 0.0001
+)
+```
+
+## 配置文件的继承
+
+有时候,两个不同的配置文件之间的差异很小,可能仅仅只改了一个字段,我们就需要将所有内容复制粘贴一次,而且在后续观察的时候,不容易定位到具体差异的字段。又有些情况下,多个配置文件可能都有相同的一批字段,我们不得不在这些配置文件中进行复制粘贴,给后续的修改和维护带来了不便。
+
+为了解决这些问题,我们给配置文件增加了继承的机制,即一个配置文件 A 可以将另一个配置文件 B 作为自己的基础,直接继承了 B 中所有字段,而不必显式复制粘贴。
+
+### 继承机制概述
+
+这里我们举一个例子来说明继承机制。定义如下两个配置文件,
+
+`optimizer_cfg.py`:
+
+```python
+optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)
+```
+
+`resnet50.py`:
+
+```python
+_base_ = ['optimizer_cfg.py']
+model = dict(type='ResNet', depth=50)
+```
+
+虽然我们在 `resnet50.py` 中没有定义 optimizer 字段,但由于我们写了 `_base_ = ['optimizer_cfg.py']`,会使这个配置文件获得 `optimizer_cfg.py` 中的所有字段。
+
+```python
+cfg = Config.fromfile('resnet50.py')
+print(cfg.optimizer)
+```
+
+```
+{'type': 'SGD', 'lr': 0.02, 'momentum': 0.9, 'weight_decay': 0.0001}
+```
+
+这里 `_base_` 是配置文件的保留字段,指定了该配置文件的继承来源。支持继承多个文件,将同时获得这多个文件中的所有字段,但是要求继承的多个文件中**没有**相同名称的字段,否则会报错。
+
+`runtime_cfg.py`:
+
+```python
+gpu_ids = [0, 1]
+```
+
+`resnet50_runtime.py`:
+
+```python
+_base_ = ['optimizer_cfg.py', 'runtime_cfg.py']
+model = dict(type='ResNet', depth=50)
+```
+
+这时,读取配置文件 `resnet50_runtime.py` 会获得 3 个字段 `model`,`optimizer`,`gpu_ids`。
+
+```python
+cfg = Config.fromfile('resnet50_runtime.py')
+print(cfg.optimizer)
+```
+
+```
+{'type': 'SGD', 'lr': 0.02, 'momentum': 0.9, 'weight_decay': 0.0001}
+```
+
+通过这种方式,我们可以将配置文件进行拆分,定义一些通用配置文件,在实际配置文件中继承各种通用配置文件,可以减少具体任务的配置流程。
+
+### 修改继承字段
+
+有时候,我们继承一个配置文件之后,可能需要对其中个别字段进行修改,例如继承了 `optimizer_cfg.py` 之后,想将学习率从 0.02 修改为 0.01。
+
+这时候,只需要在新的配置文件中,重新定义一下需要修改的字段即可。注意由于 optimizer 这个字段是一个字典,我们只需要重新定义这个字典里面需修改的下级字段即可。这个规则也适用于增加一些下级字段。
+
+`resnet50_lr0.01.py`:
+
+```python
+_base_ = ['optimizer_cfg.py', 'runtime_cfg.py']
+model = dict(type='ResNet', depth=50)
+optimizer = dict(lr=0.01)
+```
+
+读取这个配置文件之后,就可以得到期望的结果。
+
+```python
+cfg = Config.fromfile('resnet50_lr0.01.py')
+print(cfg.optimizer)
+```
+
+```
+{'type': 'SGD', 'lr': 0.01, 'momentum': 0.9, 'weight_decay': 0.0001}
+```
+
+对于非字典类型的字段,例如整数,字符串,列表等,重新定义即可完全覆盖,例如下面的写法就将 `gpu_ids` 这个字段的值修改成了 `[0]`。
+
+```python
+_base_ = ['optimizer_cfg.py', 'runtime_cfg.py']
+model = dict(type='ResNet', depth=50)
+gpu_ids = [0]
+```
+
+### 删除字典中的 key
+
+有时候我们对于继承过来的字典类型字段,不仅仅是想修改其中某些 key,可能还需要删除其中的一些 key。这时候在重新定义这个字典时,需要指定 `_delete_=True`,表示将没有在新定义的字典中出现的 key 全部删除。
+
+`resnet50_delete_key.py`:
+
+```python
+_base_ = ['optimizer_cfg.py', 'runtime_cfg.py']
+model = dict(type='ResNet', depth=50)
+optimizer = dict(_delete_=True, type='SGD', lr=0.01)
+```
+
+这时候,`optimizer` 这个字典中就只有 `type` 和 `lr` 这两个 key,`momentum` 和 `weight_decay` 将不再被继承。
+
+```python
+cfg = Config.fromfile('resnet50_delete_key.py')
+print(cfg.optimizer)
+```
+
+```
+{'type': 'SGD', 'lr': 0.01}
+```
+
+### 引用被继承文件中的变量
+
+有时我们想重复利用 `_base_` 中定义的字段内容,就可以通过 `{{_base_.xxxx}}` 获取来获取对应变量的拷贝。例如:
+
+`refer_base_var.py`
+
+```python
+_base_ = ['resnet50.py']
+a = {{_base_.model}}
+```
+
+解析后发现,`a` 的值变成了 `resnet50.py` 中定义的 `model`
+
+```python
+cfg = Config.fromfile('refer_base_var.py')
+print(cfg.a)
+```
+
+```
+{'type': 'ResNet', 'depth': 50}
+```
+
+我们可以在 `json`、`yaml`、`python` 三种类型的配置文件中,使用这种方式来获取 `_base_` 中定义的变量。
+
+尽管这种获取 `_base_` 中定义变量的方式非常通用,但是在语法上存在一些限制,无法充分利用 `python` 类配置文件的动态特性。比如我们想在 `python` 类配置文件中,修改 `_base_` 中定义的变量:
+
+```python
+_base_ = ['resnet50.py']
+a = {{_base_.model}}
+a['type'] = 'MobileNet'
+```
+
+配置类是无法解析这样的配置文件的(解析时报错)。配置类提供了一种更 `pythonic` 的方式,让我们能够在 `python` 类配置文件中修改 `_base_` 中定义的变量(`python` 类配置文件专属特性,目前不支持在 `json`、`yaml` 配置文件中修改 `_base_` 中定义的变量)。
+
+`modify_base_var.py`:
+
+```python
+_base_ = ['resnet50.py']
+a = _base_.model
+a.type = 'MobileNet'
+```
+
+```python
+cfg = Config.fromfile('modify_base_var.py')
+print(cfg.a)
+```
+
+```
+{'type': 'MobileNet', 'depth': 50}
+```
+
+解析后发现,`a` 的 type 变成了 `MobileNet`。
+
+## 配置文件的导出
+
+在启动训练脚本时,用户可能通过传参的方式来修改配置文件的部分字段,为此我们提供了 `dump` 接口来导出更改后的配置文件。与读取配置文件类似,用户可以通过 `cfg.dump('config.xxx')` 来选择导出文件的格式。`dump` 同样可以导出有继承关系的配置文件,导出的文件可以被独立使用,不再依赖于 `_base_` 中定义的文件。
+
+基于继承一节定义的 `resnet50.py`,我们将其加载后导出:
+
+```python
+cfg = Config.fromfile('resnet50.py')
+cfg.dump('resnet50_dump.py')
+```
+
+`resnet50_dump.py`
+
+```python
+optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)
+model = dict(type='ResNet', depth=50)
+```
+
+类似的,我们可以导出 json、yaml 格式的配置文件
+
+`resnet50_dump.yaml`
+
+```yaml
+model:
+ depth: 50
+ type: ResNet
+optimizer:
+ lr: 0.02
+ momentum: 0.9
+ type: SGD
+ weight_decay: 0.0001
+```
+
+`resnet50_dump.json`
+
+```json
+{"optimizer": {"type": "SGD", "lr": 0.02, "momentum": 0.9, "weight_decay": 0.0001}, "model": {"type": "ResNet", "depth": 50}}
+```
+
+此外,`dump` 不仅能导出加载自文件的 `cfg`,还能导出加载自字典的 `cfg`
+
+```python
+cfg = Config(dict(a=1, b=2))
+cfg.dump('dump_dict.py')
+```
+
+`dump_dict.py`
+
+```python
+a=1
+b=2
+```
+
+## 其他进阶用法
+
+这里介绍一下配置类的进阶用法,这些小技巧可能使用户开发和使用算法库更简单方便。
+
+### 预定义字段
+
+有时候我们希望配置文件中的一些字段和当前路径或者文件名等相关,这里举一个典型使用场景的例子。在训练模型时,我们会在配置文件中定义一个工作目录,存放这组实验配置的模型和日志,那么对于不同的配置文件,我们期望定义不同的工作目录。用户的一种常见选择是,直接使用配置文件名作为工作目录名的一部分,例如对于配置文件 `predefined_var.py`,工作目录就是 `./work_dir/predefined_var`。
+
+使用预定义字段可以方便地实现这种需求,在配置文件 `predefined_var.py` 中可以这样写:
+
+```Python
+work_dir = './work_dir/{{fileBasenameNoExtension}}'
+```
+
+这里 `{{fileBasenameNoExtension}}` 表示该配置文件的文件名(不含拓展名),在配置类读取配置文件的时候,会将这种用双花括号包起来的字符串自动解析为对应的实际值。
+
+```python
+cfg = Config.fromfile('./predefined_var.py')
+print(cfg.work_dir)
+```
+
+```
+./work_dir/predefined_var
+```
+
+目前支持的预定义字段有以下四种,变量名参考自 [VS Code](https://code.visualstudio.com/docs/editor/variables-reference) 中的相关字段:
+
+- `{{fileDirname}}` - 当前文件的目录名,例如 `/home/your-username/your-project/folder`
+- `{{fileBasename}}` - 当前文件的文件名,例如 `file.py`
+- `{{fileBasenameNoExtension}}` - 当前文件不包含扩展名的文件名,例如 `file`
+- `{{fileExtname}}` - 当前文件的扩展名,例如 `.py`
+
+### 命令行修改配置
+
+有时候我们只希望修改部分配置,而不想修改配置文件本身,例如实验过程中想更换学习率,但是又不想重新写一个配置文件,常用的做法是在命令行传入参数来覆盖相关配置。考虑到我们想修改的配置通常是一些内层参数,如优化器的学习率、模型卷积层的通道数等,因此 MMEngine 提供了一套标准的流程,让我们能够在命令行里轻松修改配置文件中任意层级的参数。
+
+1. 使用 `argparse` 解析脚本运行的参数
+2. 使用 `argparse.ArgumentParser.add_argument` 方法时,让 `action` 参数的值为 [DictAction](mmengine.config.DictAction),用它来进一步解析命令行参数中用于修改配置文件的参数
+3. 使用配置类的 `merge_from_dict` 方法来更新配置
+
+启动脚本示例如下:
+
+`demo_train.py`
+
+```python
+import argparse
+
+from mmengine.config import Config, DictAction
+
+
+def parse_args():
+ parser = argparse.ArgumentParser(description='Train a model')
+ parser.add_argument('config', help='train config file path')
+ parser.add_argument(
+ '--cfg-options',
+ nargs='+',
+ action=DictAction,
+ help='override some settings in the used config, the key-value pair '
+ 'in xxx=yyy format will be merged into config file. If the value to '
+ 'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
+ 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
+ 'Note that the quotation marks are necessary and that no white space '
+ 'is allowed.')
+
+ args = parser.parse_args()
+ return args
+
+
+def main():
+ args = parse_args()
+ cfg = Config.fromfile(args.config)
+ if args.cfg_options is not None:
+ cfg.merge_from_dict(args.cfg_options)
+ print(cfg)
+
+
+if __name__ == '__main__':
+ main()
+```
+
+示例配置文件如下:
+
+`example.py`
+
+```python
+model = dict(type='CustomModel', in_channels=[1, 2, 3])
+optimizer = dict(type='SGD', lr=0.01)
+```
+
+我们在命令行里通过 `.` 的方式来访问配置文件中的深层配置,例如我们想修改学习率,只需要在命令行执行:
+
+```bash
+python demo_train.py ./example.py --cfg-options optimizer.lr=0.1
+```
+
+```
+Config (path: ./example.py): {'model': {'type': 'CustomModel', 'in_channels': [1, 2, 3]}, 'optimizer': {'type': 'SGD', 'lr': 0.1}}
+```
+
+我们成功地把学习率从 0.01 修改成 0.1。如果想改变列表、元组类型的配置,如上例中的 `in_channels`,则需要在命令行赋值时给 `()`,`[]` 外加上双引号:
+
+```bash
+python demo_train.py ./example.py --cfg-options model.in_channels="[1, 1, 1]"
+```
+
+```
+Config (path: ./example.py): {'model': {'type': 'CustomModel', 'in_channels': [1, 1, 1]}, 'optimizer': {'type': 'SGD', 'lr': 0.01}}
+```
+
+`model.in_channels` 已经从 \[1, 2, 3\] 修改成 \[1, 1, 1\]。
+
+```{note}
+上述流程只支持在命令行里修改字符串、整型、浮点型、布尔型、None、列表、元组类型的配置项。对于列表、元组类型的配置,里面每个元素的类型也必须为上述七种类型之一。
+```
+
+:::{note}
+`DictAction` 的行为与 `"extend"` 相似,支持多次传递,并保存在同一个列表中。如
+
+```bash
+python demo_train.py ./example.py --cfg-options optimizer.type="Adam" --cfg-options model.in_channels="[1, 1, 1]"
+```
+
+```
+Config (path: ./example.py): {'model': {'type': 'CustomModel', 'in_channels': [1, 1, 1]}, 'optimizer': {'type': 'Adam', 'lr': 0.01}}
+```
+
+:::
+
+### 导入自定义 Python 模块
+
+将配置与注册器结合起来使用时,如果我们往注册器中注册了一些自定义的类,就可能会遇到一些问题。因为读取配置文件的时候,这部分代码可能还没有被执行到,所以并未完成注册过程,从而导致构建自定义类的时候报错。
+
+例如我们新实现了一种优化器 `CustomOptim`,相应代码在 `my_module.py` 中。
+
+```python
+from mmengine.registry import OPTIMIZERS
+
+@OPTIMIZERS.register_module()
+class CustomOptim:
+ pass
+```
+
+我们为这个优化器的使用写了一个新的配置文件 `custom_imports.py`:
+
+```python
+optimizer = dict(type='CustomOptim')
+```
+
+那么就需要在读取配置文件和构造优化器之前,增加一行 `import my_module` 来保证将自定义的类 `CustomOptim` 注册到 OPTIMIZERS 注册器中:为了解决这个问题,我们给配置文件定义了一个保留字段 `custom_imports`,用于将需要提前导入的 Python 模块,直接写在配置文件中。对于上述例子,就可以将配置文件写成如下:
+
+`custom_imports.py`
+
+```python
+custom_imports = dict(imports=['my_module'], allow_failed_imports=False)
+optimizer = dict(type='CustomOptim')
+```
+
+这样我们就不用在训练代码中增加对应的 import 语句,只需要修改配置文件就可以实现非侵入式导入自定义注册模块。
+
+```python
+cfg = Config.fromfile('custom_imports.py')
+
+from mmengine.registry import OPTIMIZERS
+
+custom_optim = OPTIMIZERS.build(cfg.optimizer)
+print(custom_optim)
+```
+
+```
+
+```
+
+### 跨项目继承配置文件
+
+为了避免基于已有算法库开发新项目时需要复制大量的配置文件,MMEngine 的配置类支持配置文件的跨项目继承。例如我们基于 MMDetection 开发新的算法库,需要使用以下 MMDetection 的配置文件:
+
+```text
+configs/_base_/schedules/schedule_1x.py
+configs/_base_/datasets.coco_instance.py
+configs/_base_/default_runtime.py
+configs/_base_/models/faster-rcnn_r50_fpn.py
+```
+
+如果没有配置文件跨项目继承的功能,我们就需要把 MMDetection 的配置文件拷贝到当前项目,而我们现在只需要安装 MMDetection(如使用 `mim install mmdet`),在新项目的配置文件中按照以下方式继承 MMDetection 的配置文件:
+
+`cross_repo.py`
+
+```python
+_base_ = [
+ 'mmdet::_base_/schedules/schedule_1x.py',
+ 'mmdet::_base_/datasets/coco_instance.py',
+ 'mmdet::_base_/default_runtime.py',
+ 'mmdet::_base_/models/faster-rcnn_r50_fpn.py',
+]
+```
+
+我们可以像加载普通配置文件一样加载 `cross_repo.py`
+
+```python
+cfg = Config.fromfile('cross_repo.py')
+print(cfg.train_cfg)
+```
+
+```
+{'type': 'EpochBasedTrainLoop', 'max_epochs': 12, 'val_interval': 1, '_scope_': 'mmdet'}
+```
+
+通过指定 `mmdet::`,Config 类会去检索 mmdet 包中的配置文件目录,并继承指定的配置文件。实际上,只要算法库的 `setup.py` 文件符合 [MMEngine 安装规范](todo),在正确安装算法库以后,新的项目就可以使用上述用法去继承已有算法库的配置文件而无需拷贝。
+
+### 跨项目获取配置文件
+
+MMEngine 还提供了 `get_config` 和 `get_model` 两个接口,支持对符合 [MMEngine 安装规范](todo) 的算法库中的模型和配置文件做索引并进行 API 调用。通过 `get_model` 接口可以获得构建好的模型。通过 `get_config` 接口可以获得配置文件。
+
+`get_model` 的使用样例如下所示,使用和跨项目继承配置文件相同的语法,指定 `mmdet::`,即可在 mmdet 包中检索对应的配置文件并构建和初始化相应模型。用户可以通过指定 `pretrained=True` 获得已经加载预训练权重的模型以进行训练或者推理。
+
+```python
+from mmengine.hub import get_model
+
+model = get_model(
+ 'mmdet::faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py', pretrained=True)
+print(type(model))
+```
+
+```
+http loads checkpoint from path: https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth
+
+```
+
+`get_config` 的使用样例如下所示,使用和跨项目继承配置文件相同的语法,指定 `mmdet::`,即可实现去 mmdet 包中检索并加载对应的配置文件。用户可以基于这样得到的配置文件进行推理修改并自定义自己的算法模型。同时,如果用户指定 `pretrained=True`,得到的配置文件中会新增 `model_path` 字段,指定了对应模型预训练权重的路径。
+
+```python
+from mmengine.hub import get_config
+
+cfg = get_config(
+ 'mmdet::faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py', pretrained=True)
+print(cfg.model_path)
+
+```
+
+```
+https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth
+```
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/cross_library.md b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/cross_library.md
new file mode 100644
index 0000000000000000000000000000000000000000..4460d59eebb5e20c8269ea4ba557656a9949a93e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/cross_library.md
@@ -0,0 +1,94 @@
+# 跨库调用模块
+
+通过使用 MMEngine 的[注册器(Registry)](registry.md)和[配置文件(Config)](config.md),用户可以实现跨软件包的模块构建。
+例如,在 [MMDetection](https://github.com/open-mmlab/mmdetection) 中使用 [MMClassification](https://github.com/open-mmlab/mmclassification) 的 Backbone,或者在 [MMRotate](https://github.com/open-mmlab/mmrotate) 中使用 [MMDetection](https://github.com/open-mmlab/mmdetection) 的 Transform,或者在 [MMTracking](https://github.com/open-mmlab/mmtracking) 中使用 [MMDetection](https://github.com/open-mmlab/mmdetection) 的 Detector。
+一般来说,同类模块都可以进行跨库调用,只需要在配置文件的模块类型前加上软件包名的前缀即可。下面举几个常见的例子:
+
+## 跨库调用 Backbone:
+
+以在 MMDetection 中调用 MMClassification 的 ConvNeXt 为例,首先需要在配置中加入 `custom_imports` 字段将 MMClassification 的 Backbone 添加进注册器,然后只需要在 Backbone 的配置中的 `type` 加上 MMClassification 的软件包名 `mmcls` 作为前缀,即 `mmcls.ConvNeXt` 即可:
+
+```python
+# 使用 custom_imports 将 mmcls 的 models 添加进注册器
+custom_imports = dict(imports=['mmcls.models'], allow_failed_imports=False)
+
+model = dict(
+ type='MaskRCNN',
+ data_preprocessor=dict(...),
+ backbone=dict(
+ type='mmcls.ConvNeXt', # 添加 mmcls 前缀完成跨库调用
+ arch='tiny',
+ out_indices=[0, 1, 2, 3],
+ drop_path_rate=0.4,
+ layer_scale_init_value=1.0,
+ gap_before_final_norm=False,
+ init_cfg=dict(
+ type='Pretrained',
+ checkpoint=
+ 'https://download.openmmlab.com/mmclassification/v0/convnext/downstream/convnext-tiny_3rdparty_32xb128-noema_in1k_20220301-795e9634.pth',
+ prefix='backbone.')),
+ neck=dict(...),
+ rpn_head=dict(...))
+```
+
+## 跨库调用 Transform:
+
+与上文的跨库调用 Backbone 一样,使用 custom_imports 和添加前缀即可实现跨库调用:
+
+```python
+# 使用 custom_imports 将 mmdet 的 transforms 添加进注册器
+custom_imports = dict(imports=['mmdet.datasets.transforms'], allow_failed_imports=False)
+
+# 添加 mmdet 前缀完成跨库调用
+train_pipeline=[
+ dict(type='mmdet.LoadImageFromFile'),
+ dict(type='mmdet.LoadAnnotations', with_bbox=True, box_type='qbox'),
+ dict(type='ConvertBoxType', box_type_mapping=dict(gt_bboxes='rbox')),
+ dict(type='mmdet.Resize', scale=(1024, 2014), keep_ratio=True),
+ dict(type='mmdet.RandomFlip', prob=0.5),
+ dict(type='mmdet.PackDetInputs')
+]
+```
+
+## 跨库调用 Detector:
+
+跨库调用算法是一个比较复杂的例子,一个算法会包含多个子模块,因此每个子模块也需要在`type`中增加前缀,以在 MMTracking 中调用 MMDetection 的 YOLOX 为例:
+
+```python
+# 使用 custom_imports 将 mmdet 的 models 添加进注册器
+custom_imports = dict(imports=['mmdet.models'], allow_failed_imports=False)
+model = dict(
+ type='mmdet.YOLOX',
+ backbone=dict(type='mmdet.CSPDarknet', deepen_factor=1.33, widen_factor=1.25),
+ neck=dict(
+ type='mmdet.YOLOXPAFPN',
+ in_channels=[320, 640, 1280],
+ out_channels=320,
+ num_csp_blocks=4),
+ bbox_head=dict(
+ type='mmdet.YOLOXHead', num_classes=1, in_channels=320, feat_channels=320),
+ train_cfg=dict(assigner=dict(type='mmdet.SimOTAAssigner', center_radius=2.5)))
+```
+
+为了避免给每个子模块手动增加前缀,配置文件中引入了 `_scope_` 关键字,当某一模块的配置中添加了 `_scope_` 关键字后,该模块配置文件下面的所有子模块配置都会从该关键字所对应的软件包内去构建:
+
+```python
+# 使用 custom_imports 将 mmdet 的 models 添加进注册器
+custom_imports = dict(imports=['mmdet.models'], allow_failed_imports=False)
+model = dict(
+ _scope_='mmdet', # 使用 _scope_ 关键字,避免给所有子模块添加前缀
+ type='YOLOX',
+ backbone=dict(type='CSPDarknet', deepen_factor=1.33, widen_factor=1.25),
+ neck=dict(
+ type='YOLOXPAFPN',
+ in_channels=[320, 640, 1280],
+ out_channels=320,
+ num_csp_blocks=4),
+ bbox_head=dict(
+ type='YOLOXHead', num_classes=1, in_channels=320, feat_channels=320),
+ train_cfg=dict(assigner=dict(type='SimOTAAssigner', center_radius=2.5)))
+```
+
+以上这两种写法互相等价。
+
+若希望了解更多关于注册器和配置文件的内容,请参考[配置文件教程](config.md)和[注册器教程](registry.md)
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/data_element.md b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/data_element.md
new file mode 100644
index 0000000000000000000000000000000000000000..6796c24b8906e103285db74700446eb368fa859c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/data_element.md
@@ -0,0 +1,1097 @@
+# 抽象数据接口
+
+在模型的训练/测试过程中,组件之间往往有大量的数据需要传递,不同的算法需要传递的数据经常是不一样的,例如,训练单阶段检测器需要获得数据集的标注框(ground truth bounding boxes)和标签(ground truth box labels),训练 Mask R-CNN 时还需要实例掩码(instance masks)。
+训练这些模型时的代码如下所示
+
+```python
+for img, img_metas, gt_bboxes, gt_labels in data_loader:
+ loss = retinanet(img, img_metas, gt_bboxes, gt_labels)
+```
+
+```python
+for img, img_metas, gt_bboxes, gt_masks, gt_labels in data_loader:
+ loss = mask_rcnn(img, img_metas, gt_bboxes, gt_masks, gt_labels)
+```
+
+可以发现,在不加封装的情况下,不同算法所需数据的不一致导致了不同算法模块之间接口的不一致,影响了算法库的拓展性,同时一个算法库内的模块为了保持兼容性往往在接口上存在冗余。
+上述弊端在算法库之间会体现地更加明显,导致在实现多任务(同时进行如语义分割、检测、关键点检测等多个任务)感知模型时模块难以复用,接口难以拓展。
+
+为了解决上述问题,MMEngine 定义了一套抽象的数据接口来封装模型运行过程中的各种数据。假设将上述不同的数据封装进 `data_sample` ,不同算法的训练都可以被抽象和统一成如下代码
+
+```python
+for img, data_sample in dataloader:
+ loss = model(img, data_sample)
+```
+
+通过对各种数据提供统一的封装,抽象数据接口统一并简化了算法库中各个模块的接口,可以被用于算法库中 dataset,model,visualizer,和 evaluator 组件之间,或者 model 内各个模块之间的数据传递。
+抽象数据接口实现了基本的增/删/改/查功能,同时支持不同设备之间的迁移,支持类字典和张量的操作,可以充分满足算法库对于这些数据的使用要求。
+基于 MMEngine 的算法库可以继承这套抽象数据接口并实现自己的抽象数据接口来适应不同算法中数据的特点与实际需要,在保持统一接口的同时提高了算法模块的拓展性。
+
+在实际实现过程中,算法库中的各个组件所具备的数据接口,一般为如下两个种:
+
+- 一个训练或测试样本(例如一张图像)的所有的标注信息和预测信息的集合,例如数据集的输出、模型以及可视化器的输入一般为单个训练或测试样本的所有信息。MMEngine将其定义为数据样本(DataSample)
+- 单一类型的预测或标注,一般是算法模型中某个子模块的输出, 例如二阶段检测中RPN的输出、语义分割模型的输出、关键点分支的输出, GAN中生成器的输出等。MMengine将其定义为数据元素(XXXData)
+
+下边首先介绍一下数据样本与数据元素的基类 [BaseDataElement](mmengine.structures.BaseDataElement)。
+
+## 数据基类(BaseDataElement)
+
+`BaseDataElement` 中存在两种类型的数据,一种是 `data` 类型,如标注框、框的标签、和实例掩码等;另一种是 `metainfo` 类型,包含数据的元信息以确保数据的完整性,如 `img_shape`, `img_id` 等数据所在图片的一些基本信息,方便可视化等情况下对数据进行恢复和使用。用户在创建 `BaseDataElement` 的过程中需要对这两类属性的数据进行显式地区分和声明。
+
+为了能够更加方便地使用 `BaseDataElement`,`data` 和 `metainfo` 中的数据均为 `BaseDataElement` 的属性。我们可以通过访问类属性的方式直接访问 `data` 和 `metainfo` 中的数据。此外,`BaseDataElement` 还提供了很多方法,方便我们操作 `data` 内的数据:
+
+- 增/删/改/查 `data` 中不同字段的数据
+- 将 `data` 迁移至目标设备
+- 支持像访问字典/张量一样访问 data 内的数据
+ 以充分满足算法库对于这些数据的使用要求。
+
+### 1. 数据元素的创建
+
+`BaseDataElement` 的 data 参数可以直接通过 `key=value` 的方式自由添加,metainfo 的字段需要显式通过关键字 `metainfo` 指定。
+
+```python
+import torch
+from mmengine.structures import BaseDataElement
+# 可以声明一个空的 object
+data_element = BaseDataElement()
+
+bboxes = torch.rand((5, 4)) # 假定 bboxes 是一个 Nx4 维的 tensor,N 代表框的个数
+scores = torch.rand((5,)) # 假定框的分数是一个 N 维的 tensor,N 代表框的个数
+img_id = 0 # 图像的 ID
+H = 800 # 图像的高度
+W = 1333 # 图像的宽度
+
+# 直接设置 BaseDataElement 的 data 参数
+data_element = BaseDataElement(bboxes=bboxes, scores=scores)
+
+# 显式声明来设置 BaseDataElement 的参数 metainfo
+data_element = BaseDataElement(
+ bboxes=bboxes,
+ scores=scores,
+ metainfo=dict(img_id=img_id, img_shape=(H, W)))
+```
+
+### 2. `new` 与 `clone` 函数
+
+用户可以使用 `new()` 函数通过已有的数据接口创建一个具有相同状态和数据的抽象数据接口。用户可以在创建新 `BaseDataElement` 时设置 `metainfo` 和 `data`,用于创建仅 `data` 或 `metainfo` 具有相同状态和数据的抽象接口。比如 `new(metainfo=xx)` 使得新的 `BaseDataElement` 与被 clone 的 `BaseDataElement` 包含相同的 `data` 内容,但 `metainfo` 为新设置的内容。
+也可以直接使用 `clone()` 来获得一份深拷贝,`clone()` 函数的行为与 PyTorch 中 Tensor 的 `clone()` 参数保持一致。
+
+```python
+data_element = BaseDataElement(
+ bboxes=torch.rand((5, 4)),
+ scores=torch.rand((5,)),
+ metainfo=dict(img_id=1, img_shape=(640, 640)))
+
+# 可以在创建新 `BaseDataElement` 时设置 metainfo 和 data,使得新的 BaseDataElement 有相同未被设置的数据
+data_element1 = data_element.new(metainfo=dict(img_id=2, img_shape=(320, 320)))
+print('bboxes is in data_element1:', 'bboxes' in data_element1) # True
+print('bboxes in data_element1 is same as bbox in data_element', (data_element1.bboxes == data_element.bboxes).all())
+print('img_id in data_element1 is', data_element1.img_id == 2) # True
+
+data_element2 = data_element.new(label=torch.rand(5,))
+print('bboxes is not in data_element2', 'bboxes' not in data_element2) # True
+print('img_id in data_element2 is same as img_id in data_element', data_element2.img_id == data_element.img_id)
+print('label in data_element2 is', 'label' in data_element2)
+
+# 也可以通过 `clone` 构建一个新的 object,新的 object 会拥有和 data_element 相同的 data 和 metainfo 内容以及状态。
+data_element2 = data_element1.clone()
+```
+
+```
+bboxes is in data_element1: True
+bboxes in data_element1 is same as bbox in data_element tensor(True)
+img_id in data_element1 is True
+bboxes is not in data_element2 True
+img_id in data_element2 is same as img_id in data_element True
+label in data_element2 is True
+```
+
+### 3. 属性的增加与查询
+
+对增加属性而言,用户可以像增加类属性那样增加 `data` 内的属性;对`metainfo` 而言,一般储存的为一些图像的元信息,一般情况下不会修改,如果需要增加,用户应当使用 `set_metainfo` 接口显示地修改。
+
+对查询而言,用户可以可以通过 `keys`,`values`,和 `items` 来访问只存在于 data 中的键值,也可以通过 `metainfo_keys`,`metainfo_values`,和`metainfo_items` 来访问只存在于 metainfo 中的键值。
+用户还能通过 `all_keys`,`all_values`, `all_items` 来访问 `BaseDataElement` 的所有的属性并且不区分他们的类型。
+
+同时为了方便使用,用户可以像访问类属性一样访问 data 与 metainfo 内的数据,或着类字典方式通过 `get()` 接口访问数据。
+
+**注意:**
+
+1. `BaseDataElement` 不支持 metainfo 和 data 属性中有同名的字段,所以用户应当避免 metainfo 和 data 属性中设置相同的字段,否则 `BaseDataElement` 会报错。
+2. 考虑到 `InstanceData` 和 `PixelData` 支持对数据进行切片操作,为了避免 `[]` 用法的不一致,同时减少同种需求的不同方法,`BaseDataElement` 不支持像字典那样访问和设置它的属性,所以类似 `BaseDataElement[name]` 的取值赋值操作是不被支持的。
+
+```python
+data_element = BaseDataElement()
+# 通过 `set_metainfo`设置 data_element 的 metainfo 字段,
+# 同时 img_id 和 img_shape 成为 data_element 的属性
+data_element.set_metainfo(dict(img_id=9, img_shape=(100, 100)))
+# 查看 metainfo 的 key, value 和 item
+print("metainfo'keys are", data_element.metainfo_keys())
+print("metainfo'values are", data_element.metainfo_values())
+for k, v in data_element.metainfo_items():
+ print(f'{k}: {v}')
+
+print("通过类属性查看 img_id 和 img_shape")
+print('img_id:', data_element.img_id)
+print('img_shape:', data_element.img_shape)
+```
+
+```
+metainfo'keys are ['img_id', 'img_shape']
+metainfo'values are [9, (100, 100)]
+img_id: 9
+img_shape: (100, 100)
+通过类属性查看 img_id 和 img_shape
+img_id: 9
+img_shape: (100, 100)
+```
+
+```python
+
+# 通过类属性直接设置 BaseDataElement 中的 data 字段
+data_element.scores = torch.rand((5,))
+data_element.bboxes = torch.rand((5, 4))
+
+print("data's key is:", data_element.keys())
+print("data's value is:", data_element.values())
+for k, v in data_element.items():
+ print(f'{k}: {v}')
+
+print("通过类属性查看 scores 和 bboxes")
+print('scores:', data_element.scores)
+print('bboxes:', data_element.bboxes)
+
+print("通过 get() 查看 scores 和 bboxes")
+print('scores:', data_element.get('scores', None))
+print('bboxes:', data_element.get('bboxes', None))
+print('fake:', data_element.get('fake', 'not exist'))
+```
+
+```
+data's key is: ['scores', 'bboxes']
+data's value is: [tensor([0.7937, 0.6307, 0.3682, 0.4425, 0.8515]), tensor([[0.9204, 0.2110, 0.2886, 0.7925],
+ [0.7993, 0.8982, 0.5698, 0.4120],
+ [0.7085, 0.7016, 0.3069, 0.3216],
+ [0.0206, 0.5253, 0.1376, 0.9322],
+ [0.2512, 0.7683, 0.3010, 0.2672]])]
+scores: tensor([0.7937, 0.6307, 0.3682, 0.4425, 0.8515])
+bboxes: tensor([[0.9204, 0.2110, 0.2886, 0.7925],
+ [0.7993, 0.8982, 0.5698, 0.4120],
+ [0.7085, 0.7016, 0.3069, 0.3216],
+ [0.0206, 0.5253, 0.1376, 0.9322],
+ [0.2512, 0.7683, 0.3010, 0.2672]])
+通过类属性查看 scores 和 bboxes
+scores: tensor([0.7937, 0.6307, 0.3682, 0.4425, 0.8515])
+bboxes: tensor([[0.9204, 0.2110, 0.2886, 0.7925],
+ [0.7993, 0.8982, 0.5698, 0.4120],
+ [0.7085, 0.7016, 0.3069, 0.3216],
+ [0.0206, 0.5253, 0.1376, 0.9322],
+ [0.2512, 0.7683, 0.3010, 0.2672]])
+通过 get() 查看 scores 和 bboxes
+scores: tensor([0.7937, 0.6307, 0.3682, 0.4425, 0.8515])
+bboxes: tensor([[0.9204, 0.2110, 0.2886, 0.7925],
+ [0.7993, 0.8982, 0.5698, 0.4120],
+ [0.7085, 0.7016, 0.3069, 0.3216],
+ [0.0206, 0.5253, 0.1376, 0.9322],
+ [0.2512, 0.7683, 0.3010, 0.2672]])
+fake: not exist
+```
+
+```python
+
+print("All key in data_element is:", data_element.all_keys())
+print("The length of values in data_element is", len(data_element.all_values()))
+for k, v in data_element.all_items():
+ print(f'{k}: {v}')
+```
+
+```
+All key in data_element is: ['img_id', 'img_shape', 'scores', 'bboxes']
+The length of values in data_element is 4
+img_id: 9
+img_shape: (100, 100)
+scores: tensor([0.7937, 0.6307, 0.3682, 0.4425, 0.8515])
+bboxes: tensor([[0.9204, 0.2110, 0.2886, 0.7925],
+ [0.7993, 0.8982, 0.5698, 0.4120],
+ [0.7085, 0.7016, 0.3069, 0.3216],
+ [0.0206, 0.5253, 0.1376, 0.9322],
+ [0.2512, 0.7683, 0.3010, 0.2672]])
+```
+
+### 4. 属性的删改
+
+用户可以像修改实例属性一样修改 `BaseDataElement` 的 `data`, 对`metainfo` 而言 一般储存的为一些图像的元信息,一般情况下不会修改,如果需要修改,用户应当使用 `set_metainfo` 接口显示的修改。
+
+同时为了操作的便捷性,对 `data` 和 `metainfo` 中的数据可以通过 `del` 直接删除,也支持 `pop` 在访问属性后删除属性。
+
+```python
+data_element = BaseDataElement(
+ bboxes=torch.rand((6, 4)), scores=torch.rand((6,)),
+ metainfo=dict(img_id=0, img_shape=(640, 640))
+)
+for k, v in data_element.all_items():
+ print(f'{k}: {v}')
+```
+
+```
+img_id: 0
+img_shape: (640, 640)
+scores: tensor([0.8445, 0.6678, 0.8172, 0.9125, 0.7186, 0.5462])
+bboxes: tensor([[0.5773, 0.0289, 0.4793, 0.7573],
+ [0.8187, 0.8176, 0.3455, 0.3368],
+ [0.6947, 0.5592, 0.7285, 0.0281],
+ [0.7710, 0.9867, 0.7172, 0.5815],
+ [0.3999, 0.9192, 0.7817, 0.2535],
+ [0.2433, 0.0132, 0.1757, 0.6196]])
+```
+
+```python
+# 对 data 进行修改
+data_element.bboxes = data_element.bboxes * 2
+data_element.scores = data_element.scores * -1
+for k, v in data_element.items():
+ print(f'{k}: {v}')
+
+# 删除 data 中的属性
+del data_element.bboxes
+for k, v in data_element.items():
+ print(f'{k}: {v}')
+
+data_element.pop('scores', None)
+print('The keys in data is', data_element.keys())
+```
+
+```
+scores: tensor([-0.8445, -0.6678, -0.8172, -0.9125, -0.7186, -0.5462])
+bboxes: tensor([[1.1546, 0.0578, 0.9586, 1.5146],
+ [1.6374, 1.6352, 0.6911, 0.6735],
+ [1.3893, 1.1185, 1.4569, 0.0562],
+ [1.5420, 1.9734, 1.4344, 1.1630],
+ [0.7999, 1.8384, 1.5635, 0.5070],
+ [0.4867, 0.0264, 0.3514, 1.2392]])
+scores: tensor([-0.8445, -0.6678, -0.8172, -0.9125, -0.7186, -0.5462])
+The keys in data is []
+```
+
+```python
+# 对 metainfo 进行修改
+data_element.set_metainfo(dict(img_shape = (1280, 1280), img_id=10))
+print(data_element.img_shape) # (1280, 1280)
+for k, v in data_element.metainfo_items():
+ print(f'{k}: {v}')
+
+# 提供了便捷的属性删除和访问操作 pop
+del data_element.img_shape
+for k, v in data_element.metainfo_items():
+ print(f'{k}: {v}')
+
+data_element.pop('img_id')
+print('The keys in metainfo is', data_element.metainfo_keys())
+```
+
+```
+(1280, 1280)
+img_id: 10
+img_shape: (1280, 1280)
+img_id: 10
+The keys in metainfo is []
+```
+
+### 5. 类张量操作
+
+用户可以像 torch.Tensor 那样对 `BaseDataElement` 的 data 进行状态转换,目前支持 `cuda`, `cpu`, `to`, `numpy` 等操作。
+其中,`to` 函数拥有和 `torch.Tensor.to()` 相同的接口,使得用户可以灵活地将被封装的 tensor 进行状态转换。
+**注意:** 这些接口只会处理类型为 np.array,torch.Tensor,或者数字的序列,其他属性的数据(如字符串)会被跳过处理。
+
+```python
+data_element = BaseDataElement(
+ bboxes=torch.rand((6, 4)), scores=torch.rand((6,)),
+ metainfo=dict(img_id=0, img_shape=(640, 640))
+)
+# 将所有 data 转移到 GPU 上
+cuda_element_1 = data_element.cuda()
+print('cuda_element_1 is on the device of', cuda_element_1.bboxes.device) # cuda:0
+cuda_element_2 = data_element.to('cuda:0')
+print('cuda_element_1 is on the device of', cuda_element_2.bboxes.device) # cuda:0
+
+# 将所有 data 转移到 cpu 上
+cpu_element_1 = cuda_element_1.cpu()
+print('cpu_element_1 is on the device of', cpu_element_1.bboxes.device) # cpu
+cpu_element_2 = cuda_element_2.to('cpu')
+print('cpu_element_2 is on the device of', cpu_element_2.bboxes.device) # cpu
+
+# 将所有 data 变成 FP16
+fp16_instances = cuda_element_1.to(
+ device=None, dtype=torch.float16, non_blocking=False, copy=False,
+ memory_format=torch.preserve_format)
+print('The type of bboxes in fp16_instances is', fp16_instances.bboxes.dtype) # torch.float16
+
+# 阻断所有 data 的梯度
+cuda_element_3 = cuda_element_2.detach()
+print('The data in cuda_element_3 requires grad: ', cuda_element_3.bboxes.requires_grad)
+# 转移 data 到 numpy array
+np_instances = cpu_element_1.numpy()
+print('The type of cpu_element_1 is convert to', type(np_instances.bboxes))
+```
+
+```
+cuda_element_1 is on the device of cuda:0
+cuda_element_1 is on the device of cuda:0
+cpu_element_1 is on the device of cpu
+cpu_element_2 is on the device of cpu
+The type of bboxes in fp16_instances is torch.float16
+The data in cuda_element_3 requires grad: False
+The type of cpu_element_1 is convert to
+```
+
+### 6. 属性的展示
+
+`BaseDataElement` 还实现了 `__repr__`,因此,用户可以直接通过 `print` 函数看到其中的所有数据信息。
+同时,为了便捷开发者 debug,`BaseDataElement` 中的属性都会添加进 `__dict__` 中,方便用户在 IDE 界面可以直观看到 `BaseDataElement` 中的内容。
+一个完整的属性展示如下
+
+```python
+img_meta = dict(img_shape=(800, 1196, 3), pad_shape=(800, 1216, 3))
+instance_data = BaseDataElement(metainfo=img_meta)
+instance_data.det_labels = torch.LongTensor([0, 1, 2, 3])
+instance_data.det_scores = torch.Tensor([0.01, 0.1, 0.2, 0.3])
+print(instance_data)
+```
+
+```
+
+```
+
+## 数据元素(xxxData)
+
+MMEngine 将数据元素情况划分为三个类别:
+
+- 实例数据(InstanceData): 主要针对的是上层任务(high-level)中,对图像中所有实例相关的数据进行封装,比如检测框(bounding boxes), 物体类别(box labels),实例掩码(instance masks), 关键点(key points), 文字边界(polygons), 跟踪id(tracking ids) 等. 所有实例相关的数据的**长度一致**,均为图像中实例的个数。
+- 像素数据(PixelData): 主要针对底层任务(low-level) 以及需要感知像素级别标签的部分上层任务。像素数据对像素级相关的数据进行封装,比如语义分割中的分割图(segmentation map), 光流任务中的光流图(flow map), 全景分割中的全景分割图(panoptic seg map);底层任务中生成的各种图像,比如超分辨图,去噪图,以及生成的各种风格图。这些数据的特点是都是三维或四维数组,最后两维度为数据的高度(height)和宽度(width),且具有相同的height和width
+- 标签数据(LabelData): 主要标签级别的数据进行封装,比如图像分类,多分类中的类别,图像生成中生成图像的类别内容,或者文字识别中的文本等。
+
+### InstanceData
+
+[`InstanceData`](mmengine.structures.InstanceData) 在 `BaseDataElement` 的基础上,对 `data` 存储的数据做了限制,即要求存储在 `data` 中的数据的长度一致。比如在目标检测中, 假设一张图像中有 N 个目标(instance),可以将图像的所有边界框(bbox),类别(label)等存储在 `InstanceData` 中, `InstanceData` 的 bbox 和 label 的长度相同。
+基于上述假定对 `InstanceData`进行了扩展,包括:
+
+- 对 `InstanceData` 中 data 所存储的数据进行了长度校验
+- data 部分支持类字典访问和设置它的属性
+- 支持基础索引,切片以及高级索引功能
+- 支持具有**相同的 `key`** 但是不同 `InstanceData` 的拼接功能。
+ 这些扩展功能除了支持基础的数据结构, 比如`torch.tensor`, `numpy.dnarray`, `list`, `str`, `tuple`, 也可以是自定义的数据结构,只要自定义数据结构实现了 `__len__`, `__getitem__` and `cat`.
+
+#### 数据校验
+
+`InstanceData` 中 data 的数据长度要保持一致,如果传入不同长度的新数据,将会报错。
+
+```python
+from mmengine.structures import InstanceData
+import torch
+import numpy as np
+
+img_meta = dict(img_shape=(800, 1196, 3), pad_shape=(800, 1216, 3))
+instance_data = InstanceData(metainfo=img_meta)
+instance_data.det_labels = torch.LongTensor([2, 3])
+instance_data.det_scores = torch.Tensor([0.8, 0.7])
+instance_data.bboxes = torch.rand((2, 4))
+print('The length of instance_data is', len(instance_data)) # 2
+
+instance_data.bboxes = torch.rand((3, 4))
+```
+
+```
+The length of instance_data is 2
+AssertionError: the length of values 3 is not consistent with the length of this :obj:`InstanceData` 2
+```
+
+### 类字典访问和设置属性
+
+`InstanceData` 支持类似字典的操作访问和设置其 **data** 属性。
+
+```python
+img_meta = dict(img_shape=(800, 1196, 3), pad_shape=(800, 1216, 3))
+instance_data = InstanceData(metainfo=img_meta)
+instance_data["det_labels"] = torch.LongTensor([2, 3])
+instance_data["det_scores"] = torch.Tensor([0.8, 0.7])
+instance_data.bboxes = torch.rand((2, 4))
+print(instance_data)
+```
+
+```
+
+```
+
+#### 索引与切片
+
+`InstanceData` 支持 Python 中类似列表的索引与切片,同时也支持类似 numpy 的高级索引操作。
+
+```python
+img_meta = dict(img_shape=(800, 1196, 3), pad_shape=(800, 1216, 3))
+instance_data = InstanceData(metainfo=img_meta)
+instance_data.det_labels = torch.LongTensor([2, 3])
+instance_data.det_scores = torch.Tensor([0.8, 0.7])
+instance_data.bboxes = torch.rand((2, 4))
+print(instance_data)
+```
+
+```
+
+```
+
+1. 索引
+
+```python
+print(instance_data[1])
+```
+
+```
+
+```
+
+2. 切片
+
+```python
+print(instance_data[0:1])
+```
+
+```
+
+```
+
+3. 高级索引
+
+- 列表索引
+
+```python
+sorted_results = instance_data[instance_data.det_scores.sort().indices]
+print(sorted_results)
+```
+
+```
+
+```
+
+- 布尔索引
+
+```python
+filter_results = instance_data[instance_data.det_scores > 0.75]
+print(filter_results)
+```
+
+```
+
+```
+
+4. 结果为空
+
+```python
+empty_results = instance_data[instance_data.det_scores > 1]
+print(empty_results)
+```
+
+```
+
+```
+
+#### 拼接(cat)
+
+用户可以将两个具有相同 key 的 `InstanceData` 拼接成一个 `InstanceData`。对于长度分别为 N 和 M 的两个 `InstanceData`, 拼接后为长度 N + M 的新的 `InstanceData`
+
+```python
+img_meta = dict(img_shape=(800, 1196, 3), pad_shape=(800, 1216, 3))
+instance_data = InstanceData(metainfo=img_meta)
+instance_data.det_labels = torch.LongTensor([2, 3])
+instance_data.det_scores = torch.Tensor([0.8, 0.7])
+instance_data.bboxes = torch.rand((2, 4))
+print('The length of instance_data is', len(instance_data))
+cat_results = InstanceData.cat([instance_data, instance_data])
+print('The length of instance_data is', len(cat_results))
+print(cat_results)
+```
+
+```
+The length of instance_data is 2
+The length of instance_data is 4
+
+```
+
+#### 自定义数据结构
+
+对于自定义结构如果想使用上述扩展要求需要实现`__len__`, `__getitem__` 和 `cat`三个接口.
+
+```python
+import itertools
+
+class TmpObject:
+ def __init__(self, tmp) -> None:
+ assert isinstance(tmp, list)
+ self.tmp = tmp
+
+ def __len__(self):
+ return len(self.tmp)
+
+ def __getitem__(self, item):
+ if type(item) == int:
+ if item >= len(self) or item < -len(self): # type:ignore
+ raise IndexError(f'Index {item} out of range!')
+ else:
+ # keep the dimension
+ item = slice(item, None, len(self))
+ return TmpObject(self.tmp[item])
+
+ @staticmethod
+ def cat(tmp_objs):
+ assert all(isinstance(results, TmpObject) for results in tmp_objs)
+ if len(tmp_objs) == 1:
+ return tmp_objs[0]
+ tmp_list = [tmp_obj.tmp for tmp_obj in tmp_objs]
+ tmp_list = list(itertools.chain(*tmp_list))
+ new_data = TmpObject(tmp_list)
+ return new_data
+
+ def __repr__(self):
+ return str(self.tmp)
+```
+
+```python
+img_meta = dict(img_shape=(800, 1196, 3), pad_shape=(800, 1216, 3))
+instance_data = InstanceData(metainfo=img_meta)
+instance_data.det_labels = torch.LongTensor([2, 3])
+instance_data["det_scores"] = torch.Tensor([0.8, 0.7])
+instance_data.bboxes = torch.rand((2, 4))
+instance_data.polygons = TmpObject([[1, 2, 3, 4], [5, 6, 7, 8]])
+print(instance_data)
+```
+
+```
+
+```
+
+```python
+# 高级索引
+print(instance_data[instance_data.det_scores > 0.75])
+```
+
+```
+
+```
+
+```python
+# 拼接
+print(InstanceData.cat([instance_data, instance_data]))
+```
+
+```
+
+```
+
+### PixelData
+
+[`PixelData`](mmengine.structures.PixelData) 在 `BaseDataElement` 的基础上,同样对对 data 中存储的数据做了限制:
+
+- 所有 data 内的数据均为 3 维,并且顺序为 (通道,高, 宽)
+- 所有在 data 内的数据要有相同的长和宽
+ 基于上述假定对 `PixelData`进行了扩展,包括:
+- 对 `PixelData` 中 data 所存储的数据进行了尺寸的校验
+- 支持对 data 部分的数据对实例进行空间维度的索引和切片。
+
+### 数据校验
+
+`PixelData` 会对传入到 data 的数据进行维度与长宽的校验。
+
+```python
+from mmengine.structures import PixelData
+import random
+import torch
+import numpy as np
+metainfo = dict(
+ img_id=random.randint(0, 100),
+ img_shape=(random.randint(400, 600), random.randint(400, 600)))
+image = np.random.randint(0, 255, (4, 20, 40))
+featmap = torch.randint(0, 255, (10, 20, 40))
+pixel_data = PixelData(metainfo=metainfo,
+ image=image,
+ featmap=featmap)
+print('The shape of pixel_data is', pixel_data.shape)
+# set
+pixel_data.map3 = torch.randint(0, 255, (20, 40))
+print('The shape of pixel_data is', pixel_data.map3.shape)
+```
+
+```
+The shape of pixel_data is (20, 40)
+The shape of pixel_data is torch.Size([1, 20, 40])
+```
+
+```python
+pixel_data.map2 = torch.randint(0, 255, (3, 20, 30))
+# AssertionError: the height and width of values (20, 30) is not consistent with the length of this :obj:`PixelData` (20, 40)
+```
+
+```
+AssertionError: the height and width of values (20, 30) is not consistent with the length of this :obj:`PixelData` (20, 40)
+```
+
+```python
+pixel_data.map2 = torch.randint(0, 255, (1, 3, 20, 40))
+# AssertionError: The dim of value must be 2 or 3, but got 4
+```
+
+```
+AssertionError: The dim of value must be 2 or 3, but got 4
+```
+
+### 空间维度索引
+
+`PixelData` 支持对 data 部分的数据对实例进行空间维度的索引和切片,只需传入长宽的索引即可。
+
+```python
+metainfo = dict(
+ img_id=random.randint(0, 100),
+ img_shape=(random.randint(400, 600), random.randint(400, 600)))
+image = np.random.randint(0, 255, (4, 20, 40))
+featmap = torch.randint(0, 255, (10, 20, 40))
+pixel_data = PixelData(metainfo=metainfo,
+ image=image,
+ featmap=featmap)
+print('The shape of pixel_data is', pixel_data.shape)
+```
+
+```
+The shape of pixel_data is (20, 40)
+```
+
+- 索引
+
+```python
+index_data = pixel_data[10, 20]
+print('The shape of index_data is', index_data.shape)
+```
+
+```
+The shape of index_data is (1, 1)
+```
+
+- 切片
+
+```python
+slice_data = pixel_data[10:20, 20:40]
+print('The shape of slice_data is', slice_data.shape)
+```
+
+```
+The shape of slice_data is (10, 20)
+```
+
+### LabelData
+
+[`LabelData`](mmengine.structures.LabelData) 主要用来封装标签数据,如场景分类标签,文字识别标签等。`LabelData` 没有对 data 做任何限制,只提供了两个额外功能:onehot 与 index 的转换。
+
+```python
+from mmengine.structures import LabelData
+import torch
+
+item = torch.tensor([1], dtype=torch.int64)
+num_classes = 10
+
+```
+
+```python
+onehot = LabelData.label_to_onehot(label=item, num_classes=num_classes)
+print(f'{num_classes} is convert to ', onehot)
+
+index = LabelData.onehot_to_label(onehot=onehot)
+print(f'{onehot} is convert to ', index)
+```
+
+```
+10 is convert to tensor([0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
+tensor([0, 1, 0, 0, 0, 0, 0, 0, 0, 0]) is convert to tensor([1])
+```
+
+## 数据样本(DataSample)
+
+数据样本作为不同模块最外层的接口,提供了 xxxDataSample 用于单任务中各模块之间统一格式的传递,同时为了各个模块从统一字段获取或写入信息,数据样本中的命名以及类型要进行约束和统一,保证各模块接口的统一性。 OpenMMLab 中各个算法库的命名规范可以参考 [`OpenMMLab` 中的命名规范](命名规范.md)。
+
+### 下游库使用
+
+以 MMDet 为例,说明下游库中数据样本的使用,以及数据样本字段的约束和命名。MMDet 中定义了 `DetDataSample`, 同时定义了 7 个字段,分别为:
+
+- 标注信息
+ - gt_instance(InstanceData): 实例标注信息,包括实例的类别、边界框等, 类型约束为 `InstanceData`。
+ - gt_panoptic_seg(PixelData): 全景分割的标注信息,类型约束为 `PixelData`。
+ - gt_semantic_seg(PixelData): 语义分割的标注信息, 类型约束为 `PixelData`。
+- 预测结果
+ - pred_instance(InstanceData): 实例预测结果,包括实例的类别、边界框等, 类型约束为 `InstanceData`。
+ - pred_panoptic_seg(PixelData): 全景分割的预测结果,类型约束为 `PixelData`。
+ - pred_semantic_seg(PixelData): 语义分割的预测结果, 类型约束为 `PixelData`。
+- 中间结果
+ - proposal(InstanceData): 主要为二阶段中 RPN 的预测结果, 类型约束为 `InstanceData`。
+
+```python
+from mmengine.structures import BaseDataElement
+import torch
+
+class DetDataSample(BaseDataElement):
+
+ # 标注
+ @property
+ def gt_instances(self) -> InstanceData:
+ return self._gt_instances
+
+ @gt_instances.setter
+ def gt_instances(self, value: InstanceData):
+ self.set_field(value, '_gt_instances', dtype=InstanceData)
+
+ @gt_instances.deleter
+ def gt_instances(self):
+ del self._gt_instances
+
+ @property
+ def gt_panoptic_seg(self) -> PixelData:
+ return self._gt_panoptic_seg
+
+ @gt_panoptic_seg.setter
+ def gt_panoptic_seg(self, value: PixelData):
+ self.set_field(value, '_gt_panoptic_seg', dtype=PixelData)
+
+ @gt_panoptic_seg.deleter
+ def gt_panoptic_seg(self):
+ del self._gt_panoptic_seg
+
+ @property
+ def gt_sem_seg(self) -> PixelData:
+ return self._gt_sem_seg
+
+ @gt_sem_seg.setter
+ def gt_sem_seg(self, value: PixelData):
+ self.set_field(value, '_gt_sem_seg', dtype=PixelData)
+
+ @gt_sem_seg.deleter
+ def gt_sem_seg(self):
+ del self._gt_sem_seg
+
+ # 预测
+ @property
+ def pred_instances(self) -> InstanceData:
+ return self._pred_instances
+
+ @pred_instances.setter
+ def pred_instances(self, value: InstanceData):
+ self.set_field(value, '_pred_instances', dtype=InstanceData)
+
+ @pred_instances.deleter
+ def pred_instances(self):
+ del self._pred_instances
+
+ @property
+ def pred_panoptic_seg(self) -> PixelData:
+ return self._pred_panoptic_seg
+
+ @pred_panoptic_seg.setter
+ def pred_panoptic_seg(self, value: PixelData):
+ self.set_field(value, '_pred_panoptic_seg', dtype=PixelData)
+
+ @pred_panoptic_seg.deleter
+ def pred_panoptic_seg(self):
+ del self._pred_panoptic_seg
+
+ # 中间结果
+ @property
+ def pred_sem_seg(self) -> PixelData:
+ return self._pred_sem_seg
+
+ @pred_sem_seg.setter
+ def pred_sem_seg(self, value: PixelData):
+ self.set_field(value, '_pred_sem_seg', dtype=PixelData)
+
+ @pred_sem_seg.deleter
+ def pred_sem_seg(self):
+ del self._pred_sem_seg
+
+ @property
+ def proposals(self) -> InstanceData:
+ return self._proposals
+
+ @proposals.setter
+ def proposals(self, value: InstanceData):
+ self.set_field(value, '_proposals', dtype=InstanceData)
+
+ @proposals.deleter
+ def proposals(self):
+ del self._proposals
+
+```
+
+### 类型约束
+
+DetDataSample 的用法如下所示,在数据类型不符合要求的时候(例如用 torch.Tensor 而非 InstanceData 定义 proposals 时),DetDataSample 就会报错。
+
+```python
+data_sample = DetDataSample()
+
+data_sample.proposals = InstanceData(data=dict(bboxes=torch.rand((5,4))))
+print(data_sample)
+```
+
+```
+
+) at 0x7f9f1c090430>
+```
+
+```python
+data_sample.proposals = torch.rand((5, 4))
+```
+
+```
+AssertionError: tensor([[0.4370, 0.1661, 0.0902, 0.8421],
+ [0.4947, 0.1668, 0.0083, 0.1111],
+ [0.2041, 0.8663, 0.0563, 0.3279],
+ [0.7817, 0.1938, 0.2499, 0.6748],
+ [0.4524, 0.8265, 0.4262, 0.2215]]) should be a but got
+```
+
+## 接口的简化
+
+下面以 MMDetection 为例更具体地说明 OpenMMLab 的算法库将如何迁移使用抽象数据接口,以简化模块和组件接口的。我们假定 MMDetection 和 MMEngine 中实现了 DetDataSample 和 InstanceData。
+
+#### 1. 组件接口的简化
+
+检测器的外部接口可以得到显著的简化和统一。MMDet 2.X 中单阶段检测器和单阶段分割算法的接口如下。在训练过程中,`SingleStageDetector` 需要获取
+`img`, `img_metas`, `gt_bboxes`, `gt_labels`, `gt_bboxes_ignore` 作为输入,但是 `SingleStageInstanceSegmentor` 还需要 `gt_masks`,导致 detector 的训练接口不一致,影响了代码的灵活性。
+
+```python
+
+class SingleStageDetector(BaseDetector):
+ ...
+
+ def forward_train(self,
+ img,
+ img_metas,
+ gt_bboxes,
+ gt_labels,
+ gt_bboxes_ignore=None):
+
+
+class SingleStageInstanceSegmentor(BaseDetector):
+ ...
+
+ def forward_train(self,
+ img,
+ img_metas,
+ gt_masks,
+ gt_labels,
+ gt_bboxes=None,
+ gt_bboxes_ignore=None,
+ **kwargs):
+```
+
+在 MMDet 3.0 中,所有检测器的训练接口都可以使用 DetDataSample 统一简化为 `img` 和 `data_samples`,不同模块可以根据需要去访问 `data_samples` 封装的各种所需要的属性。
+
+```python
+class SingleStageDetector(BaseDetector):
+ ...
+
+ def forward_train(self,
+ img,
+ data_samples):
+
+class SingleStageInstanceSegmentor(BaseDetector):
+ ...
+
+ def forward_train(self,
+ img,
+ data_samples):
+
+```
+
+#### 2. 模块接口的简化
+
+MMDet 2.X 中 `HungarianAssigner` 和 `MaskHungarianAssigner` 分别用于在训练过程中将检测框和实例掩码和标注的实例进行匹配。他们内部的匹配逻辑实现是一样的,只是接口和损失函数的计算不同。
+但是,接口的不同使得 `HungarianAssigner` 中的代码无法被复用,`MaskHungarianAssigner` 中重写了很多冗余的逻辑。
+
+```python
+class HungarianAssigner(BaseAssigner):
+
+ def assign(self,
+ bbox_pred,
+ cls_pred,
+ gt_bboxes,
+ gt_labels,
+ img_meta,
+ gt_bboxes_ignore=None,
+ eps=1e-7):
+
+class MaskHungarianAssigner(BaseAssigner):
+
+ def assign(self,
+ cls_pred,
+ mask_pred,
+ gt_labels,
+ gt_mask,
+ img_meta,
+ gt_bboxes_ignore=None,
+ eps=1e-7):
+```
+
+`InstanceData` 可以封装实例的框、分数、和掩码,将 `HungarianAssigner` 的核心参数简化成 `pred_instances`,`gt_instancess`,和 `gt_instances_ignore`
+使得 `HungarianAssigner` 和 `MaskHungarianAssigner` 可以合并成一个通用的 `HungarianAssigner`。
+
+```python
+class HungarianAssigner(BaseAssigner):
+
+ def assign(self,
+ pred_instances,
+ gt_instancess,
+ gt_instances_ignore=None,
+ eps=1e-7):
+```
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/data_transform.md b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/data_transform.md
new file mode 100644
index 0000000000000000000000000000000000000000..ff6ce852a54b14d79b1b43856247b96c5d90bda2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/data_transform.md
@@ -0,0 +1,136 @@
+# 数据变换 (Data Transform)
+
+在 OpenMMLab 算法库中,数据集的构建和数据的准备是相互解耦的。通常,数据集的构建只对数据集进行解析,记录每个样本的基本信息;而数据的准备则是通过一系列的数据变换,根据样本的基本信息进行数据加载、预处理、格式化等操作。
+
+## 使用数据变换类
+
+在 MMEngine 中,我们使用各种可调用的数据变换类来进行数据的操作。这些数据变换类可以接受若干配置参数进行实例化,之后通过调用的方式对输入的数据字典进行处理。同时,我们约定所有数据变换都接受一个字典作为输入,并将处理后的数据输出为一个字典。一个简单的例子如下:
+
+```{note}
+MMEngine 中仅约定了数据变换类的规范,常用的数据变换类实现及基类都在 MMCV 中,因此在本篇教程需要提前安装好 MMCV,参见 {external+mmcv:doc}`MMCV 安装教程 `。
+```
+
+```python
+>>> import numpy as np
+>>> from mmcv.transforms import Resize
+>>>
+>>> transform = Resize(scale=(224, 224))
+>>> data_dict = {'img': np.random.rand(256, 256, 3)}
+>>> data_dict = transform(data_dict)
+>>> print(data_dict['img'].shape)
+(224, 224, 3)
+```
+
+## 在配置文件中使用
+
+在配置文件中,我们将一系列数据变换组合成为一个列表,称为数据流水线(Data Pipeline),传给数据集的 `pipeline` 参数。通常数据流水线由以下几个部分组成:
+
+1. 数据加载,通常使用 [`LoadImageFromFile`](mmcv.transforms.LoadImageFromFile)
+2. 标签加载,通常使用 [`LoadAnnotations`](mmcv.transforms.LoadAnnotations)
+3. 数据处理及增强,例如 [`RandomResize`](mmcv.transforms.RandomResize)
+4. 数据格式化,根据任务不同,在各个仓库使用自己的变换操作,通常名为 `PackXXXInputs`,其中 XXX 是任务的名称,如分类任务中的 `PackClsInputs`。
+
+以分类任务为例,我们在下图展示了一个典型的数据流水线。对每个样本,数据集中保存的基本信息是一个如图中最左侧所示的字典,之后每经过一个由蓝色块代表的数据变换操作,数据字典中都会加入新的字段(标记为绿色)或更新现有的字段(标记为橙色)。
+
+
+
+
+
+如果我们希望在测试中使用上述数据流水线,则配置文件如下所示:
+
+```python
+test_dataloader = dict(
+ batch_size=32,
+ dataset=dict(
+ type='ImageNet',
+ data_root='data/imagenet',
+ pipeline = [
+ dict(type='LoadImageFromFile'),
+ dict(type='Resize', size=256, keep_ratio=True),
+ dict(type='CenterCrop', crop_size=224),
+ dict(type='PackClsInputs'),
+ ]
+ )
+)
+```
+
+## 常用的数据变换类
+
+按照功能,常用的数据变换类可以大致分为数据加载、数据预处理与增强、数据格式化。我们在 MMCV 中提供了一系列常用的数据变换类:
+
+### 数据加载
+
+为了支持大规模数据集的加载,通常在数据集初始化时不加载数据,只加载相应的路径。因此需要在数据流水线中进行具体数据的加载。
+
+| 数据变换类 | 功能 |
+| :------------------------------------------------------: | :---------------------------------------: |
+| [`LoadImageFromFile`](mmcv.transforms.LoadImageFromFile) | 根据路径加载图像 |
+| [`LoadAnnotations`](mmcv.transforms.LoadAnnotations) | 加载和组织标注信息,如 bbox、语义分割图等 |
+
+### 数据预处理及增强
+
+数据预处理和增强通常是对图像本身进行变换,如裁剪、填充、缩放等。
+
+| 数据变换类 | 功能 |
+| :--------------------------------------------------------: | :--------------------------------: |
+| [`Pad`](mmcv.transforms.Pad) | 填充图像边缘 |
+| [`CenterCrop`](mmcv.transforms.CenterCrop) | 居中裁剪 |
+| [`Normalize`](mmcv.transforms.Normalize) | 对图像进行归一化 |
+| [`Resize`](mmcv.transforms.Resize) | 按照指定尺寸或比例缩放图像 |
+| [`RandomResize`](mmcv.transforms.RandomResize) | 缩放图像至指定范围的随机尺寸 |
+| [`RandomChoiceResize`](mmcv.transforms.RandomChoiceResize) | 缩放图像至多个尺寸中的随机一个尺寸 |
+| [`RandomGrayscale`](mmcv.transforms.RandomGrayscale) | 随机灰度化 |
+| [`RandomFlip`](mmcv.transforms.RandomFlip) | 图像随机翻转 |
+
+### 数据格式化
+
+数据格式化操作通常是对数据进行的类型转换。
+
+| 数据变换类 | 功能 |
+| :----------------------------------------------: | :-------------------------------: |
+| [`ToTensor`](mmcv.transforms.ToTensor) | 将指定的数据转换为 `torch.Tensor` |
+| [`ImageToTensor`](mmcv.transforms.ImageToTensor) | 将图像转换为 `torch.Tensor` |
+
+## 自定义数据变换类
+
+要实现一个新的数据变换类,需要继承 `BaseTransform`,并实现 `transform` 方法。这里,我们使用一个简单的翻转变换(`MyFlip`)作为示例:
+
+```python
+import random
+import mmcv
+from mmcv.transforms import BaseTransform, TRANSFORMS
+
+@TRANSFORMS.register_module()
+class MyFlip(BaseTransform):
+ def __init__(self, direction: str):
+ super().__init__()
+ self.direction = direction
+
+ def transform(self, results: dict) -> dict:
+ img = results['img']
+ results['img'] = mmcv.imflip(img, direction=self.direction)
+ return results
+```
+
+从而,我们可以实例化一个 `MyFlip` 对象,并将之作为一个可调用对象,来处理我们的数据字典。
+
+```python
+import numpy as np
+
+transform = MyFlip(direction='horizontal')
+data_dict = {'img': np.random.rand(224, 224, 3)}
+data_dict = transform(data_dict)
+processed_img = data_dict['img']
+```
+
+又或者,在配置文件的 pipeline 中使用 `MyFlip` 变换
+
+```python
+pipeline = [
+ ...
+ dict(type='MyFlip', direction='horizontal'),
+ ...
+]
+```
+
+需要注意的是,如需在配置文件中使用,需要保证 `MyFlip` 类所在的文件在运行时能够被导入。
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/distributed.md b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/distributed.md
new file mode 100644
index 0000000000000000000000000000000000000000..ffa2e5ee3808acab5034c4537b3034a7c3be0868
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/distributed.md
@@ -0,0 +1,47 @@
+# 分布式通信原语
+
+在分布式训练或测试的过程中,不同进程有时需要根据分布式的环境信息执行不同的代码逻辑,同时不同进程之间也经常会有相互通信的需求,对一些数据进行同步等操作。
+PyTorch 提供了一套基础的通信原语用于多进程之间张量的通信,基于这套原语,MMEngine 实现了更高层次的通信原语封装以满足更加丰富的需求。基于 MMEngine 的通信原语,算法库中的模块可以
+
+1. 在使用通信原语封装时不显式区分分布式/非分布式环境
+2. 进行除 Tensor 以外类型数据的多进程通信
+3. 无需了解底层通信后端或框架
+
+这些通信原语封装的接口和功能可以大致归类为如下三种,我们在后续章节中逐个介绍
+
+1. 分布式初始化:`init_dist` 负责初始化执行器的分布式环境
+2. 分布式信息获取与控制:包括 `get_world_size` 等函数获取当前的 `rank` 和 `world_size` 等信息
+3. 分布式通信接口:包括如 `all_reduce` 等通信函数(collective functions)
+
+## 分布式初始化
+
+- [init_dist](mmengine.dist.init_dist): 是分布式训练的启动函数,目前支持 pytorch,slurm,MPI 3 种分布式启动方式,同时允许设置通信的后端,默认使用 NCCL。
+
+## 分布式信息获取与控制
+
+分布式信息的获取与控制函数没有参数,这些函数兼容非分布式训练的情况,功能如下
+
+- [get_world_size](mmengine.dist.get_world_size):获取当前进程组的进程总数,非分布式情况下返回 1
+- [get_rank](mmengine.dist.get_rank):获取当前进程对应的全局 rank 数,非分布式情况下返回 0
+- [get_backend](mmengine.dist.get_backend):获取当前通信使用的后端,非分布式情况下返回 None
+- [get_local_rank](mmengine.dist.get_local_rank):获取当前进程对应到当前机器的 rank 数,非分布式情况下返回 0
+- [get_local_size](mmengine.dist.get_local_size):获取当前进程所在机器的总进程数,非分布式情况下返回 0
+- [get_dist_info](mmengine.dist.get_dist_info):获取当前任务的进程总数和当前进程对应到全局的 rank 数,非分布式情况下 word_size = 1,rank = 0
+- [is_main_process](mmengine.dist.is_main_process):判断是否为 0 号主进程,非分布式情况下返回 True
+- [master_only](mmengine.dist.master_only):函数装饰器,用于修饰只需要全局 0 号进程(rank 0 而不是 local rank 0)执行的函数
+- [barrier](mmengine.dist.barrier):同步所有进程到达相同位置
+
+## 分布式通信函数
+
+通信函数 (Collective functions),主要用于进程间数据的通信,基于 PyTorch 原生的 all_reduce,all_gather,gather,broadcast 接口,MMEngine 提供了如下接口,兼容非分布式训练的情况,并支持更丰富数据类型的通信。
+
+- [all_reduce](mmengine.dist.all_reduce): 对进程间 tensor 进行 AllReduce 操作
+- [all_gather](mmengine.dist.all_gather):对进程间 tensor 进行 AllGather 操作
+- [gather](mmengine.dist.gather):将进程的 tensor 收集到一个目标 rank
+- [broadcast](mmengine.dist.broadcast):对某个进程的 tensor 进行广播
+- [sync_random_seed](mmengine.dist.sync_random_seed):同步进程之间的随机种子
+- [broadcast_object_list](mmengine.dist.broadcast_object_list):支持对任意可被 Pickle 序列化的 Python 对象列表进行广播,基于 broadcast 接口实现
+- [all_reduce_dict](mmengine.dist.all_reduce_dict):对 dict 中的内容进行 all_reduce 操作,基于 broadcast 和 all_reduce 接口实现
+- [all_gather_object](mmengine.dist.all_gather_object):基于 all_gather 实现对任意可以被 Pickle 序列化的 Python 对象进行 all_gather 操作
+- [gather_object](mmengine.dist.gather_object):将 group 里每个 rank 中任意可被 Pickle 序列化的 Python 对象 gather 到指定的目标 rank
+- [collect_results](mmengine.dist.collect_results):支持基于 CPU 通信或者 GPU 通信对不同进程间的列表数据进行收集
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/fileio.md b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/fileio.md
new file mode 100644
index 0000000000000000000000000000000000000000..5bd3f7d012fefd53d2a8a1fc339ed16e3d43b26e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/fileio.md
@@ -0,0 +1,214 @@
+# 文件读写
+
+`MMEngine` 实现了一套统一的文件读写接口,可以用同一个函数来处理不同的文件格式,如 `json`、
+`yaml` 和 `pickle`,并且可以方便地拓展其它的文件格式。除此之外,文件读写模块还支持从多种文件存储后端读写文件,包括本地磁盘、Petrel(内部使用)、Memcached、LMDB 和 HTTP。
+
+## 读取和保存数据
+
+`MMEngine` 提供了两个通用的接口用于读取和保存数据,目前支持的格式有 `json`、`yaml` 和
+`pickle`。
+
+### 从硬盘读取数据或者将数据保存至硬盘
+
+```python
+from mmengine import load, dump
+
+# 从文件中读取数据
+data = load('test.json')
+data = load('test.yaml')
+data = load('test.pkl')
+# 从文件对象中读取数据
+with open('test.json', 'r') as f:
+ data = load(f, file_format='json')
+
+# 将数据序列化为字符串
+json_str = dump(data, file_format='json')
+
+# 将数据保存至文件 (根据文件名后缀反推文件类型)
+dump(data, 'out.pkl')
+
+# 将数据保存至文件对象
+with open('test.yaml', 'w') as f:
+ data = dump(data, f, file_format='yaml')
+```
+
+### 从其它文件存储后端读写文件
+
+```python
+from mmengine import load, dump
+
+# 从 s3 文件读取数据
+data = load('s3://bucket-name/test.json')
+data = load('s3://bucket-name/test.yaml')
+data = load('s3://bucket-name/test.pkl')
+
+# 将数据保存至 s3 文件 (根据文件名后缀反推文件类型)
+dump(data, 's3://bucket-name/out.pkl')
+```
+
+我们提供了易于拓展的方式以支持更多的文件格式,我们只需要创建一个继承自 `BaseFileHandler` 的文件句柄类,句柄类至少需要重写三个方法。然后使用使用 `register_handler` 装饰器将句柄类注册为对应文件格式的读写句柄。
+
+```python
+from mmengine import register_handler, BaseFileHandler
+
+# 支持为文件句柄类注册多个文件格式
+# @register_handler(['txt', 'log'])
+@register_handler('txt')
+class TxtHandler1(BaseFileHandler):
+
+ def load_from_fileobj(self, file):
+ return file.read()
+
+ def dump_to_fileobj(self, obj, file):
+ file.write(str(obj))
+
+ def dump_to_str(self, obj, **kwargs):
+ return str(obj)
+```
+
+以 `PickleHandler` 为例
+
+```python
+from mmengine import BaseFileHandler
+import pickle
+
+class PickleHandler(BaseFileHandler):
+
+ def load_from_fileobj(self, file, **kwargs):
+ return pickle.load(file, **kwargs)
+
+ def load_from_path(self, filepath, **kwargs):
+ return super(PickleHandler, self).load_from_path(
+ filepath, mode='rb', **kwargs)
+
+ def dump_to_str(self, obj, **kwargs):
+ kwargs.setdefault('protocol', 2)
+ return pickle.dumps(obj, **kwargs)
+
+ def dump_to_fileobj(self, obj, file, **kwargs):
+ kwargs.setdefault('protocol', 2)
+ pickle.dump(obj, file, **kwargs)
+
+ def dump_to_path(self, obj, filepath, **kwargs):
+ super(PickleHandler, self).dump_to_path(
+ obj, filepath, mode='wb', **kwargs)
+```
+
+## 读取文件并返回列表或字典
+
+例如, `a.txt` 是文本文件,一共有5行内容。
+
+```
+a
+b
+c
+d
+e
+```
+
+### 从硬盘读取
+
+使用 `list_from_file` 读取 `a.txt`
+
+```python
+from mmengine import list_from_file
+
+print(list_from_file('a.txt'))
+# ['a', 'b', 'c', 'd', 'e']
+print(list_from_file('a.txt', offset=2))
+# ['c', 'd', 'e']
+print(list_from_file('a.txt', max_num=2))
+# ['a', 'b']
+print(list_from_file('a.txt', prefix='/mnt/'))
+# ['/mnt/a', '/mnt/b', '/mnt/c', '/mnt/d', '/mnt/e']
+```
+
+同样, `b.txt` 也是文本文件,一共有3行内容
+
+```
+1 cat
+2 dog cow
+3 panda
+```
+
+使用 `dict_from_file` 读取 `b.txt`
+
+```python
+from mmengine import dict_from_file
+
+print(dict_from_file('b.txt'))
+# {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
+print(dict_from_file('b.txt', key_type=int))
+# {1: 'cat', 2: ['dog', 'cow'], 3: 'panda'}
+```
+
+### 从其他存储后端读取
+
+使用 `list_from_file` 读取 `s3://bucket-name/a.txt`
+
+```python
+from mmengine import list_from_file
+
+print(list_from_file('s3://bucket-name/a.txt'))
+# ['a', 'b', 'c', 'd', 'e']
+print(list_from_file('s3://bucket-name/a.txt', offset=2))
+# ['c', 'd', 'e']
+print(list_from_file('s3://bucket-name/a.txt', max_num=2))
+# ['a', 'b']
+print(list_from_file('s3://bucket-name/a.txt', prefix='/mnt/'))
+# ['/mnt/a', '/mnt/b', '/mnt/c', '/mnt/d', '/mnt/e']
+```
+
+使用 `dict_from_file` 读取 `b.txt`
+
+```python
+from mmengine import dict_from_file
+
+print(dict_from_file('s3://bucket-name/b.txt'))
+# {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
+print(dict_from_file('s3://bucket-name/b.txt', key_type=int))
+# {1: 'cat', 2: ['dog', 'cow'], 3: 'panda'}
+```
+
+## 读取和保存权重文件
+
+通常情况下,我们可以通过下面的方式从磁盘或者网络远端读取权重文件。
+
+```python
+import torch
+
+filepath1 = '/path/of/your/checkpoint1.pth'
+filepath2 = 'http://path/of/your/checkpoint3.pth'
+
+# 从本地磁盘读取权重文件
+checkpoint = torch.load(filepath1)
+# 保存权重文件到本地磁盘
+torch.save(checkpoint, filepath1)
+
+# 从网络远端读取权重文件
+checkpoint = torch.utils.model_zoo.load_url(filepath2)
+```
+
+在 `MMEngine` 中,得益于多文件存储后端的支持,不同存储形式的权重文件读写可以通过
+`load_checkpoint` 和 `save_checkpoint` 来统一实现。
+
+```python
+from mmengine import load_checkpoint, save_checkpoint
+
+filepath1 = '/path/of/your/checkpoint1.pth'
+filepath2 = 's3://bucket-name/path/of/your/checkpoint1.pth'
+filepath3 = 'http://path/of/your/checkpoint3.pth'
+
+# 从本地磁盘读取权重文件
+checkpoint = load_checkpoint(filepath1)
+# 保存权重文件到本地磁盘
+save_checkpoint(checkpoint, filepath1)
+
+# 从 s3 读取权重文件
+checkpoint = load_checkpoint(filepath2)
+# 保存权重文件到 s3
+save_checkpoint(checkpoint, filepath2)
+
+# 从网络远端读取权重文件
+checkpoint = load_checkpoint(filepath3)
+```
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/initialize.md b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/initialize.md
new file mode 100644
index 0000000000000000000000000000000000000000..b53813ce9b9978a295248dc5065ebf98d262d0db
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/initialize.md
@@ -0,0 +1,328 @@
+# 初始化
+
+基于 Pytorch 构建模型时,我们通常会选择 [nn.Module](https://pytorch.org/docs/stable/nn.html?highlight=nn%20module#module-torch.nn.modules) 作为模型的基类,搭配使用 Pytorch 的初始化模块 [torch.nn.init](https://pytorch.org/docs/stable/nn.init.html?highlight=kaiming#torch.nn.init.kaiming_normal_),完成模型的初始化。MMEngine 在此基础上抽象出基础模块(BaseModule),让我们能够通过传参或配置文件来选择模型的初始化方式。此外,`MMEngine` 还提供了一系列模块初始化函数,让我们能够更加方便灵活地初始化模型参数。
+
+## 配置式初始化
+
+为了能够更加灵活地初始化模型权重,`MMEngine` 抽象出了模块基类 `BaseModule`。模块基类继承自 `nn.Module`,在具备 `nn.Module` 基础功能的同时,还支持在构造时接受参数,以此来选择权重初始化方式。继承自 `BaseModule` 的模型可以在实例化阶段接受 `init_cfg` 参数,我们可以通过配置 `init_cfg` 为模型中任意组件灵活地选择初始化方式。目前我们可以在 `init_cfg` 中配置以下初始化器:
+
+| 初始化器 | 注册名 | 功能 |
+| :-------------------------------------------------------------- | :----------: | :--------------------------------------------------------------------------------------------------------------------------------- |
+| [ConstantInit](../api.html#mmengine.model.ConstantInit) | Constant | 将 weight 和 bias 初始化为指定常量,通常用于初始化卷积 |
+| [XavierInit](../api.html#mmengine.model.XavierInit) | Xavier | 将 weight `Xavier` 方式初始化,将 bias 初始化成指定常量,通常用于初始化卷积 |
+| [NormalInit](../api.html#mmengine.model.NormalInit) | Normal | 将 weight 以正态分布的方式初始化,将 bias 初始化成指定常量,通常用于初始化卷积 |
+| [TruncNormalInit](../api.html#mmengine.model.TruncNormalInit) | TruncNormal | 将 weight 以被截断的正态分布的方式初始化,参数 a 和 b 为正态分布的有效区域;将 bias 初始化成指定常量,通常用于初始化 `transformer` |
+| [UniformInit](../api.html#mmengine.model.UniformInit) | Uniform | 将 weight 以均匀分布的方式初始化,参数 a 和 b 为均匀分布的范围;将 bias 初始化为指定常量,通常用于初始化卷积 |
+| [KaimingInit](../api.html#mmengine.model.KaimingInit) | Kaiming | 将 weight 以 `Kaiming` 的方式初始化,将 bias 初始化成指定常量,通常用于初始化卷积 |
+| [Caffe2XavierInit](../api.html#mmengine.model.Caffe2XavierInit) | Caffe2Xavier | Caffe2 中 Xavier 初始化方式,在 Pytorch 中对应 `fan_in`, `normal` 模式的 `Kaiming` 初始化,,通常用于初始化卷 |
+| [PretrainedInit](../api.html#mmengine.model.PretrainedInit) | Pretrained | 加载预训练权重 |
+
+我们通过几个例子来理解如何在 `init_cfg` 里配置初始化器,来选择模型的初始化方式。
+
+### 使用预训练权重初始化
+
+假设我们定义了模型类 `ToyNet`,它继承自模块基类(`BaseModule`)。此时我们可以在 `ToyNet` 初始化时传入 `init_cfg` 参数来选择模型的初始化方式,实例化后再调用 `init_weights` 方法,完成权重的初始化。以加载预训练权重为例:
+
+```python
+import torch
+import torch.nn as nn
+
+from mmengine.model import BaseModule
+
+
+class ToyNet(BaseModule):
+
+ def __init__(self, init_cfg=None):
+ super().__init__(init_cfg)
+ self.conv1 = nn.Linear(1, 1)
+
+
+# 保存预训练权重
+toy_net = ToyNet()
+torch.save(toy_net.state_dict(), './pretrained.pth')
+pretrained = './pretrained.pth'
+
+# 配置加载预训练权重的初始化方式
+toy_net = ToyNet(init_cfg=dict(type='Pretrained', checkpoint=pretrained))
+# 加载权重
+toy_net.init_weights()
+```
+
+```
+08/19 16:50:24 - mmengine - INFO - load model from: ./pretrained.pth
+08/19 16:50:24 - mmengine - INFO - local loads checkpoint from path: ./pretrained.pth
+```
+
+当 `init_cfg` 是一个字典时,`type` 字段就表示一种初始化器,它需要被注册到 `WEIGHT_INITIALIZERS` [注册器](registry.md)。我们可以通过指定 `init_cfg=dict(type='Pretrained', checkpoint='path/to/ckpt')` 来加载预训练权重,其中 `Pretrained` 为 `PretrainedInit` 初始化器的缩写,这个映射名由 `WEIGHT_INITIALIZERS` 维护;`checkpoint` 是 `PretrainedInit` 的初始化参数,用于指定权重的加载路径,它可以是本地磁盘路径,也可以是 URL。
+
+### 常用的初始化方式
+
+和使用 `PretrainedInit` 初始化器类似,如果我们想对卷积做 `Kaiming` 初始化,需要令 `init_cfg=dict(type='Kaiming', layer='Conv2d')`。这样模型初始化时,就会以 `Kaiming` 初始化的方式来初始化类型为 `Conv2d` 的模块。
+
+有时候我们可能需要用不同的初始化方式去初始化不同类型的模块,例如对卷积使用 `Kaiming` 初始化,对线性层使用 `Xavier`
+初始化。此时我们可以使 `init_cfg` 成为一个列表,其中的每一个元素都表示对某些层使用特定的初始化方式。
+
+```python
+import torch.nn as nn
+
+from mmengine.model import BaseModule
+
+
+class ToyNet(BaseModule):
+
+ def __init__(self, init_cfg=None):
+ super().__init__(init_cfg)
+ self.linear = nn.Linear(1, 1)
+ self.conv = nn.Conv2d(1, 1, 1)
+
+
+# 对卷积做 Kaiming 初始化,线性层做 Xavier 初始化
+toy_net = ToyNet(
+ init_cfg=[
+ dict(type='Kaiming', layer='Conv2d'),
+ dict(type='Xavier', layer='Linear')
+ ], )
+toy_net.init_weights()
+```
+
+```
+08/19 16:50:24 - mmengine - INFO -
+linear.weight - torch.Size([1, 1]):
+XavierInit: gain=1, distribution=normal, bias=0
+
+08/19 16:50:24 - mmengine - INFO -
+linear.bias - torch.Size([1]):
+XavierInit: gain=1, distribution=normal, bias=0
+
+08/19 16:50:24 - mmengine - INFO -
+conv.weight - torch.Size([1, 1, 1, 1]):
+KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0
+
+08/19 16:50:24 - mmengine - INFO -
+conv.bias - torch.Size([1]):
+KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0
+```
+
+类似地,`layer` 参数也可以是一个列表,表示列表中的多种不同的 `layer` 均使用 `type` 指定的初始化方式
+
+```python
+# 对卷积和线性层做 Kaiming 初始化
+toy_net = ToyNet(init_cfg=[dict(type='Kaiming', layer=['Conv2d', 'Linear'])], )
+toy_net.init_weights()
+```
+
+```
+08/19 16:50:24 - mmengine - INFO -
+linear.weight - torch.Size([1, 1]):
+KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0
+
+08/19 16:50:24 - mmengine - INFO -
+linear.bias - torch.Size([1]):
+KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0
+
+08/19 16:50:24 - mmengine - INFO -
+conv.weight - torch.Size([1, 1, 1, 1]):
+KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0
+
+08/19 16:50:24 - mmengine - INFO -
+conv.bias - torch.Size([1]):
+KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0
+```
+
+### 更细粒度的初始化
+
+有时同一类型的不同模块有不同初始化方式,例如现在有 `conv1` 和 `conv2` 两个模块,他们的类型均为 `Conv2d`
+。我们需要对 conv1 进行 `Kaiming` 初始化,conv2 进行 `Xavier` 初始化,则可以通过配置 `override` 参数来满足这样的需求:
+
+```python
+import torch.nn as nn
+
+from mmengine.model import BaseModule
+
+
+class ToyNet(BaseModule):
+
+ def __init__(self, init_cfg=None):
+ super().__init__(init_cfg)
+ self.conv1 = nn.Conv2d(1, 1, 1)
+ self.conv2 = nn.Conv2d(1, 1, 1)
+
+
+# 对 conv1 做 Kaiming 初始化,对 从 conv2 做 Xavier 初始化
+toy_net = ToyNet(
+ init_cfg=[
+ dict(
+ type='Kaiming',
+ layer=['Conv2d'],
+ override=dict(name='conv2', type='Xavier')),
+ ], )
+toy_net.init_weights()
+```
+
+```
+08/19 16:50:24 - mmengine - INFO -
+conv1.weight - torch.Size([1, 1, 1, 1]):
+KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0
+
+08/19 16:50:24 - mmengine - INFO -
+conv1.bias - torch.Size([1]):
+KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0
+
+08/19 16:50:24 - mmengine - INFO -
+conv2.weight - torch.Size([1, 1, 1, 1]):
+XavierInit: gain=1, distribution=normal, bias=0
+
+08/19 16:50:24 - mmengine - INFO -
+conv2.bias - torch.Size([1]):
+KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0
+```
+
+`override` 可以理解成一个嵌套的 `init_cfg`, 他同样可以是 `list` 或者 `dict`,也需要通过 `type`
+字段指定初始化方式。不同的是 `override` 必须指定 `name`,`name` 相当于 `override`
+的作用域,如上例中,`override` 的作用域为 `toy_net.conv2`,我们会以 `Xavier` 初始化方式初始化 `toy_net.conv2` 下的所有参数,而不会影响作用域以外的模块。
+
+### 自定义的初始化方式
+
+尽管 `init_cfg` 能够控制各个模块的初始化方式,但是在不扩展 `WEIGHT_INITIALIZERS`
+的情况下,我们是无法初始化一些自定义模块的,例如表格中提到的大多数初始化器,都需要对应的模块有 `weight` 和 `bias` 属性 。对于这种情况,我们建议让自定义模块实现 `init_weights` 方法。模型调用 `init_weights`
+时,会链式地调用所有子模块的 `init_weights`。
+
+假设我们定义了以下模块:
+
+- 继承自 `nn.Module` 的 `ToyConv`,实现了 `init_weights` 方法,让 `custom_weight` 初始化为 1,`custom_bias` 初始化为 0
+
+- 继承自模块基类的模型 `ToyNet`,且含有 `ToyConv` 子模块
+
+我们在调用 `ToyNet` 的 `init_weights` 方法时,会链式的调用的子模块 `ToyConv` 的 `init_weights` 方法,实现自定义模块的初始化。
+
+```python
+import torch
+import torch.nn as nn
+
+from mmengine.model import BaseModule
+
+
+class ToyConv(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.custom_weight = nn.Parameter(torch.empty(1, 1, 1, 1))
+ self.custom_bias = nn.Parameter(torch.empty(1))
+
+ def init_weights(self):
+ with torch.no_grad():
+ self.custom_weight = self.custom_weight.fill_(1)
+ self.custom_bias = self.custom_bias.fill_(0)
+
+
+class ToyNet(BaseModule):
+
+ def __init__(self, init_cfg=None):
+ super().__init__(init_cfg)
+ self.conv1 = nn.Conv2d(1, 1, 1)
+ self.conv2 = nn.Conv2d(1, 1, 1)
+ self.custom_conv = ToyConv()
+
+
+toy_net = ToyNet(
+ init_cfg=[
+ dict(
+ type='Kaiming',
+ layer=['Conv2d'],
+ override=dict(name='conv2', type='Xavier'))
+ ])
+# 链式调用 `ToyConv.init_weights()`,以自定义的方式初始化
+toy_net.init_weights()
+```
+
+```
+08/19 16:50:24 - mmengine - INFO -
+conv1.weight - torch.Size([1, 1, 1, 1]):
+KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0
+
+08/19 16:50:24 - mmengine - INFO -
+conv1.bias - torch.Size([1]):
+KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0
+
+08/19 16:50:24 - mmengine - INFO -
+conv2.weight - torch.Size([1, 1, 1, 1]):
+XavierInit: gain=1, distribution=normal, bias=0
+
+08/19 16:50:24 - mmengine - INFO -
+conv2.bias - torch.Size([1]):
+KaimingInit: a=0, mode=fan_out, nonlinearity=relu, distribution =normal, bias=0
+
+08/19 16:50:24 - mmengine - INFO -
+custom_conv.custom_weight - torch.Size([1, 1, 1, 1]):
+Initialized by user-defined `init_weights` in ToyConv
+
+08/19 16:50:24 - mmengine - INFO -
+custom_conv.custom_bias - torch.Size([1]):
+Initialized by user-defined `init_weights` in ToyConv
+```
+
+### 小结
+
+最后我们对 `init_cfg` 和 `init_weights` 两种初始化方式做一些总结:
+
+**1. 配置 `init_cfg` 控制初始化**
+
+- 通常用于初始化一些比较底层的模块,例如卷积、线性层等。如果想通过 `init_cfg` 配置自定义模块的初始化方式,需要将相应的初始化器注册到 `WEIGHT_INITIALIZERS` 里。
+- 动态初始化特性,初始化方式随 `init_cfg` 的值改变。
+
+**2. 实现 `init_weights` 方法**
+
+- 通常用于初始化自定义模块。相比于 `init_cfg` 的自定义初始化,实现 `init_weights` 方法更加简单,无需注册。然而,它的灵活性不及 `init_cfg`,无法动态地指定任意模块的初始化方式。
+
+```{note}
+- init_weights 的优先级比 `init_cfg` 高
+- 执行器会在 train() 函数中调用 init_weights。
+```
+
+## 函数式初始化
+
+在[自定义的初始化方式](#自定义的初始化方式)一节提到,我们可以在 `init_weights` 里实现自定义的参数初始化逻辑。为了能够更加方便地实现参数初始化,MMEngine 在 `torch.nn.init`的基础上,提供了一系列**模块初始化函数**来初始化整个模块。例如我们对卷积层的权重(`weight`)进行正态分布初始化,卷积层的偏置(`bias`)进行常数初始化,基于 `torch.nn.init` 的实现如下:
+
+```python
+from torch.nn.init import normal_, constant_
+import torch.nn as nn
+
+model = nn.Conv2d(1, 1, 1)
+normal_(model.weight, mean=0, std=0.01)
+constant_(model.bias, val=0)
+```
+
+```
+Parameter containing:
+tensor([0.], requires_grad=True)
+```
+
+上述流程实际上是卷积正态分布初始化的标准流程,因此 MMEngine 在此基础上做了进一步地简化,实现了一系列常用的**模块**初始化函数。相比 `torch.nn.init`,MMEngine 提供的初始化函数直接接受卷积模块,一行代码能实现同样的初始化逻辑:
+
+```python
+from mmengine.model import normal_init
+
+normal_init(model, mean=0, std=0.01, bias=0)
+```
+
+类似地,我们也可以用 [Kaiming](http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf) 初始化和 [Xavier](http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf) 初始化:
+
+```python
+from mmengine.model import kaiming_init, xavier_init
+
+kaiming_init(model)
+xavier_init(model)
+```
+
+目前 MMEngine 提供了以下初始化函数:
+
+| 初始化函数 | 功能 |
+| :-------------------------------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------------- |
+| [constant_init](../api.html#mmengine.model.constant_init) | 将 weight 和 bias 初始化为指定常量,通常用于初始化卷积 |
+| [xavier_init](../api.html#mmengine.model.xavier_init) | 将 weight 以 `Xavier` 方式初始化,将 bias 初始化成指定常量,通常用于初始化卷积 |
+| [normal_init](../api.html#mmengine.model.normal_init) | 将 weight 以正态分布的方式初始化,将 bias 初始化成指定常量,通常用于初始化卷积 |
+| [trunc_normal_init](../api.html#mmengine.model.trunc_normal_init) | 将 weight 以被截断的正态分布的方式初始化,参数 a 和 b 为正态分布的有效区域;将 bias 初始化成指定常量,通常用于初始化 `transformer` |
+| [uniform_init](../api.html#mmengine.model.uniform_init) | 将 weight 以均匀分布的方式初始化,参数 a 和 b 为均匀分布的范围;将 bias 初始化为指定常量,通常用于初始化卷积 |
+| [kaiming_init](../api.html#mmengine.model.kaiming_init) | 将 weight 以 `Kaiming` 方式初始化,将 bias 初始化成指定常量,通常用于初始化卷积 |
+| [caffe2_xavier_init](../api.html#mmengine.model.caffe2_xavier_init) | Caffe2 中 Xavier 初始化方式,在 Pytorch 中对应 `fan_in`, `normal` 模式的 `Kaiming` 初始化,通常用于初始化卷积 |
+| [bias_init_with_prob](../api.html#mmengine.model.bias_init_with_prob) | 以概率值的形式初始化 bias |
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/logging.md b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/logging.md
new file mode 100644
index 0000000000000000000000000000000000000000..5f5582124c4ea4e37fd426fbe6b075b710ecd7b0
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/logging.md
@@ -0,0 +1,312 @@
+# 记录日志
+
+[执行器(Runner)](../tutorials/runner.md)在运行过程中会产生很多日志,例如损失、迭代时间、学习率等。MMEngine 实现了一套灵活的日志系统让我们能够在配置执行器时,选择不同类型日志的统计方式;在代码的任意位置,新增需要被统计的日志。
+
+## 灵活的日志统计方式
+
+我们可以通过在构建执行器时候配置[日志处理器](mmengine.logging.LogProcessor),来灵活地选择日志统计方式。如果不为执行器配置日志处理器,则会按照日志处理器的默认参数构建实例,效果等价于:
+
+```python
+log_processor = dict(window_size=10, by_epoch=True, custom_cfg=None, num_digits=4)
+```
+
+其输出的日志格式如下:
+
+```python
+import torch
+import torch.nn as nn
+from torch.utils.data import DataLoader
+
+from mmengine.runner import Runner
+from mmengine.model import BaseModel
+
+train_dataset = [(torch.ones(1, 1), torch.ones(1, 1))] * 50
+train_dataloader = DataLoader(train_dataset, batch_size=2)
+
+
+class ToyModel(BaseModel):
+ def __init__(self) -> None:
+ super().__init__()
+ self.linear = nn.Linear(1, 1)
+
+ def forward(self, img, label, mode):
+ feat = self.linear(img)
+ loss1 = (feat - label).pow(2)
+ loss2 = (feat - label).abs()
+ return dict(loss1=loss1, loss2=loss2)
+
+runner = Runner(
+ model=ToyModel(),
+ work_dir='tmp_dir',
+ train_dataloader=train_dataloader,
+ train_cfg=dict(by_epoch=True, max_epochs=1),
+ optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01))
+)
+runner.train()
+```
+
+```
+08/21 02:58:41 - mmengine - INFO - Epoch(train) [1][10/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0019 data_time: 0.0004 loss1: 0.8381 loss2: 0.9007 loss: 1.7388
+08/21 02:58:41 - mmengine - INFO - Epoch(train) [1][20/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0029 data_time: 0.0010 loss1: 0.1978 loss2: 0.4312 loss: 0.6290
+```
+
+以训练阶段为例,日志处理器默认会按照以下方式统计执行器输出的日志:
+
+- 日志前缀:
+ - Epoch 模式(`by_epoch=True`): `Epoch(train) [{当前epoch次数}][{当前迭代次数}/{Dataloader 总长度}]`
+ - Iter 模式(`by_epoch=False`): `Iter(train) [{当前迭代次数}/{总迭代次数}]`
+- 学习率(`lr`):统计最近一次迭代,参数更新的学习率
+- 时间
+ - 迭代时间(`time`):最近 `window_size`(日志处理器参数) 次迭代,处理一个 batch 数据(包括数据加载和模型前向推理)的平局时间
+ - 数据时间(`data_time`):最近 `window_size` 次迭代,加载一个 batch 数据的平局时间
+ - 剩余时间(`eta`):根据总迭代次数和历次迭代时间计算出来的总剩余时间,剩余时间随着迭代次数增加逐渐趋于稳定
+- 损失:模型前向推理得到的各种字段的损失,默认统计最近 `window_size` 次迭代的平均损失。
+
+默认情况下,`window_size=10`,日志处理器会统计最近 10 次迭代,损失、迭代时间、数据时间的均值。
+
+默认情况下,所有日志的有效位数(`num_digits` 参数)为 4。
+
+默认情况下,输出所有自定义日志最近一次迭代的值。
+
+基于上述规则,代码示例中的日志处理器会输出 `loss1` 和 `loss2` 每 10 次迭代的均值。如果我们想统计 `loss1` 从第一次迭代开始至今的全局均值,可以这样配置:
+
+```python
+runner = Runner(
+ model=ToyModel(),
+ work_dir='tmp_dir',
+ train_dataloader=train_dataloader,
+ train_cfg=dict(by_epoch=True, max_epochs=1),
+ optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01)),
+ log_processor=dict( # 配置日志处理器
+ custom_cfg=[
+ dict(data_src='loss1', # 原日志名:loss1
+ method_name='mean', # 统计方法:均值统计
+ window_size='global')]) # 统计窗口:全局
+)
+runner.train()
+```
+
+```
+08/21 02:58:49 - mmengine - INFO - Epoch(train) [1][10/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0026 data_time: 0.0007 loss1: 0.7381 loss2: 0.8446 loss: 1.5827
+08/21 02:58:49 - mmengine - INFO - Epoch(train) [1][20/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0030 data_time: 0.0012 loss1: 0.4521 loss2: 0.3939 loss: 0.5600
+```
+
+```{note}
+log_processor 默认输出 `by_epoch=True` 格式的日志。日志格式需要和 `train_cfg` 中的 `by_epoch` 参数保持一致,例如我们想按迭代次数输出日志,就需要另 `log_processor` 和 `train_cfg` 的 `by_epoch=False`。
+```
+
+其中 `data_src` 为原日志名,`mean` 为统计方法,`global` 为统计方法的参数。这样的话,日志中统计的 `loss1` 就是全局均值。我们可以在日志处理器中配置以下统计方法:
+
+
+
+
+ 统计方法
+ 参数
+ 功能
+
+
+ mean
+ window_size
+ 统计窗口内日志的均值
+
+
+ min
+ window_size
+ 统计窗口内日志的最小值
+
+
+ max
+ window_size
+ 统计窗口内日志的最大值
+
+
+ current
+ /
+ 返回最近一次更新的日志
+
+
+
+
+其中 `window_size` 的值可以是:
+
+- 数字:表示统计窗口的大小
+- `global`:统计全局的最大、最小和均值
+- `epoch`:统计一个 epoch 内的最大、最小和均值
+
+当然我们也可以选择自定义的统计方法,详细步骤见[日志设计](../design/logging.md)。
+
+如果我们既想统计窗口为 10 的 `loss1` 的局部均值,又想统计 `loss1` 的全局均值,则需要额外指定 `log_name`:
+
+```python
+runner = Runner(
+ model=ToyModel(),
+ work_dir='tmp_dir',
+ train_dataloader=train_dataloader,
+ train_cfg=dict(by_epoch=True, max_epochs=1),
+ optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01)),
+ log_processor=dict(
+ custom_cfg=[
+ # log_name 表示 loss1 重新统计后的日志名
+ dict(data_src='loss1', log_name='loss1_global', method_name='mean', window_size='global')])
+)
+runner.train()
+```
+
+```
+08/21 18:39:32 - mmengine - INFO - Epoch(train) [1][10/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0016 data_time: 0.0004 loss1: 0.1512 loss2: 0.3751 loss: 0.5264 loss1_global: 0.1512
+08/21 18:39:32 - mmengine - INFO - Epoch(train) [1][20/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0051 data_time: 0.0036 loss1: 0.0113 loss2: 0.0856 loss: 0.0970 loss1_global: 0.0813
+```
+
+类似地,我们也可以统计 `loss1` 的局部最大值和全局最大值:
+
+```python
+runner = Runner(
+ model=ToyModel(),
+ work_dir='tmp_dir',
+ train_dataloader=train_dataloader,
+ train_cfg=dict(by_epoch=True, max_epochs=1),
+ optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01)),
+ log_processor=dict(custom_cfg=[
+ # 统计 loss1 的局部最大值,统计窗口为 10,并在日志中重命名为 loss1_local_max
+ dict(data_src='loss1',
+ log_name='loss1_local_max',
+ window_size=10,
+ method_name='max'),
+ # 统计 loss1 的全局最大值,并在日志中重命名为 loss1_local_max
+ dict(
+ data_src='loss1',
+ log_name='loss1_global_max',
+ method_name='max',
+ window_size='global')
+ ]))
+runner.train()
+```
+
+```
+08/21 03:17:26 - mmengine - INFO - Epoch(train) [1][10/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0021 data_time: 0.0006 loss1: 1.8495 loss2: 1.3427 loss: 3.1922 loss1_local_max: 2.8872 loss1_global_max: 2.8872
+08/21 03:17:26 - mmengine - INFO - Epoch(train) [1][20/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0024 data_time: 0.0010 loss1: 0.5464 loss2: 0.7251 loss: 1.2715 loss1_local_max: 2.8872 loss1_global_max: 2.8872
+```
+
+更多配置规则见[日志处理器文档](mmengine.logging.LogProcessor)
+
+## 自定义统计内容
+
+除了 MMEngine 默认的日志统计类型,如损失、迭代时间、学习率,用户也可以自行添加日志的统计内容。例如我们想统计损失的中间结果,可以这样做:
+
+```python
+from mmengine.logging import MessageHub
+
+
+class ToyModel(BaseModel):
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.linear = nn.Linear(1, 1)
+
+ def forward(self, img, label, mode):
+ feat = self.linear(img)
+ loss_tmp = (feat - label).abs()
+ loss = loss_tmp.pow(2)
+
+ message_hub = MessageHub.get_current_instance()
+ # 在日志中额外统计 `loss_tmp`
+ message_hub.update_scalar('train/loss_tmp', loss_tmp.sum())
+ return dict(loss=loss)
+
+
+runner = Runner(
+ model=ToyModel(),
+ work_dir='tmp_dir',
+ train_dataloader=train_dataloader,
+ train_cfg=dict(by_epoch=True, max_epochs=1),
+ optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01)),
+ log_processor=dict(
+ custom_cfg=[
+ # 统计 loss_tmp 的局部均值
+ dict(
+ data_src='loss_tmp',
+ window_size=10,
+ method_name='mean')
+ ]
+ )
+)
+runner.train()
+```
+
+```
+08/21 03:40:31 - mmengine - INFO - Epoch(train) [1][10/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0026 data_time: 0.0008 loss_tmp: 0.0097 loss: 0.0000
+08/21 03:40:31 - mmengine - INFO - Epoch(train) [1][20/25] lr: 1.0000e-02 eta: 0:00:00 time: 0.0028 data_time: 0.0013 loss_tmp: 0.0065 loss: 0.0000
+```
+
+通过调用[消息枢纽](mmengine.logging.MessageHub)的接口实现自定义日志的统计,具体步骤如下:
+
+1. 调用 `get_current_instance` 接口获取执行器的消息枢纽。
+2. 调用 `update_scalar` 接口更新日志内容,其中第一个参数为日志的名称,日志名称以 `train/`,`val/`,`test/` 前缀打头,用于区分训练状态,然后才是实际的日志名,如上例中的 `train/loss_tmp`,这样统计的日志中就会出现 `loss_tmp`。
+3. 配置日志处理器,以均值的方式统计 `loss_tmp`。如果不配置,日志里显示 `loss_tmp` 最近一次更新的值。
+
+## 输出调试日志
+
+初始化执行器(Runner)时,将 `log_level` 设置成 `debug`。这样终端上就会额外输出日志等级为 `debug` 的日志
+
+```python
+runner = Runner(
+ model=ToyModel(),
+ work_dir='tmp_dir',
+ train_dataloader=train_dataloader,
+ log_level='DEBUG',
+ train_cfg=dict(by_epoch=True, max_epochs=1),
+ optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01)))
+runner.train()
+```
+
+```
+08/21 18:16:22 - mmengine - DEBUG - Get class `LocalVisBackend` from "vis_backend" registry in "mmengine"
+08/21 18:16:22 - mmengine - DEBUG - An `LocalVisBackend` instance is built from registry, its implementation can be found in mmengine.visualization.vis_backend
+08/21 18:16:22 - mmengine - DEBUG - Get class `RuntimeInfoHook` from "hook" registry in "mmengine"
+08/21 18:16:22 - mmengine - DEBUG - An `RuntimeInfoHook` instance is built from registry, its implementation can be found in mmengine.hooks.runtime_info_hook
+08/21 18:16:22 - mmengine - DEBUG - Get class `IterTimerHook` from "hook" registry in "mmengine"
+...
+```
+
+此外,分布式训练时,`DEBUG` 模式还会分进程存储日志。单机多卡,或者多机多卡但是共享存储的情况下,导出的分布式日志路径如下
+
+```text
+# 共享存储
+./tmp
+├── tmp.log
+├── tmp_rank1.log
+├── tmp_rank2.log
+├── tmp_rank3.log
+├── tmp_rank4.log
+├── tmp_rank5.log
+├── tmp_rank6.log
+└── tmp_rank7.log
+...
+└── tmp_rank63.log
+```
+
+多机多卡,独立存储的情况:
+
+```text
+# 独立存储
+# 设备0:
+work_dir/
+└── exp_name_logs
+ ├── exp_name.log
+ ├── exp_name_rank1.log
+ ├── exp_name_rank2.log
+ ├── exp_name_rank3.log
+ ...
+ └── exp_name_rank7.log
+
+# 设备7:
+work_dir/
+└── exp_name_logs
+ ├── exp_name_rank56.log
+ ├── exp_name_rank57.log
+ ├── exp_name_rank58.log
+ ...
+ └── exp_name_rank63.log
+```
+
+如果想要更加深入的了解 MMEngine 的日志系统,可以参考[日志系统设计](../design/logging.md)。
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/manager_mixin.md b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/manager_mixin.md
new file mode 100644
index 0000000000000000000000000000000000000000..b90f70eaf2ed13cc3629ff2d24ec89cac98e1c28
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/manager_mixin.md
@@ -0,0 +1,55 @@
+# 全局管理器(ManagerMixin)
+
+Runner 在训练过程中,难免会使用全局变量来共享信息,例如我们会在 model 中获取全局的 [logger](mmengine.logging.MMLogger) 来打印初始化信息;在 model 中获取全局的 [Visualizer](./visualization.md) 来可视化预测结果、特征图;在 [Registry](../tutorials/registry.md) 中获取全局的 [DefaultScope](mmengine.registry.DefaultScope) 来确定注册域。为了管理这些功能相似的模块,MMEngine 设计了管理器 [ManagerMix](mmengine.utils.ManagerMixin) 来统一全局变量的创建和获取方式。
+
+
+
+## 接口介绍
+
+- get_instance(name='', \*\*kwargs):创建或者返回对应名字的的实例。
+- get_current_instance():返回最近被创建的实例。
+- instance_name:获取对应实例的 name。
+
+## 使用方法
+
+1. 定义有全局访问需求的类
+
+```python
+from mmengine.utils import ManagerMixin
+
+
+class GlobalClass(ManagerMixin):
+ def __init__(self, name, value):
+ super().__init__(name)
+ self.value = value
+```
+
+注意全局类的构造函数必须带有 name 参数,并在构造函数中调用 `super().__init__(name)`,以确保后续能够根据 name 来获取对应的实例。
+
+2. 在任意位置实例化该对象,以 Hook 为例(要确保访问该实例时,对象已经被创建):
+
+```python
+from mmengine import Hook
+
+class CustomHook(Hook):
+ def before_run(self, runner):
+ GlobalClass.get_instance('mmengine', value=50)
+ GlobalClass.get_instance(runner.experiment_name, value=100)
+```
+
+当我们调用子类的 `get_instance` 接口时,`ManagerMixin` 会根据名字来判断对应实例是否已经存在,进而创建/获取实例。如上例所示,当我们第一次调用 `GlobalClass.get_instance('mmengine', value=50)` 时,会创建一个名为 "mmengine" 的 `GlobalClass` 实例,其初始 value 为 50。为了方便后续介绍 `get_current_instance` 接口,这里我们创建了两个 `GlobalClass` 实例。
+
+3. 在任意组件中访问该实例
+
+```python
+import torch.nn as nn
+
+
+class CustomModule(nn.Module):
+ def forward(self, x):
+ value = GlobalClass.get_current_instance().value # 最近一次被创建的实例 value 为 100(步骤二中按顺序创建)
+ value = GlobalClass.get_instance('mmengine').value # 名为 mmengine 的实例 value 为 50
+ # value = GlobalClass.get_instance('mmengine', 1000).value # mmengine 已经被创建,不能再接受额外参数
+```
+
+在同一进程里,我们可以在不同组件中访问 `GlobalClass` 实例。例如我们在 `CustomModule` 中,调用 `get_instance` 和 `get_current_instance` 接口来获取对应名字的实例和最近被创建的实例。需要注意的是,由于 "mmengine" 实例已经被创建,再次调用时不能再传入额外参数,否则会报错。
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/registry.md b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/registry.md
new file mode 100644
index 0000000000000000000000000000000000000000..89a8de854b3779c851bd7c31a86e6f364423c774
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/registry.md
@@ -0,0 +1,302 @@
+# 注册器(Registry)
+
+OpenMMLab 的算法库支持了丰富的算法和数据集,因此实现了很多功能相近的模块。例如 ResNet 和 SE-ResNet 的算法实现分别基于 `ResNet` 和 `SEResNet` 类,这些类有相似的功能和接口,都属于算法库中的模型组件。为了管理这些功能相似的模块,MMEngine 实现了 [注册器](mmengine.registry.Registry)。OpenMMLab 大多数算法库均使用注册器来管理它们的代码模块,包括 [MMDetection](https://github.com/open-mmlab/mmdetection), [MMDetection3D](https://github.com/open-mmlab/mmdetection3d),[MMClassification](https://github.com/open-mmlab/mmclassification) 和 [MMEditing](https://github.com/open-mmlab/mmediting) 等。
+
+## 什么是注册器
+
+MMEngine 实现的[注册器](mmengine.registry.Registry)可以看作一个映射表和模块构建方法(build function)的组合。映射表维护了一个字符串到**类或者函数的映射**,使得用户可以借助字符串查找到相应的类或函数,例如维护字符串 `"ResNet"` 到 `ResNet` 类或函数的映射,使得用户可以通过 `"ResNet"` 找到 `ResNet` 类;而模块构建方法则定义了如何根据字符串查找到对应的类或函数以及如何实例化这个类或者调用这个函数,例如,通过字符串 `"bn"` 找到 `nn.BatchNorm2d` 并实例化 `BatchNorm2d` 模块;又或者通过字符串 `"build_batchnorm2d"` 找到 `build_batchnorm2d` 函数并返回该函数的调用结果。MMEngine 中的注册器默认使用 [build_from_cfg](mmengine.registry.build_from_cfg) 函数来查找并实例化字符串对应的类或者函数。
+
+一个注册器管理的类或函数通常有相似的接口和功能,因此该注册器可以被视作这些类或函数的抽象。例如注册器 `MODELS` 可以被视作所有模型的抽象,管理了 `ResNet`,`SEResNet` 和 `RegNetX` 等分类网络的类以及 `build_ResNet`, `build_SEResNet` 和 `build_RegNetX` 等分类网络的构建函数。
+
+## 入门用法
+
+使用注册器管理代码库中的模块,需要以下三个步骤。
+
+1. 创建注册器
+2. 创建一个用于实例化类的构建方法(可选,在大多数情况下可以只使用默认方法)
+3. 将模块加入注册器中
+
+假设我们要实现一系列激活模块并且希望仅修改配置就能够使用不同的激活模块而无需修改代码。
+
+首先创建注册器,
+
+```python
+from mmengine import Registry
+# scope 表示注册器的作用域,如果不设置,默认为包名,例如在 mmdetection 中,它的 scope 为 mmdet
+ACTIVATION = Registry('activation', scope='mmengine')
+```
+
+然后我们可以实现不同的激活模块,例如 `Sigmoid`,`ReLU` 和 `Softmax`。
+
+```python
+import torch.nn as nn
+
+# 使用注册器管理模块
+@ACTIVATION.register_module()
+class Sigmoid(nn.Module):
+ def __init__(self):
+ super().__init__()
+
+ def forward(self, x):
+ print('call Sigmoid.forward')
+ return x
+
+@ACTIVATION.register_module()
+class ReLU(nn.Module):
+ def __init__(self, inplace=False):
+ super().__init__()
+
+ def forward(self, x):
+ print('call ReLU.forward')
+ return x
+
+@ACTIVATION.register_module()
+class Softmax(nn.Module):
+ def __init__(self):
+ super().__init__()
+
+ def forward(self, x):
+ print('call Softmax.forward')
+ return x
+```
+
+使用注册器管理模块的关键步骤是,将实现的模块注册到注册表 `ACTIVATION` 中。通过 `@ACTIVATION.register_module()` 装饰所实现的模块,字符串和类或函数之间的映射就可以由 `ACTIVATION` 构建和维护,我们也可以通过 `ACTIVATION.register_module(module=ReLU)` 实现同样的功能。
+
+通过注册,我们就可以通过 `ACTIVATION` 建立字符串与类或函数之间的映射,
+
+```python
+print(ACTIVATION.module_dict)
+# {
+# 'Sigmoid': __main__.Sigmoid,
+# 'ReLU': __main__.ReLU,
+# 'Softmax': __main__.Softmax
+# }
+```
+
+```{note}
+只有模块所在的文件被导入时,注册机制才会被触发,所以我们需要在某处导入该文件或者使用 `custom_imports` 字段动态导入该模块进而触发注册机制,详情见[导入自定义 Python 模块](config.md#导入自定义-python-模块)。
+```
+
+模块成功注册后,我们可以通过配置文件使用这个激活模块。
+
+```python
+import torch
+
+input = torch.randn(2)
+
+act_cfg = dict(type='Sigmoid')
+activation = ACTIVATION.build(act_cfg)
+output = activation(input)
+# call Sigmoid.forward
+print(output)
+```
+
+如果我们想使用 `ReLU`,仅需修改配置。
+
+```python
+act_cfg = dict(type='ReLU', inplace=True)
+activation = ACTIVATION.build(act_cfg)
+output = activation(input)
+# call ReLU.forward
+print(output)
+```
+
+如果我们希望在创建实例前检查输入参数的类型(或者任何其他操作),我们可以实现一个构建方法并将其传递给注册器从而实现自定义构建流程。
+
+创建一个构建方法,
+
+```python
+
+def build_activation(cfg, registry, *args, **kwargs):
+ cfg_ = cfg.copy()
+ act_type = cfg_.pop('type')
+ print(f'build activation: {act_type}')
+ act_cls = registry.get(act_type)
+ act = act_cls(*args, **kwargs, **cfg_)
+ return act
+```
+
+并将 `build_activation` 传递给 `build_func` 参数
+
+```python
+ACTIVATION = Registry('activation', build_func=build_activation, scope='mmengine')
+
+@ACTIVATION.register_module()
+class Tanh(nn.Module):
+ def __init__(self):
+ super().__init__()
+
+ def forward(self, x):
+ print('call Tanh.forward')
+ return x
+
+act_cfg = dict(type='Tanh')
+activation = ACTIVATION.build(act_cfg)
+output = activation(input)
+# build activation: Tanh
+# call Tanh.forward
+print(output)
+```
+
+```{note}
+在这个例子中,我们演示了如何使用参数 `build_func` 自定义构建类的实例的方法。
+该功能类似于默认的 `build_from_cfg` 方法。在大多数情况下,使用默认的方法就可以了。
+```
+
+MMEngine 的注册器除了可以注册类,也可以注册函数。
+
+```python
+FUNCTION = Registry('function', scope='mmengine')
+
+@FUNCTION.register_module()
+def print_args(**kwargs):
+ print(kwargs)
+
+func_cfg = dict(type='print_args', a=1, b=2)
+func_res = FUNCTION.build(func_cfg)
+```
+
+## 进阶用法
+
+MMEngine 的注册器支持层级注册,利用该功能可实现跨项目调用,即可以在一个项目中使用另一个项目的模块。虽然跨项目调用也有其他方法的可以实现,但 MMEngine 注册器提供了更为简便的方法。
+
+为了方便跨库调用,MMEngine 提供了 20 个根注册器:
+
+- RUNNERS: Runner 的注册器
+- RUNNER_CONSTRUCTORS: Runner 的构造器
+- LOOPS: 管理训练、验证以及测试流程,如 `EpochBasedTrainLoop`
+- HOOKS: 钩子,如 `CheckpointHook`, `ParamSchedulerHook`
+- DATASETS: 数据集
+- DATA_SAMPLERS: `DataLoader` 的 `Sampler`,用于采样数据
+- TRANSFORMS: 各种数据预处理,如 `Resize`, `Reshape`
+- MODELS: 模型的各种模块
+- MODEL_WRAPPERS: 模型的包装器,如 `MMDistributedDataParallel`,用于对分布式数据并行
+- WEIGHT_INITIALIZERS: 权重初始化的工具
+- OPTIMIZERS: 注册了 PyTorch 中所有的 `Optimizer` 以及自定义的 `Optimizer`
+- OPTIM_WRAPPER: 对 Optimizer 相关操作的封装,如 `OptimWrapper`,`AmpOptimWrapper`
+- OPTIM_WRAPPER_CONSTRUCTORS: optimizer wrapper 的构造器
+- PARAM_SCHEDULERS: 各种参数调度器,如 `MultiStepLR`
+- METRICS: 用于计算模型精度的评估指标,如 `Accuracy`
+- EVALUATOR: 用于计算模型精度的一个或多个评估指标
+- TASK_UTILS: 任务强相关的一些组件,如 `AnchorGenerator`, `BboxCoder`
+- VISUALIZERS: 管理绘制模块,如 `DetVisualizer` 可在图片上绘制预测框
+- VISBACKENDS: 存储训练日志的后端,如 `LocalVisBackend`, `TensorboardVisBackend`
+- LOG_PROCESSORS: 控制日志的统计窗口和统计方法,默认使用 `LogProcessor`,如有特殊需求可自定义 `LogProcessor`
+
+### 调用父节点的模块
+
+`MMEngine` 中定义模块 `RReLU`,并往 `MODELS` 根注册器注册。
+
+```python
+import torch.nn as nn
+from mmengine import Registry, MODELS
+
+@MODELS.register_module()
+class RReLU(nn.Module):
+ def __init__(self, lower=0.125, upper=0.333, inplace=False):
+ super().__init__()
+
+ def forward(self, x):
+ print('call RReLU.forward')
+ return x
+```
+
+假设有个项目叫 `MMAlpha`,它也定义了 `MODELS`,并设置其父节点为 `MMEngine` 的 `MODELS`,这样就建立了层级结构。
+
+```python
+from mmengine import Registry, MODELS as MMENGINE_MODELS
+
+MODELS = Registry('model', parent=MMENGINE_MODELS, scope='mmalpha')
+```
+
+下图是 `MMEngine` 和 `MMAlpha` 的注册器层级结构。
+
+
+
+
+
+可以调用 [count_registered_modules](mmengine.registry.count_registered_modules) 函数打印已注册到 MMEngine 的模块以及层级结构。
+
+```python
+from mmengine.registry import count_registered_modules
+
+count_registered_modules()
+```
+
+在 `MMAlpha` 中定义模块 `LogSoftmax`,并往 `MMAlpha` 的 `MODELS` 注册。
+
+```python
+@MODELS.register_module()
+class LogSoftmax(nn.Module):
+ def __init__(self, dim=None):
+ super().__init__()
+
+ def forward(self, x):
+ print('call LogSoftmax.forward')
+ return x
+```
+
+在 `MMAlpha` 中使用配置调用 `LogSoftmax`
+
+```python
+model = MODELS.build(cfg=dict(type='LogSoftmax'))
+```
+
+也可以在 `MMAlpha` 中调用父节点 `MMEngine` 的模块。
+
+```python
+model = MODELS.build(cfg=dict(type='RReLU', lower=0.2))
+# 也可以加 scope
+model = MODELS.build(cfg=dict(type='mmengine.RReLU'))
+```
+
+如果不加前缀,`build` 方法首先查找当前节点是否存在该模块,如果存在则返回该模块,否则会继续向上查找父节点甚至祖先节点直到找到该模块,因此,如果当前节点和父节点存在同一模块并且希望调用父节点的模块,我们需要指定 `scope` 前缀。
+
+```python
+import torch
+
+input = torch.randn(2)
+output = model(input)
+# call RReLU.forward
+print(output)
+```
+
+### 调用兄弟节点的模块
+
+除了可以调用父节点的模块,也可以调用兄弟节点的模块。
+
+假设有另一个项目叫 `MMBeta`,它和 `MMAlpha` 一样,定义了 `MODELS` 以及设置其父节点为 `MMEngine` 的 `MODELS`。
+
+```python
+from mmengine import Registry, MODELS as MMENGINE_MODELS
+
+MODELS = Registry('model', parent=MMENGINE_MODELS, scope='mmbeta')
+```
+
+下图是 MMEngine,MMAlpha 和 MMBeta 的注册器层级结构。
+
+
+
+
+
+在 `MMBeta` 中调用兄弟节点 `MMAlpha` 的模块,
+
+```python
+model = MODELS.build(cfg=dict(type='mmalpha.LogSoftmax'))
+output = model(input)
+# call LogSoftmax.forward
+print(output)
+```
+
+调用兄弟节点的模块需要在 `type` 中指定 `scope` 前缀,所以上面的配置需要加前缀 `mmalpha`。
+
+如果需要调用兄弟节点的数个模块,每个模块都加前缀,这需要做大量的修改。于是 `MMEngine` 引入了 [DefaultScope](mmengine.registry.DefaultScope),`Registry` 借助它可以很方便地支持临时切换当前节点为指定的节点。
+
+如果需要临时切换当前节点为指定的节点,只需在 `cfg` 设置 `_scope_` 为指定节点的作用域。
+
+```python
+model = MODELS.build(cfg=dict(type='LogSoftmax', _scope_='mmalpha'))
+output = model(input)
+# call LogSoftmax.forward
+print(output)
+```
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/visualization.md b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/visualization.md
new file mode 100644
index 0000000000000000000000000000000000000000..a3d7c686584f07ef87b84cca7e9e2cd5716cd225
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/advanced_tutorials/visualization.md
@@ -0,0 +1,384 @@
+# 可视化
+
+可视化可以给深度学习的模型训练和测试过程提供直观解释。
+
+MMEngine 提供了 `Visualizer` 可视化器用以可视化和存储模型训练和测试过程中的状态以及中间结果,具备如下功能:
+
+- 支持基础绘图接口以及特征图可视化
+- 支持本地、TensorBoard 以及 WandB 等多种后端,可以将训练状态例如 loss 、lr 或者性能评估指标以及可视化的结果写入指定的单一或多个后端
+- 允许在代码库任意位置调用,对任意位置的特征、图像和状态等进行可视化和存储。
+
+## 基础绘制接口
+
+可视化器提供了常用对象的绘制接口,例如绘制**检测框、点、文本、线、圆、多边形和二值掩码**。这些基础 API 支持以下特性:
+
+- 可以多次调用,实现叠加绘制需求
+- 均支持多输入,除了要求文本输入的绘制接口外,其余接口同时支持 Tensor 以及 Numpy array 的输入
+
+常见用法如下:
+
+(1) 绘制检测框、掩码和文本等
+
+```python
+import torch
+import mmcv
+from mmengine.visualization import Visualizer
+
+image = mmcv.imread('docs/en/_static/image/cat_dog.png', channel_order='rgb')
+visualizer = Visualizer(image=image)
+# 绘制单个检测框, xyxy 格式
+visualizer.draw_bboxes(torch.tensor([72, 13, 179, 147]))
+# 绘制多个检测框
+visualizer.draw_bboxes(torch.tensor([[33, 120, 209, 220], [72, 13, 179, 147]]))
+visualizer.show()
+```
+
+
+
+
+
+```python
+visualizer.set_image(image=image)
+visualizer.draw_texts("cat and dog", torch.tensor([10, 20]))
+visualizer.show()
+```
+
+
+
+
+
+你也可以通过各个绘制接口中提供的参数来定制绘制对象的颜色和宽度等等
+
+```python
+visualizer.set_image(image=image)
+visualizer.draw_bboxes(torch.tensor([72, 13, 179, 147]), edge_colors='r', line_widths=3)
+visualizer.draw_bboxes(torch.tensor([[33, 120, 209, 220]]),line_styles='--')
+visualizer.show()
+```
+
+
+
+
+
+(2) 叠加显示
+
+上述绘制接口可以多次调用,从而实现叠加显示需求
+
+```python
+visualizer.set_image(image=image)
+visualizer.draw_bboxes(torch.tensor([[33, 120, 209, 220], [72, 13, 179, 147]]))
+visualizer.draw_texts("cat and dog",
+ torch.tensor([10, 20])).draw_circles(torch.tensor([40, 50]), torch.tensor([20]))
+visualizer.show()
+```
+
+
+
+
+
+## 特征图绘制
+
+特征图可视化功能较多,目前只支持单张特征图的可视化,为了方便理解,将其对外接口梳理如下:
+
+```python
+@staticmethod
+def draw_featmap(featmap: torch.Tensor, # 输入格式要求为 CHW
+ overlaid_image: Optional[np.ndarray] = None, # 如果同时输入了 image 数据,则特征图会叠加到 image 上绘制
+ channel_reduction: Optional[str] = 'squeeze_mean', # 多个通道压缩为单通道的策略
+ topk: int = 10, # 可选择激活度最高的 topk 个特征图显示
+ arrangement: Tuple[int, int] = (5, 2), # 多通道展开为多张图时候布局
+ resize_shape:Optional[tuple] = None, # 可以指定 resize_shape 参数来缩放特征图
+ alpha: float = 0.5) -> np.ndarray: # 图片和特征图绘制的叠加比例
+```
+
+其功能可以归纳如下
+
+- 输入的 Tensor 一般是包括多个通道的,channel_reduction 参数可以将多个通道压缩为单通道,然后和图片进行叠加显示
+
+ - `squeeze_mean` 将输入的 C 维度采用 mean 函数压缩为一个通道,输出维度变成 (1, H, W)
+ - `select_max` 从输入的 C 维度中先在空间维度 sum,维度变成 (C, ),然后选择值最大的通道
+ - `None` 表示不需要压缩,此时可以通过 topk 参数可选择激活度最高的 topk 个特征图显示
+
+- 在 channel_reduction 参数为 None 的情况下,topk 参数生效,其会按照激活度排序选择 topk 个通道,然后和图片进行叠加显示,并且此时会通过 arrangement 参数指定显示的布局
+
+ - 如果 topk 不是 -1,则会按照激活度排序选择 topk 个通道显示
+ - 如果 topk = -1,此时通道 C 必须是 1 或者 3 表示输入数据是图片,否则报错提示用户应该设置 `channel_reduction`来压缩通道。
+
+- 考虑到输入的特征图通常非常小,函数支持输入 `resize_shape` 参数,方便将特征图进行上采样后进行可视化。
+
+常见用法如下:以预训练好的 ResNet18 模型为例,通过提取 layer4 层输出进行特征图可视化
+
+(1) 将多通道特征图采用 `select_max` 参数压缩为单通道并显示
+
+```python
+import numpy as np
+from torchvision.models import resnet18
+from torchvision.transforms import Compose, Normalize, ToTensor
+
+def preprocess_image(img, mean, std):
+ preprocessing = Compose([
+ ToTensor(),
+ Normalize(mean=mean, std=std)
+ ])
+ return preprocessing(img.copy()).unsqueeze(0)
+
+model = resnet18(pretrained=True)
+
+def _forward(x):
+ x = model.conv1(x)
+ x = model.bn1(x)
+ x = model.relu(x)
+ x = model.maxpool(x)
+
+ x1 = model.layer1(x)
+ x2 = model.layer2(x1)
+ x3 = model.layer3(x2)
+ x4 = model.layer4(x3)
+ return x4
+
+model.forward = _forward
+
+image_norm = np.float32(image) / 255
+input_tensor = preprocess_image(image_norm,
+ mean=[0.485, 0.456, 0.406],
+ std=[0.229, 0.224, 0.225])
+feat = model(input_tensor)[0]
+
+visualizer = Visualizer()
+drawn_img = visualizer.draw_featmap(feat, channel_reduction='select_max')
+visualizer.show(drawn_img)
+```
+
+
+
+
+
+由于输出的 feat 特征图尺寸为 7x7,直接可视化效果不佳,用户可以通过叠加输入图片或者 `resize_shape` 参数来缩放特征图。如果传入图片尺寸和特征图大小不一致,会强制将特征图采样到和输入图片相同空间尺寸
+
+```python
+drawn_img = visualizer.draw_featmap(feat, image, channel_reduction='select_max')
+visualizer.show(drawn_img)
+```
+
+
+
+
+
+(2) 利用 `topk=5` 参数选择多通道特征图中激活度最高的 5 个通道并采用 2x3 布局显示
+
+```python
+drawn_img = visualizer.draw_featmap(feat, image, channel_reduction=None, topk=5, arrangement=(2, 3))
+visualizer.show(drawn_img)
+```
+
+
+
+
+
+用户可以通过 `arrangement` 参数选择自己想要的布局
+
+```python
+drawn_img = visualizer.draw_featmap(feat, image, channel_reduction=None, topk=5, arrangement=(4, 2))
+visualizer.show(drawn_img)
+```
+
+
+
+
+
+## 基础存储接口
+
+在绘制完成后,可以选择本地窗口显示,也可以存储到不同后端中,目前 MMEngine 内置了本地存储、Tensorboard 存储和 WandB 存储 3 个后端,且支持存储绘制后的图片、loss 等标量数据和配置文件。
+
+**(1) 存储绘制后的图片**
+
+假设存储后端为本地存储
+
+```python
+visualizer = Visualizer(image=image, vis_backends=[dict(type='LocalVisBackend')], save_dir='temp_dir')
+
+visualizer.draw_bboxes(torch.tensor([[33, 120, 209, 220], [72, 13, 179, 147]]))
+visualizer.draw_texts("cat and dog", torch.tensor([10, 20]))
+visualizer.draw_circles(torch.tensor([40, 50]), torch.tensor([20]))
+
+# 会生成 temp_dir/vis_data/vis_image/demo_0.png
+visualizer.add_image('demo', visualizer.get_image())
+```
+
+其中生成的后缀 0 是用来区分不同 step 场景
+
+```python
+# 会生成 temp_dir/vis_data/vis_image/demo_1.png
+visualizer.add_image('demo', visualizer.get_image(), step=1)
+# 会生成 temp_dir/vis_data/vis_image/demo_3.png
+visualizer.add_image('demo', visualizer.get_image(), step=3)
+```
+
+如果想使用其他后端,则只需要修改配置文件即可
+
+```python
+# TensorboardVisBackend
+visualizer = Visualizer(image=image, vis_backends=[dict(type='TensorboardVisBackend')], save_dir='temp_dir')
+# 或者 WandbVisBackend
+visualizer = Visualizer(image=image, vis_backends=[dict(type='WandbVisBackend')], save_dir='temp_dir')
+```
+
+**(2) 存储特征图**
+
+```python
+visualizer = Visualizer(vis_backends=[dict(type='LocalVisBackend')], save_dir='temp_dir')
+drawn_img = visualizer.draw_featmap(feat, image, channel_reduction=None, topk=5, arrangement=(2, 3))
+# 会生成 temp_dir/vis_data/vis_image/feat_0.png
+visualizer.add_image('feat', drawn_img)
+```
+
+**(3) 存储 loss 等标量数据**
+
+```python
+# 会生成 temp_dir/vis_data/scalars.json
+# 保存 loss
+visualizer.add_scalar('loss', 0.2, step=0)
+visualizer.add_scalar('loss', 0.1, step=1)
+# 保存 acc
+visualizer.add_scalar('acc', 0.7, step=0)
+visualizer.add_scalar('acc', 0.8, step=1)
+```
+
+也可以一次性保存多个标量数据
+
+```python
+# 会将内容追加到 temp_dir/vis_data/scalars.json
+visualizer.add_scalars({'loss': 0.3, 'acc': 0.8}, step=3)
+```
+
+**(4) 保存配置文件**
+
+```python
+from mmengine import Config
+cfg=Config.fromfile('tests/data/config/py_config/config.py')
+# 会生成 temp_dir/vis_data/config.py
+visualizer.add_config(cfg)
+```
+
+## 多后端存储
+
+实际上,任何一个可视化器都可以配置任意多个存储后端,可视化器会循环调用配置好的多个存储后端,从而将结果保存到多后端中。
+
+```python
+visualizer = Visualizer(image=image, vis_backends=[dict(type='TensorboardVisBackend'),
+ dict(type='LocalVisBackend')],
+ save_dir='temp_dir')
+# 会生成 temp_dir/vis_data/events.out.tfevents.xxx 文件
+visualizer.draw_bboxes(torch.tensor([[33, 120, 209, 220], [72, 13, 179, 147]]))
+visualizer.draw_texts("cat and dog", torch.tensor([10, 20]))
+visualizer.draw_circles(torch.tensor([40, 50]), torch.tensor([20]))
+
+visualizer.add_image('demo', visualizer.get_image())
+```
+
+注意:如果多个存储后端中存在同一个类的多个后端,那么必须指定 name 字段,否则无法区分是哪个存储后端
+
+```python
+visualizer = Visualizer(image=image, vis_backends=[dict(type='TensorboardVisBackend', name='tb_1', save_dir='temp_dir_1'),
+ dict(type='TensorboardVisBackend', name='tb_2', save_dir='temp_dir_2'),
+ dict(type='LocalVisBackend', name='local')],
+ save_dir='temp_dir')
+```
+
+## 任意点位进行可视化
+
+在深度学习过程中,会存在在某些代码位置插入可视化函数,并将其保存到不同后端的需求,这类需求主要用于可视化分析和调试阶段。MMEngine 设计的可视化器支持在任意点位获取同一个可视化器然后进行可视化的功能。
+用户只需要在初始化时候通过 `get_instance` 接口实例化可视化对象,此时该可视化对象即为全局可获取唯一对象,后续通过 `Visualizer.get_current_instance()` 即可在代码任意位置获取。
+
+```python
+# 在程序初始化时候调用
+visualizer1 = Visualizer.get_instance(name='vis', vis_backends=[dict(type='LocalVisBackend')])
+
+# 在任何代码位置都可调用
+visualizer2 = Visualizer.get_current_instance()
+visualizer2.add_scalar('map', 0.7, step=0)
+
+assert id(visualizer1) == id(visualizer2)
+```
+
+也可以通过字段配置方式全局初始化
+
+```python
+from mmengine.registry import VISUALIZERS
+
+visualizer_cfg=dict(
+ type='Visualizer',
+ name='vis_new',
+ vis_backends=[dict(type='LocalVisBackend')])
+VISUALIZERS.build(visualizer_cfg)
+```
+
+## 扩展存储后端和可视化器
+
+**(1) 调用特定存储后端**
+
+目前存储后端仅仅提供了保存配置、保存标量等基本功能,但是由于 WandB 和 Tensorboard 这类存储后端功能非常强大, 用户可能会希望利用到这类存储后端的其他功能。因此,存储后端提供了 `experiment` 属性来方便用户获取后端对象,满足各类定制化功能。
+例如 WandB 提供了表格显示的 API 接口,用户可以通过 `experiment`属性获取 WandB 对象,然后调用特定的 API 来将自定义数据保存为表格显示
+
+```python
+visualizer = Visualizer(image=image, vis_backends=[dict(type='WandbVisBackend')],
+ save_dir='temp_dir')
+
+# 获取 WandB 对象
+wandb = visualizer.get_backend('WandbVisBackend').experiment
+# 追加表格数据
+table = wandb.Table(columns=["step", "mAP"])
+table.add_data(1, 0.2)
+table.add_data(2, 0.5)
+table.add_data(3, 0.9)
+# 保存
+wandb.log({"table": table})
+```
+
+**(2) 扩展存储后端**
+
+用户可以方便快捷的扩展存储后端。只需要继承自 `BaseVisBackend` 并实现各类 `add_xx` 方法即可
+
+```python
+from mmengine.registry import VISBACKENDS
+from mmengine.visualization import BaseVisBackend
+
+@VISBACKENDS.register_module()
+class DemoVisBackend(BaseVisBackend):
+ def add_image(self, **kwargs):
+ pass
+
+visualizer = Visualizer(vis_backends=[dict(type='DemoVisBackend')], save_dir='temp_dir')
+visualizer.add_image('demo',image)
+```
+
+**(3) 扩展可视化器**
+
+同样的,用户可以通过继承 Visualizer 并实现想覆写的函数来方便快捷的扩展可视化器。大部分情况下,用户需要覆写 `add_datasample`来进行拓展。数据中通常包括标注或模型预测的检测框和实例掩码,该接口为各个下游库绘制 datasample 数据的抽象接口。以 MMDetection 为例,datasample 数据中通常包括标注 bbox、标注 mask 、预测 bbox 或者预测 mask 等数据,MMDetection 会继承 Visualizer 并实现 `add_datasample` 接口,在该接口内部会针对检测任务相关数据进行可视化绘制,从而简化检测任务可视化需求。
+
+```python
+from mmengine.registry import VISUALIZERS
+
+@VISUALIZERS.register_module()
+class DetLocalVisualizer(Visualizer):
+ def add_datasample(self,
+ name,
+ image: np.ndarray,
+ data_sample: Optional['BaseDataElement'] = None,
+ draw_gt: bool = True,
+ draw_pred: bool = True,
+ show: bool = False,
+ wait_time: int = 0,
+ step: int = 0) -> None:
+ pass
+
+visualizer_cfg = dict(
+ type='DetLocalVisualizer', vis_backends=[dict(type='WandbVisBackend')], name='visualizer')
+
+# 全局初始化
+VISUALIZERS.build(visualizer_cfg)
+
+# 任意代码位置
+det_local_visualizer = Visualizer.get_current_instance()
+det_local_visualizer.add_datasample('det', image, data_sample)
+```
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/config.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/config.rst
new file mode 100644
index 0000000000000000000000000000000000000000..c6c066e67466e3bb81e83fb9fe9053d682927e21
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/config.rst
@@ -0,0 +1,16 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.config
+===================================
+
+.. currentmodule:: mmengine.config
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ Config
+ ConfigDict
+ DictAction
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/dataset.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/dataset.rst
new file mode 100644
index 0000000000000000000000000000000000000000..84ea849101b42aebfc797420dc705a3f21c7b229
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/dataset.rst
@@ -0,0 +1,57 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.dataset
+===================================
+
+.. contents:: mmengine.dataset
+ :depth: 2
+ :local:
+ :backlinks: top
+
+.. currentmodule:: mmengine.dataset
+
+Dataset
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ BaseDataset
+ Compose
+
+Dataset Wrapper
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ ClassBalancedDataset
+ ConcatDataset
+ RepeatDataset
+
+Sampler
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ DefaultSampler
+ InfiniteSampler
+
+Utils
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ default_collate
+ pseudo_collate
+ worker_init_fn
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/device.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/device.rst
new file mode 100644
index 0000000000000000000000000000000000000000..4a16c7383789322908127c8780c3be9b54f11c20
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/device.rst
@@ -0,0 +1,18 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.device
+===================================
+
+.. currentmodule:: mmengine.device
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ get_device
+ get_max_cuda_memory
+ is_cuda_available
+ is_npu_available
+ is_mlu_available
+ is_mps_available
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/dist.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/dist.rst
new file mode 100644
index 0000000000000000000000000000000000000000..1d1bd2e846253cf59071b96991109bc6259d181c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/dist.rst
@@ -0,0 +1,58 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.dist
+===================================
+
+.. contents:: mmengine.dist
+ :depth: 2
+ :local:
+ :backlinks: top
+
+.. currentmodule:: mmengine.dist
+
+dist
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ gather
+ gather_object
+ all_gather
+ all_gather_object
+ all_reduce
+ all_reduce_dict
+ all_reduce_params
+ broadcast
+ sync_random_seed
+ broadcast_object_list
+ collect_results
+ collect_results_cpu
+ collect_results_gpu
+
+utils
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ get_dist_info
+ init_dist
+ init_local_group
+ get_backend
+ get_world_size
+ get_rank
+ get_local_size
+ get_local_rank
+ is_main_process
+ master_only
+ barrier
+ is_distributed
+ get_local_group
+ get_default_group
+ get_data_device
+ get_comm_device
+ cast_data_device
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/evaluator.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/evaluator.rst
new file mode 100644
index 0000000000000000000000000000000000000000..65dfeba940b09ac5c7d1edc4a4a5a7036fad0b48
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/evaluator.rst
@@ -0,0 +1,43 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.evaluator
+===================================
+
+.. contents:: mmengine.evaluator
+ :depth: 2
+ :local:
+ :backlinks: top
+
+.. currentmodule:: mmengine.evaluator
+
+Evaluator
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ Evaluator
+
+Metric
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ BaseMetric
+
+ DumpResults
+
+Utils
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ get_metric_value
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/fileio.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/fileio.rst
new file mode 100644
index 0000000000000000000000000000000000000000..1b8c14b42ab2b66a4c3eb3232549608dd70a6637
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/fileio.rst
@@ -0,0 +1,95 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.fileio
+===================================
+
+.. contents:: mmengine.fileio
+ :depth: 2
+ :local:
+ :backlinks: top
+
+.. currentmodule:: mmengine.fileio
+
+File Backend
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ BaseStorageBackend
+ FileClient
+ HardDiskBackend
+ LocalBackend
+ HTTPBackend
+ LmdbBackend
+ MemcachedBackend
+ PetrelBackend
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ register_backend
+
+File Handler
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ BaseFileHandler
+ JsonHandler
+ PickleHandler
+ YamlHandler
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ register_handler
+
+File IO
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ dump
+ load
+ copy_if_symlink_fails
+ copyfile
+ copyfile_from_local
+ copyfile_to_local
+ copytree
+ copytree_from_local
+ copytree_to_local
+ exists
+ generate_presigned_url
+ get
+ get_file_backend
+ get_local_path
+ get_text
+ isdir
+ isfile
+ join_path
+ list_dir_or_file
+ put
+ put_text
+ remove
+ rmtree
+
+Parse File
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ dict_from_file
+ list_from_file
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/hooks.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/hooks.rst
new file mode 100644
index 0000000000000000000000000000000000000000..c061246b90554f3cdb02c3f41c3867d1109a791c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/hooks.rst
@@ -0,0 +1,24 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.hooks
+===================================
+
+.. currentmodule:: mmengine.hooks
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ Hook
+ CheckpointHook
+ EMAHook
+ LoggerHook
+ NaiveVisualizationHook
+ ParamSchedulerHook
+ RuntimeInfoHook
+ DistSamplerSeedHook
+ IterTimerHook
+ SyncBuffersHook
+ EmptyCacheHook
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/hub.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/hub.rst
new file mode 100644
index 0000000000000000000000000000000000000000..335da9de50dbecc8138280c67e20ec945e66f11b
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/hub.rst
@@ -0,0 +1,14 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.hub
+===================================
+
+.. currentmodule:: mmengine.hub
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ get_config
+ get_model
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/logging.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/logging.rst
new file mode 100644
index 0000000000000000000000000000000000000000..1f674c72e67ba2d19a44d0635048e5e3a960928f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/logging.rst
@@ -0,0 +1,22 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.logging
+===================================
+
+.. currentmodule:: mmengine.logging
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ MMLogger
+ MessageHub
+ HistoryBuffer
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ print_log
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/model.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/model.rst
new file mode 100644
index 0000000000000000000000000000000000000000..321c39ed4680839e06e06b57a1ae01f04b67f4fe
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/model.rst
@@ -0,0 +1,116 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.model
+===================================
+
+.. contents:: mmengine.model
+ :depth: 2
+ :local:
+ :backlinks: top
+
+.. currentmodule:: mmengine.model
+
+Module
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ BaseModule
+ ModuleDict
+ ModuleList
+ Sequential
+
+Model
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ BaseModel
+ BaseDataPreprocessor
+ ImgDataPreprocessor
+ BaseTTAModel
+
+EMA
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ BaseAveragedModel
+ ExponentialMovingAverage
+ MomentumAnnealingEMA
+ StochasticWeightAverage
+
+Model Wrapper
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ MMDistributedDataParallel
+ MMSeparateDistributedDataParallel
+ MMFullyShardedDataParallel
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ is_model_wrapper
+
+Weight Initialization
+----------------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ BaseInit
+ Caffe2XavierInit
+ ConstantInit
+ KaimingInit
+ NormalInit
+ PretrainedInit
+ TruncNormalInit
+ UniformInit
+ XavierInit
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ bias_init_with_prob
+ caffe2_xavier_init
+ constant_init
+ initialize
+ kaiming_init
+ normal_init
+ trunc_normal_init
+ uniform_init
+ update_init_info
+ xavier_init
+
+Utils
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ detect_anomalous_params
+ merge_dict
+ stack_batch
+ revert_sync_batchnorm
+ convert_sync_batchnorm
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/optim.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/optim.rst
new file mode 100644
index 0000000000000000000000000000000000000000..634884c9f522d437fbe8e50c2515d9218848c8b7
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/optim.rst
@@ -0,0 +1,65 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.optim
+===================================
+
+.. contents:: mmengine.optim
+ :depth: 2
+ :local:
+ :backlinks: top
+
+.. currentmodule:: mmengine.optim
+
+Optimizer
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ AmpOptimWrapper
+ OptimWrapper
+ OptimWrapperDict
+ DefaultOptimWrapperConstructor
+ ZeroRedundancyOptimizer
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ build_optim_wrapper
+
+Scheduler
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ _ParamScheduler
+ ConstantLR
+ ConstantMomentum
+ ConstantParamScheduler
+ CosineAnnealingLR
+ CosineAnnealingMomentum
+ CosineAnnealingParamScheduler
+ ExponentialLR
+ ExponentialMomentum
+ ExponentialParamScheduler
+ LinearLR
+ LinearMomentum
+ LinearParamScheduler
+ MultiStepLR
+ MultiStepMomentum
+ MultiStepParamScheduler
+ OneCycleLR
+ OneCycleParamScheduler
+ PolyLR
+ PolyMomentum
+ PolyParamScheduler
+ StepLR
+ StepMomentum
+ StepParamScheduler
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/registry.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/registry.rst
new file mode 100644
index 0000000000000000000000000000000000000000..84bbba8cc32427a0e30ed42af6fa3356949dcf94
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/registry.rst
@@ -0,0 +1,26 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.registry
+===================================
+
+.. currentmodule:: mmengine.registry
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ Registry
+ DefaultScope
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ build_from_cfg
+ build_model_from_cfg
+ build_runner_from_cfg
+ build_scheduler_from_cfg
+ count_registered_modules
+ traverse_registry_tree
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/runner.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/runner.rst
new file mode 100644
index 0000000000000000000000000000000000000000..3217d17b92dea68a6bd7123d7e2b9cecf5ef69c3
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/runner.rst
@@ -0,0 +1,87 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.runner
+===================================
+
+.. contents:: mmengine.runner
+ :depth: 2
+ :local:
+ :backlinks: top
+
+.. currentmodule:: mmengine.runner
+
+Runner
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ Runner
+
+Loop
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ BaseLoop
+ EpochBasedTrainLoop
+ IterBasedTrainLoop
+ ValLoop
+ TestLoop
+
+Checkpoints
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ CheckpointLoader
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ find_latest_checkpoint
+ get_deprecated_model_names
+ get_external_models
+ get_mmcls_models
+ get_state_dict
+ get_torchvision_models
+ load_checkpoint
+ load_state_dict
+ save_checkpoint
+ weights_to_cpu
+
+AMP
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ autocast
+
+Miscellaneous
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ LogProcessor
+ Priority
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ get_priority
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/structures.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/structures.rst
new file mode 100644
index 0000000000000000000000000000000000000000..bfb651be30d12ca16c9a1d226627276c1ea61a43
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/structures.rst
@@ -0,0 +1,22 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.structures
+===================================
+
+.. contents:: mmengine.structures
+ :depth: 2
+ :local:
+ :backlinks: top
+
+.. currentmodule:: mmengine.structures
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ BaseDataElement
+ InstanceData
+ LabelData
+ PixelData
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/utils.dl_utils.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/utils.dl_utils.rst
new file mode 100644
index 0000000000000000000000000000000000000000..8f40f18da1d45c06ed97fec030b51a727a4742ee
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/utils.dl_utils.rst
@@ -0,0 +1,29 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.utils.dl_utils
+===================================
+
+.. currentmodule:: mmengine.utils.dl_utils
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ TimeCounter
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ collect_env
+ load_url
+ has_batch_norm
+ is_norm
+ mmcv_full_available
+ tensor2imgs
+ TORCH_VERSION
+ set_multi_processing
+ torch_meshgrid
+ is_jit_tracing
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/utils.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/utils.rst
new file mode 100644
index 0000000000000000000000000000000000000000..681e15d2c0115979e756a147a2f72366e33bf255
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/utils.rst
@@ -0,0 +1,118 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.utils
+===================================
+
+.. contents:: mmengine.utils
+ :depth: 2
+ :local:
+ :backlinks: top
+
+.. currentmodule:: mmengine.utils
+
+Manager
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ ManagerMeta
+ ManagerMixin
+
+Path
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ check_file_exist
+ fopen
+ is_abs
+ is_filepath
+ mkdir_or_exist
+ scandir
+ symlink
+
+Package
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ call_command
+ install_package
+ get_installed_path
+ is_installed
+
+Version
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ digit_version
+ get_git_hash
+
+Progress Bar
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ ProgressBar
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ track_iter_progress
+ track_parallel_progress
+ track_progress
+
+
+Miscellaneous
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ Timer
+ TimerError
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+
+ is_list_of
+ is_tuple_of
+ is_seq_of
+ is_str
+ iter_cast
+ list_cast
+ tuple_cast
+ concat_list
+ slice_list
+ to_1tuple
+ to_2tuple
+ to_3tuple
+ to_4tuple
+ to_ntuple
+ check_prerequisites
+ deprecated_api_warning
+ deprecated_function
+ has_method
+ is_method_overridden
+ import_modules_from_strings
+ requires_executable
+ requires_package
+ check_time
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/api/visualization.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/api/visualization.rst
new file mode 100644
index 0000000000000000000000000000000000000000..5265dc6edbd427c0b89cbd43944d96e08016980b
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/api/visualization.rst
@@ -0,0 +1,35 @@
+.. role:: hidden
+ :class: hidden-section
+
+mmengine.visualization
+===================================
+
+.. contents:: mmengine.visualization
+ :depth: 2
+ :local:
+ :backlinks: top
+
+.. currentmodule:: mmengine.visualization
+
+Visualizer
+----------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ Visualizer
+
+visualization Backend
+---------------------
+
+.. autosummary::
+ :toctree: generated
+ :nosignatures:
+ :template: classtemplate.rst
+
+ BaseVisBackend
+ LocalVisBackend
+ TensorboardVisBackend
+ WandbVisBackend
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/conf.py b/testbed/open-mmlab__mmengine/docs/zh_cn/conf.py
new file mode 100644
index 0000000000000000000000000000000000000000..6128280373aca43040cc3f5e153dbd3ac8f64ad9
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/conf.py
@@ -0,0 +1,113 @@
+# Configuration file for the Sphinx documentation builder.
+#
+# This file only contains a selection of the most common options. For a full
+# list see the documentation:
+# https://www.sphinx-doc.org/en/master/usage/configuration.html
+
+# -- Path setup --------------------------------------------------------------
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#
+import os
+import subprocess
+import sys
+
+import pytorch_sphinx_theme
+
+sys.path.insert(0, os.path.abspath('../..'))
+
+# -- Project information -----------------------------------------------------
+
+project = 'mmengine'
+copyright = '2022, mmengine contributors'
+author = 'mmengine contributors'
+
+version_file = '../../mmengine/version.py'
+with open(version_file) as f:
+ exec(compile(f.read(), version_file, 'exec'))
+__version__ = locals()['__version__']
+# The short X.Y version
+version = __version__
+# The full version, including alpha/beta/rc tags
+release = __version__
+
+# -- General configuration ---------------------------------------------------
+
+# This is also used if you do content translation via gettext catalogs.
+# Usually you set "language" from the command line for these cases.
+language = 'zh_CN'
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
+# ones.
+
+extensions = [
+ 'sphinx.ext.autodoc',
+ 'sphinx.ext.autosummary',
+ 'sphinx.ext.intersphinx',
+ 'sphinx.ext.napoleon',
+ 'sphinx.ext.viewcode',
+ 'sphinx.ext.autosectionlabel',
+ 'myst_parser',
+ 'sphinx_copybutton',
+ 'sphinx.ext.autodoc.typehints',
+] # yapf: disable
+autodoc_typehints = 'description'
+myst_heading_anchors = 4
+myst_enable_extensions = ['colon_fence']
+
+# Configuration for intersphinx
+intersphinx_mapping = {
+ 'python': ('https://docs.python.org/3', None),
+ 'numpy': ('https://numpy.org/doc/stable', None),
+ 'torch': ('https://pytorch.org/docs/stable/', None),
+ 'mmcv': ('https://mmcv.readthedocs.io/zh_CN/2.x/', None),
+}
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+# This pattern also affects html_static_path and html_extra_path.
+exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
+
+# -- Options for HTML output -------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+#
+html_theme = 'pytorch_sphinx_theme'
+html_theme_path = [pytorch_sphinx_theme.get_html_theme_path()]
+
+html_theme_options = {
+ 'menu': [
+ {
+ 'name': 'GitHub',
+ 'url': 'https://github.com/open-mmlab/mmengine'
+ },
+ ],
+ # Specify the language of shared menu
+ 'menu_lang': 'cn',
+}
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+html_css_files = ['css/readthedocs.css']
+
+# -- Extension configuration -------------------------------------------------
+# Ignore >>> when copying code
+copybutton_prompt_text = r'>>> |\.\.\. '
+copybutton_prompt_is_regexp = True
+
+
+def builder_inited_handler(app):
+ subprocess.run(['./cp_origin_docs.sh'])
+
+
+def setup(app):
+ app.connect('builder-inited', builder_inited_handler)
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/cp_origin_docs.sh b/testbed/open-mmlab__mmengine/docs/zh_cn/cp_origin_docs.sh
new file mode 100644
index 0000000000000000000000000000000000000000..1e728323684a0aad1571eb392871d6c5de6644fc
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/cp_origin_docs.sh
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+
+# Copy *.md files from docs/ if it doesn't have a Chinese translation
+
+for filename in $(find ../en/ -name '*.md' -printf "%P\n");
+do
+ mkdir -p $(dirname $filename)
+ cp -n ../en/$filename ./$filename
+done
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/design/evaluation.md b/testbed/open-mmlab__mmengine/docs/zh_cn/design/evaluation.md
new file mode 100644
index 0000000000000000000000000000000000000000..aef780e3f2b0133e64ffa7e934de4e4e840b4779
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/design/evaluation.md
@@ -0,0 +1,88 @@
+# 模型精度评测
+
+## 评测指标与评测器
+
+在模型验证和模型测试中,通常需要对模型精度做定量评测。在 MMEngine 中实现了评测指标(Metric)和评测器(Evaluator)来完成这一功能。
+
+- **评测指标** 用于根据测试数据和模型预测结果,完成特定模型精度指标的计算。在 OpenMMLab 各算法库中提供了对应任务的常用评测指标,如 [MMClassification](https://github.com/open-mmlab/mmclassification) 中提供了[Accuracy](https://mmclassification.readthedocs.io/en/1.x/api/generated/mmcls.evaluation.Accuracy.html#mmcls.evaluation.Accuracy) 用于计算分类模型的 Top-k 分类正确率;MMDetection 中提供了 [COCOMetric](https://github.com/open-mmlab/mmdetection/blob/3.x/mmdet/evaluation/metrics/coco_metric.py) 用于计算目标检测模型的 AP,AR 等评测指标。评测指标与数据集解耦,如 COCOMetric 也可用于 COCO 以外的目标检测数据集上。
+
+- **评测器** 是评测指标的上层模块,通常包含一个或多个评测指标。评测器的作用是在模型评测时完成必要的数据格式转换,并调用评测指标计算模型精度。评测器通常由[执行器](../tutorials/runner.md)或测试脚本构建,分别用于在线评测和离线评测。
+
+### 评测指标基类 `BaseMetric`
+
+评测指标基类 `BaseMetric` 是一个抽象类,初始化参数如下:
+
+- `collect_device`:在分布式评测中用于同步结果的设备名,如 `'cpu'` 或 `'gpu'`。
+- `prefix`:评测指标名前缀,用以区别多个同名的评测指标。如果该参数未给定,则会尝试使用类属性 `default_prefix` 作为前缀。
+
+```python
+class BaseMetric(metaclass=ABCMeta):
+
+ default_prefix: Optional[str] = None
+
+ def __init__(self,
+ collect_device: str = 'cpu',
+ prefix: Optional[str] = None) -> None:
+ ...
+```
+
+`BaseMetric` 有以下 2 个重要的方法需要在子类中重写:
+
+- **`process()`** 用于处理每个批次的测试数据和模型预测结果。处理结果应存放在 `self.results` 列表中,用于在处理完所有测试数据后计算评测指标。该方法具有以下 2 个参数:
+
+ - `data_batch`:一个批次的测试数据样本,通常直接来自与数据加载器
+ - `data_samples`:对应的模型预测结果
+ 该方法没有返回值。函数接口定义如下:
+
+ ```python
+ @abstractmethod
+ def process(self, data_batch: Any, data_samples: Sequence[dict]) -> None:
+ """Process one batch of data samples and predictions. The processed
+ results should be stored in ``self.results``, which will be used to
+ compute the metrics when all batches have been processed.
+ Args:
+ data_batch (Any): A batch of data from the dataloader.
+ data_samples (Sequence[dict]): A batch of outputs from the model.
+ """
+ ```
+
+- **`compute_metrics()`** 用于计算评测指标,并将所评测指标存放在一个字典中返回。该方法有以下 1 个参数:
+
+ - `results`:列表类型,存放了所有批次测试数据经过 `process()` 方法处理后得到的结果
+ 该方法返回一个字典,里面保存了评测指标的名称和对应的评测值。函数接口定义如下:
+
+ ```python
+ @abstractmethod
+ def compute_metrics(self, results: list) -> dict:
+ """Compute the metrics from processed results.
+
+ Args:
+ results (list): The processed results of each batch.
+
+ Returns:
+ dict: The computed metrics. The keys are the names of the metrics,
+ and the values are corresponding results.
+ """
+ ```
+
+其中,`compute_metrics()` 会在 `evaluate()` 方法中被调用;后者在计算评测指标前,会在分布式测试时收集和汇总不同 rank 的中间处理结果。
+
+需要注意的是,`self.results` 中存放的具体类型取决于评测指标子类的实现。例如,当测试样本或模型输出数据量较大(如语义分割、图像生成等任务),不宜全部存放在内存中时,可以在 `self.results` 中存放每个批次计算得到的指标,并在 `compute_metrics()` 中汇总;或将每个批次的中间结果存储到临时文件中,并在 `self.results` 中存放临时文件路径,最后由 `compute_metrics()` 从文件中读取数据并计算指标。
+
+## 模型精度评测流程
+
+通常,模型精度评测的过程如下图所示。
+
+**在线评测**:测试数据通常会被划分为若干批次(batch)。通过一个循环,依次将每个批次的数据送入模型,得到对应的预测结果,并将测试数据和模型预测结果送入评测器。评测器会调用评测指标的 `process()` 方法对数据和预测结果进行处理。当循环结束后,评测器会调用评测指标的 `evaluate()` 方法,可计算得到对应指标的模型精度。
+
+**离线评测**:与在线评测过程类似,区别是直接读取预先保存的模型预测结果来进行评测。评测器提供了 `offline_evaluate` 接口,用于在离线方式下调用评测指标来计算模型精度。为了避免同时处理大量数据导致内存溢出,离线评测时会将测试数据和预测结果分成若干个块(chunk)进行处理,类似在线评测中的批次。
+
+
+
+
+
+## 增加自定义评测指标
+
+在 OpenMMLab 的各个算法库中,已经实现了对应方向的常用评测指标。如 MMDetection 中提供了 COCO 评测指标,MMClassification 中提供了 Accuracy、F1Score 等评测指标等。
+
+用户也可以增加自定义的评测指标。具体方法可以参考[教程文档](../tutorials/evaluation.md#自定义评测指标)中给出的示例。
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/design/hook.md b/testbed/open-mmlab__mmengine/docs/zh_cn/design/hook.md
new file mode 100644
index 0000000000000000000000000000000000000000..7da694ae50e9fcf399307f1ee988923cb56ed298
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/design/hook.md
@@ -0,0 +1,204 @@
+# 钩子
+
+钩子编程是一种编程模式,是指在程序的一个或者多个位置设置位点(挂载点),当程序运行至某个位点时,会自动调用运行时注册到位点的所有方法。钩子编程可以提高程序的灵活性和拓展性,用户将自定义的方法注册到位点便可被调用而无需修改程序中的代码。
+
+## 钩子示例
+
+下面是钩子的简单示例。
+
+```python
+pre_hooks = [(print, 'hello')]
+post_hooks = [(print, 'goodbye')]
+
+def main():
+ for func, arg in pre_hooks:
+ func(arg)
+ print('do something here')
+ for func, arg in post_hooks:
+ func(arg)
+
+main()
+```
+
+下面是程序的输出:
+
+```
+hello
+do something here
+goodbye
+```
+
+可以看到,`main` 函数在两个位置调用钩子中的函数而无需做任何改动。
+
+在 PyTorch 中,钩子的应用也随处可见,例如神经网络模块(nn.Module)中的钩子可以获得模块的前向输入输出以及反向的输入输出。以 [`register_forward_hook`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.register_forward_hook) 方法为例,该方法往模块注册一个前向钩子,钩子可以获得模块的前向输入和输出。
+
+下面是 `register_forward_hook` 用法的简单示例:
+
+```python
+import torch
+import torch.nn as nn
+
+def forward_hook_fn(
+ module, # 被注册钩子的对象
+ input, # module 前向计算的输入
+ output, # module 前向计算的输出
+):
+ print(f'"forward_hook_fn" is invoked by {module.name}')
+ print('weight:', module.weight.data)
+ print('bias:', module.bias.data)
+ print('input:', input)
+ print('output:', output)
+
+class Model(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.fc = nn.Linear(3, 1)
+
+ def forward(self, x):
+ y = self.fc(x)
+ return y
+
+model = Model()
+# 将 forward_hook_fn 注册到 model 每个子模块
+for module in model.children():
+ module.register_forward_hook(forward_hook_fn)
+
+x = torch.Tensor([[0.0, 1.0, 2.0]])
+y = model(x)
+```
+
+下面是程序的输出:
+
+```python
+"forward_hook_fn" is invoked by Linear(in_features=3, out_features=1, bias=True)
+weight: tensor([[-0.4077, 0.0119, -0.3606]])
+bias: tensor([-0.2943])
+input: (tensor([[0., 1., 2.]]),)
+output: tensor([[-1.0036]], grad_fn=)
+```
+
+可以看到注册到 Linear 模块的 `forward_hook_fn` 钩子被调用,在该钩子中打印了 Linear 模块的权重、偏置、模块的输入以及输出。更多关于 PyTorch 钩子的用法可以阅读 [nn.Module](https://pytorch.org/docs/stable/generated/torch.nn.Module.html)。
+
+## MMEngine 中钩子的设计
+
+在介绍 MMEngine 中钩子的设计之前,先简单介绍使用 PyTorch 实现模型训练的基本步骤(示例代码来自 [PyTorch Tutorials](https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py)):
+
+```python
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.optim as optim
+import torchvision.transforms as transforms
+from torch.utils.data import Dataset, DataLoader
+
+class CustomDataset(Dataset):
+ pass
+
+class Net(nn.Module):
+ pass
+
+def main():
+ transform = transforms.ToTensor()
+ train_dataset = CustomDataset(transform=transform, ...)
+ val_dataset = CustomDataset(transform=transform, ...)
+ test_dataset = CustomDataset(transform=transform, ...)
+ train_dataloader = DataLoader(train_dataset, ...)
+ val_dataloader = DataLoader(val_dataset, ...)
+ test_dataloader = DataLoader(test_dataset, ...)
+
+ net = Net()
+ criterion = nn.CrossEntropyLoss()
+ optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
+
+ for i in range(max_epochs):
+ for inputs, labels in train_dataloader:
+ optimizer.zero_grad()
+ outputs = net(inputs)
+ loss = criterion(outputs, labels)
+ loss.backward()
+ optimizer.step()
+
+ with torch.no_grad():
+ for inputs, labels in val_dataloader:
+ outputs = net(inputs)
+ loss = criterion(outputs, labels)
+
+ with torch.no_grad():
+ for inputs, labels in test_dataloader:
+ outputs = net(inputs)
+ accuracy = ...
+```
+
+上面的伪代码是训练模型的基本步骤。如果要在上面的代码中加入定制化的逻辑,我们需要不断修改和拓展 `main` 函数。为了提高 `main` 函数的灵活性和拓展性,我们可以在 `main` 方法中插入位点,并在对应位点实现调用 hook 的抽象逻辑。此时只需在这些位点插入 hook 来实现定制化逻辑,即可添加定制化功能,例如加载模型权重、更新模型参数等。
+
+```python
+def main():
+ ...
+ call_hooks('before_run', hooks) # 任务开始前执行的逻辑
+ call_hooks('after_load_checkpoint', hooks) # 加载权重后执行的逻辑
+ call_hooks('before_train', hooks) # 训练开始前执行的逻辑
+ for i in range(max_epochs):
+ call_hooks('before_train_epoch', hooks) # 遍历训练数据集前执行的逻辑
+ for inputs, labels in train_dataloader:
+ call_hooks('before_train_iter', hooks) # 模型前向计算前执行的逻辑
+ outputs = net(inputs)
+ loss = criterion(outputs, labels)
+ call_hooks('after_train_iter', hooks) # 模型前向计算后执行的逻辑
+ loss.backward()
+ optimizer.step()
+ call_hooks('after_train_epoch', hooks) # 遍历完训练数据集后执行的逻辑
+
+ call_hooks('before_val_epoch', hooks) # 遍历验证数据集前执行的逻辑
+ with torch.no_grad():
+ for inputs, labels in val_dataloader:
+ call_hooks('before_val_iter', hooks) # 模型前向计算前执行
+ outputs = net(inputs)
+ loss = criterion(outputs, labels)
+ call_hooks('after_val_iter', hooks) # 模型前向计算后执行
+ call_hooks('after_val_epoch', hooks) # 遍历完验证数据集前执行
+
+ call_hooks('before_save_checkpoint', hooks) # 保存权重前执行的逻辑
+ call_hooks('after_train', hooks) # 训练结束后执行的逻辑
+
+ call_hooks('before_test_epoch', hooks) # 遍历测试数据集前执行的逻辑
+ with torch.no_grad():
+ for inputs, labels in test_dataloader:
+ call_hooks('before_test_iter', hooks) # 模型前向计算后执行的逻辑
+ outputs = net(inputs)
+ accuracy = ...
+ call_hooks('after_test_iter', hooks) # 遍历完成测试数据集后执行的逻辑
+ call_hooks('after_test_epoch', hooks) # 遍历完测试数据集后执行
+
+ call_hooks('after_run', hooks) # 任务结束后执行的逻辑
+```
+
+在 MMEngine 中,我们将训练过程抽象成执行器(Runner),执行器除了完成环境的初始化,另一个功能是在特定的位点调用钩子完成定制化逻辑。更多关于执行器的介绍请阅读[执行器文档](../tutorials/runner.md)。
+
+为了方便管理,MMEngine 将位点定义为方法并集成到[钩子基类(Hook)](mmengine.hooks.Hook)中,我们只需继承钩子基类并根据需求在特定位点实现定制化逻辑,再将钩子注册到执行器中,便可自动调用钩子中相应位点的方法。
+
+钩子中一共有 22 个位点:
+
+- before_run
+- after_run
+- before_train
+- after_train
+- before_train_epoch
+- after_train_epoch
+- before_train_iter
+- after_train_iter
+- before_val
+- after_val
+- before_val_epoch
+- after_val_epoch
+- before_val_iter
+- after_val_iter
+- before_test
+- after_test
+- before_test_epoch
+- after_test_epoch
+- before_test_iter
+- after_test_iter
+- before_save_checkpoint
+- after_load_checkpoint
+
+你可能还想阅读[钩子的用法](../tutorials/hook.md)或者[钩子的 API 文档](mmengine.hooks)。
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/design/logging.md b/testbed/open-mmlab__mmengine/docs/zh_cn/design/logging.md
new file mode 100644
index 0000000000000000000000000000000000000000..fbaa5074b292640c9ac9254a7ed133308a19ef95
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/design/logging.md
@@ -0,0 +1,450 @@
+# 日志系统
+
+## 概述
+
+[执行器(Runner)](./runner.md)在运行过程中会产生很多日志,例如加载的数据集信息、模型的初始化信息、训练过程中的学习率、损失等。为了让用户能够更加自由的获取这些日志信息,MMEngine 实现了[消息枢纽(MessageHub)](mmengine.logging.MessageHub)、[历史缓冲区(HistoryBuffer)](mmengine.logging.HistoryBuffer)、[日志处理器(LogProcessor)](mmengine.runner.LogProcessor) 和 [MMLogger](mmengine.logging.MMLogger) 来支持以下功能:
+
+- 用户可以通过配置文件,根据个人偏好来选择日志统计方式,例如在终端输出整个训练过程中的平均损失而不是基于固定迭代次数平滑的损失
+- 用户可以在任意组件中获取当前的训练状态,例如当前的迭代次数、训练轮次等
+- 用户可以通过配置文件来控制是否保存分布式训练下的多进程日志
+
+
+
+训练过程中的产生的损失、学习率等数据由历史缓冲区管理和封装,汇总后交给消息枢纽维护。日志处理器将消息枢纽中的数据进行格式化,最后通过[记录器钩子(LoggerHook)](mmengine.hook.LoggerHook) 展示到各种可视化后端。**一般情况下用户无需感知数据处理流程,可以直接通过配置日志处理器来选择日志的统计方式**。在介绍 MMEngine 的日志系统的设计之前,可以先阅读[记录日志教程](../tutorials/logging.md) 了解日志系统的基本用法。
+
+## 历史缓冲区(HistoryBuffer)
+
+MMEngine 实现了历史数据存储的抽象类历史缓冲区(HistoryBuffer),用于存储训练日志的历史轨迹,如模型损失、优化器学习率、迭代时间等。通常情况下,历史缓冲区作为内部类,配合[消息枢纽(MessageHub)](mmengine.logging.MessageHub)、记录器钩子(LoggerHook )和[日志处理器(LogProcessor)](mmengine.runner.LogProcessor) 实现了训练日志的可配置化。
+
+用户也可以单独使用历史缓冲区来管理训练日志,能够非常简单的使用不同方法来统计训练日志。我们先来介绍如何单独使用历史缓冲区,在消息枢纽一节再进一步介绍二者的联动。
+
+### 历史缓冲区初始化
+
+历史缓冲区的初始化可以接受 `log_history` 和 `count_history` 两个参数。`log_history` 表示日志的历史轨迹,例如前三次迭代的 loss 为 0.3,0.2,0.1。我们就可以记 `log_history=[0.3, 0.2, 0.1]`。`count_history` 是一个比较抽象的概念,如果按照迭代次数来算,0.3,0.2,0.1 分别是三次迭代的结果,那么我们可以记 `count_history=[1, 1, 1]`,其中 “1” 表示一次迭代。如果按照 batch 来算,例如每次迭代的 `batch_size` 为 8,那么 `count_history=[8, 8, 8]`。`count_history` 只会在统计均值时用到,用于控制返回均值的粒度。就拿上面那个例子来说,`count_history=[1, 1, 1]` 时会统计每次迭代的平均 loss,而 `count_history=[8, 8, 8]` 则会统计每张图片的平均 loss。
+
+```python
+from mmengine.logging import HistoryBuffer
+
+history_buffer = HistoryBuffer() # 空初始化
+log_history, count_history = history_buffer.data
+# [] []
+history_buffer = HistoryBuffer([1, 2, 3], [1, 2, 3]) # list 初始化
+log_history, count_history = history_buffer.data
+# [1 2 3] [1 2 3]
+history_buffer = HistoryBuffer([1, 2, 3], [1, 2, 3], max_length=2)
+# The length of history buffer(3) exceeds the max_length(2), the first few elements will be ignored.
+log_history, count_history = history_buffer.data # 最大长度为2,只能存储 [2, 3]
+# [2 3] [2 3]
+```
+
+我们可以通过 `history_buffer.data` 来返回日志的历史轨迹。此外,我们可以为历史缓冲区设置最大队列长度,当历史缓冲区的长度大于最大队列长度时,会自动丢弃最早更新的数据。
+
+### 更新历史缓冲区
+
+我们可以通过 `update` 接口来更新历史缓冲区。update 接受两个参数,第一个参数用于更新 `log_history `,第二个参数用于更新 `count_history`。
+
+```python
+history_buffer = HistoryBuffer([1, 2, 3], [1, 1, 1])
+history_buffer.update(4) # 更新日志
+log_history, count_history = history_buffer.data
+# [1, 2, 3, 4] [1, 1, 1, 1]
+history_buffer.update(5, 2) # 更新日志
+log_history, count_history = history_buffer.data
+# [1, 2, 3, 4, 5] [1, 1, 1, 1, 2]
+```
+
+### 基本统计方法
+
+历史缓冲区提供了基本的数据统计方法:
+
+- `current()`:获取最新更新的数据。
+- `mean(window_size=None)`:获取窗口内数据的均值,默认返回数据的全局均值
+- `max(window_size=None)`:获取窗口内数据的最大值,默认返回全局最大值
+- `min(window_size=None)`:获取窗口内数据的最小值,默认返回全局最小值
+
+```python
+history_buffer = HistoryBuffer([1, 2, 3], [1, 1, 1])
+history_buffer.min(2)
+# 2,从 [2, 3] 中统计最小值
+history_buffer.min()
+# 返回全局最小值 1
+
+history_buffer.max(2)
+# 3,从 [2, 3] 中统计最大值
+history_buffer.min()
+# 返回全局最大值 3
+history_buffer.mean(2)
+# 2.5,从 [2, 3] 中统计均值, (2 + 3) / (1 + 1)
+history_buffer.mean() # (1 + 2 + 3) / (1 + 1 + 1)
+# 返回全局均值 2
+history_buffer = HistoryBuffer([1, 2, 3], [2, 2, 2]) # 当 count 不为 1时
+history_buffer.mean() # (1 + 2 + 3) / (2 + 2 + 2)
+# 返回均值 1
+history_buffer = HistoryBuffer([1, 2, 3], [1, 1, 1])
+history_buffer.update(4, 1)
+history_buffer.current()
+# 4
+```
+
+### 统计方法的统一入口
+
+要想支持在配置文件中通过配置 'max','min' 等字段来选择日志的统计方式,那么 HistoryBuffer 就需要一个接口来接受 'min','max' 等统计方法字符串和相应参数,进而找到对应的统计方法,最后输出统计结果。`statistics(name, *args, **kwargs)` 接口就起到了这个作用。其中 name 是已注册的方法名(已经注册 `min`,`max` 等基本统计方法),`*arg` 和 `**kwarg` 用于接受对应方法的参数。
+
+```python
+history_buffer = HistoryBuffer([1, 2, 3], [1, 1, 1])
+history_buffer.statistics('mean')
+# 2 返回全局均值
+history_buffer.statistics('mean', 2)
+# 2.5 返回 [2, 3] 的均值
+history_buffer.statistics('mean', 2, 3) # 错误!传入了不匹配的参数
+history_buffer.statistics('data') # 错误! data 方法未被注册,无法被调用
+```
+
+### 注册统计方法
+
+为了保证历史缓冲区的可扩展性,用户可以通过 `register_statistics` 接口注册自定义的统计函数
+
+```python
+from mmengine.logging import HistoryBuffer
+import numpy as np
+
+
+@HistoryBuffer.register_statistics
+def weighted_mean(self, window_size, weight):
+ assert len(weight) == window_size
+ return (self._log_history[-window_size:] * np.array(weight)).sum() / \
+ self._count_history[-window_size:]
+
+
+history_buffer = HistoryBuffer([1, 2], [1, 1])
+history_buffer.statistics('weighted_mean', 2, [2, 1]) # get (2 * 1 + 1 * 2) / (1 + 1)
+```
+
+用户可以通过 `statistics` 接口,传入方法名和对应参数来调用被注册的函数。
+
+### 使用样例
+
+用户可以独立使用历史缓冲区来记录日志,通过简单的接口调用就能得到期望的统计接口。
+
+```Python
+logs = dict(lr=HistoryBuffer(), loss=HistoryBuffer()) # 字典配合 HistoryBuffer 记录不同字段的日志
+max_iter = 10
+log_interval = 5
+for iter in range(1, max_iter+1):
+ lr = iter / max_iter * 0.1 # 线性学习率变化
+ loss = 1 / iter # loss
+ logs['lr'].update(lr, 1)
+ logs['loss'].update(loss, 1)
+ if iter % log_interval == 0:
+ latest_lr = logs['lr'].statistics('current') # 通过字符串来选择统计方法
+ mean_loss = logs['loss'].statistics('mean', log_interval)
+ print(f'lr: {latest_lr}\n' # 返回最近一次更新的学习率。
+ f'loss: {mean_loss}') # 平滑最新更新的 log_interval 个数据。
+# lr: 0.05
+# loss: 0.45666666666666667
+# lr: 0.1
+# loss: 0.12912698412698415
+```
+
+MMEngine 利用历史缓冲区的特性,结合消息枢纽,实现了训练日志的高度可定制化。
+
+## 消息枢纽(MessageHub)
+
+历史缓冲区(HistoryBuffer)可以十分简单地完成单个日志的更新和统计,而在模型训练过程中,日志的种类繁多,并且来自于不同的组件,因此如何完成日志的分发和收集是需要考虑的问题。 MMEngine 使用消息枢纽(MessageHub)来实现组件与组件、执行器与执行器之间的数据共享。消息枢纽继承自全局管理器(ManagerMixin),支持跨模块访问。
+
+消息枢纽存储了两种含义的数据:
+
+- 历史缓冲区字典:消息枢纽会收集各个模块更新的训练日志,如损失、学习率、迭代时间,并将其更新至内部的历史缓冲区字典中。历史缓冲区字典经[消息处理器(LogProcessor)](mmengine.runner.LogProcessor)处理后,会被输出到终端/保存到本地。如果用户需要记录自定义日志,可以往历史缓冲区字典中更新相应内容。
+- 运行时信息字典:运行时信息字典用于存储迭代次数、训练轮次等运行时信息,方便 MMEngine 中所有组件共享这些信息。
+
+```{note}
+当用户想在终端输出自定义日志,或者想跨模块共享一些自定义数据时,才会用到消息枢纽。
+```
+
+为了方便用户理解消息枢纽在训练过程中更新信息以及分发信息的流程,我们通过几个例子来介绍消息枢纽的使用方法,以及如何使用消息枢纽向终端输出自定义日志。
+
+### 更新/获取训练日志
+
+历史缓冲区以字典的形式存储在消息枢纽中。当我们第一次调用 `update_scalar` 时,会初始化对应字段的历史缓冲区,后续的每次更新等价于调用对应字段历史缓冲区的 `update` 方法。同样的我们可以通过 `get_scalar` 来获取对应字段的历史缓冲区,并按需计算统计值。如果想获取消息枢纽的全部日志,可以访问其 `log_scalars` 属性。
+
+```python
+from mmengine import MessageHub
+
+message_hub = MessageHub.get_instance('task')
+message_hub.update_scalar('train/loss', 1, 1)
+message_hub.get_scalar('train/loss').current() # 1,最近一次更新值为 1
+message_hub.update_scalar('train/loss', 3, 1)
+message_hub.get_scalar('train/loss').mean() # 2,均值为 (3 + 1) / (1 + 1)
+message_hub.update_scalar('train/lr', 0.1, 1)
+
+message_hub.update_scalars({'train/time': {'value': 0.1, 'count': 1},
+ 'train/data_time': {'value': 0.1, 'count': 1}})
+
+train_time = message_hub.get_scalar('train/time') # 获取单个日志
+
+log_dict = message_hub.log_scalars # 返回存储全部 HistoryBuffer 的字典
+lr_buffer, loss_buffer, time_buffer, data_time_buffer = (
+ log_dict['train/lr'], log_dict['train/loss'], log_dict['train/time'],
+ log_dict['train/data_time'])
+```
+
+```{note}
+损失、学习率、迭代时间等训练日志在执行器和钩子中自动更新,无需用户维护。
+```
+
+```{note}
+消息枢纽的历史缓冲区字典对 key 没有特殊要求,但是 MMEngine 约定历史缓冲区字典的 key 要有 train/val/test 的前缀,只有带前缀的日志会被输出当终端。
+```
+
+### 更新/获取运行时信息
+
+运行时信息以字典的形式存储在消息枢纽中,能够存储任意数据类型,每次更新都会被覆盖。
+
+```python
+message_hub = MessageHub.get_instance('task')
+message_hub.update_info('iter', 1)
+message_hub.get_info('iter') # 1
+message_hub.update_info('iter', 2)
+message_hub.get_info('iter') # 2 覆盖上一次结果
+```
+
+### 消息枢纽的跨组件通讯
+
+执行器运行过程中,各个组件会通过消息枢纽来分发、接受消息。[RuntimeInfoHook](mmengine.hooks.RuntimeInfoHook) 会汇总其他组件更新的学习率、损失等信息,将其导出到用户指定的输出端(Tensorboard,WandB 等)。由于上述流程较为复杂,这里用一个简单示例来模拟日志钩子和其他组件通讯的过程。
+
+```python
+from mmengine import MessageHub
+
+class LogProcessor:
+ # 汇总不同模块更新的消息,类似 LoggerHook
+ def __init__(self, name):
+ self.message_hub = MessageHub.get_instance(name) # 获取 MessageHub
+
+ def run(self):
+ print(f"Learning rate is {self.message_hub.get_scalar('train/lr').current()}")
+ print(f"loss is {self.message_hub.get_scalar('train/loss').current()}")
+ print(f"meta is {self.message_hub.get_info('meta')}")
+
+
+class LrUpdater:
+ # 更新学习率
+ def __init__(self, name):
+ self.message_hub = MessageHub.get_instance(name) # 获取 MessageHub
+
+ def run(self):
+ self.message_hub.update_scalar('train/lr', 0.001)
+ # 更新学习率,以 HistoryBuffer 形式存储
+
+
+class MetaUpdater:
+ # 更新元信息
+ def __init__(self, name):
+ self.message_hub = MessageHub.get_instance(name)
+
+ def run(self):
+ self.message_hub.update_info(
+ 'meta',
+ dict(experiment='retinanet_r50_caffe_fpn_1x_coco.py',
+ repo='mmdetection')) # 更新元信息,每次更新会覆盖上一次的信息
+
+
+class LossUpdater:
+ # 更新损失函数
+ def __init__(self, name):
+ self.message_hub = MessageHub.get_instance(name)
+
+ def run(self):
+ self.message_hub.update_scalar('train/loss', 0.1)
+
+class ToyRunner:
+ # 组合个各个模块
+ def __init__(self, name):
+ self.message_hub = MessageHub.get_instance(name) # 创建 MessageHub
+ self.log_processor = LogProcessor(name)
+ self.updaters = [LossUpdater(name),
+ MetaUpdater(name),
+ LrUpdater(name)]
+
+ def run(self):
+ for updater in self.updaters:
+ updater.run()
+ self.log_processor.run()
+
+if __name__ == '__main__':
+ task = ToyRunner('name')
+ task.run()
+ # Learning rate is 0.001
+ # loss is 0.1
+ # meta {'experiment': 'retinanet_r50_caffe_fpn_1x_coco.py', 'repo': 'mmdetection'}
+```
+
+### 添加自定义日志
+
+我们可以在任意模块里更新消息枢纽的历史缓冲区字典,历史缓冲区字典中所有的合法字段经统计后最后显示到终端。
+
+```{note}
+更新历史缓冲区字典时,需要保证更新的日志名带有 train,val,test 前缀,否则日志不会在终端显示。
+```
+
+```python
+class CustomModule:
+ def __init__(self):
+ self.message_hub = MessageHub.get_current_instance()
+
+ def custom_method(self):
+ self.message_hub.update_scalar('train/a', 100)
+ self.message_hub.update_scalars({'train/b': 1, 'train/c': 2})
+```
+
+默认情况下,终端上额外显示 a、b、c 最后一次更新的结果。我们也可以通过配置[日志处理器](mmengine.runner.LogProcessor)来切换自定义日志的统计方式。
+
+## 日志处理器(LogProcessor)
+
+用户可以通过配置日志处理器(LogProcessor)来控制日志的统计方法及其参数。默认配置下,日志处理器会统计最近一次更新的学习率、基于迭代次数平滑的损失和迭代时间。用户可以在日志处理器中配置已知字段的统计方式。
+
+### 最简配置
+
+```python
+log_processor = dict(
+ window_size=10,
+)
+```
+
+此时终端会输出每 10 次迭代的平均损失和平均迭代时间。假设此时终端的输出为
+
+```bash
+04/15 12:34:24 - mmengine - INFO - Iter [10/12] , eta: 0:00:00, time: 0.003, data_time: 0.002, loss: 0.13
+```
+
+### 自定义的统计方式
+
+我们可以通过配置 `custom_cfg` 列表来选择日志的统计方式。`custom_cfg` 中的每一个元素需要包括以下信息:
+
+- `data_src`:日志的数据源,用户通过指定 `data_src` 来选择需要被重新统计的日志,一份数据源可以有多种统计方式。默认的日志源包括模型输出的损失字典的 `key`、学习率(`lr`)和迭代时间(`time`/`data_time`),一切经消息枢纽的 `update_scalar`/`update_scalars` 更新的日志均为可以配置的数据源(需要去掉 `train/`、`val/` 前缀)。(必填项)
+- `method_name`:日志的统计方法,即历史缓冲区中的基本统计方法以及用户注册的自定义统计方法(必填项)
+- `log_name`:日志被重新统计后的名字,如果不定义 `log_name`,新日志会覆盖旧日志(选填项)
+- 其他参数:统计方法会用到的参数,其中 `window_size` 为特殊字段,可以为普通的整型、字符串 epoch 和字符串 global。LogProcessor 会实时解析这些参数,以返回基于 iteration、epoch 和全局平滑的统计结果(选填项)
+
+1. 覆盖旧的统计方式
+
+```python
+log_processor = dict(
+ window_size=10,
+ by_epoch=True,
+ custom_cfg=[
+ dict(data_src='loss',
+ method_name='mean',
+ window_size=100)])
+```
+
+此时会无视日志处理器的默认窗口 10,用更大的窗口 100 去统计 loss 的均值,并将原有结果覆盖。
+
+```bash
+04/15 12:34:24 - mmengine - INFO - Iter [10/12] , eta: 0:00:00, time: 0.003, data_time: 0.002, loss: 0.11
+```
+
+2. 新增统计方式,不覆盖
+
+```python
+log_processor = dict(
+ window_size=10,
+ by_epoch=True,
+ custom_cfg=[
+ dict(data_src='loss',
+ log_name='loss_min',
+ method_name='min',
+ window_size=100)])
+```
+
+```bash
+04/15 12:34:24 - mmengine - INFO - Iter [10/12] , eta: 0:00:00, time: 0.003, data_time: 0.002, loss: 0.11, loss_min: 0.08
+```
+
+## MMLogger
+
+为了能够导出层次分明、格式统一、且不受三方库日志系统干扰的日志,MMEngine 在 `logging` 模块的基础上实现了 `MMLogger`。`MMLogger` 继承自全局管理器(`ManagerMixin`),相比于 `logging.Logger`,`MMLogger` 能够在无法获取 `logger` 的名字(logger name)的情况下,拿到当前执行器的 `logger`。
+
+### 创建 MMLogger
+
+我们可以通过 `get_instance` 接口创建全局可获取的 `logger`,默认的日志格式如下
+
+```python
+logger = MMLogger.get_instance('mmengine', log_level='INFO')
+logger.info("this is a test")
+# 04/15 14:01:11 - mmengine - INFO - this is a test
+```
+
+`logger` 除了输出消息外,还会额外输出时间戳、logger 的名字和日志等级。对于 ERROR 等级的日志,我们会用红色高亮日志等级,并额外输出错误日志的代码位置
+
+```python
+logger = MMLogger.get_instance('mmengine', log_level='INFO')
+logger.error('division by zero')
+# 04/15 14:01:56 - mmengine - ERROR - /mnt/d/PythonCode/DeepLearning/OpenMMLab/mmengine/a.py - - 4 - division by zero
+```
+
+### 导出日志
+
+调用 `get_instance` 时,如果指定了 log_file,会将日志记录的信息以文本格式导出到本地。
+
+```Python
+logger = MMLogger.get_instance('mmengine', log_file='tmp.log', log_level='INFO')
+logger.info("this is a test")
+# 04/15 14:01:11 - mmengine - INFO - this is a test
+```
+
+`tmp/tmp.log`:
+
+```text
+04/15 14:01:11 - mmengine - INFO - this is a test
+```
+
+由于分布式情况下会创建多个日志文件,因此我们在预定的导出路径下,增加一级和导出文件同名的目录,用于存储所有进程的日志。上例中导出路径为 `tmp.log`,实际存储路径为 `tmp/tmp.log`。
+
+### 分布式训练时导出日志
+
+使用 pytorch 分布式训练时,我们可以通过配置 `distributed=True` 来导出分布式训练时各个进程的日志(默认关闭)。
+
+```python
+logger = MMLogger.get_instance('mmengine', log_file='tmp.log', distributed=True, log_level='INFO')
+```
+
+单机多卡,或者多机多卡但是共享存储的情况下,导出的分布式日志路径如下
+
+```text
+# 共享存储
+./tmp
+├── tmp.log
+├── tmp_rank1.log
+├── tmp_rank2.log
+├── tmp_rank3.log
+├── tmp_rank4.log
+├── tmp_rank5.log
+├── tmp_rank6.log
+└── tmp_rank7.log
+...
+└── tmp_rank63.log
+```
+
+多机多卡,独立存储的情况:
+
+```text
+# 独立存储
+# 设备0:
+work_dir/
+└── exp_name_logs
+ ├── exp_name.log
+ ├── exp_name_rank1.log
+ ├── exp_name_rank2.log
+ ├── exp_name_rank3.log
+ ...
+ └── exp_name_rank7.log
+
+# 设备7:
+work_dir/
+└── exp_name_logs
+ ├── exp_name_rank56.log
+ ├── exp_name_rank57.log
+ ├── exp_name_rank58.log
+ ...
+ └── exp_name_rank63.log
+```
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/design/runner.md b/testbed/open-mmlab__mmengine/docs/zh_cn/design/runner.md
new file mode 100644
index 0000000000000000000000000000000000000000..474d7bdc42101c2f600e4bcd0355a5e1303ee87c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/design/runner.md
@@ -0,0 +1,157 @@
+# 执行器
+
+深度学习算法的训练、验证和测试通常都拥有相似的流程,因此, MMEngine 抽象出了执行器来负责通用的算法模型的训练、测试、推理任务。用户一般可以直接使用 MMEngine 中的默认执行器,也可以对执行器进行修改以满足定制化需求。
+
+在介绍执行器的设计之前,我们先举几个例子来帮助用户理解为什么需要执行器。下面是一段使用 PyTorch 进行模型训练的伪代码:
+
+```python
+model = ResNet()
+optimizer = SGD(model.parameters(), lr=0.01, momentum=0.9)
+train_dataset = ImageNetDataset(...)
+train_dataloader = DataLoader(train_dataset, ...)
+
+for i in range(max_epochs):
+ for data_batch in train_dataloader:
+ optimizer.zero_grad()
+ outputs = model(data_batch)
+ loss = loss_func(outputs, data_batch)
+ loss.backward()
+ optimizer.step()
+```
+
+下面是一段使用 PyTorch 进行模型测试的伪代码:
+
+```python
+model = ResNet()
+model.load_state_dict(torch.load(CKPT_PATH))
+model.eval()
+
+test_dataset = ImageNetDataset(...)
+test_dataloader = DataLoader(test_dataset, ...)
+
+for data_batch in test_dataloader:
+ outputs = model(data_batch)
+ acc = calculate_acc(outputs, data_batch)
+```
+
+下面是一段使用 PyTorch 进行模型推理的伪代码:
+
+```python
+model = ResNet()
+model.load_state_dict(torch.load(CKPT_PATH))
+model.eval()
+
+for img in imgs:
+ prediction = model(img)
+```
+
+可以从上面的三段代码看出,这三个任务的执行流程都可以归纳为构建模型、读取数据、循环迭代等步骤。上述代码都是以图像分类为例,但不论是图像分类还是目标检测或是图像分割,都脱离不了这套范式。
+因此,我们将模型的训练、验证、测试的流程整合起来,形成了执行器。在执行器中,我们只需要准备好模型、数据等任务必须的模块或是这些模块的配置文件,执行器会自动完成任务流程的准备和执行。
+通过使用执行器以及 MMEngine 中丰富的功能模块,用户不再需要手动搭建训练测试的流程,也不再需要去处理分布式与非分布式训练的区别,可以专注于算法和模型本身。
+
+
+
+MMEngine 的执行器内包含训练、测试、验证所需的各个模块,以及循环控制器(Loop)和[钩子(Hook)](../tutorials/hook.md)。用户通过提供配置文件或已构建完成的模块,执行器将自动完成运行环境的配置,模块的构建和组合,最终通过循环控制器执行任务循环。执行器对外提供三个接口:`train`, `val`, `test`,当调用这三个接口时,便会运行对应的循环控制器,并在循环的运行过程中调用钩子模块各个位点的钩子函数。
+
+当用户构建一个执行器并调用训练、验证、测试的接口时,执行器的执行流程如下:创建工作目录 -> 配置运行环境 -> 准备任务所需模块 -> 注册钩子 -> 运行循环
+
+
+
+执行器具有延迟初始化(Lazy Initialization)的特性,在初始化执行器时,并不需要依赖训练、验证和测试的全量模块,只有当运行某个循环控制器时,才会检查所需模块是否构建。因此,若用户只需要执行训练、验证或测试中的某一项功能,只需提供对应的模块或模块的配置即可。
+
+## 循环控制器
+
+在 MMEngine 中,我们将任务的执行流程抽象成循环控制器(Loop),因为大部分的深度学习任务执行流程都可以归纳为模型在一组或多组数据上进行循环迭代。
+MMEngine 内提供了四种默认的循环控制器:
+
+- EpochBasedTrainLoop 基于轮次的训练循环
+- IterBasedTrainLoop 基于迭代次数的训练循环
+- ValLoop 标准的验证循环
+- TestLoop 标准的测试循环
+
+
+
+MMEngine 中的默认执行器和循环控制器能够完成大部分的深度学习任务,但不可避免会存在无法满足的情况。有的用户希望能够对执行器进行更多自定义修改,因此,MMEngine 支持自定义模型的训练、验证以及测试的流程。
+
+用户可以通过继承循环基类来实现自己的训练流程。循环基类需要提供两个输入:`runner` 执行器的实例和 `dataloader` 循环所需要迭代的迭代器。
+用户如果有自定义的需求,也可以增加更多的输入参数。MMEngine 中同样提供了 LOOPS 注册器对循环类进行管理,用户可以向注册器内注册自定义的循环模块,然后在配置文件的 `train_cfg`、`val_cfg`、`test_cfg` 中增加 `type` 字段来指定使用何种循环。
+用户可以在自定义的循环中实现任意的执行逻辑,也可以增加或删减钩子(hook)点位,但需要注意的是一旦钩子点位被修改,默认的钩子函数可能不会被执行,导致一些训练过程中默认发生的行为发生变化。
+因此,我们强烈建议用户按照本文档中定义的循环执行流程图以及[钩子设计](../tutorials/hook.md) 去重载循环基类。
+
+```python
+from mmengine.registry import LOOPS, HOOKS
+from mmengine.runner import BaseLoop
+from mmengine.hooks import Hook
+
+
+# 自定义验证循环
+@LOOPS.register_module()
+class CustomValLoop(BaseLoop):
+ def __init__(self, runner, dataloader, evaluator, dataloader2):
+ super().__init__(runner, dataloader, evaluator)
+ self.dataloader2 = runner.build_dataloader(dataloader2)
+
+ def run(self):
+ self.runner.call_hooks('before_val_epoch')
+ for idx, data_batch in enumerate(self.dataloader):
+ self.runner.call_hooks(
+ 'before_val_iter', batch_idx=idx, data_batch=data_batch)
+ outputs = self.run_iter(idx, data_batch)
+ self.runner.call_hooks(
+ 'after_val_iter', batch_idx=idx, data_batch=data_batch, outputs=outputs)
+ metric = self.evaluator.evaluate()
+
+ # 增加额外的验证循环
+ for idx, data_batch in enumerate(self.dataloader2):
+ # 增加额外的钩子点位
+ self.runner.call_hooks(
+ 'before_valloader2_iter', batch_idx=idx, data_batch=data_batch)
+ self.run_iter(idx, data_batch)
+ # 增加额外的钩子点位
+ self.runner.call_hooks(
+ 'after_valloader2_iter', batch_idx=idx, data_batch=data_batch, outputs=outputs)
+ metric2 = self.evaluator.evaluate()
+
+ ...
+
+ self.runner.call_hooks('after_val_epoch')
+
+
+# 定义额外点位的钩子类
+@HOOKS.register_module()
+class CustomValHook(Hook):
+ def before_valloader2_iter(self, batch_idx, data_batch):
+ ...
+
+ def after_valloader2_iter(self, batch_idx, data_batch, outputs):
+ ...
+
+```
+
+上面的例子中实现了一个与默认验证循环不一样的自定义验证循环,它在两个不同的验证集上进行验证,同时对第二次验证增加了额外的钩子点位,并在最后对两个验证结果进行进一步的处理。在实现了自定义的循环类之后,只需要在配置文件的 `val_cfg` 内设置 `type='CustomValLoop'`,并添加额外的配置即可。
+
+```python
+# 自定义验证循环
+val_cfg = dict(type='CustomValLoop', dataloader2=dict(dataset=dict(type='ValDataset2'), ...))
+# 额外点位的钩子
+custom_hooks = [dict(type='CustomValHook')]
+```
+
+## 自定义执行器
+
+更进一步,如果默认执行器中依然有其他无法满足需求的部分,用户可以像自定义其他模块一样,通过继承重写的方式,实现自定义的执行器。执行器同样也可以通过注册器进行管理。具体实现流程与其他模块无异:继承 MMEngine 中的 Runner,重写需要修改的函数,添加进 RUNNERS 注册器中,最后在配置文件中指定 `runner_type` 即可。
+
+```python
+from mmengine.registry import RUNNERS
+from mmengine.runner import Runner
+
+@RUNNERS.register_module()
+class CustomRunner(Runner):
+
+ def setup_env(self):
+ ...
+```
+
+上述例子实现了一个自定义的执行器,并重写了 `setup_env` 函数,然后添加进了 RUNNERS 注册器中,完成了这些步骤之后,便可以在配置文件中设置 `runner_type='CustomRunner'` 来构建自定义的执行器。
+
+你可能还想阅读[执行器的教程](../tutorials/runner.md)或者[执行器的 API 文档](mmengine.runner.Runner)。
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/design/visualization.md b/testbed/open-mmlab__mmengine/docs/zh_cn/design/visualization.md
new file mode 100644
index 0000000000000000000000000000000000000000..72ea232e441d506046e7d284c9632bd1e93b49b0
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/design/visualization.md
@@ -0,0 +1,76 @@
+# 可视化
+
+## 1 总体设计
+
+可视化可以给深度学习的模型训练和测试过程提供直观解释。在 OpenMMLab 算法库中,我们期望可视化功能的设计能满足以下需求:
+
+- 提供丰富的开箱即用可视化功能,能够满足大部分计算机视觉可视化任务
+- 高扩展性,可视化功能通常多样化,应该能够通过简单扩展实现定制需求
+- 能够在训练和测试流程的任意点位进行可视化
+- OpenMMLab 各个算法库具有统一可视化接口,利于用户理解和维护
+
+基于上述需求,OpenMMLab 2.0 引入了可视化对象 Visualizer 和各个可视化存储后端 VisBackend 如 `LocalVisBackend`、`WandbVisBackend` 和 `TensorboardVisBackend` 等。此处的可视化不仅仅包括图片数据格式,还包括配置内容、标量和模型图等数据的可视化。
+
+- 为了方便调用,Visualizer 提供的接口实现了绘制和存储的功能。可视化存储后端 VisBackend 作为 Visualizer 的内部属性,会在需要的时候被 Visualizer 调用,将数据存到不同的后端
+- 考虑到绘制后会希望存储到多个后端,Visualizer 可以配置多个 VisBackend,当用户调用 Visualizer 的存储接口时候,Visualizer 内部会遍历的调用 VisBackend 存储接口
+
+两者的 UML 关系图如下
+
+
+
+
+
+## 2 可视化器 Visualizer
+
+可视化对象 Visualizer 对外提供了所有接口。可以将其接口分成 3 大类,如下所示
+
+**(1) 绘制相关接口**
+
+- [draw_bboxes](mmengine.visualization.Visualizer.draw_bboxes) 绘制单个或多个边界框
+- [draw_points](mmengine.visualization.Visualizer.draw_points) 绘制单个或多个点
+- [draw_texts](mmengine.visualization.Visualizer.draw_texts) 绘制单个或多个文本框
+- [draw_lines](mmengine.visualization.Visualizer.lines) 绘制单个或多个线段
+- [draw_circles](mmengine.visualization.Visualizer.draw_circles) 绘制单个或多个圆
+- [draw_polygons](mmengine.visualization.Visualizer.draw_polygons) 绘制单个或多个多边形
+- [draw_binary_masks](mmengine.visualization.Visualizer.draw_binary_mask) 绘制单个或多个二值掩码
+- [draw_featmap](mmengine.visualization.Visualizer.draw_featmap) 绘制特征图,静态方法
+
+上述接口除了 `draw_featmap` 外都可以链式调用,因为该方法调用后可能会导致图片尺寸发生改变。为了避免给用户带来困扰, `draw_featmap` 被设置为静态方法。
+
+**(2) 存储相关接口**
+
+- [add_config](mmengine.visualization.writer.BaseWriter.add_config) 写配置到特定存储后端
+- [add_graph](mmengine.visualization.writer.BaseWriter.add_graph) 写模型图到特定存储后端
+- [add_image](mmengine.visualization.writer.BaseWriter.add_image) 写图片到特定存储后端
+- [add_scalar](mmengine.visualization.writer.BaseWriter.add_scalar) 写标量到特定存储后端
+- [add_scalars](mmengine.visualization.writer.BaseWriter.add_scalars) 一次性写多个标量到特定存储后端
+- [add_datasample](mmengine.visualization.writer.BaseWriter.add_datasample) 各个下游库绘制 datasample 数据的抽象接口
+
+以 add 前缀开头的接口表示存储接口。datasample 是 OpenMMLab 2.0 架构中设计的各个下游库统一的抽象数据接口,而 `add_datasample` 接口可以直接处理该数据格式,例如可视化预测结果、可视化 Dataset 或者 DataLoader 输出、可视化中间预测结果等等都可以直接调用下游库重写的 `add_datasample` 接口。
+所有下游库都必须要继承 Visualizer 并实现 `add_datasample` 接口。以 MMDetection 为例,应该继承并通过该接口实现目标检测中所有预置任务的可视化功能,例如目标检测、实例分割、全景分割任务结果的绘制和存储。
+
+**(3) 其余功能性接口**
+
+- [set_image](mmengine.visualization.Visualizer.set_image) 设置原始图片数据,默认输入图片格式为 RGB
+- [get_image](mmengine.visualization.Visualizer.get_image) 获取绘制后的 Numpy 格式图片数据,默认输出格式为 RGB
+- [show](mmengine.visualization.Visualizer.show) 可视化
+- [get_backend](mmengine.visualization.Visualizer.get_backend) 通过 name 获取特定存储后端
+- [close](mmengine.visualization.Visualizer.close) 关闭所有已经打开的资源,包括 VisBackend
+
+关于其用法,可以参考 [可视化器用户教程](../tutorials/visualization.md)。
+
+## 3 可视化存储后端 VisBackend
+
+在绘制后可以将绘制后的数据存储到多个可视化存储后端中。为了统一接口调用,MMEngine 提供了统一的抽象类 `BaseVisBackend`,和一些常用的 VisBackend 如 `LocalVisBackend`、`WandbVisBackend` 和 `TensorboardVisBackend`。
+BaseVisBackend 定义了对外调用的接口规范,主要接口和属性如下:
+
+- [add_config](mmengine.visualization.vis_backend.BaseVisBackend.add_config) 写配置到特定存储后端
+- [add_graph](mmengine.visualization.vis_backend.BaseVisBackend.add_graph) 写模型图到特定后端
+- [add_image](mmengine.visualization.vis_backend.BaseVisBackend.add_image) 写图片到特定后端
+- [add_scalar](mmengine.visualization.vis_backend.BaseVisBackend.add_scalar) 写标量到特定后端
+- [add_scalars](mmengine.visualization.vis_backend.BaseVisBackend.add_scalars) 一次性写多个标量到特定后端
+- [close](mmengine.visualization.vis_backend.BaseVisBackend.close) 关闭已经打开的资源
+- [experiment](mmengine.visualization.vis_backend.BaseVisBackend.experiment) 写后端对象,例如 WandB 对象和 Tensorboard 对象
+
+`BaseVisBackend` 定义了 5 个常见的写数据接口,考虑到某些写后端功能非常强大,例如 WandB,其具备写表格,写视频等等功能,针对这类需求用户可以直接获取 `experiment` 对象,然后调用写后端对象本身的 API 即可。而 `LocalVisBackend`、`WandbVisBackend` 和 `TensorboardVisBackend` 等都是继承自 `BaseVisBackend`,并根据自身特性实现了对应的存储功能。用户也可以继承 `BaseVisBackend` 从而扩展存储后端,实现自定义存储需求。
+关于其用法,可以参考 [存储后端用户教程](../advanced_tutorials//visualization.md)。
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/docutils.conf b/testbed/open-mmlab__mmengine/docs/zh_cn/docutils.conf
new file mode 100644
index 0000000000000000000000000000000000000000..0c00c84688701117f231fd0c8ec295fb747b7d8f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/docutils.conf
@@ -0,0 +1,2 @@
+[html writers]
+table_style: colwidths-auto
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/examples/resume_training.md b/testbed/open-mmlab__mmengine/docs/zh_cn/examples/resume_training.md
new file mode 100644
index 0000000000000000000000000000000000000000..a7382597a32836780153dfd90fc3356a702252d9
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/examples/resume_training.md
@@ -0,0 +1,36 @@
+# 恢复训练
+
+恢复训练是指从之前某次训练保存下来的状态开始继续训练,这里的状态包括模型的权重、优化器和优化器参数调整策略的状态。
+
+## 自动恢复训练
+
+用户可以设置 `Runner` 的 `resume` 参数开启自动恢复训练的功能。在启动训练时,设置 `Runner` 的 `resume` 等于 `True`,`Runner` 会从 `work_dir` 中加载最新的 checkpoint。如果 `work_dir` 中有最新的 checkpoint(例如该训练在上一次训练时被中断),则会从该 checkpoint 恢复训练,否则(例如上一次训练还没来得及保存 checkpoint 或者启动了新的训练任务)会重新开始训练。下面是一个开启自动恢复训练的示例
+
+```python
+runner = Runner(
+ model=ResNet18(),
+ work_dir='./work_dir',
+ train_dataloader=train_dataloader_cfg,
+ optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.001, momentum=0.9)),
+ train_cfg=dict(by_epoch=True, max_epochs=3),
+ resume=True,
+)
+runner.train()
+```
+
+## 指定 checkpoint 路径
+
+如果希望指定恢复训练的路径,除了设置 `resume=True`,还需要设置 `load_from` 参数。需要注意的是,如果只设置了 `load_from` 而没有设置 `resume=True`,则只会加载 checkpoint 中的权重并重新开始训练,而不是接着之前的状态继续训练。
+
+```python
+runner = Runner(
+ model=ResNet18(),
+ work_dir='./work_dir',
+ train_dataloader=train_dataloader_cfg,
+ optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.001, momentum=0.9)),
+ train_cfg=dict(by_epoch=True, max_epochs=3),
+ load_from='./work_dir/epoch_2.pth',
+ resume=True,
+)
+runner.train()
+```
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/examples/save_gpu_memory.md b/testbed/open-mmlab__mmengine/docs/zh_cn/examples/save_gpu_memory.md
new file mode 100644
index 0000000000000000000000000000000000000000..82bd5b40e9c879aee7c239be5105aeed20796c12
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/examples/save_gpu_memory.md
@@ -0,0 +1,112 @@
+# 节省显存
+
+在深度学习训练推理过程中显存容量至关重要,其决定了模型是否能成功运行。常见的节省显存办法包括:
+
+- 梯度累加
+
+ 梯度累加是指在每计算一个批次的梯度后,不进行清零而是进行梯度累加,当累加到一定的次数之后,再更新网络参数和梯度清零。 通过这种参数延迟更新的手段,实现与采用大 batch 尺寸相近的效果,达到节省显存的目的。但是需要注意如果模型中包含 batch normalization 层,使用梯度累加会对性能有一定影响。
+
+- 梯度检查点
+
+ 梯度检查点是一种以时间换空间的方法,通过减少保存的激活值来压缩模型占用空间,但是在计算梯度时必须重新计算没有存储的激活值。在 torch.utils.checkpoint 包中已经实现了对应功能。简要实现过程是:在前向阶段传递到 checkpoint 中的 forward 函数会以 `torch.no_grad` 模式运行,并且仅仅保存 forward 函数的输入和输出,然后在反向阶段重新计算中间层的激活值 (intermediate activations)。
+
+- 大模型训练技术
+
+ 最近的研究表明大型模型训练将有利于提高模型质量,但是训练如此大的模型需要巨大的资源,单卡显存已经越来越难以满足存放整个模型,因此诞生了大模型训练技术,典型的如 [DeepSpeed ZeRO](https://www.deepspeed.ai/tutorials/zero/#zero-overview) 和 FairScale 的[完全分片数据并行](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/)(Fully Sharded Data Parallel, FSDP)技术,其允许在数据并行进程之间分片模型的参数、梯度和优化器状态,并同时仍然保持数据并行的简单性。
+
+MMEngine 目前支持`梯度累加`和`大模型训练 FSDP 技术 `。下面说明其用法。
+
+## 梯度累加
+
+配置写法如下所示:
+
+```python
+optim_wrapper_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(type='SGD', lr=0.001, momentum=0.9),
+ # 累加 4 次参数更新一次
+ accumulative_counts=4)
+```
+
+配合 Runner 使用的完整例子如下:
+
+```python
+import torch
+import torch.nn as nn
+from torch.utils.data import DataLoader
+from mmengine.runner import Runner
+from mmengine.model import BaseModel
+
+train_dataset = [(torch.ones(1, 1), torch.ones(1, 1))] * 50
+train_dataloader = DataLoader(train_dataset, batch_size=2)
+
+
+class ToyModel(BaseModel):
+ def __init__(self) -> None:
+ super().__init__()
+ self.linear = nn.Linear(1, 1)
+
+ def forward(self, img, label, mode):
+ feat = self.linear(img)
+ loss1 = (feat - label).pow(2)
+ loss2 = (feat - label).abs()
+ return dict(loss1=loss1, loss2=loss2)
+
+
+runner = Runner(
+ model=ToyModel(),
+ work_dir='tmp_dir',
+ train_dataloader=train_dataloader,
+ train_cfg=dict(by_epoch=True, max_epochs=1),
+ optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01),
+ accumulative_counts=4)
+)
+runner.train()
+```
+
+## 大模型训练
+
+PyTorch 1.11 中已经原生支持了 FSDP 技术。配置写法如下所示:
+
+```python
+# 位于 cfg 配置文件中
+model_wrapper_cfg=dict(type='MMFullyShardedDataParallel', cpu_offload=True)
+```
+
+配合 Runner 使用的完整例子如下:
+
+```python
+import torch
+import torch.nn as nn
+from torch.utils.data import DataLoader
+from mmengine.runner import Runner
+from mmengine.model import BaseModel
+
+train_dataset = [(torch.ones(1, 1), torch.ones(1, 1))] * 50
+train_dataloader = DataLoader(train_dataset, batch_size=2)
+
+
+class ToyModel(BaseModel):
+ def __init__(self) -> None:
+ super().__init__()
+ self.linear = nn.Linear(1, 1)
+
+ def forward(self, img, label, mode):
+ feat = self.linear(img)
+ loss1 = (feat - label).pow(2)
+ loss2 = (feat - label).abs()
+ return dict(loss1=loss1, loss2=loss2)
+
+
+runner = Runner(
+ model=ToyModel(),
+ work_dir='tmp_dir',
+ train_dataloader=train_dataloader,
+ train_cfg=dict(by_epoch=True, max_epochs=1),
+ optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01)),
+ cfg=dict(model_wrapper_cfg=dict(type='MMFullyShardedDataParallel', cpu_offload=True))
+)
+runner.train()
+```
+
+注意必须在分布式训练环境中 FSDP 才能生效。
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/examples/speed_up_training.md b/testbed/open-mmlab__mmengine/docs/zh_cn/examples/speed_up_training.md
new file mode 100644
index 0000000000000000000000000000000000000000..0aef22437bf4c750a3deb308487d0653e92f75f2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/examples/speed_up_training.md
@@ -0,0 +1,79 @@
+# 加速训练
+
+## 分布式训练
+
+MMEngine 支持 CPU、单卡、单机多卡以及多机多卡的训练。当环境中有多张显卡时,我们可以使用以下命令开启单机多卡或者多机多卡的方式从而缩短模型的训练时间。
+
+- 单机多卡
+
+ 假设当前机器有 8 张显卡,可以使用以下命令开启多卡训练
+
+ ```bash
+ python -m torch.distributed.launch --nproc_per_node=8 examples/train.py --launcher pytorch
+ ```
+
+ 如果需要指定显卡的编号,可以设置 `CUDA_VISIBLE_DEVICES` 环境变量,例如使用第 0 和第 3 张卡
+
+ ```bash
+ CUDA_VISIBLE_DEVICES=0,3 python -m torch.distributed.launch --nproc_per_node=2 examples/train.py --launcher pytorch
+ ```
+
+- 多机多卡
+
+ 假设有 2 台机器,每台机器有 8 张卡。
+
+ 第一台机器运行以下命令
+
+ ```bash
+ python -m torch.distributed.launch \
+ --nnodes 8 \
+ --node_rank 0 \
+ --master_addr 127.0.0.1 \
+ --master_port 29500 \
+ --nproc_per_node=8 \
+ examples/train.py --launcher pytorch
+ ```
+
+ 第 2 台机器运行以下命令
+
+ ```bash
+ python -m torch.distributed.launch \
+ --nnodes 8 \
+ --node_rank 1 \
+ --master_addr 127.0.0.1 \
+ --master_port 29500 \
+ --nproc_per_node=8 \
+ examples/train.py --launcher pytorch
+ ```
+
+ 如果在 slurm 集群运行 MMEngine,只需运行以下命令即可开启 2 机 16 卡的训练
+
+ ```bash
+ srun -p mm_dev \
+ --job-name=test \
+ --gres=gpu:8 \
+ --ntasks=16 \
+ --ntasks-per-node=8 \
+ --cpus-per-task=5 \
+ --kill-on-bad-exit=1 \
+ python examples/train.py --launcher="slurm"
+ ```
+
+## 混合精度训练
+
+Nvidia 在 Volta 和 Turing 架构中引入 Tensor Core 单元,来支持 FP32 和 FP16 混合精度计算。开启自动混合精度训练后,部分算子的操作精度是 FP16,其余算子的操作精度是 FP32。这样在不改变模型、不降低模型训练精度的前提下,可以缩短训练时间,降低存储需求,因而能支持更大的 batch size、更大模型和尺寸更大的输入的训练。
+
+[PyTorch 从 1.6 开始官方支持 amp](https://pytorch.org/blog/accelerating-training-on-nvidia-gpus-with-pytorch-automatic-mixed-precision/)。如果你对自动混合精度的实现感兴趣,可以阅读 [torch.cuda.amp: 自动混合精度详解](https://zhuanlan.zhihu.com/p/348554267)。
+
+MMEngine 提供自动混合精度的封装 [AmpOptimWrapper](mmengine.optim.AmpOptimWrapper) ,只需在 `optim_wrapper` 设置 `type='AmpOptimWrapper'` 即可开启自动混合精度训练,无需对代码做其他修改。
+
+```python
+runner = Runner(
+ model=ResNet18(),
+ work_dir='./work_dir',
+ train_dataloader=train_dataloader_cfg,
+ optim_wrapper=dict(type='AmpOptimWrapper', optimizer=dict(type='SGD', lr=0.001, momentum=0.9)),
+ train_cfg=dict(by_epoch=True, max_epochs=3),
+)
+runner.train()
+```
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/examples/train_a_gan.md b/testbed/open-mmlab__mmengine/docs/zh_cn/examples/train_a_gan.md
new file mode 100644
index 0000000000000000000000000000000000000000..6e2ffd1812dae65fd89478c6a750af3d8fa136ed
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/examples/train_a_gan.md
@@ -0,0 +1,308 @@
+# 训练生成对抗网络
+
+生成对抗网络(Generative Adversarial Network, GAN)可以用来生成图像视频等数据。这篇教程将带你一步步用 MMEngine 训练 GAN !
+
+我们可以通过以下步骤来训练一个生成对抗网络。
+
+- [训练生成对抗网络](#训练生成对抗网络)
+ - [构建数据加载器](#构建数据加载器)
+ - [构建数据集](#构建数据集)
+ - [构建生成器网络和判别器网络](#构建生成器网络和判别器网络)
+ - [构建一个生成对抗网络模型](#构建一个生成对抗网络模型)
+ - [构建优化器](#构建优化器)
+ - [使用执行器进行训练](#使用执行器进行训练)
+
+## 构建数据加载器
+
+### 构建数据集
+
+接下来, 我们为 MNIST 数据集构建一个数据集类 `MNISTDataset`, 继承自数据集基类 [BaseDataset](mmengine.dataset.BaseDataset), 并且重载数据集基类的 `load_data_list` 函数, 保证返回值为 `list[dict]`,其中每个 `dict` 代表一个数据样本。更多关于 MMEngine 中数据集的用法,可以参考[数据集教程](../tutorials/basedataset.md)。
+
+```python
+import numpy as np
+from mmcv.transforms import to_tensor
+from torch.utils.data import random_split
+from torchvision.datasets import MNIST
+
+from mmengine.dataset import BaseDataset
+
+
+class MNISTDataset(BaseDataset):
+
+ def __init__(self, data_root, pipeline, test_mode=False):
+ # 下载 MNIST 数据集
+ if test_mode:
+ mnist_full = MNIST(data_root, train=True, download=True)
+ self.mnist_dataset, _ = random_split(mnist_full, [55000, 5000])
+ else:
+ self.mnist_dataset = MNIST(data_root, train=False, download=True)
+
+ super().__init__(
+ data_root=data_root, pipeline=pipeline, test_mode=test_mode)
+
+ @staticmethod
+ def totensor(img):
+ if len(img.shape) < 3:
+ img = np.expand_dims(img, -1)
+ img = np.ascontiguousarray(img.transpose(2, 0, 1))
+ return to_tensor(img)
+
+ def load_data_list(self):
+ return [
+ dict(inputs=self.totensor(np.array(x[0]))) for x in self.mnist_dataset
+ ]
+
+
+dataset = MNISTDataset("./data", [])
+
+```
+
+使用 Runner 中的函数 build_dataloader 来构建数据加载器。
+
+```python
+import os
+import torch
+from mmengine.runner import Runner
+
+NUM_WORKERS = int(os.cpu_count() / 2)
+BATCH_SIZE = 256 if torch.cuda.is_available() else 64
+
+train_dataloader = dict(
+ batch_size=BATCH_SIZE,
+ num_workers=NUM_WORKERS,
+ persistent_workers=True,
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ dataset=dataset)
+train_dataloader = Runner.build_dataloader(train_dataloader)
+```
+
+## 构建生成器网络和判别器网络
+
+下面的代码构建并实例化了一个生成器(Generator)和一个判别器(Discriminator)。
+
+```python
+import torch.nn as nn
+
+class Generator(nn.Module):
+ def __init__(self, noise_size, img_shape):
+ super().__init__()
+ self.img_shape = img_shape
+ self.noise_size = noise_size
+
+ def block(in_feat, out_feat, normalize=True):
+ layers = [nn.Linear(in_feat, out_feat)]
+ if normalize:
+ layers.append(nn.BatchNorm1d(out_feat, 0.8))
+ layers.append(nn.LeakyReLU(0.2, inplace=True))
+ return layers
+
+ self.model = nn.Sequential(
+ *block(noise_size, 128, normalize=False),
+ *block(128, 256),
+ *block(256, 512),
+ *block(512, 1024),
+ nn.Linear(1024, int(np.prod(img_shape))),
+ nn.Tanh(),
+ )
+
+ def forward(self, z):
+ img = self.model(z)
+ img = img.view(img.size(0), *self.img_shape)
+ return img
+```
+
+```python
+class Discriminator(nn.Module):
+ def __init__(self, img_shape):
+ super().__init__()
+
+ self.model = nn.Sequential(
+ nn.Linear(int(np.prod(img_shape)), 512),
+ nn.LeakyReLU(0.2, inplace=True),
+ nn.Linear(512, 256),
+ nn.LeakyReLU(0.2, inplace=True),
+ nn.Linear(256, 1),
+ nn.Sigmoid(),
+ )
+
+ def forward(self, img):
+ img_flat = img.view(img.size(0), -1)
+ validity = self.model(img_flat)
+
+ return validity
+```
+
+```python
+generator = Generator(100, (1, 28, 28))
+discriminator = Discriminator((1, 28, 28))
+```
+
+## 构建一个生成对抗网络模型
+
+在使用 MMEngine 时,我们用 [ImgDataPreprocessor](mmengine.model.ImgDataPreprocessor) 来对数据进行归一化和颜色通道的转换。
+
+```python
+from mmengine.model import ImgDataPreprocessor
+
+data_preprocessor = ImgDataPreprocessor(mean=([127.5]), std=([127.5]))
+```
+
+下面的代码实现了基础 GAN 的算法。使用 MMEngine 实现算法类,需要继承 [BaseModel](mmengine.model.BaseModel) 基类,在 train_step 中实现训练过程。GAN 需要交替训练生成器和判别器,分别由 train_discriminator 和 train_generator 实现,并实现 disc_loss 和 gen_loss 计算判别器损失函数和生成器损失函数。
+关于 BaseModel 的更多信息,请参考[模型教程](../tutorials/model.md).
+
+```python
+import torch.nn.functional as F
+from mmengine.model import BaseModel
+
+class GAN(BaseModel):
+
+ def __init__(self, generator, discriminator, noise_size,
+ data_preprocessor):
+ super().__init__(data_preprocessor=data_preprocessor)
+ assert generator.noise_size == noise_size
+ self.generator = generator
+ self.discriminator = discriminator
+ self.noise_size = noise_size
+
+ def train_step(self, data, optim_wrapper):
+ # 获取数据和数据预处理
+ inputs_dict = self.data_preprocessor(data, True)
+ # 训练判别器
+ disc_optimizer_wrapper = optim_wrapper['discriminator']
+ with disc_optimizer_wrapper.optim_context(self.discriminator):
+ log_vars = self.train_discriminator(inputs_dict,
+ disc_optimizer_wrapper)
+
+ # 训练生成器
+ set_requires_grad(self.discriminator, False)
+ gen_optimizer_wrapper = optim_wrapper['generator']
+ with gen_optimizer_wrapper.optim_context(self.generator):
+ log_vars_gen = self.train_generator(inputs_dict,
+ gen_optimizer_wrapper)
+
+ set_requires_grad(self.discriminator, True)
+ log_vars.update(log_vars_gen)
+
+ return log_vars
+
+ def forward(self, batch_inputs, data_samples=None, mode=None):
+ return self.generator(batch_inputs)
+
+ def disc_loss(self, disc_pred_fake, disc_pred_real):
+ losses_dict = dict()
+ losses_dict['loss_disc_fake'] = F.binary_cross_entropy(
+ disc_pred_fake, 0. * torch.ones_like(disc_pred_fake))
+ losses_dict['loss_disc_real'] = F.binary_cross_entropy(
+ disc_pred_real, 1. * torch.ones_like(disc_pred_real))
+
+ loss, log_var = self.parse_losses(losses_dict)
+ return loss, log_var
+
+ def gen_loss(self, disc_pred_fake):
+ losses_dict = dict()
+ losses_dict['loss_gen'] = F.binary_cross_entropy(
+ disc_pred_fake, 1. * torch.ones_like(disc_pred_fake))
+ loss, log_var = self.parse_losses(losses_dict)
+ return loss, log_var
+
+ def train_discriminator(self, inputs, optimizer_wrapper):
+ real_imgs = inputs['inputs']
+ z = torch.randn(
+ (real_imgs.shape[0], self.noise_size)).type_as(real_imgs)
+ with torch.no_grad():
+ fake_imgs = self.generator(z)
+
+ disc_pred_fake = self.discriminator(fake_imgs)
+ disc_pred_real = self.discriminator(real_imgs)
+
+ parsed_losses, log_vars = self.disc_loss(disc_pred_fake,
+ disc_pred_real)
+ optimizer_wrapper.update_params(parsed_losses)
+ return log_vars
+
+ def train_generator(self, inputs, optimizer_wrapper):
+ real_imgs = inputs['inputs']
+ z = torch.randn(real_imgs.shape[0], self.noise_size).type_as(real_imgs)
+
+ fake_imgs = self.generator(z)
+
+ disc_pred_fake = self.discriminator(fake_imgs)
+ parsed_loss, log_vars = self.gen_loss(disc_pred_fake)
+
+ optimizer_wrapper.update_params(parsed_loss)
+ return log_vars
+```
+
+其中一个函数 set_requires_grad 用来锁定训练生成器时判别器的权重。
+
+```python
+def set_requires_grad(nets, requires_grad=False):
+ """Set requires_grad for all the networks.
+
+ Args:
+ nets (nn.Module | list[nn.Module]): A list of networks or a single
+ network.
+ requires_grad (bool): Whether the networks require gradients or not.
+ """
+ if not isinstance(nets, list):
+ nets = [nets]
+ for net in nets:
+ if net is not None:
+ for param in net.parameters():
+ param.requires_grad = requires_grad
+```
+
+```python
+
+model = GAN(generator, discriminator, 100, data_preprocessor)
+
+```
+
+## 构建优化器
+
+MMEngine 使用 [OptimWrapper](mmengine.optim.OptimWrapper) 来封装优化器,对于多个优化器的情况,使用 [OptimWrapperDict](mmengine.optim.OptimWrapperDict) 对 OptimWrapper 再进行一次封装。
+关于优化器的更多信息,请参考[优化器教程](../tutorials/optimizer.md).
+
+```python
+from mmengine.optim import OptimWrapper, OptimWrapperDict
+
+opt_g = torch.optim.Adam(generator.parameters(), lr=0.0001, betas=(0.5, 0.999))
+opt_g_wrapper = OptimWrapper(opt_g)
+
+opt_d = torch.optim.Adam(
+ discriminator.parameters(), lr=0.0001, betas=(0.5, 0.999))
+opt_d_wrapper = OptimWrapper(opt_d)
+
+opt_wrapper_dict = OptimWrapperDict(
+ generator=opt_g_wrapper, discriminator=opt_d_wrapper)
+
+```
+
+## 使用执行器进行训练
+
+下面的代码演示了如何使用 Runner 进行模型训练。关于 Runner 的更多信息,请参考[执行器教程](../tutorials/runner.md)。
+
+```python
+train_cfg = dict(by_epoch=True, max_epochs=220)
+runner = Runner(
+ model,
+ work_dir='runs/gan/',
+ train_dataloader=train_dataloader,
+ train_cfg=train_cfg,
+ optim_wrapper=opt_wrapper_dict)
+runner.train()
+```
+
+到这里,我们就完成了一个 GAN 的训练,通过下面的代码可以查看刚才训练的 GAN 生成的结果。
+
+```python
+z = torch.randn(64, 100).cuda()
+img = model(z)
+
+from torchvision.utils import save_image
+save_image(img, "result.png", normalize=True)
+```
+
+
+
+如果你想了解更多如何使用 MMEngine 实现 GAN 和生成模型,我们强烈建议你使用同样基于 MMEngine 开发的生成框架 [MMGen](https://github.com/open-mmlab/mmgeneration/tree/dev-1.x)。
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/get_started/15_minutes.md b/testbed/open-mmlab__mmengine/docs/zh_cn/get_started/15_minutes.md
new file mode 100644
index 0000000000000000000000000000000000000000..8ca102f5fc26024369c5f4eb57a268553e70389a
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/get_started/15_minutes.md
@@ -0,0 +1,242 @@
+# 15 分钟上手 MMEngine
+
+以在 CIFAR-10 数据集上训练一个 ResNet-50 模型为例,我们将使用 80 行以内的代码,利用 MMEngine 构建一个完整的、
+可配置的训练和验证流程,整个流程包含如下步骤:
+
+1. [构建模型](#构建模型)
+2. [构建数据集和数据加载器](#构建数据集和数据加载器)
+3. [构建评测指标](#构建评测指标)
+4. [构建执行器并执行任务](#构建执行器并执行任务)
+
+## 构建模型
+
+首先,我们需要构建一个**模型**,在 MMEngine 中,我们约定这个模型应当继承 `BaseModel`,并且其 `forward` 方法除了接受来自数据集的若干参数外,还需要接受额外的参数 `mode`:对于训练,我们需要 `mode` 接受字符串 "loss",并返回一个包含 "loss" 字段的字典;对于验证,我们需要 `mode` 接受字符串 "predict",并返回同时包含预测信息和真实信息的结果。
+
+```python
+import torch.nn.functional as F
+import torchvision
+from mmengine.model import BaseModel
+
+
+class MMResNet50(BaseModel):
+ def __init__(self):
+ super().__init__()
+ self.resnet = torchvision.models.resnet50()
+
+ def forward(self, imgs, labels, mode):
+ x = self.resnet(imgs)
+ if mode == 'loss':
+ return {'loss': F.cross_entropy(x, labels)}
+ elif mode == 'predict':
+ return x, labels
+```
+
+## 构建数据集和数据加载器
+
+其次,我们需要构建训练和验证所需要的**数据集 (Dataset)**和**数据加载器 (DataLoader)**。
+对于基础的训练和验证功能,我们可以直接使用符合 PyTorch 标准的数据加载器和数据集。
+
+```python
+import torchvision.transforms as transforms
+from torch.utils.data import DataLoader
+
+norm_cfg = dict(mean=[0.491, 0.482, 0.447], std=[0.202, 0.199, 0.201])
+train_dataloader = DataLoader(batch_size=32,
+ shuffle=True,
+ dataset=torchvision.datasets.CIFAR10(
+ 'data/cifar10',
+ train=True,
+ download=True,
+ transform=transforms.Compose([
+ transforms.RandomCrop(32, padding=4),
+ transforms.RandomHorizontalFlip(),
+ transforms.ToTensor(),
+ transforms.Normalize(**norm_cfg)
+ ])))
+
+val_dataloader = DataLoader(batch_size=32,
+ shuffle=False,
+ dataset=torchvision.datasets.CIFAR10(
+ 'data/cifar10',
+ train=False,
+ download=True,
+ transform=transforms.Compose([
+ transforms.ToTensor(),
+ transforms.Normalize(**norm_cfg)
+ ])))
+```
+
+## 构建评测指标
+
+为了进行验证和测试,我们需要定义模型推理结果的**评测指标**。我们约定这一评测指标需要继承 `BaseMetric`,并实现 `process` 和 `compute_metrics` 方法。其中 `process` 方法接受数据集的输出和模型 `mode="predict"`
+时的输出,此时的数据为一个批次的数据,对这一批次的数据进行处理后,保存信息至 `self.results` 属性。
+而 `compute_metrics` 接受 `results` 参数,这一参数的输入为 `process` 中保存的所有信息
+(如果是分布式环境,`results` 中为已收集的,包括各个进程 `process` 保存信息的结果),利用这些信息计算并返回保存有评测指标结果的字典。
+
+```python
+from mmengine.evaluator import BaseMetric
+
+class Accuracy(BaseMetric):
+ def process(self, data_batch, data_samples):
+ score, gt = data_samples
+ # 将一个批次的中间结果保存至 `self.results`
+ self.results.append({
+ 'batch_size': len(gt),
+ 'correct': (score.argmax(dim=1) == gt).sum().cpu(),
+ })
+
+ def compute_metrics(self, results):
+ total_correct = sum(item['correct'] for item in results)
+ total_size = sum(item['batch_size'] for item in results)
+ # 返回保存有评测指标结果的字典,其中键为指标名称
+ return dict(accuracy=100 * total_correct / total_size)
+```
+
+## 构建执行器并执行任务
+
+最后,我们利用构建好的**模型**,**数据加载器**,**评测指标**构建一个**执行器 (Runner)**,同时在其中配置
+**优化器**、**工作路径**、**训练与验证配置**等选项,即可通过调用 `train()` 接口启动训练:
+
+```python
+from torch.optim import SGD
+from mmengine.runner import Runner
+
+runner = Runner(
+ # 用以训练和验证的模型,需要满足特定的接口需求
+ model=MMResNet50(),
+ # 工作路径,用以保存训练日志、权重文件信息
+ work_dir='./work_dir',
+ # 训练数据加载器,需要满足 PyTorch 数据加载器协议
+ train_dataloader=train_dataloader,
+ # 优化器包装,用于模型优化,并提供 AMP、梯度累积等附加功能
+ optim_wrapper=dict(optimizer=dict(type=SGD, lr=0.001, momentum=0.9)),
+ # 训练配置,用于指定训练周期、验证间隔等信息
+ train_cfg=dict(by_epoch=True, max_epochs=5, val_interval=1),
+ # 验证数据加载器,需要满足 PyTorch 数据加载器协议
+ val_dataloader=val_dataloader,
+ # 验证配置,用于指定验证所需要的额外参数
+ val_cfg=dict(),
+ # 用于验证的评测器,这里使用默认评测器,并评测指标
+ val_evaluator=dict(type=Accuracy),
+)
+
+runner.train()
+```
+
+最后,让我们把以上部分汇总成为一个完整的,利用 MMEngine 执行器进行训练和验证的脚本:
+
+
+
+```python
+import torch.nn.functional as F
+import torchvision
+import torchvision.transforms as transforms
+from torch.optim import SGD
+from torch.utils.data import DataLoader
+
+from mmengine.evaluator import BaseMetric
+from mmengine.model import BaseModel
+from mmengine.runner import Runner
+
+
+class MMResNet50(BaseModel):
+ def __init__(self):
+ super().__init__()
+ self.resnet = torchvision.models.resnet50()
+
+ def forward(self, imgs, labels, mode):
+ x = self.resnet(imgs)
+ if mode == 'loss':
+ return {'loss': F.cross_entropy(x, labels)}
+ elif mode == 'predict':
+ return x, labels
+
+
+class Accuracy(BaseMetric):
+ def process(self, data_batch, data_samples):
+ score, gt = data_samples
+ self.results.append({
+ 'batch_size': len(gt),
+ 'correct': (score.argmax(dim=1) == gt).sum().cpu(),
+ })
+
+ def compute_metrics(self, results):
+ total_correct = sum(item['correct'] for item in results)
+ total_size = sum(item['batch_size'] for item in results)
+ return dict(accuracy=100 * total_correct / total_size)
+
+
+norm_cfg = dict(mean=[0.491, 0.482, 0.447], std=[0.202, 0.199, 0.201])
+train_dataloader = DataLoader(batch_size=32,
+ shuffle=True,
+ dataset=torchvision.datasets.CIFAR10(
+ 'data/cifar10',
+ train=True,
+ download=True,
+ transform=transforms.Compose([
+ transforms.RandomCrop(32, padding=4),
+ transforms.RandomHorizontalFlip(),
+ transforms.ToTensor(),
+ transforms.Normalize(**norm_cfg)
+ ])))
+
+val_dataloader = DataLoader(batch_size=32,
+ shuffle=False,
+ dataset=torchvision.datasets.CIFAR10(
+ 'data/cifar10',
+ train=False,
+ download=True,
+ transform=transforms.Compose([
+ transforms.ToTensor(),
+ transforms.Normalize(**norm_cfg)
+ ])))
+
+runner = Runner(
+ model=MMResNet50(),
+ work_dir='./work_dir',
+ train_dataloader=train_dataloader,
+ optim_wrapper=dict(optimizer=dict(type=SGD, lr=0.001, momentum=0.9)),
+ train_cfg=dict(by_epoch=True, max_epochs=5, val_interval=1),
+ val_dataloader=val_dataloader,
+ val_cfg=dict(),
+ val_evaluator=dict(type=Accuracy),
+)
+runner.train()
+```
+
+输出的训练日志如下:
+
+```
+2022/08/22 15:51:53 - mmengine - INFO -
+------------------------------------------------------------
+System environment:
+ sys.platform: linux
+ Python: 3.8.12 (default, Oct 12 2021, 13:49:34) [GCC 7.5.0]
+ CUDA available: True
+ numpy_random_seed: 1513128759
+ GPU 0: NVIDIA GeForce GTX 1660 SUPER
+ CUDA_HOME: /usr/local/cuda
+...
+
+2022/08/22 15:51:54 - mmengine - INFO - Checkpoints will be saved to /home/mazerun/work_dir by HardDiskBackend.
+2022/08/22 15:51:56 - mmengine - INFO - Epoch(train) [1][10/1563] lr: 1.0000e-03 eta: 0:18:23 time: 0.1414 data_time: 0.0077 memory: 392 loss: 5.3465
+2022/08/22 15:51:56 - mmengine - INFO - Epoch(train) [1][20/1563] lr: 1.0000e-03 eta: 0:11:29 time: 0.0354 data_time: 0.0077 memory: 392 loss: 2.7734
+2022/08/22 15:51:56 - mmengine - INFO - Epoch(train) [1][30/1563] lr: 1.0000e-03 eta: 0:09:10 time: 0.0352 data_time: 0.0076 memory: 392 loss: 2.7789
+2022/08/22 15:51:57 - mmengine - INFO - Epoch(train) [1][40/1563] lr: 1.0000e-03 eta: 0:08:00 time: 0.0353 data_time: 0.0073 memory: 392 loss: 2.5725
+2022/08/22 15:51:57 - mmengine - INFO - Epoch(train) [1][50/1563] lr: 1.0000e-03 eta: 0:07:17 time: 0.0347 data_time: 0.0073 memory: 392 loss: 2.7382
+2022/08/22 15:51:57 - mmengine - INFO - Epoch(train) [1][60/1563] lr: 1.0000e-03 eta: 0:06:49 time: 0.0347 data_time: 0.0072 memory: 392 loss: 2.5956
+2022/08/22 15:51:58 - mmengine - INFO - Epoch(train) [1][70/1563] lr: 1.0000e-03 eta: 0:06:28 time: 0.0348 data_time: 0.0072 memory: 392 loss: 2.7351
+...
+2022/08/22 15:52:50 - mmengine - INFO - Saving checkpoint at 1 epochs
+2022/08/22 15:52:51 - mmengine - INFO - Epoch(val) [1][10/313] eta: 0:00:03 time: 0.0122 data_time: 0.0047 memory: 392
+2022/08/22 15:52:51 - mmengine - INFO - Epoch(val) [1][20/313] eta: 0:00:03 time: 0.0122 data_time: 0.0047 memory: 308
+2022/08/22 15:52:51 - mmengine - INFO - Epoch(val) [1][30/313] eta: 0:00:03 time: 0.0123 data_time: 0.0047 memory: 308
+...
+2022/08/22 15:52:54 - mmengine - INFO - Epoch(val) [1][313/313] accuracy: 35.7000
+```
+
+基于 PyTorch 和基于 MMEngine 的训练流程对比如下:
+
+
+
+除了以上基础组件,你还可以利用**执行器**轻松地组合配置各种训练技巧,如开启混合精度训练和梯度累积(见 [优化器封装(OptimWrapper)](../tutorials/optim_wrapper.md))、配置学习率衰减曲线(见 [评测指标与评测器(Metrics & Evaluator)](../tutorials/evaluation.md))等。
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/get_started/installation.md b/testbed/open-mmlab__mmengine/docs/zh_cn/get_started/installation.md
new file mode 100644
index 0000000000000000000000000000000000000000..b50deb2fca5c4aafe789f11114521eb320d540da
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/get_started/installation.md
@@ -0,0 +1,75 @@
+## 安装
+
+### 环境依赖
+
+- Python 3.6+
+- PyTorch 1.6+
+- CUDA 9.2+
+- GCC 5.4+
+
+### 准备环境
+
+1. 使用 conda 新建虚拟环境,并进入该虚拟环境;
+
+ ```bash
+ conda create -n open-mmlab python=3.7 -y
+ conda activate open-mmlab
+ ```
+
+2. 安装 PyTorch
+
+ 在安装 MMEngine 之前,请确保 PyTorch 已经成功安装在环境中,可以参考 [PyTorch 官方安装文档](https://pytorch.org/get-started/locally/#start-locally)。使用以下命令验证 PyTorch 是否安装
+
+ ```bash
+ python -c 'import torch;print(torch.__version__)'
+ ```
+
+### 安装 MMEngine
+
+#### 使用 mim 安装
+
+[mim](https://github.com/open-mmlab/mim) 是 OpenMMLab 项目的包管理工具,使用它可以很方便地安装 OpenMMLab 项目。
+
+```bash
+pip install -U openmim
+mim install mmengine
+```
+
+#### 使用 pip 安装
+
+```bash
+pip install mmengine
+```
+
+#### 使用 docker 镜像
+
+1. 构建镜像
+
+ ```bash
+ docker build -t mmengine https://github.com/open-mmlab/mmengine.git#main:docker/release
+ ```
+
+ 更多构建方式请参考 [mmengine/docker](https://github.com/open-mmlab/mmengine/tree/main/docker)。
+
+2. 运行镜像
+
+ ```bash
+ docker run --gpus all --shm-size=8g -it mmengine
+ ```
+
+#### 源码安装
+
+```bash
+# 如果克隆代码仓库的速度过慢,可以从 https://gitee.com/open-mmlab/mmengine.git 克隆
+git clone https://github.com/open-mmlab/mmengine.git
+cd mmengine
+pip install -e . -v
+```
+
+### 验证安装
+
+为了验证是否正确安装了 MMEngine 和所需的环境,我们可以运行以下命令
+
+```bash
+python -c 'import mmengine;print(mmengine.__version__)'
+```
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/get_started/introduction.md b/testbed/open-mmlab__mmengine/docs/zh_cn/get_started/introduction.md
new file mode 100644
index 0000000000000000000000000000000000000000..2e69af6cd5cf2687097f0489a8710e74c138e389
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/get_started/introduction.md
@@ -0,0 +1,60 @@
+## 介绍
+
+MMEngine 是一个用于深度学习模型训练的基础库,基于 PyTorch,支持在 Linux、Windows、macOS 上运行。它具有如下三个亮点:
+
+1. 通用:MMEngine 实现了一个高级的通用训练器,它能够:
+
+ - 支持用少量代码训练不同的任务,例如仅使用 80 行代码就可以训练 imagenet(pytorch example 400 行)
+ - 轻松兼容流行的算法库如 TIMM、TorchVision 和 Detectron2 中的模型
+
+2. 统一:MMEngine 设计了一个接口统一的开放架构,使得
+
+ - 用户可以仅依赖一份代码实现所有任务的轻量化,例如 MMRazor 1.x 相比 MMRazor 0.x 优化了 40% 的代码量
+ - 上下游的对接更加统一便捷,在为上层算法库提供统一抽象的同时,支持多种后端设备。目前 MMEngine 支持 Nvidia CUDA、Mac MPS、AMD、MLU 等设备进行模型训练。
+
+3. 灵活:MMEngine 实现了“乐高”式的训练流程,支持了
+
+ - 根据迭代数、 loss 和评测结果等动态调整的训练流程、优化策略和数据增强策略,例如早停(early stopping)机制等
+ - 任意形式的模型权重平均,如 Exponential Momentum Average (EMA) 和 Stochastic Weight Averaging (SWA)
+ - 训练过程中针对任意数据和任意节点的灵活可视化和日志控制
+ - 对神经网络模型中各个层的优化配置进行细粒度调整
+ - 混合精度训练的灵活控制
+
+### 架构
+
+
+
+上图展示了 MMEngine 在 OpenMMLab 2.0 中的层次。MMEngine 实现了 OpenMMLab 算法库的新一代训练架构,为 OpenMMLab 中的 30 多个算法库提供了统一的执行基座。其核心组件包含训练引擎、评测引擎和模块管理等。
+
+### 模块介绍
+
+
+
+MMEngine 将训练过程中涉及的组件和它们的关系进行了抽象,如上图所示。不同算法库中的同类型组件具有相同的接口定义。
+
+#### 核心模块与相关组件
+
+训练引擎的核心模块是[执行器(Runner)](../tutorials/runner.md)。 执行器负责执行训练、测试和推理任务并管理这些过程中所需要的各个组件。在训练、测试、推理任务执行过程中的特定位置,执行器设置了[钩子(Hook)](../tutorials/hook.md) 来允许用户拓展、插入和执行自定义逻辑。执行器主要调用如下组件来完成训练和推理过程中的循环:
+
+- [数据集(Dataset)](../tutorials/basedataset.md):负责在训练、测试、推理任务中构建数据集,并将数据送给模型。实际使用过程中会被数据加载器(DataLoader)封装一层,数据加载器会启动多个子进程来加载数据。
+- [模型(Model)](../tutorials/model.md):在训练过程中接受数据并输出 loss;在测试、推理任务中接受数据,并进行预测。分布式训练等情况下会被模型的封装器(Model Wrapper,如`MMDistributedDataParallel`)封装一层。
+- [优化器封装(Optimizer)](../tutorials/optim_wrapper.md):优化器封装负责在训练过程中执行反向传播优化模型,并且以统一的接口支持了混合精度训练和梯度累加。
+- [参数调度器(Parameter Scheduler)](../tutorials/param_scheduler.md):训练过程中,对学习率、动量等优化器超参数进行动态调整。
+
+在训练间隙或者测试阶段,[评测指标与评测器(Metrics & Evaluator)](../tutorials/metric_and_evaluator.md)会负责对模型性能进行评测。其中评测器负责基于数据集对模型的预测进行评估。评测器内还有一层抽象是评测指标,负责计算具体的一个或多个评测指标(如召回率、正确率等)。
+
+为了统一接口,OpenMMLab 2.0 中各个算法库的评测器,模型和数据之间交流的接口都使用了[数据元素(Data Element)](../tutorials/data_element.md)来进行封装。
+
+在训练、推理执行过程中,上述各个组件都可以调用日志管理模块和可视化器进行结构化和非结构化日志的存储与展示。[日志管理(Logging Modules)](../tutorials/logging.md):负责管理执行器运行过程中产生的各种日志信息。其中消息枢纽 (MessageHub)负责实现组件与组件、执行器与执行器之间的数据共享,日志处理器(Log Processor)负责对日志信息进行处理,处理后的日志会分别发送给执行器的日志器(Logger)和可视化器(Visualizer)进行日志的管理与展示。[可视化器(Visualizer)](../tutorials/visualization.md):可视化器负责对模型的特征图、预测结果和训练过程中产生的结构化日志进行可视化,支持 Tensorboard 和 WanDB 等多种可视化后端。
+
+#### 公共基础模块
+
+MMEngine 中还实现了各种算法模型执行过程中需要用到的公共基础模块,包括
+
+- [配置类(Config)](../advanced_tutorials/config.md):在 OpenMMLab 算法库中,用户可以通过编写 config 来配置训练、测试过程以及相关的组件。
+- [注册器(Registry)](../advanced_tutorials/registry.md):负责管理算法库中具有相同功能的模块。MMEngine 根据对算法库模块的抽象,定义了一套根注册器,算法库中的注册器可以继承自这套根注册器,实现模块的跨算法库调用。
+- [文件读写(File I/O)](../tutorials/fileio.md):为各个模块的文件读写提供了统一的接口,以统一的形式支持了多种文件读写后端和多种文件格式,并具备扩展性。
+- [分布式通信原语(Distributed Communication Primitives)](../tutorials/distributed.md):负责在程序分布式运行过程中不同进程间的通信。这套接口屏蔽了分布式和非分布式环境的区别,同时也自动处理了数据的设备和通信后端。
+- [其他工具(Utils)](../tutorials/utils.md):还有一些工具性的模块,如 ManagerMixin,它实现了一种全局变量的创建和获取方式,执行器内很多全局可见对象的基类就是 ManagerMixin。
+
+用户可以进一步阅读[教程](<>)来了解这些模块的高级用法,也可以参考[设计文档](<>) 了解它们的设计思路与细节。
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/index.rst b/testbed/open-mmlab__mmengine/docs/zh_cn/index.rst
new file mode 100644
index 0000000000000000000000000000000000000000..e0a027679c2e43a69a313ac364e863e381edf8b1
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/index.rst
@@ -0,0 +1,111 @@
+欢迎来到 MMEngine 的中文文档!
+=========================================
+您可以在页面左下角切换中英文文档。
+
+.. toctree::
+ :maxdepth: 1
+ :caption: 开始你的第一步
+
+ get_started/introduction.md
+ get_started/installation.md
+ get_started/15_minutes.md
+
+.. toctree::
+ :maxdepth: 1
+ :caption: 常用功能
+
+ examples/resume_training.md
+ examples/speed_up_training.md
+ examples/save_gpu_memory.md
+ examples/train_a_gan.md
+
+.. toctree::
+ :maxdepth: 3
+ :caption: 入门教程
+
+ tutorials/runner.md
+ tutorials/dataset.md
+ tutorials/model.md
+ tutorials/evaluation.md
+ tutorials/optim_wrapper.md
+ tutorials/param_scheduler.md
+ tutorials/hook.md
+
+.. toctree::
+ :maxdepth: 1
+ :caption: 进阶教程
+
+ advanced_tutorials/registry.md
+ advanced_tutorials/config.md
+ advanced_tutorials/basedataset.md
+ advanced_tutorials/data_transform.md
+ advanced_tutorials/initialize.md
+ advanced_tutorials/visualization.md
+ advanced_tutorials/data_element.md
+ advanced_tutorials/distributed.md
+ advanced_tutorials/logging.md
+ advanced_tutorials/fileio.md
+ advanced_tutorials/manager_mixin.md
+ advanced_tutorials/cross_library.md
+
+.. toctree::
+ :maxdepth: 1
+ :caption: 架构设计
+
+ design/hook.md
+ design/runner.md
+ design/evaluation.md
+ design/visualization.md
+ design/logging.md
+
+.. toctree::
+ :maxdepth: 1
+ :caption: 迁移指南
+
+ migration/runner.md
+ migration/hook.md
+ migration/model.md
+ migration/param_scheduler.md
+ migration/transform.md
+
+.. toctree::
+ :maxdepth: 2
+ :caption: API 文档
+
+ mmengine.registry
+ mmengine.config
+ mmengine.runner
+ mmengine.hooks
+ mmengine.model
+ mmengine.optim
+ mmengine.evaluator
+ mmengine.structures
+ mmengine.dataset
+ mmengine.device
+ mmengine.hub
+ mmengine.logging
+ mmengine.visualization
+ mmengine.fileio
+ mmengine.dist
+ mmengine.utils
+ mmengine.utils.dl_utils
+
+.. toctree::
+ :maxdepth: 2
+ :caption: 说明
+
+ notes/changelog.md
+ notes/contributing.md
+ notes/code_style.md
+
+.. toctree::
+ :caption: 语言切换
+
+ switch_language.md
+
+Indices and tables
+==================
+
+* :ref:`genindex`
+* :ref:`modindex`
+* :ref:`search`
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/make.bat b/testbed/open-mmlab__mmengine/docs/zh_cn/make.bat
new file mode 100644
index 0000000000000000000000000000000000000000..922152e96a04a242e6fc40f124261d74890617d8
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/make.bat
@@ -0,0 +1,35 @@
+@ECHO OFF
+
+pushd %~dp0
+
+REM Command file for Sphinx documentation
+
+if "%SPHINXBUILD%" == "" (
+ set SPHINXBUILD=sphinx-build
+)
+set SOURCEDIR=.
+set BUILDDIR=_build
+
+if "%1" == "" goto help
+
+%SPHINXBUILD% >NUL 2>NUL
+if errorlevel 9009 (
+ echo.
+ echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
+ echo.installed, then set the SPHINXBUILD environment variable to point
+ echo.to the full path of the 'sphinx-build' executable. Alternatively you
+ echo.may add the Sphinx directory to PATH.
+ echo.
+ echo.If you don't have Sphinx installed, grab it from
+ echo.http://sphinx-doc.org/
+ exit /b 1
+)
+
+%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
+goto end
+
+:help
+%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
+
+:end
+popd
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/migration/hook.md b/testbed/open-mmlab__mmengine/docs/zh_cn/migration/hook.md
new file mode 100644
index 0000000000000000000000000000000000000000..558015818fbd03157848052f85b744383ccc0ff3
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/migration/hook.md
@@ -0,0 +1,319 @@
+# 迁移 MMCV 钩子到 MMEngine
+
+## 简介
+
+由于架构设计的更新和用户需求的不断增加,MMCV 的钩子(Hook)点位已经满足不了需求,因此在 MMEngine 中对钩子点位进行了重新设计以及对钩子的功能做了调整。在开始迁移前,阅读[钩子的设计](../design/hook.md)会很有帮助。
+
+本文对比 [MMCV v1.6.0](https://github.com/open-mmlab/mmcv/tree/v1.6.0) 和 [MMEngine v0.5.0](https://github.com/open-mmlab/mmengine/tree/v0.5.0) 的钩子在功能、点位、用法和实现上的差异。
+
+## 功能差异
+
+
+
+
+
+ MMCV
+ MMEngine
+
+
+
+
+ 反向传播以及梯度更新
+ OptimizerHook
+ 将反向传播以及梯度更新的操作抽象成 OptimWrapper 而不是钩子
+
+
+ GradientCumulativeOptimizerHook
+
+
+ 学习率调整
+ LrUpdaterHook
+ ParamSchdulerHook 以及 _ParamScheduler 的子类完成优化器超参的调整
+
+
+ 动量调整
+ MomentumUpdaterHook
+
+
+ 按指定间隔保存权重
+ CheckpointHook
+ CheckpointHook 除了保存权重,还有保存最优权重的功能,而 EvalHook 的模型评估功能则交由 ValLoop 或 TestLoop 完成
+
+
+ 模型评估并保存最优模型
+ EvalHook
+
+
+ 打印日志
+ LoggerHook 及其子类实现打印日志、保存日志以及可视化功能
+ LoggerHook
+
+
+ 可视化
+ NaiveVisualizationHook
+
+
+ 添加运行时信息
+ RuntimeInfoHook
+
+
+ 模型参数指数滑动平均
+ EMAHook
+ EMAHook
+
+
+ 确保分布式 Sampler 的 shuffle 生效
+ DistSamplerSeedHook
+ DistSamplerSeedHook
+
+
+ 同步模型的 buffer
+ SyncBufferHook
+ SyncBufferHook
+
+
+ PyTorch CUDA 缓存清理
+ EmptyCacheHook
+ EmptyCacheHook
+
+
+ 统计迭代耗时
+ IterTimerHook
+ IterTimerHook
+
+
+ 分析训练时间的瓶颈
+ ProfilerHook
+ 暂未提供
+
+
+ 提供注册方法给钩子点位的功能
+ ClosureHook
+ 暂未提供
+
+
+
+
+## 点位差异
+
+
+
+
+
+ MMCV
+ MMEngine
+
+
+
+
+ 全局位点
+ 执行前
+ before_run
+ before_run
+
+
+ 执行后
+ after_run
+ after_run
+
+
+ Checkpoint 相关
+ 加载 checkpoint 后
+ 无
+ after_load_checkpoint
+
+
+ 保存 checkpoint 前
+ 无
+ before_save_checkpoint
+
+
+ 训练相关
+ 训练前触发
+ 无
+ before_train
+
+
+ 训练后触发
+ 无
+ after_train
+
+
+ 每个 epoch 前
+ before_train_epoch
+ before_train_epoch
+
+
+ 每个 epoch 后
+ after_train_epoch
+ after_train_epoch
+
+
+ 每次迭代前
+ before_train_iter
+ before_train_iter,新增 batch_idx 和 data_batch 参数
+
+
+ 每次迭代后
+ after_train_iter
+ after_train_iter,新增 batch_idx、data_batch 和 outputs 参数
+
+
+ 验证相关
+ 验证前触发
+ 无
+ before_val
+
+
+ 验证后触发
+ 无
+ after_val
+
+
+ 每个 epoch 前
+ before_val_epoch
+ before_val_epoch
+
+
+ 每个 epoch 后
+ after_val_epoch
+ after_val_epoch
+
+
+ 每次迭代前
+ before_val_iter
+ before_val_iter,新增 batch_idx 和 data_batch 参数
+
+
+ 每次迭代后
+ after_val_iter
+ after_val_iter,新增 batch_idx、data_batch 和 outputs 参数
+
+
+ 测试相关
+ 测试前触发
+ 无
+ before_test
+
+
+ 测试后触发
+ 无
+ after_test
+
+
+ 每个 epoch 前
+ 无
+ before_test_epoch
+
+
+ 每个 epoch 后
+ 无
+ after_test_epoch
+
+
+ 每次迭代前
+ 无
+ before_test_iter,新增 batch_idx 和 data_batch 参数
+
+
+ 每次迭代后
+ 无
+ after_test_iter,新增 batch_idx、data_batch 和 outputs 参数
+
+
+
+
+## 用法差异
+
+在 MMCV 中,将钩子注册到执行器(Runner),需调用执行器的 `register_training_hooks` 方法往执行器注册钩子,而在 MMEngine 中,可以通过参数传递给执行器的初始化方法进行注册。
+
+- MMCV
+
+```python
+model = ResNet18()
+optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
+lr_config = dict(policy='step', step=[2, 3])
+optimizer_config = dict(grad_clip=None)
+checkpoint_config = dict(interval=5)
+log_config = dict(interval=100, hooks=[dict(type='TextLoggerHook')])
+custom_hooks = [dict(type='NumClassCheckHook')]
+runner = EpochBasedRunner(
+ model=model,
+ optimizer=optimizer,
+ work_dir='./work_dir',
+ max_epochs=3,
+ xxx,
+)
+runner.register_training_hooks(
+ lr_config=lr_config,
+ optimizer_config=optimizer_config,
+ checkpoint_config=checkpoint_config,
+ log_config=log_config,
+ custom_hooks_config=custom_hooks,
+)
+runner.run([trainloader], [('train', 1)])
+```
+
+- MMEngine
+
+```python
+model=ResNet18()
+optim_wrapper=dict(
+ type='OptimizerWrapper',
+ optimizer=dict(type='SGD', lr=0.001, momentum=0.9))
+param_scheduler = dict(type='MultiStepLR', milestones=[2, 3]),
+default_hooks = dict(
+ logger=dict(type='LoggerHook'),
+ param_scheduler=dict(type='ParamSchedulerHook'),
+ checkpoint=dict(type='CheckpointHook', interval=5),
+)
+custom_hooks = [dict(type='NumClassCheckHook')]
+runner = Runner(
+ model=model,
+ work_dir='./work_dir',
+ optim_wrapper=optim_wrapper,
+ param_scheduler=param_scheduler,
+ train_cfg=dict(by_epoch=True, max_epochs=3),
+ default_hooks=default_hooks,
+ custom_hooks=custom_hooks,
+ xxx,
+)
+runner.train()
+```
+
+MMEngine 钩子的更多用法请参考[钩子的用法](../tutorials/hook.md)。
+
+## 实现差异
+
+以 `CheckpointHook` 为例,MMEngine 的 [CheckpointHook](https://github.com/open-mmlab/mmengine/blob/main/mmengine/hooks/checkpoint_hook.py) 相比 MMCV 的 [CheckpointHook](https://github.com/open-mmlab/mmcv/blob/v1.6.0/mmcv/runner/hooks/checkpoint.py)(新增保存最优权重的功能,在 MMCV 中,保存最优权重的功能由 EvalHook 提供),因此,它需要实现 `after_val_epoch` 点位。
+
+- MMCV
+
+```python
+class CheckpointHook(Hook):
+ def before_run(self, runner):
+ """初始化 out_dir 和 file_client 属性"""
+
+ def after_train_epoch(self, runner):
+ """同步 buffer 和保存权重,用于以 epoch 为单位训练的任务"""
+
+ def after_train_iter(self, runner):
+ """同步 buffer 和保存权重,用于以 iteration 为单位训练的任务"""
+```
+
+- MMEngine
+
+```python
+class CheckpointHook(Hook):
+ def before_run(self, runner):
+ """初始化 out_dir 和 file_client 属性"""
+
+ def after_train_epoch(self, runner):
+ """同步 buffer 和保存权重,用于以 epoch 为单位训练的任务"""
+
+ def after_train_iter(self, runner, batch_idx, data_batch, outputs):
+ """同步 buffer 和保存权重,用于以 iteration 为单位训练的任务"""
+
+ def after_val_epoch(self, runner, metrics):
+ """根据 metrics 保存最优权重"""
+```
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/migration/model.md b/testbed/open-mmlab__mmengine/docs/zh_cn/migration/model.md
new file mode 100644
index 0000000000000000000000000000000000000000..dd7f3f2db839627638b52e84aac042f2bf58dbc9
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/migration/model.md
@@ -0,0 +1,443 @@
+# 迁移 MMCV 模型到 MMEngine
+
+## 简介
+
+MMCV 早期支持的计算机视觉任务,例如目标检测、物体识别等,都采用了一种典型的模型参数优化流程,可以被归纳为以下四个步骤:
+
+1. 计算损失
+2. 计算梯度
+3. 更新参数
+4. 梯度清零
+
+上述流程的一大特点就是调用位置统一(在训练迭代后调用)、执行步骤统一(依次执行步骤 1->2->3->4),非常契合[钩子(Hook)](../design/hook.md)的设计原则,因此这类任务通常会使用 `Hook`
+来优化模型。MMCV 为此实现了一系列的 `Hook`,例如 `OptimizerHook`(单精度训练)、`Fp16OptimizerHook`(混合精度训练) 和 `GradientCumulativeFp16OptimizerHook`(混合精度训练 + 梯度累加),为这类任务提供各种优化策略。
+
+一些例如生成对抗网络(GAN),自监督(Self-supervision)等领域的算法一般有更加灵活的训练流程,这类流程并不满足调用位置统一、执行步骤统一的原则,难以使用 `Hook` 对参数进行优化。为了支持训练这类任务,MMCV 的执行器会在调用 `model.train_step` 时,额外传入 `optimizer` 参数,让模型在 `train_step` 里实现自定义的优化流程。这样虽然可以支持训练这类任务,但也会导致无法使用各种 `OptimizerHook`,需要算法在 `train_step` 中实现混合精度训练、梯度累加等训练策略。
+
+为了统一深度学习任务的参数优化流程,MMEngine 设计了[优化器封装](mmengine.optim.OptimWrapper),集成了混合精度训练、梯度累加等训练策略,各类深度学习任务一律在 `model.train_step` 里执行参数优化流程。
+
+## 优化流程的迁移
+
+### 常用的参数更新流程
+
+考虑到目标检测、物体识别一类的深度学习任务参数优化的流程基本一致,我们可以通过继承[模型基类](../tutorials/model.md)来完成迁移。
+
+**基于 MMCV 执行器的模型**
+
+在介绍如何迁移模型之前,我们先来看一个基于 MMCV 执行器训练模型的最简示例:
+
+```python
+import torch
+import torch.nn as nn
+from torch.optim import SGD
+from torch.utils.data import DataLoader
+
+from mmcv.runner import Runner
+from mmcv.utils.logging import get_logger
+
+
+train_dataset = [(torch.ones(1, 1), torch.ones(1, 1))] * 50
+train_dataloader = DataLoader(train_dataset, batch_size=2)
+
+
+class MMCVToyModel(nn.Module):
+ def __init__(self) -> None:
+ super().__init__()
+ self.linear = nn.Linear(1, 1)
+
+ def forward(self, img, label, return_loss=False):
+ feat = self.linear(img)
+ loss1 = (feat - label).pow(2)
+ loss2 = (feat - label).abs()
+ loss = (loss1 + loss2).sum()
+ return dict(loss=loss,
+ num_samples=len(img),
+ log_vars=dict(
+ loss1=loss1.sum().item(),
+ loss2=loss2.sum().item()))
+
+ def train_step(self, data, optimizer=None):
+ return self(*data, return_loss=True)
+
+ def val_step(self, data, optimizer=None):
+ return self(*data, return_loss=False)
+
+
+model = MMCVToyModel()
+optimizer = SGD(model.parameters(), lr=0.01)
+logger = get_logger('demo')
+
+lr_config = dict(policy='step', step=[2, 3])
+optimizer_config = dict(grad_clip=None)
+log_config = dict(interval=10, hooks=[dict(type='TextLoggerHook')])
+
+
+runner = Runner(
+ model=model,
+ work_dir='tmp_dir',
+ optimizer=optimizer,
+ logger=logger,
+ max_epochs=5)
+
+runner.register_training_hooks(
+ lr_config=lr_config,
+ optimizer_config=optimizer_config,
+ log_config=log_config)
+runner.run([train_dataloader], [('train', 1)])
+```
+
+基于 MMCV 执行器训练模型时,我们必须实现 `train_step` 接口,并返回一个字典,字典需要包含以下三个字段:
+
+- loss:传给 `OptimizerHook` 计算梯度
+- num_samples:传给 `LogBuffer`,用于计算平滑后的损失
+- log_vars:传给 `LogBuffer` 用于计算平滑后的损失
+
+**基于 MMEngine 执行器的模型**
+
+基于 MMEngine 的执行器,实现同样逻辑的代码:
+
+```python
+import torch
+import torch.nn as nn
+from torch.utils.data import DataLoader
+
+from mmengine.runner import Runner
+from mmengine.model import BaseModel
+
+train_dataset = [(torch.ones(1, 1), torch.ones(1, 1))] * 50
+train_dataloader = DataLoader(train_dataset, batch_size=2)
+
+
+class MMEngineToyModel(BaseModel):
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.linear = nn.Linear(1, 1)
+
+ def forward(self, img, label, mode):
+ feat = self.linear(img)
+ # 被 `train_step` 调用,返回用于更新参数的损失字典
+ if mode == 'loss':
+ loss1 = (feat - label).pow(2)
+ loss2 = (feat - label).abs()
+ return dict(loss1=loss1, loss2=loss2)
+ # 被 `val_step` 调用,返回传给 `evaluator` 的预测结果
+ elif mode == 'predict':
+ return [_feat for _feat in feat]
+ # tensor 模式,功能详见模型教程文档: tutorials/model.md
+ else:
+ pass
+
+
+runner = Runner(
+ model=MMEngineToyModel(),
+ work_dir='tmp_dir',
+ train_dataloader=train_dataloader,
+ train_cfg=dict(by_epoch=True, max_epochs=5),
+ optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.01)))
+runner.train()
+```
+
+MMEngine 实现了模型基类,模型基类在 `train_step` 里实现了 `OptimizerHook` 的优化流程。因此上例中,我们无需实现 `train_step`,运行时直接调用基类的 `train_step`。
+
+
+
+
+ MMCV 模型
+ MMEngine 模型
+
+
+
+
+```python
+class MMCVToyModel(nn.Module):
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.linear = nn.Linear(1, 1)
+
+ def forward(self, img, label, return_loss=False):
+ feat = self.linear(img)
+ loss1 = (feat - label).pow(2)
+ loss2 = (feat - label).abs()
+ loss = (loss1 + loss2).sum()
+ return dict(loss=loss,
+ num_samples=len(img),
+ log_vars=dict(
+ loss1=loss1.sum().item(),
+ loss2=loss2.sum().item()))
+
+ def train_step(self, data, optimizer=None):
+ return self(*data, return_loss=True)
+
+ def val_step(self, data, optimizer=None):
+ return self(*data, return_loss=False)
+```
+
+
+
+
+
+```python
+class MMEngineToyModel(BaseModel):
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.linear = nn.Linear(1, 1)
+
+ def forward(self, img, label, mode):
+ if mode == 'loss':
+ feat = self.linear(img)
+ loss1 = (feat - label).pow(2)
+ loss2 = (feat - label).abs()
+ return dict(loss1=loss1, loss2=loss2)
+ elif mode == 'predict':
+ return [_feat for _feat in feat]
+ else:
+ pass
+
+ # 模型基类 `train_step` 等效代码
+ # def train_step(self, data, optim_wrapper):
+ # data = self.data_preprocessor(data)
+ # loss_dict = self(*data, mode='loss')
+ # loss_dict['loss1'] = loss_dict['loss1'].sum()
+ # loss_dict['loss2'] = loss_dict['loss2'].sum()
+ # loss = (loss_dict['loss1'] + loss_dict['loss2']).sum()
+ # 调用优化器封装更新模型参数
+ # optim_wrapper.update_params(loss)
+ # return loss_dict
+```
+
+
+
+
+
+
+
+关于等效代码中的[数据处理器(data_preprocessor)](mmengine.model.BaseDataPreprocessor) 和[优化器封装(optim_wrapper)](mmengine.optim.OptimWrapper) 的说明,详见[模型教程](../tutorials/model.md#数据处理器(DataPreprocessor))和[优化器封装教程](../tutorials/optim_wrapper.md)。
+
+模型具体差异如下:
+
+- `MMCVToyModel` 继承自 `nn.Module`,而 `MMEngineToyModel` 继承自 `BaseModel`
+- `MMCVToyModel` 必须实现 `train_step`,且必须返回损失字典,损失字典包含 `loss` 和 `log_vars` 和 `num_samples` 字段。`MMEngineToyModel` 继承自 `BaseModel`,只需要实现 `forward` 接口,并返回损失字典,损失字典的每一个值必须是可微的张量
+- `MMCVToyModel` 和 `MMEngineModel` 的 `forward` 的接口需要匹配 `train_step` 中的调用方式,由于 `MMEngineToyModel` 直接调用基类的 `train_step` 方法,因此 `forward` 需要接受参数 `mode`,具体规则详见[模型教程文档](../tutorials/model.md)
+
+### 自定义的参数更新流程
+
+以训练生成对抗网络为例,生成器和判别器的优化需要交替进行,且优化流程可能会随着迭代次数的增多发生变化,因此很难使用 `OptimizerHook` 来满足这种需求。在基于 MMCV 训练生成对抗网络时,通常会在模型的 `train_step` 接口中传入 `optimizer`,然后在 `train_step` 里实现自定义的参数更新逻辑。这种训练流程和 MMEngine 非常相似,只不过 MMEngine 在 `train_step` 接口中传入[优化器封装](../tutorials/optim_wrapper.md),能够更加简单地优化模型。
+
+参考[训练生成对抗网络](../examples/train_a_gan.md),MMCV 和 MMEngine 的对比实现如下:
+
+
+
+
+ Training gan in MMCV
+ Training gan in MMEngine
+
+
+
+
+```python
+ def train_discriminator(self, inputs, optimizer):
+ real_imgs = inputs['inputs']
+ z = torch.randn(
+ (real_imgs.shape[0], self.noise_size)).type_as(real_imgs)
+ with torch.no_grad():
+ fake_imgs = self.generator(z)
+
+ disc_pred_fake = self.discriminator(fake_imgs)
+ disc_pred_real = self.discriminator(real_imgs)
+
+ parsed_losses, log_vars = self.disc_loss(disc_pred_fake,
+ disc_pred_real)
+ parsed_losses.backward()
+ optimizer.step()
+ optimizer.zero_grad()
+ return log_vars
+
+ def train_generator(self, inputs, optimizer_wrapper):
+ real_imgs = inputs['inputs']
+ z = torch.randn(inputs['inputs'].shape[0], self.noise_size).type_as(
+ real_imgs)
+
+ fake_imgs = self.generator(z)
+
+ disc_pred_fake = self.discriminator(fake_imgs)
+ parsed_loss, log_vars = self.gen_loss(disc_pred_fake)
+
+ parsed_losses.backward()
+ optimizer.step()
+ optimizer.zero_grad()
+ return log_vars
+```
+
+
+
+
+
+```python
+ def train_discriminator(self, inputs, optimizer_wrapper):
+ real_imgs = inputs['inputs']
+ z = torch.randn(
+ (real_imgs.shape[0], self.noise_size)).type_as(real_imgs)
+ with torch.no_grad():
+ fake_imgs = self.generator(z)
+
+ disc_pred_fake = self.discriminator(fake_imgs)
+ disc_pred_real = self.discriminator(real_imgs)
+
+ parsed_losses, log_vars = self.disc_loss(disc_pred_fake,
+ disc_pred_real)
+ optimizer_wrapper.update_params(parsed_losses)
+ return log_vars
+
+
+
+ def train_generator(self, inputs, optimizer_wrapper):
+ real_imgs = inputs['inputs']
+ z = torch.randn(real_imgs.shape[0], self.noise_size).type_as(real_imgs)
+
+ fake_imgs = self.generator(z)
+
+ disc_pred_fake = self.discriminator(fake_imgs)
+ parsed_loss, log_vars = self.gen_loss(disc_pred_fake)
+
+ optimizer_wrapper.update_params(parsed_loss)
+ return log_vars
+```
+
+
+
+
+
+
+
+二者的区别主要在于优化器的使用方式。此外,`train_step` 接口返回值的差异和[上一节](参数更新流程统一的深度学习任务)提到的一致。
+
+## 验证/测试流程的迁移
+
+基于 MMCV 执行器实现的模型通常不需要为验证、测试流程提供独立的 `val_step`、`test_step`(测试流程由 `EvalHook` 实现,这里不做展开)。基于 MMEngine 执行器实现的模型则有所不同,[ValLoop](mmengine.runner.ValLoop)、[TestLoop](mmengine.runner.TestLoop) 会分别调用模型的 `val_step` 和 `test_step` 接口,输出会进一步传给 [Evaluator.process](mmengine.evaluator.Evaluator.process)。因此模型的 `val_step` 和 `test_step` 接口输出需要和 `Evaluator.process` 的入参(第一个参数)对齐,即返回列表(推荐,也可以是其他可迭代类型)类型的结果。列表中的每一个元素代表一个批次(batch)数据中每个样本的预测结果。模型的 `test_step` 和 `val_step` 会调 `forward` 接口(详见[模型教程文档](../tutorials/model.md)),因此在上一节的模型示例中,模型 `forward` 的 `predict` 模式会将 `feat` 切片后,以列表的形式返回预测结果。
+
+```python
+
+class MMEngineToyModel(BaseModel):
+
+ ...
+ def forward(self, img, label, mode):
+ if mode == 'loss':
+ ...
+ elif mode == 'predict':
+ # 把一个 batch 的预测结果切片成列表,每个元素代表一个样本的预测结果
+ return [_feat for _feat in feat]
+ else:
+ ...
+ # tensor 模式,功能详见模型教程文档: tutorials/model.md
+```
+
+## 迁移分布式训练
+
+MMCV 需要在执行器构建之前,使用 `MMDistributedDataParallel` 对模型进行分布式封装。MMEngine 实现了 [MMDistributedDataParallel](mmengine.model.MMDistributedDataParallel) 和 [MMSeparateDistributedDataParallel](mmengine.model.MMSeparateDistributedDataParallel) 两种分布式模型封装,供不同类型的任务选择。执行器会在构建时对模型进行分布式封装。
+
+1. **常用训练流程**
+
+ 对于[简介](#简介)中提到的常用优化流程的训练任务,即一次参数更新可以被拆解成梯度计算、参数优化、梯度清零的任务,使用 Runner 默认的 `MMDistributedDataParallel` 即可满足需求,无需为 runner 其他额外参数。
+
+
+
+
+ MMCV 分布式训练构建模型
+ MMEngine 分布式训练
+
+
+
+
+
+```python
+model = MMDistributedDataParallel(
+ model,
+ device_ids=[int(os.environ['LOCAL_RANK'])],
+ broadcast_buffers=False,
+ find_unused_parameters=find_unused_parameters)
+...
+runner = Runner(model=model, ...)
+```
+
+
+
+
+
+```python
+runner = Runner(
+ model=model,
+ launcher='pytorch', #开启分布式训练
+ ..., # 其他参数
+)
+```
+
+
+
+
+
+
+
+
+
+2. **以自定义流程分模块优化模型的学习任务**
+
+ 同样以训练生成对抗网络为例,生成对抗网络有两个需要分别优化的子模块,即生成器和判别器。因此需要使用 `MMSeparateDistributedDataParallel` 对模型进行封装。我们需要在构建执行器时指定:
+
+ ```python
+ cfg = dict(model_wrapper_cfg='MMSeparateDistributedDataParallel')
+ runner = Runner(
+ model=model,
+ ...,
+ launcher='pytorch',
+ cfg=cfg)
+ ```
+
+ 即可进行分布式训练。
+
+
+
+3. **以自定义流程优化整个模型的深度学习任务**
+
+ 有时候我们需要用自定义的优化流程来优化单个模块,这时候我们就不能复用模型基类的 `train_step`,而需要重新实现,例如我们想用同一批图片对模型优化两次,第一次开启批数据增强,第二次关闭:
+
+ ```python
+ class CustomModel(BaseModel):
+
+ def train_step(self, data, optim_wrapper):
+ data = self.data_preprocessor(data, training=True) # 开启批数据增强
+ loss = self(data, mode='loss')
+ optim_wrapper.update_params(loss)
+ data = self.data_preprocessor(data, training=False) # 关闭批数据增强
+ loss = self(data, mode='loss')
+ optim_wrapper.update_params(loss)
+ ```
+
+ 要想启用分布式训练,我们就需要重载 `MMSeparateDistributedDataParallel`,并在 `train_step` 中实现和 `CustomModel.train_step` 相同的流程(`test_step`、`val_step` 同理)。
+
+ ```python
+ class CustomDistributedDataParallel(MMSeparateDistributedDataParallel):
+
+ def train_step(self, data, optim_wrapper):
+ data = self.data_preprocessor(data, training=True) # 开启批数据增强
+ loss = self(data, mode='loss')
+ optim_wrapper.update_params(loss)
+ data = self.data_preprocessor(data, training=False) # 关闭批数据增强
+ loss = self(data, mode='loss')
+ optim_wrapper.update_params(loss)
+ ```
+
+ 最后在构建 `runner` 时指定:
+
+ ```python
+ # 指定封装类型为 `CustomDistributedDataParallel`,并基于默认参数封装模型。
+ cfg = dict(model_wrapper_cfg=dict(type='CustomDistributedDataParallel'))
+ runner = Runner(
+ model=model,
+ ...,
+ launcher='pytorch',
+ cfg=cfg
+ )
+ ```
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/migration/param_scheduler.md b/testbed/open-mmlab__mmengine/docs/zh_cn/migration/param_scheduler.md
new file mode 100644
index 0000000000000000000000000000000000000000..fe26fff90d84dac246117cc5b2491f90aaa65964
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/migration/param_scheduler.md
@@ -0,0 +1,563 @@
+# 迁移 MMCV 参数调度器到 MMEngine
+
+MMCV 1.x 版本使用 [LrUpdaterHook](https://mmcv.readthedocs.io/zh_CN/v1.6.0/api.html#mmcv.runner.LrUpdaterHook) 和 [MomentumUpdaterHook](https://mmcv.readthedocs.io/zh_CN/v1.6.0/api.html#mmcv.runner.MomentumUpdaterHook) 来调整学习率和动量。
+但随着深度学习算法训练方式的不断发展,使用 Hook 修改学习率已经难以满足更加丰富的自定义需求,因此 MMEngine 提供了参数调度器(ParamScheduler)。
+一方面,参数调度器的接口与 PyTroch 的学习率调度器(LRScheduler)对齐,另一方面,参数调度器提供了更丰富的功能,详细请参考[参数调度器使用指南](../tutorials/param_scheduler.md)。
+
+## 学习率调度器(LrUpdater)迁移
+
+MMEngine 中使用 LRScheduler 替代 LrUpdaterHook,配置文件中的字段从原本的 `lr_config` 修改为 `param_scheduler`。
+MMCV 中的学习率配置与 MMEngine 中的参数调度器配置对应关系如下:
+
+### 学习率预热(Warmup)迁移
+
+由于 MMEngine 中的学习率调度器在实现时增加了 begin 和 end 参数,指定了调度器的生效区间,所以可以通过调度器组合的方式实现学习率预热。MMCV 中有 3 种学习率预热方式,分别是 `'constant'`, `'linear'`, `'exp'`,在 MMEngine 中对应的配置应修改为:
+
+#### 常数预热(constant)
+
+
+
+
+ MMCV-1.x
+ MMEngine
+
+
+
+
+```python
+lr_config = dict(
+ warmup='constant',
+ warmup_ratio=0.1,
+ warmup_iters=500,
+ warmup_by_epoch=False
+)
+```
+
+
+
+
+```python
+param_scheduler = [
+ dict(type='ConstantLR',
+ factor=0.1,
+ begin=0,
+ end=500,
+ by_epoch=False),
+ dict(...) # 主学习率调度器配置
+]
+```
+
+
+
+
+
+
+#### 线性预热(linear)
+
+
+
+
+ MMCV-1.x
+ MMEngine
+
+
+
+
+```python
+lr_config = dict(
+ warmup='linear',
+ warmup_ratio=0.1,
+ warmup_iters=500,
+ warmup_by_epoch=False
+)
+```
+
+
+
+
+```python
+param_scheduler = [
+ dict(type='LinearLR',
+ start_factor=0.1,
+ begin=0,
+ end=500,
+ by_epoch=False),
+ dict(...) # 主学习率调度器配置
+]
+```
+
+
+
+
+
+
+#### 指数预热(exp)
+
+
+
+
+ MMCV-1.x
+ MMEngine
+
+
+
+
+```python
+lr_config = dict(
+ warmup='exp',
+ warmup_ratio=0.1,
+ warmup_iters=500,
+ warmup_by_epoch=False
+)
+```
+
+
+
+
+```python
+param_scheduler = [
+ dict(type='ExponentialLR',
+ gamma=0.1,
+ begin=0,
+ end=500,
+ by_epoch=False),
+ dict(...) # 主学习率调度器配置
+]
+```
+
+
+
+
+
+
+### fixed 学习率(FixedLrUpdaterHook)迁移
+
+
+
+
+ MMCV-1.x
+ MMEngine
+
+
+
+
+```python
+lr_config = dict(policy='fixed')
+```
+
+
+
+
+```python
+param_scheduler = [
+ dict(type='ConstantLR', factor=1)
+]
+```
+
+
+
+
+
+
+### step 学习率(StepLrUpdaterHook)迁移
+
+
+
+
+ MMCV-1.x
+ MMEngine
+
+
+
+
+```python
+lr_config = dict(
+ policy='step',
+ step=[8, 11],
+ gamma=0.1,
+ by_epoch=True
+)
+```
+
+
+
+
+```python
+param_scheduler = [
+ dict(type='MultiStepLR',
+ milestone=[8, 11],
+ gamma=0.1,
+ by_epoch=True)
+]
+```
+
+
+
+
+
+
+### poly 学习率(PolyLrUpdaterHook)迁移
+
+
+
+
+ MMCV-1.x
+ MMEngine
+
+
+
+
+```python
+lr_config = dict(
+ policy='poly',
+ power=0.7,
+ min_lr=0.001,
+ by_epoch=True
+)
+```
+
+
+
+
+```python
+param_scheduler = [
+ dict(type='PolyLR',
+ power=0.7,
+ eta_min=0.001,
+ begin=0,
+ end=num_epochs,
+ by_epoch=True)
+]
+```
+
+
+
+
+
+
+### exp 学习率(ExpLrUpdaterHook)迁移
+
+
+
+
+ MMCV-1.x
+ MMEngine
+
+
+
+
+```python
+lr_config = dict(
+ policy='exp',
+ power=0.5,
+ by_epoch=True
+)
+```
+
+
+
+
+```python
+param_scheduler = [
+ dict(type='ExponentialLR',
+ gamma=0.5,
+ begin=0,
+ end=num_epochs,
+ by_epoch=True)
+]
+```
+
+
+
+
+
+
+### CosineAnnealing 学习率(CosineAnnealingLrUpdaterHook)迁移
+
+
+
+
+ MMCV-1.x
+ MMEngine
+
+
+
+
+```python
+lr_config = dict(
+ policy='CosineAnnealing',
+ min_lr=0.5,
+ by_epoch=True
+)
+```
+
+
+
+
+```python
+param_scheduler = [
+ dict(type='CosineAnnealingLR',
+ eta_min=0.5,
+ T_max=num_epochs,
+ begin=0,
+ end=num_epochs,
+ by_epoch=True)
+]
+```
+
+
+
+
+
+
+### FlatCosineAnnealing 学习率(FlatCosineAnnealingLrUpdaterHook)迁移
+
+像 FlatCosineAnnealing 这种由多个学习率策略拼接而成的学习率,原本需要重写 Hook 来实现,而在 MMEngine 中只需将两个参数调度器组合即可
+
+
+
+
+ MMCV-1.x
+ MMEngine
+
+
+
+
+```python
+lr_config = dict(
+ policy='FlatCosineAnnealing',
+ start_percent=0.5,
+ min_lr=0.005,
+ by_epoch=True
+)
+```
+
+
+
+
+```python
+param_scheduler = [
+ dict(type='ConstantLR', factor=1, begin=0, end=num_epochs * 0.75)
+ dict(type='CosineAnnealingLR',
+ eta_min=0.005,
+ begin=num_epochs * 0.75,
+ end=num_epochs,
+ T_max=num_epochs * 0.25,
+ by_epoch=True)
+]
+```
+
+
+
+
+
+
+### CosineRestart 学习率(CosineRestartLrUpdaterHook)迁移
+
+
+
+
+ MMCV-1.x
+ MMEngine
+
+
+
+
+```python
+lr_config = dict(policy='CosineRestart',
+ periods=[5, 10, 15],
+ restart_weights=[1, 0.7, 0.3],
+ min_lr=0.001,
+ by_epoch=True)
+```
+
+
+
+
+```python
+param_scheduler = [
+ dict(type='CosineRestartLR',
+ periods=[5, 10, 15],
+ restart_weights=[1, 0.7, 0.3],
+ eta_min=0.001,
+ by_epoch=True)
+]
+```
+
+
+
+
+
+
+### OneCycle 学习率(OneCycleLrUpdaterHook)迁移
+
+
+
+
+ MMCV-1.x
+ MMEngine
+
+
+
+
+```python
+lr_config = dict(policy='OneCycle',
+ max_lr=0.02,
+ total_steps=90000,
+ pct_start=0.3,
+ anneal_strategy='cos',
+ div_factor=25,
+ final_div_factor=1e4,
+ three_phase=True,
+ by_epoch=False)
+```
+
+
+
+
+```python
+param_scheduler = [
+ dict(type='OneCycleLR',
+ eta_max=0.02,
+ total_steps=90000,
+ pct_start=0.3,
+ anneal_strategy='cos',
+ div_factor=25,
+ final_div_factor=1e4,
+ three_phase=True,
+ by_epoch=False)
+]
+```
+
+
+
+
+
+
+需要注意的是 `by_epoch` 参数 MMCV 默认是 `False`, MMEngine 默认是 `True`
+
+### LinearAnnealing 学习率(LinearAnnealingLrUpdaterHook)迁移
+
+
+
+
+ MMCV-1.x
+ MMEngine
+
+
+
+
+```python
+lr_config = dict(
+ policy='LinearAnnealing',
+ min_lr_ratio=0.01,
+ by_epoch=True
+)
+```
+
+
+
+
+```python
+param_scheduler = [
+ dict(type='LinearLR',
+ start_factor=1,
+ end_factor=0.01,
+ begin=0,
+ end=num_epochs,
+ by_epoch=True)
+]
+```
+
+
+
+
+
+
+## 动量调度器(MomentumUpdater)迁移
+
+MMCV 使用 `momentum_config` 字段和 MomentumUpdateHook 调整动量。 MMEngine 中动量同样由参数调度器控制。用户可以简单将学习率调度器后的 `LR` 修改为 `Momentum`,即可使用同样的策略来调整动量。动量调度器只需要和学习率调度器一样添加进 `param_scheduler` 列表中即可。举一个简单的例子:
+
+
+
+
+ MMCV-1.x
+ MMEngine
+
+
+
+
+```python
+lr_config = dict(...)
+momentum_config = dict(
+ policy='CosineAnnealing',
+ min_momentum=0.1,
+ by_epoch=True
+)
+```
+
+
+
+
+```python
+param_scheduler = [
+ # 学习率调度器配置
+ dict(...),
+ # 动量调度器配置
+ dict(type='CosineAnnealingMomentum',
+ eta_min=0.1,
+ T_max=num_epochs,
+ begin=0,
+ end=num_epochs,
+ by_epoch=True)
+]
+```
+
+
+
+
+
+
+## 参数更新频率相关配置迁移
+
+如果在使用 epoch-based 训练循环且配置文件中按 epoch 设置生效区间(`begin`,`end`)或周期(`T_max`)等变量的同时希望参数率按 iteration 更新,在 MMCV 中需要将 `by_epoch` 设置为 False。而在 MMEngine 中需要注意,配置中的 `by_epoch` 仍需设置为 True,通过在配置中添加 `convert_to_iter_based=True` 来构建按 iteration 更新的参数调度器,关于此配置详见[参数调度器教程](../tutorials/param_scheduler.md)。
+以迁移CosineAnnealing为例:
+
+
+
+
+ MMCV-1.x
+ MMEngine
+
+
+
+
+```python
+lr_config = dict(
+ policy='CosineAnnealing',
+ min_lr=0.5,
+ by_epoch=False
+)
+```
+
+
+
+
+```python
+param_scheduler = [
+ dict(
+ type='CosineAnnealingLR',
+ eta_min=0.5,
+ T_max=num_epochs,
+ by_epoch=True, # 注意,by_epoch 需要设置为 True
+ convert_to_iter_based=True # 转换为按 iter 更新参数
+ )
+]
+```
+
+
+
+
+
+
+你可能还想阅读[参数调度器的教程](../tutorials/param_scheduler.md)或者[参数调度器的 API 文档](mmengine.optim.scheduler)。
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/migration/runner.md b/testbed/open-mmlab__mmengine/docs/zh_cn/migration/runner.md
new file mode 100644
index 0000000000000000000000000000000000000000..b4056c4ff20b2f3fc5f208eca8d667db0155eaed
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/migration/runner.md
@@ -0,0 +1,1507 @@
+# 迁移 MMCV 执行器到 MMEngine
+
+## 简介
+
+随着支持的深度学习任务越来越多,用户的需求不断增加,我们对 MMCV 已有的执行器(Runner)的灵活性和通用性有了更高的要求。
+因此,MMEngine 在 MMCV 的基础上,实现了一个更加通用灵活的执行器以支持更多复杂的模型训练流程。
+MMEngine 中的执行器扩大了作用域,也承担了更多的功能;我们抽象出了[训练循环控制器(EpochBasedTrainLoop/IterBasedTrainLoop)](mmengine.runner.EpochBasedLoop)、[验证循环控制器(ValLoop)](mmengine.runner.ValLoop)和[测试循环控制器(TestLoop)](mmengine.runner.TestLoop)来方便用户灵活拓展模型的执行流程。
+
+我们将首先介绍算法库的执行入口该如何从 MMCV 迁移到 MMEngine, 以最大程度地简化和统一执行入口的代码。
+然后我们将详细介绍在 MMCV 和 MMEngine 中构造执行器及其内部组件进行训练的差异。
+在开始迁移前,我们建议用户先阅读[执行器教程](../tutorials/runner.md)。
+
+## 执行入口
+
+以 MMDet 为例,我们首先展示基于 MMEngine 重构前后,配置文件和训练启动脚本的区别:
+
+### 配置文件的迁移
+
+
+
+
+ 基于 MMCV 执行器的配置文件概览
+ 基于 MMEngine 执行器的配置文件概览
+
+
+
+
+```python
+# default_runtime.py
+checkpoint_config = dict(interval=1)
+# yapf:disable
+log_config = dict(
+ interval=50,
+ hooks=[
+ dict(type='TextLoggerHook'),
+ # dict(type='TensorboardLoggerHook')
+ ])
+# yapf:enable
+custom_hooks = [dict(type='NumClassCheckHook')]
+
+dist_params = dict(backend='nccl')
+log_level = 'INFO'
+load_from = None
+resume_from = None
+workflow = [('train', 1)]
+
+
+opencv_num_threads = 0
+mp_start_method = 'fork'
+auto_scale_lr = dict(enable=False, base_batch_size=16)
+```
+
+
+
+
+
+```python
+# default_runtime.py
+default_scope = 'mmdet'
+
+default_hooks = dict(
+ timer=dict(type='IterTimerHook'),
+ logger=dict(type='LoggerHook', interval=50),
+ param_scheduler=dict(type='ParamSchedulerHook'),
+ checkpoint=dict(type='CheckpointHook', interval=1),
+ sampler_seed=dict(type='DistSamplerSeedHook'),
+ visualization=dict(type='DetVisualizationHook'))
+
+env_cfg = dict(
+ cudnn_benchmark=False,
+ mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0),
+ dist_cfg=dict(backend='nccl'),
+)
+
+vis_backends = [dict(type='LocalVisBackend')]
+visualizer = dict(
+ type='DetLocalVisualizer', vis_backends=vis_backends, name='visualizer')
+log_processor = dict(type='LogProcessor', window_size=50, by_epoch=True)
+
+log_level = 'INFO'
+load_from = None
+resume = False
+```
+
+
+
+
+
+
+
+```python
+# schedule.py
+
+# optimizer
+optimizer = dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001)
+optimizer_config = dict(grad_clip=None)
+# learning policy
+lr_config = dict(
+ policy='step',
+ warmup='linear',
+ warmup_iters=500,
+ warmup_ratio=0.001,
+ step=[8, 11])
+runner = dict(type='EpochBasedRunner', max_epochs=12)
+```
+
+
+
+
+
+```python
+# scheduler.py
+
+# training schedule for 1x
+train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=12, val_interval=1)
+val_cfg = dict(type='ValLoop')
+test_cfg = dict(type='TestLoop')
+
+# learning rate
+param_scheduler = [
+ dict(
+ type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500),
+ dict(
+ type='MultiStepLR',
+ begin=0,
+ end=12,
+ by_epoch=True,
+ milestones=[8, 11],
+ gamma=0.1)
+]
+
+# optimizer
+optim_wrapper = dict(
+ type='OptimWrapper',
+ optimizer=dict(type='SGD', lr=0.02, momentum=0.9, weight_decay=0.0001))
+
+# Default setting for scaling LR automatically
+# - `enable` means enable scaling LR automatically
+# or not by default.
+# - `base_batch_size` = (8 GPUs) x (2 samples per GPU).
+auto_scale_lr = dict(enable=False, base_batch_size=16)
+```
+
+
+
+
+
+
+
+```python
+# coco_detection.py
+
+# dataset settings
+dataset_type = 'CocoDataset'
+data_root = 'data/coco/'
+img_norm_cfg = dict(
+ mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
+train_pipeline = [
+ dict(type='LoadImageFromFile'),
+ dict(type='LoadAnnotations', with_bbox=True),
+ dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
+ dict(type='RandomFlip', flip_ratio=0.5),
+ dict(type='Normalize', **img_norm_cfg),
+ dict(type='Pad', size_divisor=32),
+ dict(type='DefaultFormatBundle'),
+ dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
+]
+test_pipeline = [
+ dict(type='LoadImageFromFile'),
+ dict(
+ type='MultiScaleFlipAug',
+ img_scale=(1333, 800),
+ flip=False,
+ transforms=[
+ dict(type='Resize', keep_ratio=True),
+ dict(type='RandomFlip'),
+ dict(type='Normalize', **img_norm_cfg),
+ dict(type='Pad', size_divisor=32),
+ dict(type='ImageToTensor', keys=['img']),
+ dict(type='Collect', keys=['img']),
+ ])
+]
+data = dict(
+ samples_per_gpu=2,
+ workers_per_gpu=2,
+ train=dict(
+ type=dataset_type,
+ ann_file=data_root + 'annotations/instances_train2017.json',
+ img_prefix=data_root + 'train2017/',
+ pipeline=train_pipeline),
+ val=dict(
+ type=dataset_type,
+ ann_file=data_root + 'annotations/instances_val2017.json',
+ img_prefix=data_root + 'val2017/',
+ pipeline=test_pipeline),
+ test=dict(
+ type=dataset_type,
+ ann_file=data_root + 'annotations/instances_val2017.json',
+ img_prefix=data_root + 'val2017/',
+ pipeline=test_pipeline))
+evaluation = dict(interval=1, metric='bbox')
+```
+
+
+
+
+
+```python
+# coco_detection.py
+
+# dataset settings
+dataset_type = 'CocoDataset'
+data_root = 'data/coco/'
+
+file_client_args = dict(backend='disk')
+
+train_pipeline = [
+ dict(type='LoadImageFromFile', file_client_args=file_client_args),
+ dict(type='LoadAnnotations', with_bbox=True),
+ dict(type='Resize', scale=(1333, 800), keep_ratio=True),
+ dict(type='RandomFlip', prob=0.5),
+ dict(type='PackDetInputs')
+]
+test_pipeline = [
+ dict(type='LoadImageFromFile', file_client_args=file_client_args),
+ dict(type='Resize', scale=(1333, 800), keep_ratio=True),
+ # If you don't have a gt annotation, delete the pipeline
+ dict(type='LoadAnnotations', with_bbox=True),
+ dict(
+ type='PackDetInputs',
+ meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',
+ 'scale_factor'))
+]
+train_dataloader = dict(
+ batch_size=2,
+ num_workers=2,
+ persistent_workers=True,
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ batch_sampler=dict(type='AspectRatioBatchSampler'),
+ dataset=dict(
+ type=dataset_type,
+ data_root=data_root,
+ ann_file='annotations/instances_train2017.json',
+ data_prefix=dict(img='train2017/'),
+ filter_cfg=dict(filter_empty_gt=True, min_size=32),
+ pipeline=train_pipeline))
+val_dataloader = dict(
+ batch_size=1,
+ num_workers=2,
+ persistent_workers=True,
+ drop_last=False,
+ sampler=dict(type='DefaultSampler', shuffle=False),
+ dataset=dict(
+ type=dataset_type,
+ data_root=data_root,
+ ann_file='annotations/instances_val2017.json',
+ data_prefix=dict(img='val2017/'),
+ test_mode=True,
+ pipeline=test_pipeline))
+test_dataloader = val_dataloader
+
+val_evaluator = dict(
+ type='CocoMetric',
+ ann_file=data_root + 'annotations/instances_val2017.json',
+ metric='bbox',
+ format_only=False)
+test_evaluator = val_evaluator
+```
+
+
+
+
+
+
+
+
+MMEngine 中的执行器提供了更多可自定义的部分,包括训练、验证、测试过程和数据加载器的配置,因此配置文件和之前相比会长一些。
+为了方便用户的理解和阅读,我们遵循所见即所得的原则,重新调整了各个组件配置的层次,使得大部分一级字段都对应着执行器中关键属性的配置,例如数据加载器、评测器、钩子配置等。
+这些配置在 OpenMMLab 2.0 算法库中都有默认配置,因此用户很多时候无需关心其中的大部分参数。
+
+### 启动脚本的迁移
+
+相比于 MMCV 的执行器,MMEngine 的执行器可以承担更多的功能,例如构建 `DataLoader`,构建分布式模型等。因此我们需要在配置文件中指定更多的参数,例如 `DataLoader` 的 `sampler` 和 `batch_sampler`,而无需在训练的启动脚本里实现构建 `DataLoader` 相关的代码。以 MMDet 的训练启动脚本为例:
+
+
+
+
+ 基于 MMCV 执行器的训练启动脚本
+ 基于 MMEngine 执行器的训练启动脚本
+
+
+
+
+```python
+# tools/train.py
+
+args = parse_args()
+
+cfg = Config.fromfile(args.config)
+
+# replace the ${key} with the value of cfg.key
+cfg = replace_cfg_vals(cfg)
+
+# update data root according to MMDET_DATASETS
+update_data_root(cfg)
+
+if args.cfg_options is not None:
+ cfg.merge_from_dict(args.cfg_options)
+
+if args.auto_scale_lr:
+ if 'auto_scale_lr' in cfg and \
+ 'enable' in cfg.auto_scale_lr and \
+ 'base_batch_size' in cfg.auto_scale_lr:
+ cfg.auto_scale_lr.enable = True
+ else:
+ warnings.warn('Can not find "auto_scale_lr" or '
+ '"auto_scale_lr.enable" or '
+ '"auto_scale_lr.base_batch_size" in your'
+ ' configuration file. Please update all the '
+ 'configuration files to mmdet >= 2.24.1.')
+
+# set multi-process settings
+setup_multi_processes(cfg)
+
+# set cudnn_benchmark
+if cfg.get('cudnn_benchmark', False):
+ torch.backends.cudnn.benchmark = True
+
+# work_dir is determined in this priority: CLI > segment in file > filename
+if args.work_dir is not None:
+ # update configs according to CLI args if args.work_dir is not None
+ cfg.work_dir = args.work_dir
+elif cfg.get('work_dir', None) is None:
+ # use config filename as default work_dir if cfg.work_dir is None
+ cfg.work_dir = osp.join('./work_dirs',
+ osp.splitext(osp.basename(args.config))[0])
+
+if args.resume_from is not None:
+ cfg.resume_from = args.resume_from
+cfg.auto_resume = args.auto_resume
+if args.gpus is not None:
+ cfg.gpu_ids = range(1)
+ warnings.warn('`--gpus` is deprecated because we only support '
+ 'single GPU mode in non-distributed training. '
+ 'Use `gpus=1` now.')
+if args.gpu_ids is not None:
+ cfg.gpu_ids = args.gpu_ids[0:1]
+ warnings.warn('`--gpu-ids` is deprecated, please use `--gpu-id`. '
+ 'Because we only support single GPU mode in '
+ 'non-distributed training. Use the first GPU '
+ 'in `gpu_ids` now.')
+if args.gpus is None and args.gpu_ids is None:
+ cfg.gpu_ids = [args.gpu_id]
+
+# init distributed env first, since logger depends on the dist info.
+if args.launcher == 'none':
+ distributed = False
+else:
+ distributed = True
+ init_dist(args.launcher, **cfg.dist_params)
+ # re-set gpu_ids with distributed training mode
+ _, world_size = get_dist_info()
+ cfg.gpu_ids = range(world_size)
+
+# create work_dir
+mmcv.mkdir_or_exist(osp.abspath(cfg.work_dir))
+# dump config
+cfg.dump(osp.join(cfg.work_dir, osp.basename(args.config)))
+# init the logger before other steps
+timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime())
+log_file = osp.join(cfg.work_dir, f'{timestamp}.log')
+logger = get_root_logger(log_file=log_file, log_level=cfg.log_level)
+
+# init the meta dict to record some important information such as
+# environment info and seed, which will be logged
+meta = dict()
+# log env info
+env_info_dict = collect_env()
+env_info = '\n'.join([(f'{k}: {v}') for k, v in env_info_dict.items()])
+dash_line = '-' * 60 + '\n'
+logger.info('Environment info:\n' + dash_line + env_info + '\n' +
+ dash_line)
+meta['env_info'] = env_info
+meta['config'] = cfg.pretty_text
+# log some basic info
+logger.info(f'Distributed training: {distributed}')
+logger.info(f'Config:\n{cfg.pretty_text}')
+
+cfg.device = get_device()
+# set random seeds
+seed = init_random_seed(args.seed, device=cfg.device)
+seed = seed + dist.get_rank() if args.diff_seed else seed
+logger.info(f'Set random seed to {seed}, '
+ f'deterministic: {args.deterministic}')
+set_random_seed(seed, deterministic=args.deterministic)
+cfg.seed = seed
+meta['seed'] = seed
+meta['exp_name'] = osp.basename(args.config)
+
+model = build_detector(
+ cfg.model,
+ train_cfg=cfg.get('train_cfg'),
+ test_cfg=cfg.get('test_cfg'))
+model.init_weights()
+
+datasets = []
+train_detector(
+ model,
+ datasets,
+ cfg,
+ distributed=distributed,
+ validate=(not args.no_validate),
+ timestamp=timestamp,
+ meta=meta)
+```
+
+
+
+
+
+```python
+# tools/train.py
+
+args = parse_args()
+
+# register all modules in mmdet into the registries
+# do not init the default scope here because it will be init in the runner
+register_all_modules(init_default_scope=False)
+
+# load config
+cfg = Config.fromfile(args.config)
+cfg.launcher = args.launcher
+if args.cfg_options is not None:
+ cfg.merge_from_dict(args.cfg_options)
+
+# work_dir is determined in this priority: CLI > segment in file > filename
+if args.work_dir is not None:
+ # update configs according to CLI args if args.work_dir is not None
+ cfg.work_dir = args.work_dir
+elif cfg.get('work_dir', None) is None:
+ # use config filename as default work_dir if cfg.work_dir is None
+ cfg.work_dir = osp.join('./work_dirs',
+ osp.splitext(osp.basename(args.config))[0])
+
+# enable automatic-mixed-precision training
+if args.amp is True:
+ optim_wrapper = cfg.optim_wrapper.type
+ if optim_wrapper == 'AmpOptimWrapper':
+ print_log(
+ 'AMP training is already enabled in your config.',
+ logger='current',
+ level=logging.WARNING)
+ else:
+ assert optim_wrapper == 'OptimWrapper', (
+ '`--amp` is only supported when the optimizer wrapper type is '
+ f'`OptimWrapper` but got {optim_wrapper}.')
+ cfg.optim_wrapper.type = 'AmpOptimWrapper'
+ cfg.optim_wrapper.loss_scale = 'dynamic'
+
+# enable automatically scaling LR
+if args.auto_scale_lr:
+ if 'auto_scale_lr' in cfg and \
+ 'enable' in cfg.auto_scale_lr and \
+ 'base_batch_size' in cfg.auto_scale_lr:
+ cfg.auto_scale_lr.enable = True
+ else:
+ raise RuntimeError('Can not find "auto_scale_lr" or '
+ '"auto_scale_lr.enable" or '
+ '"auto_scale_lr.base_batch_size" in your'
+ ' configuration file.')
+
+cfg.resume = args.resume
+
+# build the runner from config
+if 'runner_type' not in cfg:
+ # build the default runner
+ runner = Runner.from_cfg(cfg)
+else:
+ # build customized runner from the registry
+ # if 'runner_type' is set in the cfg
+ runner = RUNNERS.build(cfg)
+
+# start training
+runner.train()
+```
+
+
+
+
+
+
+
+```python
+def init_random_seed(...):
+ ...
+
+def set_random_seed(...):
+ ...
+
+# define function tools.
+...
+
+
+def train_detector(model,
+ dataset,
+ cfg,
+ distributed=False,
+ validate=False,
+ timestamp=None,
+ meta=None):
+
+ cfg = compat_cfg(cfg)
+ logger = get_root_logger(log_level=cfg.log_level)
+
+ # put model on gpus
+ if distributed:
+ find_unused_parameters = cfg.get('find_unused_parameters', False)
+ # Sets the `find_unused_parameters` parameter in
+ # torch.nn.parallel.DistributedDataParallel
+ model = build_ddp(
+ model,
+ cfg.device,
+ device_ids=[int(os.environ['LOCAL_RANK'])],
+ broadcast_buffers=False,
+ find_unused_parameters=find_unused_parameters)
+ else:
+ model = build_dp(model, cfg.device, device_ids=cfg.gpu_ids)
+
+ # build optimizer
+ auto_scale_lr(cfg, distributed, logger)
+ optimizer = build_optimizer(model, cfg.optimizer)
+
+ runner = build_runner(
+ cfg.runner,
+ default_args=dict(
+ model=model,
+ optimizer=optimizer,
+ work_dir=cfg.work_dir,
+ logger=logger,
+ meta=meta))
+
+ # an ugly workaround to make .log and .log.json filenames the same
+ runner.timestamp = timestamp
+
+ # fp16 setting
+ fp16_cfg = cfg.get('fp16', None)
+ if fp16_cfg is not None:
+ optimizer_config = Fp16OptimizerHook(
+ **cfg.optimizer_config, **fp16_cfg, distributed=distributed)
+ elif distributed and 'type' not in cfg.optimizer_config:
+ optimizer_config = OptimizerHook(**cfg.optimizer_config)
+ else:
+ optimizer_config = cfg.optimizer_config
+
+ # register hooks
+ runner.register_training_hooks(
+ cfg.lr_config,
+ optimizer_config,
+ cfg.checkpoint_config,
+ cfg.log_config,
+ cfg.get('momentum_config', None),
+ custom_hooks_config=cfg.get('custom_hooks', None))
+
+ if distributed:
+ if isinstance(runner, EpochBasedRunner):
+ runner.register_hook(DistSamplerSeedHook())
+
+ # register eval hooks
+ if validate:
+ val_dataloader_default_args = dict(
+ samples_per_gpu=1,
+ workers_per_gpu=2,
+ dist=distributed,
+ shuffle=False,
+ persistent_workers=False)
+
+ val_dataloader_args = {
+ **val_dataloader_default_args,
+ **cfg.data.get('val_dataloader', {})
+ }
+ # Support batch_size > 1 in validation
+
+ if val_dataloader_args['samples_per_gpu'] > 1:
+ # Replace 'ImageToTensor' to 'DefaultFormatBundle'
+ cfg.data.val.pipeline = replace_ImageToTensor(
+ cfg.data.val.pipeline)
+ val_dataset = build_dataset(cfg.data.val, dict(test_mode=True))
+
+ val_dataloader = build_dataloader(val_dataset, **val_dataloader_args)
+ eval_cfg = cfg.get('evaluation', {})
+ eval_cfg['by_epoch'] = cfg.runner['type'] != 'IterBasedRunner'
+ eval_hook = DistEvalHook if distributed else EvalHook
+ # In this PR (https://github.com/open-mmlab/mmcv/pull/1193), the
+ # priority of IterTimerHook has been modified from 'NORMAL' to 'LOW'.
+ runner.register_hook(
+ eval_hook(val_dataloader, **eval_cfg), priority='LOW')
+
+ resume_from = None
+ if cfg.resume_from is None and cfg.get('auto_resume'):
+ resume_from = find_latest_checkpoint(cfg.work_dir)
+ if resume_from is not None:
+ cfg.resume_from = resume_from
+
+ if cfg.resume_from:
+ runner.resume(cfg.resume_from)
+ elif cfg.load_from:
+ runner.load_checkpoint(cfg.load_from)
+ runner.run(data_loaders, cfg.workflow)
+```
+
+
+
+
+
+```python
+# `apis/train.py` is removed in `mmengine`
+```
+
+
+
+
+
+
+上表对比了基于 MMCV 执行器和 MMEngine 执行器 MMDet 启动脚本的区别。
+OpenMMLab 1.x 中的算法库都实现了一套 runner 的构建和训练流程,其中存在着大量的冗余代码。因此,MMEngine 的执行器在内部实现了很多流程化的代码以统一各个算法库的执行流程,例如初始化随机种子、初始化分布式环境、构建 `DataLoader` 等,使得下游算法库从此无需在训练启动脚本里实现相关代码,只需配置执行器的构造参数,就能够执行相应的流程。
+基于 MMEngine 执行器的启动脚本不仅简化了 `tools/train.py` 的代码,甚至可以直接删除 `apis/train.py`,极大程度的简化了训练启动脚本。同样的,我们在基于 MMEngine 开发自己的代码仓库时,可以通过配置执行器参数来设置随机种子、初始化分布式环境,无需自行实现相关代码。
+
+## 迁移执行器(Runner)
+
+本节主要介绍 MMCV 执行器和 MMEngine 执行器在训练、验证、测试流程上的区别。
+在使用 MMCV 执行器和 MMEngine 执行器训练、测试模型时,以下流程有着明显的不同:
+
+01. [准备logger](#准备logger)
+02. [设置随机种子](#设置随机种子)
+03. [初始化环境变量](#初始化训练环境)
+04. [准备数据](#准备数据)
+05. [准备模型](#准备模型)
+06. [准备优化器](#准备优化器)
+07. [准备钩子](#准备训练钩子)
+08. [准备验证/测试模块](#准备验证模块)
+09. [构建执行器](#构建执行器)
+10. [执行器加载检查点](#执行器加载检查点)
+11. [开始训练](#执行器训练流程)、[开始测试](#执行器测试流程)
+12. [迁移自定义训练流程](#迁移自定义执行流程)
+
+后续的教程中,我们会对每个流程的差异进行详细介绍。
+
+### 准备logger
+
+**MMCV 准备 logger**
+
+MMCV 需要在训练脚本里调用 `get_logger` 接口获得 logger,并用它输出、记录训练环境。
+
+```python
+logger = get_logger(name='custom', log_file=log_file, log_level=cfg.log_level)
+env_info_dict = collect_env()
+env_info = '\n'.join([(f'{k}: {v}') for k, v in env_info_dict.items()])
+dash_line = '-' * 60 + '\n'
+logger.info('Environment info:\n' + dash_line + env_info + '\n' +
+ dash_line)
+```
+
+执行器构造时,也需要传入 logger。
+
+```python
+runner = Runner(
+ ...
+ logger=logger
+ ...)
+```
+
+**MMEngine 准备 logger**
+
+在执行器构建时传入 logger 的日志等级,执行器构建时会自动创建 logger,并输出、记录训练环境。
+
+```python
+log_level = 'INFO'
+```
+
+### 设置随机种子
+
+**MMCV 设置随机种子**
+
+在训练脚本中手动设置随机种子:
+
+```python
+...
+seed = init_random_seed(args.seed, device=cfg.device)
+seed = seed + dist.get_rank() if args.diff_seed else seed
+logger.info(f'Set random seed to {seed}, '
+ f'deterministic: {args.deterministic}')
+set_random_seed(seed, deterministic=args.deterministic)
+...
+```
+
+**MMEngine 设计随机种子**
+
+配置执行器的 `randomness` 参数,配置规则详见[执行器 api 文档](mmengine.runner.Runner.set_randomnes1s)
+
+**OpenMMLab 系列算法库配置变更**
+
+
+
+
+ MMCV 配置
+ MMEngine 配置
+
+
+
+
+```python
+seed = 1
+deterministic=False
+diff_seed=False
+```
+
+
+
+
+
+```python
+randomness=dict(seed=1,
+ deterministic=True,
+ diff_rank_seed=False)
+```
+
+
+
+
+
+
+
+在本教程中,我们将 `randomness` 配置为:
+
+```python
+randomness = dict(seed=5)
+```
+
+### 初始化训练环境
+
+**MMCV 初始化训练环境**
+
+MMCV 需要在训练脚本中配置多进程启动方式、多进程通信后端等环境变量,并在执行器构建之前初始化分布式环境,对模型进行分布式封装:
+
+```python
+...
+setup_multi_processes(cfg)
+init_dist(cfg.launcher, **cfg.dist_params)
+model = MMDistributedDataParallel(
+ model,
+ device_ids=[int(os.environ['LOCAL_RANK'])],
+ broadcast_buffers=False,
+ find_unused_parameters=find_unused_parameters)
+```
+
+**MMEngine 初始化训练环境**
+
+MMEngine 通过配置 `env_cfg` 来选择多进程启动方式和多进程通信后端, 其默认值为 `dict(dist_cfg=dict(backend='nccl'))`,配置方式详见[执行器 api 文档](mmengine.runner.Runner.setup_env)。
+
+执行器构建时接受 `launcher` 参数,如果其值不为 `'none'`,执行器构建时会自动执行分布式初始化,模型分布式封装。换句话说,使用 `MMEngine` 的执行器时,我们无需在执行器外做分布式相关的操作,只需配置 `launcher` 参数,选择训练的启动方式即可。
+
+**OpenMMLab 系列算法库配置变更**
+
+
+
+
+ MMCV 配置
+ MMEngine 配置
+
+
+
+
+```python
+launcher = 'pytorch' # 开启分布式训练
+dist_params = dict(backend='nccl') # 选择多进程通信后端
+```
+
+
+
+
+
+```python
+launcher = 'pytorch'
+env_cfg = dict(dist_cfg=dict(backend='nccl'))
+```
+
+
+
+
+
+
+
+在本教程中,我们将 `env_cfg` 配置为:
+
+```python
+env_cfg = dict(dist_cfg=dict(backend='nccl'))
+```
+
+### 准备数据
+
+MMCV 和 MMEngine 的执行器均可接受构建好的 `DataLoader` 实例。因此准备数据的流程没有差异:
+
+```python
+import torchvision.transforms as transforms
+from torch.utils.data import DataLoader
+from torchvision.datasets import CIFAR10
+
+transform = transforms.Compose([
+ transforms.ToTensor(),
+ transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
+])
+
+train_dataset = CIFAR10(
+ root='data', train=True, download=True, transform=transform)
+train_dataloader = DataLoader(
+ train_dataset, batch_size=128, shuffle=True, num_workers=2)
+
+val_dataset = CIFAR10(
+ root='data', train=False, download=True, transform=transform)
+val_dataloader = DataLoader(
+ val_dataset, batch_size=128, shuffle=False, num_workers=2)
+```
+
+**OpenMMLab 系列算法库配置变更**
+
+
+
+
+ MMCV 配置
+ MMEngine 配置
+
+
+
+
+```python
+data = dict(
+ samples_per_gpu=2, # 单卡 batch_size
+ workers_per_gpu=2, # Dataloader 采样进程数
+ train=dict(
+ type=dataset_type,
+ ann_file=data_root + 'annotations/instances_train2017.json',
+ img_prefix=data_root + 'train2017/',
+ pipeline=train_pipeline),
+ val=dict(
+ type=dataset_type,
+ ann_file=data_root + 'annotations/instances_val2017.json',
+ img_prefix=data_root + 'val2017/',
+ pipeline=test_pipeline),
+ test=dict(
+ type=dataset_type,
+ ann_file=data_root + 'annotations/instances_val2017.json',
+ img_prefix=data_root + 'val2017/',
+ pipeline=test_pipeline))
+```
+
+
+
+
+
+```python
+train_dataloader = dict(
+ batch_size=2, # samples_per_gpu -> batch_size,
+ num_workers=2,
+ # 遍历完 DataLoader 后,是否重启多进程采样
+ persistent_workers=True,
+ # 可配置的 sampler
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ # 可配置的 batch_sampler
+ batch_sampler=dict(type='AspectRatioBatchSampler'),
+ dataset=dict(
+ type=dataset_type,
+ data_root=data_root,
+ ann_file='annotations/instances_train2017.json',
+ data_prefix=dict(img='train2017/'),
+ filter_cfg=dict(filter_empty_gt=True, min_size=32),
+ pipeline=train_pipeline))
+
+val_dataloader = dict(
+ batch_size=1, # 验证阶段的 batch_size
+ num_workers=2,
+ persistent_workers=True,
+ drop_last=False, # 是否丢弃最后一个 batch
+ sampler=dict(type='DefaultSampler', shuffle=False),
+ dataset=dict(
+ type=dataset_type,
+ data_root=data_root,
+ ann_file='annotations/instances_val2017.json',
+ data_prefix=dict(img='val2017/'),
+ test_mode=True,
+ pipeline=test_pipeline))
+
+test_dataloader = val_dataloader
+```
+
+
+
+
+
+
+
+相比于 MMCV 的算法库配置,MMEngine 的配置更加复杂,但是也更加灵活。`DataLoader` 的配置过程由 `Runner` 负责,无需各个算法库实现。
+
+### 准备模型
+
+详见[迁移 MMCV 模型至 MMEngine](./migrate_model_from_mmcv.md)
+
+```python
+import torch.nn as nn
+import torch.nn.functional as F
+from mmengine.model import BaseModel
+
+
+class Model(BaseModel):
+
+ def __init__(self):
+ super().__init__()
+ self.conv1 = nn.Conv2d(3, 6, 5)
+ self.pool = nn.MaxPool2d(2, 2)
+ self.conv2 = nn.Conv2d(6, 16, 5)
+ self.fc1 = nn.Linear(16 * 5 * 5, 120)
+ self.fc2 = nn.Linear(120, 84)
+ self.fc3 = nn.Linear(84, 10)
+ self.loss_fn = nn.CrossEntropyLoss()
+
+ def forward(self, img, label, mode):
+ feat = self.pool(F.relu(self.conv1(img)))
+ feat = self.pool(F.relu(self.conv2(feat)))
+ feat = feat.view(-1, 16 * 5 * 5)
+ feat = F.relu(self.fc1(feat))
+ feat = F.relu(self.fc2(feat))
+ feat = self.fc3(feat)
+ if mode == 'loss':
+ loss = self.loss_fn(feat, label)
+ return dict(loss=loss)
+ else:
+ return [feat.argmax(1)]
+
+model = Model()
+```
+
+需要注意的是,分布式训练时,MMCV 的执行器需要接受分布式封装后的模型,而 `MMEngine` 接受分布式封装前的模型,在执行器实例化阶段对其段进行分布式封装。
+
+### 准备优化器
+
+**MMCV 准备优化器**
+
+MMCV 执行器构造时,可以直接接受 Pytorch 优化器,如
+
+```python
+optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9)
+```
+
+对于复杂配置的优化器,MMCV 需要基于优化器构造器来构建优化器:
+
+```python
+
+optimizer_cfg = dict(
+ optimizer=dict(type='SGD', lr=0.01, weight_decay=0.0001),
+ paramwise_cfg=dict(norm_decay_mult=0))
+
+def build_optimizer_constructor(cfg):
+ constructor_type = cfg.get('type')
+ if constructor_type in OPTIMIZER_BUILDERS:
+ return build_from_cfg(cfg, OPTIMIZER_BUILDERS)
+ elif constructor_type in MMCV_OPTIMIZER_BUILDERS:
+ return build_from_cfg(cfg, MMCV_OPTIMIZER_BUILDERS)
+ else:
+ raise KeyError(f'{constructor_type} is not registered '
+ 'in the optimizer builder registry.')
+
+
+def build_optimizer(model, cfg):
+ optimizer_cfg = copy.deepcopy(cfg)
+ constructor_type = optimizer_cfg.pop('constructor',
+ 'DefaultOptimizerConstructor')
+ paramwise_cfg = optimizer_cfg.pop('paramwise_cfg', None)
+ optim_constructor = build_optimizer_constructor(
+ dict(
+ type=constructor_type,
+ optimizer_cfg=optimizer_cfg,
+ paramwise_cfg=paramwise_cfg))
+ optimizer = optim_constructor(model)
+ return optimizer
+
+optimizer = build_optimizer(model, optimizer_cfg)
+```
+
+**MMEngine 准备优化器**
+
+构建 MMEngine 执行器时,需要接受 `optim_wrapper` 参数,即[优化器封装](mmengine.optim.OptimWrapper)实例或者优化器封装配置,对于复杂配置的优化器封装,`MMEngine` 同样只需要配置 `optim_wrapper`。`optim_wrapper` 的详细介绍见[执行器 api 文档](mmengine.runner.Runner.build_optim_wrapper)。
+
+**OpenMMLab 系列算法库配置变更**
+
+
+
+
+ MMCV 配置
+ MMEngine 配置
+
+
+
+
+```python
+optimizer = dict(
+ constructor='CustomConstructor',
+ type='AdamW', # 优化器配置为一级字段
+ lr=0.0001, # 优化器配置为一级字段
+ betas=(0.9, 0.999), # 优化器配置为一级字段
+ weight_decay=0.05, # 优化器配置为一级字段
+ paramwise_cfg={ # constructor 的参数
+ 'decay_rate': 0.95,
+ 'decay_type': 'layer_wise',
+ 'num_layers': 6
+ })
+# MMCV 还需要配置 `optim_config`
+# 来构建优化器钩子,而 MMEngine 不需要
+optimizer_config = dict(grad_clip=None)
+```
+
+
+
+
+
+```python
+optim_wrapper = dict(
+ constructor='CustomConstructor',
+ type='OptimWrapper', # 指定优化器封装类型
+ optimizer=dict( # 将优化器配置集中在 optimizer 内
+ type='AdamW',
+ lr=0.0001,
+ betas=(0.9, 0.999),
+ weight_decay=0.05)
+ paramwise_cfg={
+ 'decay_rate': 0.95,
+ 'decay_type': 'layer_wise',
+ 'num_layers': 6
+ })
+```
+
+
+
+
+
+
+
+```{note}:
+对于检测、分类一类的上层任务(High level)MMCV 需要配置 `optim_config` 来构建优化器钩子,而 MMEngine 不需要。
+```
+
+本教程使用的 `optim_wrapper` 如下:
+
+```python
+from torch.optim import SGD
+
+optimizer = SGD(model.parameters(), lr=0.1, momentum=0.9)
+optim_wrapper = dict(optimizer=optimizer)
+```
+
+### 准备训练钩子
+
+**MMCV 准备训练钩子:**
+
+MMCV 常用训练钩子的配置如下:
+
+```python
+# learning rate scheduler config
+lr_config = dict(policy='step', step=[2, 3])
+# configuration of optimizer
+optimizer_config = dict(grad_clip=None)
+# configuration of saving checkpoints periodically
+checkpoint_config = dict(interval=1)
+# save log periodically and multiple hooks can be used simultaneously
+log_config = dict(interval=100, hooks=[dict(type='TextLoggerHook')])
+# register hooks to runner and those hooks will be invoked automatically
+runner.register_training_hooks(
+ lr_config=lr_config,
+ optimizer_config=optimizer_config,
+ checkpoint_config=checkpoint_config,
+ log_config=log_config)
+```
+
+其中:
+
+- `lr_config` 用于配置 `LrUpdaterHook`
+- `optimizer_config` 用于配置 `OptimizerHook`
+- `checkpoint_config` 用于配置 `CheckPointHook`
+- `log_config` 用于配置 `LoggerHook`
+
+除了上面提到的 4 个 Hook,MMCV 执行器自带 `IterTimerHook`。MMCV 需要先实例化执行器,再注册训练钩子,而 `MMEngine` 则在实例化阶段配置钩子。
+
+**MMEngine 准备训练钩子**
+
+MMEngine 执行器将 MMCV 常用的训练钩子配置成默认钩子:
+
+- [RuntimeInfoHook](mmengine.hooks.RuntimeInfoHook)
+- [IterTimerHook](mmengine.hooks.IterTimerHook)
+- [DistSamplerSeedHook](mmengine.hooks.DistSamplerSeedHook)
+- [LoggerHook](mmedge.hooks.LoggerHook)
+- [CheckpointHook](mmengine.hooks.CheckpointHook)
+- [ParamSchedulerHook](mmengine.hooks.ParamSchedulerHook)
+
+对比上例中 MMCV 配置的训练钩子:
+
+- `LrUpdaterHook` 对应 MMEngine 中的 `ParamSchedulerHook`,二者对应关系详见[迁移 `scheduler` 文档](./param_scheduler.md)
+- MMEngine 在模型的 [train_step](mmengine.BaseModel.train_step) 时更新参数,因此不需要配置优化器钩子(`OptimizerHook`)
+- MMEngine 自带 `CheckPointHook`,可以使用默认配置
+- MMEngine 自带 `LoggerHook`,可以使用默认配置
+
+因此我们只需要配置执行器[优化器参数调整策略(param_scheduler)](../tutorials/param_scheduler.md),就能达到和 MMCV 示例一样的效果。
+MMEngine 也支持注册自定义钩子,具体教程详见[执行器教程](../tutorials/runner.md#通过配置文件使用执行器) 和[迁移 `hook` 文档](./migrate_hook_from_mmcv.md)。
+
+
+
+
+ MMCV 常用训练钩子
+ MMEngine 默认钩子
+
+
+
+
+```python
+# MMCV 零散的配置训练钩子
+# 配置 LrUpdaterHook,相当于 MMEngine 的参数调度器
+lr_config = dict(
+ policy='step',
+ warmup='linear',
+ warmup_iters=500,
+ warmup_ratio=0.001,
+ step=[8, 11])
+
+# 配置 OptimizerHook,MMEngine 不需要
+optimizer_config = dict(grad_clip=None)
+
+# 配置 LoggerHook
+log_config = dict( # LoggerHook
+ interval=50,
+ hooks=[
+ dict(type='TextLoggerHook'),
+ # dict(type='TensorboardLoggerHook')
+ ])
+
+# 配置 CheckPointHook
+checkpoint_config = dict(interval=1) # CheckPointHook
+```
+
+
+
+
+
+```python
+# 配置参数调度器
+param_scheduler = [
+ dict(
+ type='LinearLR', start_factor=0.001, by_epoch=False, begin=0, end=500),
+ dict(
+ type='MultiStepLR',
+ begin=0,
+ end=12,
+ by_epoch=True,
+ milestones=[8, 11],
+ gamma=0.1)
+]
+
+# MMEngine 集中配置默认钩子
+default_hooks = dict(
+ timer=dict(type='IterTimerHook'),
+ logger=dict(type='LoggerHook', interval=50),
+ param_scheduler=dict(type='ParamSchedulerHook'),
+ checkpoint=dict(type='CheckpointHook', interval=1),
+ sampler_seed=dict(type='DistSamplerSeedHook'),
+ visualization=dict(type='DetVisualizationHook'))
+```
+
+
+
+
+
+
+
+```{note}
+MMEngine 移除了 `OptimizerHook`,优化步骤在 model 中执行。
+```
+
+本教程使用的 param_scheduler 如下:
+
+```python
+from math import gamma
+
+param_scheduler = dict(type='MultiStepLR', milestones=[2, 3], gamma=0.1)
+```
+
+### 准备验证模块
+
+MMCV 借助 `EvalHook` 实现验证流程,受限于篇幅,这里不做进一步展开。MMEngine 通过[验证循环控制器(ValLoop)](../tutorials/runner.md#自定义执行流程) 和[评测器(Evaluator)](../tutorials/evaluation.md)实现执行流程,如果我们想基于自定义的评价指标完成验证流程,则需要定义一个 `Metric`,并将其注册至 `METRICS` 注册器:
+
+```python
+import torch
+from mmengine.evaluator import BaseMetric
+from mmengine.registry import METRICS
+
+@METRICS.register_module(force=True)
+class ToyAccuracyMetric(BaseMetric):
+
+ def process(self, label, pred) -> None:
+ self.results.append((label[1], pred, len(label[1])))
+
+ def compute_metrics(self, results: list) -> dict:
+ num_sample = 0
+ acc = 0
+ for label, pred, batch_size in results:
+ acc += (label == torch.stack(pred)).sum()
+ num_sample += batch_size
+ return dict(Accuracy=acc / num_sample)
+```
+
+实现自定义 `Metric` 后,我们还需在执行器的构造参数中配置评测器和[验证循环控制器](../tutorials/runner.md#自定义执行流程),本教程中示例配置如下:
+
+```python
+val_evaluator = dict(type='ToyAccuracyMetric')
+val_cfg = dict(type='ValLoop')
+```
+
+
+
+
+ MMCV 配置验证流程
+ MMEngine 配置验证流程
+
+
+
+
+```python
+eval_cfg = cfg.get('evaluation', {})
+eval_cfg['by_epoch'] = cfg.runner['type'] != 'IterBasedRunner'
+eval_hook = DistEvalHook if distributed else EvalHook # 配置 EvalHook
+runner.register_hook(
+ eval_hook(val_dataloader, **eval_cfg), priority='LOW') # 注册 EvalHook
+```
+
+
+
+
+
+```python
+val_dataloader = val_dataloader # 配置验证数据
+val_evaluator = dict(type='ToyAccuracyMetric') # 配置评测器
+val_cfg = dict(type='ValLoop') # 配置验证循环控制器
+```
+
+
+
+
+
+
+
+### 构建执行器
+
+**MMCV 构建执行器**
+
+```python
+runner = EpochBasedRunner(
+ model=model,
+ optimizer=optimizer,
+ work_dir=work_dir,
+ logger=logger,
+ max_epochs=4
+)
+```
+
+**MMEngine 构建执行器**
+
+`MMEngine` 执行器的作用域比 MMCV 更广,将设置随机种子、启动分布式训练等流程参数化。除了前几节提到的参数,上例中出现的`EpochBasedRunner`,`max_epochs`,`val_iterval` 现在由 `train_cfg` 配置:
+
+- `by_epoch`: `True` 时相当于 MMCV 的 ``` EpochBasedRunner``,False ``` 时相当于 `IterBasedRunner`。
+- `max_epoch`/`max_iters`: 同 MMCV 执行器的配置
+- `val_iterval`: 同 `EvalHook` 的 `interval` 参数
+
+`train_cfg` 实际上是训练循环控制器的构造参数,当 `by_epoch=True` 时,使用 `EpochBasedTrainLoop`。
+
+```python
+from mmengine.runner import Runner
+
+runner = Runner(
+ model=model, # 待优化的模型
+ work_dir='./work_dir', # 配置工作目录
+ randomness=randomness, # 配置随机种子
+ env_cfg=env_cfg, # 配置环境变量
+ launcher='none', # 分布式训练启动方式
+ optim_wrapper=optim_wrapper, # 配置优化器
+ param_scheduler=param_scheduler, # 配置学习率调度器
+ train_dataloader=train_dataloader, # 配置训练数据
+ train_cfg=dict(by_epoch=True, max_epochs=4, val_interval=1), # 配置训练循环控制器
+ val_dataloader=val_dataloader, # 配置验证数据
+ val_evaluator=val_evaluator, # 配置评测器
+ val_cfg=val_cfg) # 配置验证循环控制器
+```
+
+### 执行器加载检查点
+
+**MMCV 加载检查点**:
+
+在训练之前执行加载权重、恢复训练的流程。
+
+```python
+if cfg.resume_from:
+ runner.resume(cfg.resume_from)
+elif cfg.load_from:
+ runner.load_checkpoint(cfg.load_from)
+```
+
+**MMEngine 加载检查点**
+
+```python
+runner = Runner(
+ ...
+ load_from='/path/to/checkpoint',
+ resume=True
+)
+```
+
+
+
+
+ MMCV 加载检查点配置
+ MMEngine 加载检查点配置
+
+
+
+
+```python
+load_from = 'path/to/ckpt'
+```
+
+
+
+
+
+```python
+load_from = 'path/to/ckpt'
+resume = False
+```
+
+
+
+
+
+
+
+```python
+resume_from = 'path/to/ckpt'
+```
+
+
+
+
+
+```python
+load_from = 'path/to/ckpt'
+resume = True
+```
+
+
+
+
+
+
+
+### 执行器训练流程
+
+**MMCV 执行器训练流程**:
+
+在训练之前执行加载权重、恢复训练的流程。然后再执行 `runner.run`,并传入训练数据。
+
+```python
+if cfg.resume_from:
+ runner.resume(cfg.resume_from)
+elif cfg.load_from:
+ runner.load_checkpoint(cfg.load_from)
+runner.run(data_loaders, cfg.workflow)
+```
+
+**MMEngine** 执行器训练流程
+
+在执行器构建时配置加载权重、恢复训练参数
+
+由于 MMEngine 的执行器在构造阶段就传入了训练数据,因此在调用 runner.train() 无需传入参数。
+
+```python
+runner.train()
+```
+
+### 执行器测试流程
+
+MMCV 的执行器没有测试功能,因此需要自行实现测试脚本。MMEngine 的执行器只需要在构建时配置 `test_dataloader`、`test_cfg` 和 `test_evaluator`,然后再调用 `runner.test()` 就能完成测试流程。
+
+**`work_dir` 和训练时一致,无需手动加载 checkpoint:**
+
+```python
+runner = Runner(
+ model=model,
+ work_dir='./work_dir',
+ randomness=randomness,
+ env_cfg=env_cfg,
+ launcher='none', # 不开启分布式训练
+ optim_wrapper=optim_wrapper,
+ train_dataloader=train_dataloader,
+ train_cfg=dict(by_epoch=True, max_epochs=5, val_interval=1),
+ val_dataloader=val_dataloader,
+ val_evaluator=val_evaluator,
+ val_cfg=val_cfg,
+ test_dataloader=val_dataloader, # 假设测试和验证使用相同的数据和评测器
+ test_evaluator=val_evaluator,
+ test_cfg=dict(type='TestLoop'),
+)
+runner.test()
+```
+
+**`work_dir` 和训练时不一致,需要额外指定 load_from:**
+
+```python
+runner = Runner(
+ model=model,
+ work_dir='./test_work_dir',
+ load_from='./work_dir/epoch_5.pth', # work_dir 不一致,指定 load_from,以加载指定的模型
+ randomness=randomness,
+ env_cfg=env_cfg,
+ launcher='none',
+ optim_wrapper=optim_wrapper,
+ train_dataloader=train_dataloader,
+ train_cfg=dict(by_epoch=True, max_epochs=5, val_interval=1),
+ val_dataloader=val_dataloader,
+ val_evaluator=val_evaluator,
+ val_cfg=val_cfg,
+ test_dataloader=val_dataloader,
+ test_evaluator=val_evaluator,
+ test_cfg=dict(type='TestLoop'),
+)
+runner.test()
+```
+
+### 迁移自定义执行流程
+
+使用 MMCV 执行器时,我们可能会重载 `runner.train/runner.val` 或者 `runner.run_iter` 实现自定义的训练、测试流程。以重载 `runner.train` 为例,假设我们想对每个批次的图片训练两遍,我们可以这样重载 MMCV 的执行器:
+
+```python
+class CustomRunner(EpochBasedRunner):
+ def train(self, data_loader, **kwargs):
+ self.model.train()
+ self.mode = 'train'
+ self.data_loader = data_loader
+ self._max_iters = self._max_epochs * len(self.data_loader)
+ self.call_hook('before_train_epoch')
+ time.sleep(2) # Prevent possible deadlock during epoch transition
+ for i, data_batch in enumerate(self.data_loader):
+ self.data_batch = data_batch
+ self._inner_iter = i
+ for _ in range(2)
+ self.call_hook('before_train_iter')
+ self.run_iter(data_batch, train_mode=True, **kwargs)
+ self.call_hook('after_train_iter')
+ del self.data_batch
+ self._iter += 1
+
+ self.call_hook('after_train_epoch')
+ self._epoch += 1
+```
+
+在 MMEngine 中,要实现上述功能,我们需要重载一个新的循环控制器
+
+```python
+from mmengine.registry import LOOPS
+from mmengine.runner import EpochBasedTrainLoop
+
+
+@LOOPS.register_module()
+class CustomEpochBasedTrainLoop(EpochBasedTrainLoop):
+ def run_iter(self, idx, data_batch) -> None:
+ for _ in range(2):
+ super().run_iter(idx, data_batch)
+```
+
+在构建执行器时,指定 `train_cfg` 的 `type` 为 `CustomEpochBasedTrainLoop`。需要注意的是,`by_epoch` 和 `type` 不能同时配置,当配置 `by_epoch` 时,会推断训练循环控制器的类型为 `EpochBasedTrainLoop`。
+
+```python
+runner = Runner(
+ model=model,
+ work_dir='./test_work_dir',
+ randomness=randomness,
+ env_cfg=env_cfg,
+ launcher='none',
+ optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.001, momentum=0.9)),
+ train_dataloader=train_dataloader,
+ train_cfg=dict(
+ type='CustomEpochBasedTrainLoop',
+ max_epochs=5,
+ val_interval=1),
+ val_dataloader=val_dataloader,
+ val_evaluator=val_evaluator,
+ val_cfg=val_cfg,
+ test_dataloader=val_dataloader,
+ test_evaluator=val_evaluator,
+ test_cfg=dict(type='TestLoop'),
+)
+runner.train()
+```
+
+如果有更加复杂的执行器迁移需求,可以参考[执行器教程](../tutorials/runner.md) 和[执行器设计文档](../design/runner.md)。
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/migration/transform.md b/testbed/open-mmlab__mmengine/docs/zh_cn/migration/transform.md
new file mode 100644
index 0000000000000000000000000000000000000000..bf7f85a2579eb825a7bd06232673d8f68bd5be27
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/migration/transform.md
@@ -0,0 +1,151 @@
+# 数据变换类的迁移
+
+## 简介
+
+在 TorchVision 的数据变换类接口约定中,数据变换类需要实现 `__call__` 方法,而在 OpenMMLab 1.0 的接口约定中,进一步要求
+`__call__` 方法的输出应当是一个字典,在各种数据变换中对这个字典进行增删查改。在 OpenMMLab 2.0 中,为了提升后续的可扩展性,我们将原先的 `__call__` 方法迁移为 `transform` 方法,并要求数据变换类应当继承
+[`mmcv.transforms.BaseTransfrom`](https://mmcv.readthedocs.io/en/dev-2.x/api.html#TODO)。具体如何实现一个数据变换类,可以参见[文档](../advanced_tutorials/data_transform.md)。
+
+由于在此次更新中,我们将部分共用的数据变换类统一迁移至 MMCV 中,因此本文将会对比这些数据变换在旧版本([MMClassification v0.23.2](https://github.com/open-mmlab/mmclassification/tree/v0.23.2)、[MMDetection v2.25.1](https://github.com/open-mmlab/mmdetection/tree/v2.25.1))和新版本([MMCV v2.0.0rc0](https://github.com/open-mmlab/mmcv/tree/2.x))中的功能、用法和实现上的差异。
+
+## 功能差异
+
+
+
+
+
+ MMClassification (旧)
+ MMDetection (旧)
+ MMCV (新)
+
+
+
+
+ LoadImageFromFile
+ 从 'img_prefix' 和 'img_info.filename' 字段组合获得文件路径并读取
+ 从 'img_prefix' 和 'img_info.filename' 字段组合获得文件路径并读取,支持指定通道顺序
+ 从 'img_path' 获得文件路径并读取,支持指定加载失败不报错,支持指定解码后端
+
+
+ LoadAnnotations
+ 无
+ 支持读取 bbox,label,mask(包括多边形样式),seg map,转换 bbox 坐标系
+ 支持读取 bbox,label,mask(不包括多边形样式),seg map
+
+
+ Pad
+ 填充 "img_fields" 中所有字段,不支持指定填充至整数倍
+ 填充 "img_fields" 中所有字段,支持指定填充至整数倍
+ 填充 "img" 字段,支持指定填充至整数倍
+
+
+ CenterCrop
+ 裁切 "img_fields" 中所有字段,支持以 EfficientNet 方式进行裁切
+ 无
+ 裁切 "img" 字段的图像,"gt_bboxes" 字段的 bbox,"gt_seg_map" 字段的分割图,"gt_keypoints" 字段的关键点,支持自动填充裁切边缘
+
+
+ Normalize
+ 图像归一化
+ 无差异
+ 无差异,但 MMEngine 推荐在数据预处理器 中进行归一化
+
+
+ Resize
+ 缩放 "img_fields" 中所有字段,允许指定根据某边长等比例缩放
+ 功能由 Resize 实现。需要 ratio_range 为 None,img_scale 仅指定一个尺寸,且 multiscale_mode 为 "value" 。
+ 缩放 "img" 字段的图像,"gt_bboxes" 字段的 bbox,"gt_seg_map" 字段的分割图,"gt_keypoints" 字段的关键点,支持指定缩放比例,支持等比例缩放图像至指定尺寸内
+
+
+ RandomResize
+ 无
+ 功能由 Resize 实现。需要 ratio_range 为 None,img_scale指定两个尺寸,且 multiscale_mode 为 "range",或 ratio_range 不为 None。
+ Resize(
+ img_sacle=[(640, 480), (960, 720)],
+ mode="range",
+)
+
+ 缩放功能同 Resize,支持从指定尺寸范围或指定比例范围随机采样缩放尺寸。
+ RandomResize(scale=[(640, 480), (960, 720)])
+
+
+
+ RandomChoiceResize
+ 无
+ 功能由 Resize 实现。需要 ratio_range 为 None,img_scale 指定多个尺寸,且 multiscale_mode 为 "value"。
+ Resize(
+ img_sacle=[(640, 480), (960, 720)],
+ mode="value",
+)
+
+ 缩放功能同 Resize,支持从若干指定尺寸中随机选择缩放尺寸。
+ RandomChoiceResize(scales=[(640, 480), (960, 720)])
+
+
+
+ RandomGrayscale
+ 灰度化 "img_fields" 中所有字段,灰度化后保持通道数。
+ 无
+ 灰度化 "img" 字段,支持指定灰度化权重,支持指定是否在灰度化后保持通道数(默认不保持)。
+
+
+ RandomFlip
+ 翻转 "img_fields" 中所有字段,支持指定水平或垂直翻转。
+ 翻转 "img_fields", "bbox_fields", "mask_fields", "seg_fields" 中所有字段,支持指定水平、垂直或对角翻转,支持指定各类翻转概率。
+ 翻转 "img", "gt_bboxes", "gt_seg_map", "gt_keypoints" 字段,支持指定水平、垂直或对角翻转,支持指定各类翻转概率。
+
+
+ MultiScaleFlipAug
+ 无
+ 用于测试时增强
+ 使用 TestTimeAug
+
+
+ ToTensor
+ 将指定字段转换为 torch.Tensor
+ 无差异
+ 无差异
+
+
+ ImageToTensor
+ 将指定字段转换为 torch.Tensor,并调整通道顺序至 CHW。
+ 无差异
+ 无差异
+
+
+
+
+## 实现差异
+
+以 `RandomFlip` 为例,MMCV 的 [RandomFlip](https://github.com/open-mmlab/mmcv/blob/5947178e855c23eea6103b1d70e1f8027f7b2ca8/mmcv/transforms/processing.py#L985) 相比旧版 MMDetection 的 [RandomFlip](https://github.com/open-mmlab/mmdetection/blob/3b72b12fe9b14de906d1363982b9fba05e7d47c1/mmdet/datasets/pipelines/transforms.py#L333),需要继承 `BaseTransfrom`,将功能实现放在 `transforms` 方法,并将生成随机结果的部分放在单独的方法中,用 `cache_randomness` 包装。有关随机方法的包装相关功能,参见[相关文档](TODO)。
+
+- MMDetection (旧)
+
+```python
+class RandomFlip:
+ def __call__(self, results):
+ """调用时进行随机翻转"""
+ ...
+ # 随机选择翻转方向
+ cur_dir = np.random.choice(direction_list, p=flip_ratio_list)
+ ...
+ return results
+```
+
+- MMCV
+
+```python
+class RandomFlip(BaseTransfrom):
+ def transform(self, results):
+ """调用时进行随机翻转"""
+ ...
+ cur_dir = self._random_direction()
+ ...
+ return results
+
+ @cache_randomness
+ def _random_direction(self):
+ """随机选择翻转方向"""
+ ...
+ return np.random.choice(direction_list, p=flip_ratio_list)
+```
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/notes/changelog.md b/testbed/open-mmlab__mmengine/docs/zh_cn/notes/changelog.md
new file mode 100644
index 0000000000000000000000000000000000000000..20e476a37166a53e90577fe8ad3a590d774b6541
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/notes/changelog.md
@@ -0,0 +1,57 @@
+# Changelog of v0.x
+
+## v0.2.0 (11/10/2022)
+
+### New Features & Enhancements
+
+- Add SMDDP backend and support running on AWS by @austinmw in https://github.com/open-mmlab/mmengine/pull/579
+- Refactor `FileIO` but without breaking bc by @zhouzaida in https://github.com/open-mmlab/mmengine/pull/533
+- Add test time augmentation base model by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/538
+- Use `torch.lerp\_()` to speed up EMA by @RangiLyu in https://github.com/open-mmlab/mmengine/pull/519
+- Support converting `BN` to `SyncBN` by config by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/506
+- Support defining metric name in wandb backend by @okotaku in https://github.com/open-mmlab/mmengine/pull/509
+- Add dockerfile by @zhouzaida in https://github.com/open-mmlab/mmengine/pull/347
+
+### Docs
+
+- Fix API files of English documentation by @zhouzaida in https://github.com/open-mmlab/mmengine/pull/525
+- Fix typo in `instance_data.py` by @Dai-Wenxun in https://github.com/open-mmlab/mmengine/pull/530
+- Fix the docstring of the model sub-package by @zhouzaida in https://github.com/open-mmlab/mmengine/pull/573
+- Fix a spelling error in docs/zh_cn by @cxiang26 in https://github.com/open-mmlab/mmengine/pull/548
+- Fix typo in docstring by @MengzhangLI in https://github.com/open-mmlab/mmengine/pull/527
+- Update `config.md` by @Zhengfei-0311 in https://github.com/open-mmlab/mmengine/pull/562
+
+### Bug Fixes
+
+- Fix `LogProcessor` does not smooth loss if the name of loss doesn't start with `loss` by @liuyanyi in
+ https://github.com/open-mmlab/mmengine/pull/539
+- Fix failed to enable `detect_anomalous_params` in `MMSeparateDistributedDataParallel` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/588
+- Fix CheckpointHook behavior unexpected if given `filename_tmpl` argument by @C1rN09 in https://github.com/open-mmlab/mmengine/pull/518
+- Fix error argument sequence in `FSDP` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/520
+- Fix uploading image in wandb backend @okotaku in https://github.com/open-mmlab/mmengine/pull/510
+- Fix loading state dictionary in `EMAHook` by @okotaku in https://github.com/open-mmlab/mmengine/pull/507
+- Fix circle import in `EMAHook` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/523
+- Fix unit test could fail caused by `MultiProcessTestCase` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/535
+- Remove unnecessary "if statement" in `Registry` by @MambaWong in https://github.com/open-mmlab/mmengine/pull/536
+- Fix `_save_to_state_dict` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/542
+- Support comparing NumPy array dataset meta in `Runner.resume` by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/511
+- Use `get` instead of `pop` to dump `runner_type` in `build_runner_from_cfg` by @nijkah in https://github.com/open-mmlab/mmengine/pull/549
+- Upgrade pre-commit hooks by @zhouzaida in https://github.com/open-mmlab/mmengine/pull/576
+- Delete the error comment in `registry.md` by @vansin in https://github.com/open-mmlab/mmengine/pull/514
+- Fix Some out-of-date unit tests by @C1rN09 in https://github.com/open-mmlab/mmengine/pull/586
+- Fix typo in `MMFullyShardedDataParallel` by @yhna940 in https://github.com/open-mmlab/mmengine/pull/569
+- Update Github Action CI and CircleCI by @zhouzaida in https://github.com/open-mmlab/mmengine/pull/512
+- Fix unit test in windows by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/515
+- Fix merge ci & multiprocessing unit test by @HAOCHENYE in https://github.com/open-mmlab/mmengine/pull/529
+
+### New Contributors
+
+- @okotaku made their first contribution in https://github.com/open-mmlab/mmengine/pull/510
+- @MengzhangLI made their first contribution in https://github.com/open-mmlab/mmengine/pull/527
+- @MambaWong made their first contribution in https://github.com/open-mmlab/mmengine/pull/536
+- @cxiang26 made their first contribution in https://github.com/open-mmlab/mmengine/pull/548
+- @nijkah made their first contribution in https://github.com/open-mmlab/mmengine/pull/549
+- @Zhengfei-0311 made their first contribution in https://github.com/open-mmlab/mmengine/pull/562
+- @austinmw made their first contribution in https://github.com/open-mmlab/mmengine/pull/579
+- @yhna940 made their first contribution in https://github.com/open-mmlab/mmengine/pull/569
+- @liuyanyi made their first contribution in https://github.com/open-mmlab/mmengine/pull/539
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/notes/code_style.md b/testbed/open-mmlab__mmengine/docs/zh_cn/notes/code_style.md
new file mode 100644
index 0000000000000000000000000000000000000000..8ddb87c2391e07b848aa073287cc2a230da8c3ec
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/notes/code_style.md
@@ -0,0 +1,609 @@
+## 代码规范
+
+### 代码规范标准
+
+#### PEP 8 —— Python 官方代码规范
+
+[Python 官方的代码风格指南](https://www.python.org/dev/peps/pep-0008/),包含了以下几个方面的内容:
+
+- 代码布局,介绍了 Python 中空行、断行以及导入相关的代码风格规范。比如一个常见的问题:当我的代码较长,无法在一行写下时,何处可以断行?
+
+- 表达式,介绍了 Python 中表达式空格相关的一些风格规范。
+
+- 尾随逗号相关的规范。当列表较长,无法一行写下而写成如下逐行列表时,推荐在末项后加逗号,从而便于追加选项、版本控制等。
+
+ ```python
+ # Correct:
+ FILES = ['setup.cfg', 'tox.ini']
+ # Correct:
+ FILES = [
+ 'setup.cfg',
+ 'tox.ini',
+ ]
+ # Wrong:
+ FILES = ['setup.cfg', 'tox.ini',]
+ # Wrong:
+ FILES = [
+ 'setup.cfg',
+ 'tox.ini'
+ ]
+ ```
+
+- 命名相关规范、注释相关规范、类型注解相关规范,我们将在后续章节中做详细介绍。
+
+ "A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important." PEP 8 -- Style Guide for Python Code
+
+:::{note}
+PEP 8 的代码规范并不是绝对的,项目内的一致性要优先于 PEP 8 的规范。OpenMMLab 各个项目都在 setup.cfg 设定了一些代码规范的设置,请遵照这些设置。一个例子是在 PEP 8 中有如下一个例子:
+
+```python
+# Correct:
+hypot2 = x*x + y*y
+# Wrong:
+hypot2 = x * x + y * y
+```
+
+这一规范是为了指示不同优先级,但 OpenMMLab 的设置中通常没有启用 yapf 的 `ARITHMETIC_PRECEDENCE_INDICATION` 选项,因而格式规范工具不会按照推荐样式格式化,以设置为准。
+:::
+
+#### Google 开源项目风格指南
+
+[Google 使用的编程风格指南](https://google.github.io/styleguide/pyguide.html),包括了 Python 相关的章节。相较于 PEP 8,该指南提供了更为详尽的代码指南。该指南包括了语言规范和风格规范两个部分。
+
+其中,语言规范对 Python 中很多语言特性进行了优缺点的分析,并给出了使用指导意见,如异常、Lambda 表达式、列表推导式、metaclass 等。
+
+风格规范的内容与 PEP 8 较为接近,大部分约定建立在 PEP 8 的基础上,也有一些更为详细的约定,如函数长度、TODO 注释、文件与 socket 对象的访问等。
+
+推荐将该指南作为参考进行开发,但不必严格遵照,一来该指南存在一些 Python 2 兼容需求,例如指南中要求所有无基类的类应当显式地继承 Object, 而在仅使用 Python 3 的环境中,这一要求是不必要的,依本项目中的惯例即可。二来 OpenMMLab 的项目作为框架级的开源软件,不必对一些高级技巧过于避讳,尤其是 MMCV。但尝试使用这些技巧前应当认真考虑是否真的有必要,并寻求其他开发人员的广泛评估。
+
+另外需要注意的一处规范是关于包的导入,在该指南中,要求导入本地包时必须使用路径全称,且导入的每一个模块都应当单独成行,通常这是不必要的,而且也不符合目前项目的开发惯例,此处进行如下约定:
+
+```python
+# Correct
+from mmcv.cnn.bricks import (Conv2d, build_norm_layer, DropPath, MaxPool2d,
+ Linear)
+from ..utils import ext_loader
+
+# Wrong
+from mmcv.cnn.bricks import Conv2d, build_norm_layer, DropPath, MaxPool2d, \
+ Linear # 使用括号进行连接,而不是反斜杠
+from ...utils import is_str # 最多向上回溯一层,过多的回溯容易导致结构混乱
+```
+
+OpenMMLab 项目使用 pre-commit 工具自动格式化代码,详情见[贡献代码](./contributing.md#代码风格)。
+
+### 命名规范
+
+#### 命名规范的重要性
+
+优秀的命名是良好代码可读的基础。基础的命名规范对各类变量的命名做了要求,使读者可以方便地根据代码名了解变量是一个类 / 局部变量 / 全局变量等。而优秀的命名则需要代码作者对于变量的功能有清晰的认识,以及良好的表达能力,从而使读者根据名称就能了解其含义,甚至帮助了解该段代码的功能。
+
+#### 基础命名规范
+
+| 类型 | 公有 | 私有 |
+| --------------- | ---------------- | ------------------ |
+| 模块 | lower_with_under | \_lower_with_under |
+| 包 | lower_with_under | |
+| 类 | CapWords | \_CapWords |
+| 异常 | CapWordsError | |
+| 函数(方法) | lower_with_under | \_lower_with_under |
+| 函数 / 方法参数 | lower_with_under | |
+| 全局 / 类内常量 | CAPS_WITH_UNDER | \_CAPS_WITH_UNDER |
+| 全局 / 类内变量 | lower_with_under | \_lower_with_under |
+| 变量 | lower_with_under | \_lower_with_under |
+| 局部变量 | lower_with_under | |
+
+注意:
+
+- 尽量避免变量名与保留字冲突,特殊情况下如不可避免,可使用一个后置下划线,如 class\_
+- 尽量不要使用过于简单的命名,除了约定俗成的循环变量 i,文件变量 f,错误变量 e 等。
+- 不会被用到的变量可以命名为 \_,逻辑检查器会将其忽略。
+
+#### 命名技巧
+
+良好的变量命名需要保证三点:
+
+1. 含义准确,没有歧义
+2. 长短适中
+3. 前后统一
+
+```python
+# Wrong
+class Masks(metaclass=ABCMeta): # 命名无法表现基类;Instance or Semantic?
+ pass
+
+# Correct
+class BaseInstanceMasks(metaclass=ABCMeta):
+ pass
+
+# Wrong,不同地方含义相同的变量尽量用统一的命名
+def __init__(self, inplanes, planes):
+ pass
+
+def __init__(self, in_channels, out_channels):
+ pass
+```
+
+常见的函数命名方法:
+
+- 动宾命名法:crop_img, init_weights
+- 动宾倒置命名法:imread, bbox_flip
+
+注意函数命名与参数的顺序,保证主语在前,符合语言习惯:
+
+- check_keys_exist(key, container)
+- check_keys_contain(container, key)
+
+注意避免非常规或统一约定的缩写,如 nb -> num_blocks,in_nc -> in_channels
+
+### docstring 规范
+
+#### 为什么要写 docstring
+
+docstring 是对一个类、一个函数功能与 API 接口的详细描述,有两个功能,一是帮助其他开发者了解代码功能,方便 debug 和复用代码;二是在 Readthedocs 文档中自动生成相关的 API reference 文档,帮助不了解源代码的社区用户使用相关功能。
+
+#### 如何写 docstring
+
+与注释不同,一份规范的 docstring 有着严格的格式要求,以便于 Python 解释器以及 sphinx 进行文档解析,详细的 docstring 约定参见 [PEP 257](https://www.python.org/dev/peps/pep-0257/)。此处以例子的形式介绍各种文档的标准格式,参考格式为 [Google 风格](https://zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_style_rules/#comments)。
+
+1. 模块文档
+
+ 代码风格规范推荐为每一个模块(即 Python 文件)编写一个 docstring,但目前 OpenMMLab 项目大部分没有此类 docstring,因此不做硬性要求。
+
+ ```python
+ """A one line summary of the module or program, terminated by a period.
+
+ Leave one blank line. The rest of this docstring should contain an
+ overall description of the module or program. Optionally, it may also
+ contain a brief description of exported classes and functions and/or usage
+ examples.
+
+ Typical usage example:
+
+ foo = ClassFoo()
+ bar = foo.FunctionBar()
+ """
+ ```
+
+2. 类文档
+
+ 类文档是我们最常需要编写的,此处,按照 OpenMMLab 的惯例,我们使用了与 Google 风格不同的写法。如下例所示,文档中没有使用 Attributes 描述类属性,而是使用 Args 描述 __init__ 函数的参数。
+
+ 在 Args 中,遵照 `parameter (type): Description.` 的格式,描述每一个参数类型和功能。其中,多种类型可使用 `(float or str)` 的写法,可以为 None 的参数可以写为 `(int, optional)`。
+
+ ```python
+ class BaseRunner(metaclass=ABCMeta):
+ """The base class of Runner, a training helper for PyTorch.
+
+ All subclasses should implement the following APIs:
+
+ - ``run()``
+ - ``train()``
+ - ``val()``
+ - ``save_checkpoint()``
+
+ Args:
+ model (:obj:`torch.nn.Module`): The model to be run.
+ batch_processor (callable, optional): A callable method that process
+ a data batch. The interface of this method should be
+ ``batch_processor(model, data, train_mode) -> dict``.
+ Defaults to None.
+ optimizer (dict or :obj:`torch.optim.Optimizer`, optional): It can be
+ either an optimizer (in most cases) or a dict of optimizers
+ (in models that requires more than one optimizer, e.g., GAN).
+ Defaults to None.
+ work_dir (str, optional): The working directory to save checkpoints
+ and logs. Defaults to None.
+ logger (:obj:`logging.Logger`): Logger used during training.
+ Defaults to None. (The default value is just for backward
+ compatibility)
+ meta (dict, optional): A dict records some import information such as
+ environment info and seed, which will be logged in logger hook.
+ Defaults to None.
+ max_epochs (int, optional): Total training epochs. Defaults to None.
+ max_iters (int, optional): Total training iterations. Defaults to None.
+ """
+
+ def __init__(self,
+ model,
+ batch_processor=None,
+ optimizer=None,
+ work_dir=None,
+ logger=None,
+ meta=None,
+ max_iters=None,
+ max_epochs=None):
+ ...
+ ```
+
+ 另外,在一些算法实现的主体类中,建议加入原论文的链接;如果参考了其他开源代码的实现,则应加入 modified from,而如果是直接复制了其他代码库的实现,则应加入 copied from ,并注意源码的 License。如有必要,也可以通过 .. math:: 来加入数学公式
+
+ ```python
+ # 参考实现
+ # This func is modified from `detectron2
+ # `_.
+
+ # 复制代码
+ # This code was copied from the `ubelt
+ # library`_.
+
+ # 引用论文 & 添加公式
+ class LabelSmoothLoss(nn.Module):
+ r"""Initializer for the label smoothed cross entropy loss.
+
+ Refers to `Rethinking the Inception Architecture for Computer Vision
+ `_.
+
+ This decreases gap between output scores and encourages generalization.
+ Labels provided to forward can be one-hot like vectors (NxC) or class
+ indices (Nx1).
+ And this accepts linear combination of one-hot like labels from mixup or
+ cutmix except multi-label task.
+
+ Args:
+ label_smooth_val (float): The degree of label smoothing.
+ num_classes (int, optional): Number of classes. Defaults to None.
+ mode (str): Refers to notes, Options are "original", "classy_vision",
+ "multi_label". Defaults to "classy_vision".
+ reduction (str): The method used to reduce the loss.
+ Options are "none", "mean" and "sum". Defaults to 'mean'.
+ loss_weight (float): Weight of the loss. Defaults to 1.0.
+
+ Note:
+ if the ``mode`` is "original", this will use the same label smooth
+ method as the original paper as:
+
+ .. math::
+ (1-\epsilon)\delta_{k, y} + \frac{\epsilon}{K}
+
+ where :math:`\epsilon` is the ``label_smooth_val``, :math:`K` is
+ the ``num_classes`` and :math:`\delta_{k,y}` is Dirac delta,
+ which equals 1 for k=y and 0 otherwise.
+
+ if the ``mode`` is "classy_vision", this will use the same label
+ smooth method as the `facebookresearch/ClassyVision
+ `_ repo as:
+
+ .. math::
+ \frac{\delta_{k, y} + \epsilon/K}{1+\epsilon}
+
+ if the ``mode`` is "multi_label", this will accept labels from
+ multi-label task and smoothing them as:
+
+ .. math::
+ (1-2\epsilon)\delta_{k, y} + \epsilon
+ ```
+
+```{note}
+注意 \`\`here\`\`、\`here\`、"here" 三种引号功能是不同。
+
+在 reStructured 语法中,\`\`here\`\` 表示一段代码;\`here\` 表示斜体;"here" 无特殊含义,一般可用来表示字符串。其中 \`here\` 的用法与 Markdown 中不同,需要多加留意。
+另外还有 :obj:\`type\` 这种更规范的表示类的写法,但鉴于长度,不做特别要求,一般仅用于表示非常用类型。
+```
+
+3. 方法(函数)文档
+
+ 函数文档与类文档的结构基本一致,但需要加入返回值文档。对于较为复杂的函数和类,可以使用 Examples 字段加入示例;如果需要对参数加入一些较长的备注,可以加入 Note 字段进行说明。
+
+ 对于使用较为复杂的类或函数,比起看大段大段的说明文字和参数文档,添加合适的示例更能帮助用户迅速了解其用法。需要注意的是,这些示例最好是能够直接在 Python 交互式环境中运行的,并给出一些相对应的结果。如果存在多个示例,可以使用注释简单说明每段示例,也能起到分隔作用。
+
+ ```python
+ def import_modules_from_strings(imports, allow_failed_imports=False):
+ """Import modules from the given list of strings.
+
+ Args:
+ imports (list | str | None): The given module names to be imported.
+ allow_failed_imports (bool): If True, the failed imports will return
+ None. Otherwise, an ImportError is raise. Defaults to False.
+
+ Returns:
+ List[module] | module | None: The imported modules.
+ All these three lines in docstring will be compiled into the same
+ line in readthedocs.
+
+ Examples:
+ >>> osp, sys = import_modules_from_strings(
+ ... ['os.path', 'sys'])
+ >>> import os.path as osp_
+ >>> import sys as sys_
+ >>> assert osp == osp_
+ >>> assert sys == sys_
+ """
+ ...
+ ```
+
+ 如果函数接口在某个版本发生了变化,需要在 docstring 中加入相关的说明,必要时添加 Note 或者 Warning 进行说明,例如:
+
+ ```python
+ class CheckpointHook(Hook):
+ """Save checkpoints periodically.
+
+ Args:
+ out_dir (str, optional): The root directory to save checkpoints. If
+ not specified, ``runner.work_dir`` will be used by default. If
+ specified, the ``out_dir`` will be the concatenation of
+ ``out_dir`` and the last level directory of ``runner.work_dir``.
+ Defaults to None. `Changed in version 1.3.15.`
+ file_client_args (dict, optional): Arguments to instantiate a
+ FileClient. See :class:`mmcv.fileio.FileClient` for details.
+ Defaults to None. `New in version 1.3.15.`
+
+ Warning:
+ Before v1.3.15, the ``out_dir`` argument indicates the path where the
+ checkpoint is stored. However, in v1.3.15 and later, ``out_dir``
+ indicates the root directory and the final path to save checkpoint is
+ the concatenation of out_dir and the last level directory of
+ ``runner.work_dir``. Suppose the value of ``out_dir`` is
+ "/path/of/A" and the value of ``runner.work_dir`` is "/path/of/B",
+ then the final path will be "/path/of/A/B".
+ ```
+
+ 如果参数或返回值里带有需要展开描述字段的 dict,则应该采用如下格式:
+
+ ```python
+ def func(x):
+ r"""
+ Args:
+ x (None): A dict with 2 keys, ``padded_targets``, and ``targets``.
+
+ - ``targets`` (list[Tensor]): A list of tensors.
+ Each tensor has the shape of :math:`(T_i)`. Each
+ element is the index of a character.
+ - ``padded_targets`` (Tensor): A tensor of shape :math:`(N)`.
+ Each item is the length of a word.
+
+ Returns:
+ dict: A dict with 2 keys, ``padded_targets``, and ``targets``.
+
+ - ``targets`` (list[Tensor]): A list of tensors.
+ Each tensor has the shape of :math:`(T_i)`. Each
+ element is the index of a character.
+ - ``padded_targets`` (Tensor): A tensor of shape :math:`(N)`.
+ Each item is the length of a word.
+ """
+ return x
+ ```
+
+```{important}
+为了生成 readthedocs 文档,文档的编写需要按照 ReStructrued 文档格式,否则会产生文档渲染错误,在提交 PR 前,最好生成并预览一下文档效果。
+语法规范参考:
+
+- [reStructuredText Primer - Sphinx documentation](https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#)
+- [Example Google Style Python Docstrings ‒ napoleon 0.7 documentation](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html#example-google)
+```
+
+### 注释规范
+
+#### 为什么要写注释
+
+对于一个开源项目,团队合作以及社区之间的合作是必不可少的,因而尤其要重视合理的注释。不写注释的代码,很有可能过几个月自己也难以理解,造成额外的阅读和修改成本。
+
+#### 如何写注释
+
+最需要写注释的是代码中那些技巧性的部分。如果你在下次代码审查的时候必须解释一下,那么你应该现在就给它写注释。对于复杂的操作,应该在其操作开始前写上若干行注释。对于不是一目了然的代码,应在其行尾添加注释。
+—— Google 开源项目风格指南
+
+```python
+# We use a weighted dictionary search to find out where i is in
+# the array. We extrapolate position based on the largest num
+# in the array and the array size and then do binary search to
+# get the exact number.
+if i & (i-1) == 0: # True if i is 0 or a power of 2.
+```
+
+为了提高可读性, 注释应该至少离开代码2个空格.
+另一方面, 绝不要描述代码. 假设阅读代码的人比你更懂Python, 他只是不知道你的代码要做什么.
+—— Google 开源项目风格指南
+
+```python
+# Wrong:
+# Now go through the b array and make sure whenever i occurs
+# the next element is i+1
+
+# Wrong:
+if i & (i-1) == 0: # True if i bitwise and i-1 is 0.
+```
+
+在注释中,可以使用 Markdown 语法,因为开发人员通常熟悉 Markdown 语法,这样可以便于交流理解,如可使用单反引号表示代码和变量(注意不要和 docstring 中的 ReStructured 语法混淆)
+
+```python
+# `_reversed_padding_repeated_twice` is the padding to be passed to
+# `F.pad` if needed (e.g., for non-zero padding types that are
+# implemented as two ops: padding + conv). `F.pad` accepts paddings in
+# reverse order than the dimension.
+self._reversed_padding_repeated_twice = _reverse_repeat_tuple(self.padding, 2)
+```
+
+#### 注释示例
+
+1. 出自 `mmcv/utils/registry.py`,对于较为复杂的逻辑结构,通过注释,明确了优先级关系。
+
+ ```python
+ # self.build_func will be set with the following priority:
+ # 1. build_func
+ # 2. parent.build_func
+ # 3. build_from_cfg
+ if build_func is None:
+ if parent is not None:
+ self.build_func = parent.build_func
+ else:
+ self.build_func = build_from_cfg
+ else:
+ self.build_func = build_func
+ ```
+
+2. 出自 `mmcv/runner/checkpoint.py`,对于 bug 修复中的一些特殊处理,可以附带相关的 issue 链接,帮助其他人了解 bug 背景。
+
+ ```python
+ def _save_ckpt(checkpoint, file):
+ # The 1.6 release of PyTorch switched torch.save to use a new
+ # zipfile-based file format. It will cause RuntimeError when a
+ # checkpoint was saved in high version (PyTorch version>=1.6.0) but
+ # loaded in low version (PyTorch version<1.6.0). More details at
+ # https://github.com/open-mmlab/mmpose/issues/904
+ if digit_version(TORCH_VERSION) >= digit_version('1.6.0'):
+ torch.save(checkpoint, file, _use_new_zipfile_serialization=False)
+ else:
+ torch.save(checkpoint, file)
+ ```
+
+### 类型注解
+
+#### 为什么要写类型注解
+
+类型注解是对函数中变量的类型做限定或提示,为代码的安全性提供保障、增强代码的可读性、避免出现类型相关的错误。
+Python 没有对类型做强制限制,类型注解只起到一个提示作用,通常你的 IDE 会解析这些类型注解,然后在你调用相关代码时对类型做提示。另外也有类型注解检查工具,这些工具会根据类型注解,对代码中可能出现的问题进行检查,减少 bug 的出现。
+需要注意的是,通常我们不需要注释模块中的所有函数:
+
+1. 公共的 API 需要注释
+2. 在代码的安全性,清晰性和灵活性上进行权衡是否注释
+3. 对于容易出现类型相关的错误的代码进行注释
+4. 难以理解的代码请进行注释
+5. 若代码中的类型已经稳定,可以进行注释. 对于一份成熟的代码,多数情况下,即使注释了所有的函数,也不会丧失太多的灵活性.
+
+#### 如何写类型注解
+
+1. 函数 / 方法类型注解,通常不对 self 和 cls 注释。
+
+ ```python
+ from typing import Optional, List, Tuple
+
+ # 全部位于一行
+ def my_method(self, first_var: int) -> int:
+ pass
+
+ # 另起一行
+ def my_method(
+ self, first_var: int,
+ second_var: float) -> Tuple[MyLongType1, MyLongType1, MyLongType1]:
+ pass
+
+ # 单独成行(具体的应用场合与行宽有关,建议结合 yapf 自动化格式使用)
+ def my_method(
+ self, first_var: int, second_var: float
+ ) -> Tuple[MyLongType1, MyLongType1, MyLongType1]:
+ pass
+
+ # 引用尚未被定义的类型
+ class MyClass:
+ def __init__(self,
+ stack: List["MyClass"]) -> None:
+ pass
+ ```
+
+ 注:类型注解中的类型可以是 Python 内置类型,也可以是自定义类,还可以使用 Python 提供的 wrapper 类对类型注解进行装饰,一些常见的注解如下:
+
+ ```python
+ # 数值类型
+ from numbers import Number
+
+ # 可选类型,指参数可以为 None
+ from typing import Optional
+ def foo(var: Optional[int] = None):
+ pass
+
+ # 联合类型,指同时接受多种类型
+ from typing import Union
+ def foo(var: Union[float, str]):
+ pass
+
+ from typing import Sequence # 序列类型
+ from typing import Iterable # 可迭代类型
+ from typing import Any # 任意类型
+ from typing import Callable # 可调用类型
+
+ from typing import List, Dict # 列表和字典的泛型类型
+ from typing import Tuple # 元组的特殊格式
+ # 虽然在 Python 3.9 中,list, tuple 和 dict 本身已支持泛型,但为了支持之前的版本
+ # 我们在进行类型注解时还是需要使用 List, Tuple, Dict 类型
+ # 另外,在对参数类型进行注解时,尽量使用 Sequence & Iterable & Mapping
+ # List, Tuple, Dict 主要用于返回值类型注解
+ # 参见 https://docs.python.org/3/library/typing.html#typing.List
+ ```
+
+2. 变量类型注解,一般用于难以直接推断其类型时
+
+ ```python
+ # Recommend: 带类型注解的赋值
+ a: Foo = SomeUndecoratedFunction()
+ a: List[int]: [1, 2, 3] # List 只支持单一类型泛型,可使用 Union
+ b: Tuple[int, int] = (1, 2) # 长度固定为 2
+ c: Tuple[int, ...] = (1, 2, 3) # 变长
+ d: Dict[str, int] = {'a': 1, 'b': 2}
+
+ # Not Recommend:行尾类型注释
+ # 虽然这种方式被写在了 Google 开源指南中,但这是一种为了支持 Python 2.7 版本
+ # 而补充的注释方式,鉴于我们只支持 Python 3, 为了风格统一,不推荐使用这种方式。
+ a = SomeUndecoratedFunction() # type: Foo
+ a = [1, 2, 3] # type: List[int]
+ b = (1, 2, 3) # type: Tuple[int, ...]
+ c = (1, "2", 3.5) # type: Tuple[int, Text, float]
+ ```
+
+3. 泛型
+
+ 上文中我们知道,typing 中提供了 list 和 dict 的泛型类型,那么我们自己是否可以定义类似的泛型呢?
+
+ ```python
+ from typing import TypeVar, Generic
+
+ KT = TypeVar('KT')
+ VT = TypeVar('VT')
+
+ class Mapping(Generic[KT, VT]):
+ def __init__(self, data: Dict[KT, VT]):
+ self._data = data
+
+ def __getitem__(self, key: KT) -> VT:
+ return self._data[key]
+ ```
+
+ 使用上述方法,我们定义了一个拥有泛型能力的映射类,实际用法如下:
+
+ ```python
+ mapping = Mapping[str, float]({'a': 0.5})
+ value: float = example['a']
+ ```
+
+ 另外,我们也可以利用 TypeVar 在函数签名中指定联动的多个类型:
+
+ ```python
+ from typing import TypeVar, List
+
+ T = TypeVar('T') # Can be anything
+ A = TypeVar('A', str, bytes) # Must be str or bytes
+
+
+ def repeat(x: T, n: int) -> List[T]:
+ """Return a list containing n references to x."""
+ return [x]*n
+
+
+ def longest(x: A, y: A) -> A:
+ """Return the longest of two strings."""
+ return x if len(x) >= len(y) else y
+ ```
+
+更多关于类型注解的写法请参考 [typing](https://docs.python.org/3/library/typing.html)。
+
+#### 类型注解检查工具
+
+[mypy](https://mypy.readthedocs.io/en/stable/) 是一个 Python 静态类型检查工具。根据你的类型注解,mypy 会检查传参、赋值等操作是否符合类型注解,从而避免可能出现的 bug。
+
+例如如下的一个 Python 脚本文件 test.py:
+
+```python
+def foo(var: int) -> float:
+ return float(var)
+
+a: str = foo('2.0')
+b: int = foo('3.0') # type: ignore
+```
+
+运行 mypy test.py 可以得到如下检查结果,分别指出了第 4 行在函数调用和返回值赋值两处类型错误。而第 5 行同样存在两个类型错误,由于使用了 type: ignore 而被忽略了,只有部分特殊情况可能需要此类忽略。
+
+```
+test.py:4: error: Incompatible types in assignment (expression has type "float", variable has type "int")
+test.py:4: error: Argument 1 to "foo" has incompatible type "str"; expected "int"
+Found 2 errors in 1 file (checked 1 source file)
+```
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/notes/contributing.md b/testbed/open-mmlab__mmengine/docs/zh_cn/notes/contributing.md
new file mode 100644
index 0000000000000000000000000000000000000000..ef115d770b1f370f600784ccf8e991824dc92f36
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/notes/contributing.md
@@ -0,0 +1,257 @@
+## 贡献代码
+
+欢迎加入 MMEngine 社区,我们致力于打造最前沿的深度学习模型训练的基础库,我们欢迎任何类型的贡献,包括但不限于
+
+**修复错误**
+
+修复代码实现错误的步骤如下:
+
+1. 如果提交的代码改动较大,建议先提交 issue,并正确描述 issue 的现象、原因和复现方式,讨论后确认修复方案。
+2. 修复错误并补充相应的单元测试,提交拉取请求。
+
+**新增功能或组件**
+
+1. 如果新功能或模块涉及较大的代码改动,建议先提交 issue,确认功能的必要性。
+2. 实现新增功能并添单元测试,提交拉取请求。
+
+**文档补充**
+
+修复文档可以直接提交拉取请求
+
+添加文档或将文档翻译成其他语言步骤如下
+
+1. 提交 issue,确认添加文档的必要性。
+2. 添加文档,提交拉取请求。
+
+### 拉取请求工作流
+
+如果你对拉取请求不了解,没关系,接下来的内容将会从零开始,一步一步地指引你如何创建一个拉取请求。如果你想深入了解拉取请求的开发模式,可以参考 github [官方文档](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/about-pull-requests)
+
+#### 1. 复刻仓库
+
+当你第一次提交拉取请求时,先复刻 OpenMMLab 原代码库,点击 GitHub 页面右上角的 **Fork** 按钮,复刻后的代码库将会出现在你的 GitHub 个人主页下。
+
+
+
+将代码克隆到本地
+
+```shell
+git clone git@github.com:{username}/mmengine.git
+```
+
+添加原代码库为上游代码库
+
+```bash
+git remote add upstream git@github.com:open-mmlab/mmengine
+```
+
+检查 remote 是否添加成功,在终端输入 `git remote -v`
+
+```bash
+origin git@github.com:{username}/mmengine.git (fetch)
+origin git@github.com:{username}/mmengine.git (push)
+upstream git@github.com:open-mmlab/mmengine (fetch)
+upstream git@github.com:open-mmlab/mmengine (push)
+```
+
+```{note}
+这里对 origin 和 upstream 进行一个简单的介绍,当我们使用 git clone 来克隆代码时,会默认创建一个 origin 的 remote,它指向我们克隆的代码库地址,而 upstream 则是我们自己添加的,用来指向原始代码库地址。当然如果你不喜欢他叫 upstream,也可以自己修改,比如叫 open-mmlab。我们通常向 origin 提交代码(即 fork 下来的远程仓库),然后向 upstream 提交一个 pull request。如果提交的代码和最新的代码发生冲突,再从 upstream 拉取最新的代码,和本地分支解决冲突,再提交到 origin。
+```
+
+#### 2. 配置 pre-commit
+
+在本地开发环境中,我们使用 [pre-commit](https://pre-commit.com/#intro) 来检查代码风格,以确保代码风格的统一。在提交代码,需要先安装 pre-commit(需要在 mmengine 目录下执行):
+
+```shell
+pip install -U pre-commit
+pre-commit install
+```
+
+检查 pre-commit 是否配置成功,并安装 `.pre-commit-config.yaml` 中的钩子:
+
+```shell
+pre-commit run --all-files
+```
+
+
+
+
+
+```{note}
+如果你是中国用户,由于网络原因,可能会出现安装失败的情况,这时可以使用国内源
+pre-commit install -c .pre-commit-config-zh-cn.yaml
+pre-commit run --all-files -c .pre-commit-config-zh-cn.yaml
+```
+
+如果安装过程被中断,可以重复执行 `pre-commit run ...` 继续安装。
+
+如果提交的代码不符合代码风格规范,pre-commit 会发出警告,并自动修复部分错误。
+
+
+
+如果我们想临时绕开 pre-commit 的检查提交一次代码,可以在 `git commit` 时加上 `--no-verify`(需要保证最后推送至远程仓库的代码能够通过 pre-commit 检查)。
+
+```shell
+git commit -m "xxx" --no-verify
+```
+
+#### 3. 创建开发分支
+
+安装完 pre-commit 之后,我们需要基于 master 创建开发分支,建议的分支命名规则为 `username/pr_name`。
+
+```shell
+git checkout -b yhc/refactor_contributing_doc
+```
+
+在后续的开发中,如果本地仓库的 master 分支落后于 upstream 的 master 分支,我们需要先拉取 upstream 的代码进行同步,再执行上面的命令
+
+```shell
+git pull upstream master
+```
+
+#### 4. 提交代码并在本地通过单元测试
+
+- MMEngine 引入了 mypy 来做静态类型检查,以增加代码的鲁棒性。因此我们在提交代码时,需要补充 Type Hints。具体规则可以参考[教程](https://zhuanlan.zhihu.com/p/519335398)。
+
+- 提交的代码同样需要通过单元测试
+
+ ```shell
+ # 通过全量单元测试
+ pytest tests
+
+ # 我们需要保证提交的代码能够通过修改模块的单元测试,以 runner 为例
+ pytest tests/test_runner/test_runner.py
+ ```
+
+ 如果你由于缺少依赖无法运行修改模块的单元测试,可以参考[指引-单元测试](#单元测试)
+
+- 如果修改/添加了文档,参考[指引](#文档渲染)确认文档渲染正常。
+
+#### 5. 推送代码到远程
+
+代码通过单元测试和 pre-commit 检查后,将代码推送到远程仓库,如果是第一次推送,可以在 `git push` 后加上 `-u` 参数以关联远程分支
+
+```shell
+git push -u origin {branch_name}
+```
+
+这样下次就可以直接使用 `git push` 命令推送代码了,而无需指定分支和远程仓库。
+
+#### 6. 提交拉取请求(PR)
+
+(1) 在 GitHub 的 Pull request 界面创建拉取请求
+
+
+(2) 根据指引修改 PR 描述,以便于其他开发者更好地理解你的修改
+
+
+
+描述规范详见[拉取请求规范](#拉取请求规范)
+
+
+
+**注意事项**
+
+(a) PR 描述应该包含修改理由、修改内容以及修改后带来的影响,并关联相关 Issue(具体方式见[文档](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue))
+
+(b) 如果是第一次为 OpenMMLab 做贡献,需要签署 CLA
+
+
+
+(c) 检查提交的 PR 是否通过 CI(集成测试)
+
+
+
+MMEngine 会在不同的平台(Linux、Window、Mac),基于不同版本的 Python、PyTorch、CUDA 对提交的代码进行单元测试,以保证代码的正确性,如果有任何一个没有通过,我们可点击上图中的 `Details` 来查看具体的测试信息,以便于我们修改代码。
+
+(3) 如果 PR 通过了 CI,那么就可以等待其他开发者的 review,并根据 reviewer 的意见,修改代码,并重复 [4](#4-提交代码并本地通过单元测试)-[5](#5-推送代码到远程) 步骤,直到 reviewer 同意合入 PR。
+
+
+
+所有 reviewer 同意合入 PR 后,我们会尽快将 PR 合并到主分支。
+
+#### 7. 解决冲突
+
+随着时间的推移,我们的代码库会不断更新,这时候,如果你的 PR 与主分支存在冲突,你需要解决冲突,解决冲突的方式有两种:
+
+```shell
+git fetch --all --prune
+git rebase upstream/master
+```
+
+或者
+
+```shell
+git fetch --all --prune
+git merge upstream/master
+```
+
+如果你非常善于处理冲突,那么可以使用 rebase 的方式来解决冲突,因为这能够保证你的 commit log 的整洁。如果你不太熟悉 `rebase` 的使用,那么可以使用 `merge` 的方式来解决冲突。
+
+### 指引
+
+#### 单元测试
+
+在提交修复代码错误或新增特性的拉取请求时,我们应该尽可能的让单元测试覆盖所有提交的代码,计算单元测试覆盖率的方法如下
+
+```shell
+python -m coverage run -m pytest /path/to/test_file
+python -m coverage html
+# check file in htmlcov/index.html
+```
+
+#### 文档渲染
+
+在提交修复代码错误或新增特性的拉取请求时,可能会需要修改/新增模块的 docstring。我们需要确认渲染后的文档样式是正确的。
+本地生成渲染后的文档的方法如下
+
+```shell
+pip install -r requirements/docs.txt
+cd docs/zh_cn/
+# or docs/en
+make html
+# check file in ./docs/zh_cn/_build/html/index.html
+```
+
+### Python 代码风格
+
+[PEP8](https://www.python.org/dev/peps/pep-0008/) 作为 OpenMMLab 算法库首选的代码规范,我们使用以下工具检查和格式化代码
+
+- [flake8](https://github.com/PyCQA/flake8): Python 官方发布的代码规范检查工具,是多个检查工具的封装
+- [isort](https://github.com/timothycrosley/isort): 自动调整模块导入顺序的工具
+- [yapf](https://github.com/google/yapf): Google 发布的代码规范检查工具
+- [codespell](https://github.com/codespell-project/codespell): 检查单词拼写是否有误
+- [mdformat](https://github.com/executablebooks/mdformat): 检查 markdown 文件的工具
+- [docformatter](https://github.com/myint/docformatter): 格式化 docstring 的工具
+
+yapf 和 isort 的配置可以在 [setup.cfg](./setup.cfg) 找到
+
+通过配置 [pre-commit hook](https://pre-commit.com/) ,我们可以在提交代码时自动检查和格式化 `flake8`、`yapf`、`isort`、`trailing whitespaces`、`markdown files`,修复 `end-of-files`、`double-quoted-strings`、`python-encoding-pragma`、`mixed-line-ending`,调整 `requirments.txt` 的包顺序。
+pre-commit 钩子的配置可以在 [.pre-commit-config](./.pre-commit-config.yaml) 找到。
+
+pre-commit 具体的安装使用方式见[拉取请求](#2-配置-pre-commit)。
+
+更具体的规范请参考 [OpenMMLab 代码规范](code_style.md)。
+
+### 拉取请求规范
+
+1. 使用 [pre-commit hook](https://pre-commit.com),尽量减少代码风格相关问题
+
+2. 一个`拉取请求`对应一个短期分支
+
+3. 粒度要细,一个`拉取请求`只做一件事情,避免超大的`拉取请求`
+
+ - Bad:实现 Faster R-CNN
+ - Acceptable:给 Faster R-CNN 添加一个 box head
+ - Good:给 box head 增加一个参数来支持自定义的 conv 层数
+
+4. 每次 Commit 时需要提供清晰且有意义 commit 信息
+
+5. 提供清晰且有意义的`拉取请求`描述
+
+ - 标题写明白任务名称,一般格式:\[Prefix\] Short description of the pull request (Suffix)
+ - prefix: 新增功能 \[Feature\], 修 bug \[Fix\], 文档相关 \[Docs\], 开发中 \[WIP\] (暂时不会被review)
+ - 描述里介绍`拉取请求`的主要修改内容,结果,以及对其他部分的影响, 参考`拉取请求`模板
+ - 关联相关的`议题` (issue) 和其他`拉取请求`
+
+6. 如果引入了其他三方库,或借鉴了三方库的代码,请确认他们的许可证和 MMEngine 兼容,并在借鉴的代码上补充 `This code is inspired from http://`
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/switch_language.md b/testbed/open-mmlab__mmengine/docs/zh_cn/switch_language.md
new file mode 100644
index 0000000000000000000000000000000000000000..e47b751e33928f59c4bf1aea94110493214754ea
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/switch_language.md
@@ -0,0 +1,3 @@
+## English
+
+## 简体中文
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/dataset.md b/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/dataset.md
new file mode 100644
index 0000000000000000000000000000000000000000..18e086f500046b44395fec6b2775f8c834094844
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/dataset.md
@@ -0,0 +1,198 @@
+# 数据集(Dataset)与数据加载器(DataLoader)
+
+```{hint}
+如果你没有接触过 PyTorch 的数据集与数据加载器,我们推荐先浏览 [PyTorch 官方教程](https://pytorch.org/tutorials/beginner/basics/data_tutorial.html)以了解一些基本概念
+```
+
+数据集与数据加载器是 MMEngine 中训练流程的必要组件,它们的概念来源于 PyTorch,并且在含义上与 PyTorch 保持一致。通常来说,数据集定义了数据的总体数量、读取方式以及预处理,而数据加载器则在不同的设置下迭代地加载数据,如批次大小(`batch_size`)、随机乱序(`shuffle`)、并行(`num_workers`)等。数据集经过数据加载器封装后构成了数据源。在本篇教程中,我们将按照从外(数据加载器)到内(数据集)的顺序,逐步介绍它们在 MMEngine 执行器中的用法,并给出一些常用示例。读完本篇教程,你将会:
+
+- 掌握如何在 MMEngine 的执行器中配置数据加载器
+- 学会在配置文件中使用已有(如 `torchvision`)数据集
+- 了解如何使用自己的数据集
+
+## 数据加载器详解
+
+在执行器(`Runner`)中,你可以分别配置以下 3 个参数来指定对应的数据加载器
+
+- `train_dataloader`:在 `Runner.train()` 中被使用,为模型提供训练数据
+- `val_dataloader`:在 `Runner.val()` 中被使用,也会在 `Runner.train()` 中每间隔一段时间被使用,用于模型的验证评测
+- `test_dataloader`:在 `Runner.test()` 中被使用,用于模型的测试
+
+MMEngine 完全支持 PyTorch 的原生 `DataLoader`,因此上述 3 个参数均可以直接传入构建好的 `DataLoader`,如[15分钟上手](../get_started/15_minutes.md)中的例子所示。同时,借助 MMEngine 的[注册机制](../advanced_tutorials/registry.md),以上参数也可以传入 `dict`,如下面代码(以下简称例 1)所示。字典中的键值与 `DataLoader` 的构造参数一一对应。
+
+```python
+runner = Runner(
+ train_dataloader=dict(
+ batch_size=32,
+ sampler=dict(
+ type='DefaultSampler',
+ shuffle=True),
+ dataset=torchvision.datasets.CIFAR10(...),
+ collate_fn=dict(type='default_collate')
+ )
+)
+```
+
+在这种情况下,数据加载器会在实际被用到时,在执行器内部被构建。
+
+```{note}
+关于 `DataLoader` 的更多可配置参数,你可以参考 [PyTorch API 文档](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader)
+```
+
+```{note}
+如果你对于构建的具体细节感兴趣,你可以参考 [build_dataloader](mmengine.runner.Runner.build_dataloader)
+```
+
+细心的你可能会发现,例 1 **并非**直接由[15分钟上手](../get_started/15_minutes.md)中的示例代码简单修改而来。你可能本以为将 `DataLoader` 简单替换为 `dict` 就可以无缝切换,但遗憾的是,基于注册机制构建时 MMEngine 会有一些隐式的转换和约定。我们将介绍其中的不同点,以避免你使用配置文件时产生不必要的疑惑。
+
+### sampler 与 shuffle
+
+与 15 分钟上手明显不同,例 1 中我们添加了 `sampler` 参数,这是由于在 MMEngine 中我们要求通过 `dict` 传入的数据加载器的配置**必须包含 `sampler` 参数**。同时,`shuffle` 参数也从 `DataLoader` 中移除,这是由于在 PyTorch 中 **`sampler` 与 `shuffle` 参数是互斥的**,见 [PyTorch API 文档](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader)。
+
+```{note}
+事实上,在 PyTorch 的实现中,`shuffle` 只是一个便利记号。当设置为 `True` 时 `DataLoader` 会自动在内部使用 `RandomSampler`
+```
+
+当考虑 `sampler` 时,例 1 代码**基本**可以认为等价于下面的代码块
+
+```python
+from mmengine.dataset import DefaultSampler
+
+dataset = torchvision.datasets.CIFAR10(...)
+sampler = DefaultSampler(dataset, shuffle=True)
+
+runner = Runner(
+ train_dataloader=DataLoader(
+ batch_size=32,
+ sampler=sampler,
+ dataset=dataset,
+ collate_fn=default_collate
+ )
+)
+```
+
+```{warning}
+上述代码的等价性只有在:1)使用单进程训练,以及 2)没有配置执行器的 `randomness` 参数时成立。这是由于使用 `dict` 传入 `sampler` 时,执行器会保证它在分布式训练环境设置完成后才被惰性构造,并接收到正确的随机种子。这两点在手动构造时需要额外工作且极易出错。因此,上述的写法只是一个示意而非推荐写法。我们**强烈建议 `sampler` 以 `dict` 的形式传入**,让执行器处理构造顺序,以避免出现问题。
+```
+
+### DefaultSampler
+
+上面例子可能会让你好奇:`DefaultSampler` 是什么,为什么要使用它,是否有其他选项?事实上,`DefaultSampler` 是 MMEngine 内置的一种采样器,它屏蔽了单进程训练与多进程训练的细节差异,使得单卡与多卡训练可以无缝切换。如果你有过使用 PyTorch `DistributedDataParallel` 的经验,你一定会对其中更换数据加载器的 `sampler` 参数有所印象。但在 MMEngine 中,这一细节通过 `DefaultSampler` 而被屏蔽。
+
+除了 `Dataset` 本身之外,`DefaultSampler` 还支持以下参数配置:
+
+- `shuffle` 设置为 `True` 时会打乱数据集的读取顺序
+- `seed` 打乱数据集所用的随机种子,通常不需要在此手动设置,会从 `Runner` 的 `randomness` 入参中读取
+- `round_up` 设置为 `True` 时,与 PyTorch `DataLoader` 中设置 `drop_last=False` 行为一致。如果你在迁移 PyTorch 的项目,你可能需要注意这一点。
+
+```{note}
+更多关于 `DefaultSampler` 的内容可以参考 [API 文档](mmengine.dataset.DefaultSampler)
+```
+
+`DefaultSampler` 适用于绝大部分情况,并且我们保证在执行器中使用它时,随机数等容易出错的细节都被正确地处理,防止你陷入多进程训练的常见陷阱。如果你想要使用基于迭代次数 (iteration-based) 的训练流程,你也许会对 [InfiniteSampler](mmengine.dataset.InfiniteSampler) 感兴趣。如果你有更多的进阶需求,你可能会想要参考上述两个内置 `sampler` 的代码,实现一个自定义的 `sampler` 并注册到 `DATA_SAMPLERS` 根注册器中。
+
+```python
+@DATA_SAMPLERS.register_module()
+class MySampler(Sampler):
+ pass
+
+runner = Runner(
+ train_dataloader=dict(
+ sampler=dict(type='MySampler'),
+ ...
+ )
+)
+```
+
+### 不起眼的 collate_fn
+
+PyTorch 的 `DataLoader` 中,`collate_fn` 这一参数常常被使用者忽略,但在 MMEngine 中你需要额外注意:当你传入 `dict` 来构造数据加载器时,MMEngine 会默认使用内置的 [pseudo_collate](mmengine.dataset.pseudo_collate),这一点明显区别于 PyTorch 默认的 [default_collate](https://pytorch.org/docs/stable/data.html#torch.utils.data.default_collate)。因此,当你迁移 PyTorch 项目时,需要在配置文件中手动指明 `collate_fn` 以保持行为一致。
+
+```{note}
+MMEngine 中使用 `pseudo_collate` 作为默认值,主要是由于历史兼容性原因,你可以不必过于深究,只需了解并避免错误使用即可。
+```
+
+MMengine 中提供了 2 种内置的 `collate_fn`:
+
+- `pseudo_collate`,缺省时的默认参数。它不会将数据沿着 `batch` 的维度合并。详细说明可以参考 [pseudo_collate](mmengine.dataset.pseudo_collate)
+- `default_collate`,与 PyTorch 中的 `default_collate` 行为几乎完全一致,会将数据转化为 `Tensor` 并沿着 `batch` 维度合并。一些细微不同和详细说明可以参考 [default_collate](mmengine.dataset.default_collate)
+
+如果你想要使用自定义的 `collate_fn`,你也可以将它注册到 `COLLATE_FUNCTIONS` 根注册器中来使用
+
+```python
+@COLLATE_FUNCTIONS.register_module()
+def my_collate_func(data_batch: Sequence) -> Any:
+ pass
+
+runner = Runner(
+ train_dataloader=dict(
+ ...
+ collate_fn=dict(type='my_collate_func')
+ )
+)
+```
+
+## 数据集详解
+
+数据集通常定义了数据的数量、读取方式与预处理,并作为参数传递给数据加载器供后者分批次加载。由于我们使用了 PyTorch 的 `DataLoader`,因此数据集也自然与 PyTorch `Dataset` 完全兼容。同时得益于注册机制,当数据加载器使用 `dict` 在执行器内部构建时,`dataset` 参数也可以使用 `dict` 传入并在内部被构建。这一点使得编写配置文件成为可能。
+
+### 使用 torchvision 数据集
+
+`torchvision` 中提供了丰富的公开数据集,它们都可以在 MMEngine 中直接使用,例如 [15 分钟上手](../get_started/15_minutes.md)中的示例代码就使用了其中的 `Cifar10` 数据集,并且使用了 `torchvision` 中内置的数据预处理模块。
+
+但是,当需要将上述示例转换为配置文件时,你需要对 `torchvision` 中的数据集进行额外的注册。如果你同时用到了 `torchvision` 中的数据预处理模块,那么你也需要编写额外代码来对它们进行注册和构建。下面我们将给出一个等效的例子来展示如何做到这一点。
+
+```python
+import torchvision.transforms as tvt
+from mmengine.registry import DATASETS, TRANSFORMS
+from mmengine.dataset.base_dataset import Compose
+
+# 注册 torchvision 的 CIFAR10 数据集
+# 数据预处理也需要在此一起构建
+@DATASETS.register_module(name='Cifar10', force=False)
+def build_torchvision_cifar10(transform=None, **kwargs):
+ if isinstance(transform, dict):
+ transform = [transform]
+ if isinstance(transform, (list, tuple)):
+ transform = Compose(transform)
+ return torchvision.datasets.CIFAR10(**kwargs, transform=transform)
+
+# 注册 torchvision 中用到的数据预处理模块
+DATA_TRANSFORMS.register_module('RandomCrop', module=tvt.RandomCrop)
+DATA_TRANSFORMS.register_module('RandomHorizontalFlip', module=tvt.RandomHorizontalFlip)
+DATA_TRANSFORMS.register_module('ToTensor', module=tvt.ToTensor)
+DATA_TRANSFORMS.register_module('Normalize', module=tvt.Normalize)
+
+# 在 Runner 中使用
+runner = Runner(
+ train_dataloader=dict(
+ batch_size=32,
+ sampler=dict(
+ type='DefaultSampler',
+ shuffle=True),
+ dataset=dict(type='Cifar10',
+ root='data/cifar10',
+ train=True,
+ download=True,
+ transform=[
+ dict(type='RandomCrop', size=32, padding=4),
+ dict(type='RandomHorizontalFlip'),
+ dict(type='ToTensor'),
+ dict(type='Normalize', **norm_cfg)])
+ )
+)
+```
+
+```{note}
+上述例子中大量使用了[注册机制](../advanced_tutorials/registry.md),并且用到了 MMEngine 中的 [Compose](mmengine.dataset.Compose)。如果你急需在配置文件中使用 `torchvision` 数据集,你可以参考上述代码并略作修改。但我们更加推荐你有需要时在下游库(如 [MMDet](https://github.com/open-mmlab/mmdetection) 和 [MMCls](https://github.com/open-mmlab/mmclassification) 等)中寻找对应的数据集实现,从而获得更好的使用体验。
+```
+
+### 自定义数据集
+
+你可以像使用 PyTorch 一样,自由地定义自己的数据集,或将之前 PyTorch 项目中的数据集拷贝过来。如果你想要了解如何自定义数据集,可以参考 [PyTorch 官方教程](https://pytorch.org/tutorials/beginner/basics/data_tutorial.html#creating-a-custom-dataset-for-your-files)
+
+### 使用 MMEngine 的数据集基类
+
+除了直接使用 PyTorch 的 `Dataset` 来自定义数据集之外,你也可以使用 MMEngine 内置的 `BaseDataset`,参考[数据集基类](../advanced_tutorials/basedataset.md)文档。它对标注文件的格式做了一些约定,使得数据接口更加统一、多任务训练更加便捷。同时,数据集基类也可以轻松地搭配内置的[数据变换](../advanced_tutorials/data_transform.md)使用,减轻你从头搭建训练流程的工作量。
+
+目前,`BaseDataset` 已经在 OpenMMLab 2.0 系列的下游仓库中被广泛使用。
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/evaluation.md b/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/evaluation.md
new file mode 100644
index 0000000000000000000000000000000000000000..552fa032a9f0c865b97e55cbf65e6d5edbfeea27
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/evaluation.md
@@ -0,0 +1,136 @@
+# 模型精度评测(Evaluation)
+
+在模型验证和模型测试中,通常需要对模型精度做定量评测。我们可以通过在配置文件中指定评测指标(Metric)来实现这一功能。
+
+## 在模型训练或测试中进行评测
+
+### 使用单个评测指标
+
+在基于 MMEngine 进行模型训练或测试时,用户只需要在配置文件中通过 `val_evaluator` 和 `test_evaluator` 2 个字段分别指定模型验证和测试阶段的评测指标即可。例如,用户在使用 [MMClassification](https://github.com/open-mmlab/mmclassification) 训练分类模型时,希望在模型验证阶段评测 top-1 和 top-5 分类正确率,可以按以下方式配置:
+
+```python
+val_evaluator = dict(type='Accuracy', top_k=(1, 5)) # 使用分类正确率评测指标
+```
+
+关于具体评测指标的参数设置,用户可以查阅相关算法库的文档。如上例中的 [Accuracy 文档](https://mmclassification.readthedocs.io/en/1.x/api/generated/mmcls.evaluation.Accuracy.html#mmcls.evaluation.Accuracy)。
+
+### 使用多个评测指标
+
+如果需要同时评测多个指标,也可以将 `val_evaluator` 或 `test_evaluator` 设置为一个列表,其中每一项为一个评测指标的配置信息。例如,在使用 [MMDetection](https://github.com/open-mmlab/mmdetection) 训练全景分割模型时,希望在模型测试阶段同时评测模型的目标检测(COCO AP/AR)和全景分割精度,可以按以下方式配置:
+
+```python
+test_evaluator = [
+ # 目标检测指标
+ dict(
+ type='CocoMetric',
+ metric=['bbox', 'segm'],
+ ann_file='annotations/instances_val2017.json',
+ ),
+ # 全景分割指标
+ dict(
+ type='CocoPanopticMetric',
+ ann_file='annotations/panoptic_val2017.json',
+ seg_prefix='annotations/panoptic_val2017',
+ )
+]
+```
+
+### 自定义评测指标
+
+如果算法库中提供的常用评测指标无法满足需求,用户也可以增加自定义的评测指标。我们以简化的分类正确率为例,介绍实现自定义评测指标的方法:
+
+1. 在定义新的评测指标类时,需要继承基类 [`BaseMetric`](mmengine.evaluator.BaseMetric)(关于该基类的介绍,可以参考[设计文档](../design/evaluation.md))。此外,评测指标类需要用注册器 `METRICS` 进行注册(关于注册器的说明请参考 [Registry 文档](./registry.md))。
+
+2. 实现 `process()` 方法。该方法有 2 个输入参数,分别是一个批次的测试数据样本 `data_batch` 和模型预测结果 `data_samples`。我们从中分别取出样本类别标签和分类预测结果,并存放在 `self.results` 中。
+
+3. 实现 `compute_metrics()` 方法。该方法有 1 个输入参数 `results`,里面存放了所有批次测试数据经过 `process()` 方法处理后得到的结果。从中取出样本类别标签和分类预测结果,即可计算得到分类正确率 `acc`。最终,将计算得到的评测指标以字典的形式返回。
+
+4. (可选)可以为类属性 `default_prefix` 赋值。该属性会自动作为输出的评测指标名前缀(如 `defaut_prefix='my_metric'`,则实际输出的评测指标名为 `'my_metric/acc'`),用以进一步区分不同的评测指标。该前缀也可以在配置文件中通过 `prefix` 参数改写。我们建议在 docstring 中说明该评测指标类的 `default_prefix` 值以及所有的返回指标名称。
+
+具体实现如下:
+
+```python
+from mmengine.evaluator import BaseMetric
+from mmengine.registry import METRICS
+
+import numpy as np
+
+
+@METRICS.register_module() # 将 Accuracy 类注册到 METRICS 注册器
+class SimpleAccuracy(BaseMetric):
+ """ Accuracy Evaluator
+
+ Default prefix: ACC
+
+ Metrics:
+ - accuracy (float): classification accuracy
+ """
+
+ default_prefix = 'ACC' # 设置 default_prefix
+
+ def process(self, data_batch: Sequence[dict], data_samples: Sequence[dict]):
+ """Process one batch of data and predictions. The processed
+ Results should be stored in `self.results`, which will be used
+ to compute the metrics when all batches have been processed.
+
+ Args:
+ data_batch (Sequence[Tuple[Any, dict]]): A batch of data
+ from the dataloader.
+ data_samples (Sequence[dict]): A batch of outputs from
+ the model.
+ """
+
+ # 取出分类预测结果和类别标签
+ result = {
+ 'pred': data_samples['pred_label'],
+ 'gt': data_samples['data_sample']['gt_label']
+ }
+
+ # 将当前 batch 的结果存进 self.results
+ self.results.append(result)
+
+ def compute_metrics(self, results: List):
+ """Compute the metrics from processed results.
+
+ Args:
+ results (dict): The processed results of each batch.
+
+ Returns:
+ Dict: The computed metrics. The keys are the names of the metrics,
+ and the values are corresponding results.
+ """
+
+ # 汇总所有样本的分类预测结果和类别标签
+ preds = np.concatenate([res['pred'] for res in results])
+ gts = np.concatenate([res['gt'] for res in results])
+
+ # 计算分类正确率
+ acc = (preds == gts).sum() / preds.size
+
+ # 返回评测指标结果
+ return {'accuracy': acc}
+```
+
+## 使用离线结果进行评测
+
+另一种常见的模型评测方式,是利用提前保存在文件中的模型预测结果进行离线评测。此时,用户需要手动构建**评测器**,并调用评测器的相应接口完成评测。关于离线评测的详细说明,以及评测器和评测指标的关系,可以参考[设计文档](/docs/zh_cn/design/evaluation.md)。我们仅在此给出一个离线评测示例:
+
+```python
+from mmengine.evaluator import Evaluator
+from mmengine.fileio import load
+
+# 构建评测器。参数 `metrics` 为评测指标配置
+evaluator = Evaluator(metrics=dict(type='Accuracy', top_k=(1, 5)))
+
+# 从文件中读取测试数据。数据格式需要参考具使用的 metric。
+data = load('test_data.pkl')
+
+# 从文件中读取模型预测结果。该结果由待评测算法在测试数据集上推理得到。
+# 数据格式需要参考具使用的 metric。
+data_samples = load('prediction.pkl')
+
+# 调用评测器离线评测接口,得到评测结果
+# chunk_size 表示每次处理的样本数量,可根据内存大小调整
+results = evaluator.offline_evaluate(data, data_samples, chunk_size=128)
+
+```
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/hook.md b/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/hook.md
new file mode 100644
index 0000000000000000000000000000000000000000..dab8c55f229905051e5dfe71c30926ea201956e6
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/hook.md
@@ -0,0 +1,265 @@
+# 钩子(Hook)
+
+钩子编程是一种编程模式,是指在程序的一个或者多个位置设置位点(挂载点),当程序运行至某个位点时,会自动调用运行时注册到位点的所有方法。钩子编程可以提高程序的灵活性和拓展性,用户将自定义的方法注册到位点便可被调用而无需修改程序中的代码。
+
+## 内置钩子
+
+MMEngine 提供了很多内置的钩子,将钩子分为两类,分别是默认钩子以及自定义钩子,前者表示会默认往执行器注册,后者表示需要用户自己注册。
+
+每个钩子都有对应的优先级,在同一位点,钩子的优先级越高,越早被执行器调用,如果优先级一样,被调用的顺序和钩子注册的顺序一致。优先级列表如下:
+
+- HIGHEST (0)
+- VERY_HIGH (10)
+- HIGH (30)
+- ABOVE_NORMAL (40)
+- NORMAL (50)
+- BELOW_NORMAL (60)
+- LOW (70)
+- VERY_LOW (90)
+- LOWEST (100)
+
+**默认钩子**
+
+| 名称 | 用途 | 优先级 |
+| :-----------------------------------------: | :--------------------------------: | :---------------: |
+| [RuntimeInfoHook](#runtimeinfohook) | 往 message hub 更新运行时信息 | VERY_HIGH (10) |
+| [IterTimerHook](#itertimerhook) | 统计迭代耗时 | NORMAL (50) |
+| [DistSamplerSeedHook](#distsamplerseedhook) | 确保分布式 Sampler 的 shuffle 生效 | NORMAL (50) |
+| [LoggerHook](#loggerhook) | 打印日志 | BELOW_NORMAL (60) |
+| [ParamSchedulerHook](#paramschedulerhook) | 调用 ParamScheduler 的 step 方法 | LOW (70) |
+| [CheckpointHook](#checkpointhook) | 按指定间隔保存权重 | VERY_LOW (90) |
+
+**自定义钩子**
+
+| 名称 | 用途 | 优先级 |
+| :---------------------------------: | :-------------------: | :---------: |
+| [EMAHook](#emahook) | 模型参数指数滑动平均 | NORMAL (50) |
+| [EmptyCacheHook](#emptycachehook) | PyTorch CUDA 缓存清理 | NORMAL (50) |
+| [SyncBuffersHook](#syncbuffershook) | 同步模型的 buffer | NORMAL (50) |
+
+```{note}
+不建议修改默认钩子的优先级,因为优先级低的钩子可能会依赖优先级高的钩子。例如 CheckpointHook 的优先级需要比 ParamSchedulerHook 低,这样保存的优化器状态才是正确的状态。另外,自定义钩子的优先级默认为 `NORMAL (50)`。
+```
+
+两种钩子在执行器中的设置不同,默认钩子的配置传给执行器的 `default_hooks` 参数,自定义钩子的配置传给 `custom_hooks` 参数,如下所示:
+
+```python
+from mmengine.runner import Runner
+
+default_hooks = dict(
+ runtime_info=dict(type='RuntimeInfoHook'),
+ timer=dict(type='IterTimerHook'),
+ sampler_seed=dict(type='DistSamplerSeedHook'),
+ logger=dict(type='LoggerHook'),
+ param_scheduler=dict(type='ParamSchedulerHook'),
+ checkpoint=dict(type='CheckpointHook', interval=1),
+)
+
+custom_hooks = [dict(type='EmptyCacheHook')]
+
+runner = Runner(default_hooks=default_hooks, custom_hooks=custom_hooks, ...)
+runner.train()
+```
+
+下面逐一介绍 MMEngine 中内置钩子的用法。
+
+### CheckpointHook
+
+[CheckpointHook](mmengine.hooks.CheckpointHook) 按照给定间隔保存模型的权重,如果是分布式多卡训练,则只有主(master)进程会保存权重。`CheckpointHook` 的主要功能如下:
+
+- 按照间隔保存权重,支持按 epoch 数或者 iteration 数保存权重
+- 保存最新的多个权重
+- 保存最优权重
+- 指定保存权重的路径
+
+如需了解其他功能,请阅读 [CheckpointHook API 文档](mmengine.hooks.CheckpointHook)。
+
+下面介绍上面提到的 4 个功能。
+
+- 按照间隔保存权重,支持按 epoch 数或者 iteration 数保存权重
+
+ 假设我们一共训练 20 个 epoch 并希望每隔 5 个 epoch 保存一次权重,下面的配置即可帮我们实现该需求。
+
+ ```python
+ # by_epoch 的默认值为 True
+ default_hooks = dict(checkpoint=dict(type='CheckpointHook', interval=5, by_epoch=True))
+ ```
+
+ 如果想以迭代次数作为保存间隔,则可以将 `by_epoch` 设为 False,`interval=5` 则表示每迭代 5 次保存一次权重。
+
+ ```python
+ default_hooks = dict(checkpoint=dict(type='CheckpointHook', interval=5, by_epoch=False))
+ ```
+
+- 保存最新的多个权重
+
+ 如果只想保存一定数量的权重,可以通过设置 `max_keep_ckpts` 参数实现最多保存 `max_keep_ckpts` 个权重,当保存的权重数超过 `max_keep_ckpts` 时,前面的权重会被删除。
+
+ ```python
+ default_hooks = dict(checkpoint=dict(type='CheckpointHook', interval=5, max_keep_ckpts=2))
+ ```
+
+ 上述例子表示,假如一共训练 20 个 epoch,那么会在第 5, 10, 15, 20 个 epoch 保存模型,但是在第 15 个 epoch 的时候会删除第 5 个 epoch 保存的权重,在第 20 个 epoch 的时候会删除第 10 个 epoch 的权重,最终只有第 15 和第 20 个 epoch 的权重才会被保存。
+
+- 保存最优权重
+
+ 如果想要保存训练过程验证集的最优权重,可以设置 `save_best` 参数,如果设置为 `'auto'`,则会根据验证集的第一个评价指标(验证集返回的评价指标是一个有序字典)判断当前权重是否最优。
+
+ ```python
+ default_hooks = dict(checkpoint=dict(type='CheckpointHook', save_best='auto'))
+ ```
+
+ 也可以直接指定 `save_best` 的值为评价指标,例如在分类任务中,可以指定为 `save_best='top-1'`,则会根据 `'top-1'` 的值判断当前权重是否最优。
+
+ 除了 `save_best` 参数,和保存最优权重相关的参数还有 `rule`,`greater_keys` 和 `less_keys`,这三者用来判断 `save_best` 的值是越大越好还是越小越好。例如指定了 `save_best='top-1'`,可以指定 `rule='greater'`,则表示该值越大表示权重越好。
+
+- 指定保存权重的路径
+
+ 权重默认保存在工作目录(work_dir),但可以通过设置 `out_dir` 改变保存路径。
+
+ ```python
+ default_hooks = dict(checkpoint=dict(type='CheckpointHook', interval=5, out_dir='/path/of/directory'))
+ ```
+
+### LoggerHook
+
+[LoggerHook](mmengine.hooks.LoggerHook) 负责收集日志并把日志输出到终端或者输出到文件、TensorBoard 等后端。
+
+如果我们希望每迭代 20 次就输出(或保存)一次日志,我们可以设置 `interval` 参数,配置如下:
+
+```python
+default_hooks = dict(logger=dict(type='LoggerHook', interval=20))
+```
+
+如果你对日志的管理感兴趣,可以阅读[记录日志(logging)](logging.md)。
+
+### ParamSchedulerHook
+
+[ParamSchedulerHook](mmengine.hooks.ParamSchedulerHook) 遍历执行器的所有优化器参数调整策略(Parameter Scheduler)并逐个调用 step 方法更新优化器的参数。如需了解优化器参数调整策略的用法请阅读[文档](../tutorials/param_scheduler.md)。`ParamSchedulerHook` 默认注册到执行器并且没有可配置的参数,所以无需对其做任何配置。
+
+### IterTimerHook
+
+[IterTimerHook](mmengine.hooks.IterTimerHook) 用于记录加载数据的时间以及迭代一次耗费的时间。`IterTimerHook` 默认注册到执行器并且没有可配置的参数,所以无需对其做任何配置。
+
+### DistSamplerSeedHook
+
+[DistSamplerSeedHook](mmengine.hooks.DistSamplerSeedHook) 在分布式训练时调用 Sampler 的 step 方法以确保 shuffle 参数生效。`DistSamplerSeedHook` 默认注册到执行器并且没有可配置的参数,所以无需对其做任何配置。
+
+### RuntimeInfoHook
+
+[RuntimeInfoHook](mmengine.hooks.RuntimeInfoHook) 会在执行器的不同钩子位点将当前的运行时信息(如 epoch、iter、max_epochs、max_iters、lr、metrics等)更新至 message hub 中,以便其他无法访问执行器的模块能够获取到这些信息。`RuntimeInfoHook` 默认注册到执行器并且没有可配置的参数,所以无需对其做任何配置。
+
+### EMAHook
+
+[EMAHook](mmengine.hooks.EMAHook) 在训练过程中对模型执行指数滑动平均操作,目的是提高模型的鲁棒性。注意:指数滑动平均生成的模型只用于验证和测试,不影响训练。
+
+```python
+custom_hooks = [dict(type='EMAHook')]
+runner = Runner(custom_hooks=custom_hooks, ...)
+runner.train()
+```
+
+`EMAHook` 默认使用 `ExponentialMovingAverage`,可选值还有 `StochasticWeightAverage` 和 `MomentumAnnealingEMA`。可以通过设置 `ema_type` 使用其他的平均策略。
+
+```python
+custom_hooks = [dict(type='EMAHook', ema_type='StochasticWeightAverage')]
+```
+
+更多用法请阅读 [EMAHook API 文档](mmengine.hooks.EMAHook)。
+
+### EmptyCacheHook
+
+[EmptyCacheHook](mmengine.hooks.EmptyCacheHook) 调用 `torch.cuda.empty_cache()` 释放未被使用的显存。可以通过设置 `before_epoch`, `after_iter` 以及 `after_epoch` 参数控制释显存的时机,第一个参数表示在每个 epoch 开始之前,第二参数表示在每次迭代之后,第三个参数表示在每个 epoch 之后。
+
+```python
+# 每一个 epoch 结束都会执行释放操作
+custom_hooks = [dict(type='EmptyCacheHook', after_epoch=True)]
+runner = Runner(custom_hooks=custom_hooks, ...)
+runner.train()
+```
+
+### SyncBuffersHook
+
+[SyncBuffersHook](mmengine.hooks.SyncBuffersHook) 在分布式训练每一轮(epoch)结束时同步模型的 buffer,例如 BN 层的 `running_mean` 以及 `running_var`。
+
+```python
+custom_hooks = [dict(type='SyncBuffersHook')]
+runner = Runner(custom_hooks=custom_hooks, ...)
+runner.train()
+```
+
+## 自定义钩子
+
+如果 MMEngine 提供的默认钩子不能满足需求,用户可以自定义钩子,只需继承钩子基类并重写相应的位点方法。
+
+例如,如果希望在训练的过程中判断损失值是否有效,如果值为无穷大则无效,我们可以在每次迭代后判断损失值是否无穷大,因此只需重写 `after_train_iter` 位点。
+
+```python
+import torch
+
+from mmengine.registry import HOOKS
+from mmengine.hooks import Hook
+
+
+@HOOKS.register_module()
+class CheckInvalidLossHook(Hook):
+ """Check invalid loss hook.
+
+ This hook will regularly check whether the loss is valid
+ during training.
+
+ Args:
+ interval (int): Checking interval (every k iterations).
+ Defaults to 50.
+ """
+
+ def __init__(self, interval=50):
+ self.interval = interval
+
+ def after_train_iter(self, runner, batch_idx, data_batch=None, outputs=None):
+ """All subclasses should override this method, if they need any
+ operations after each training iteration.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ batch_idx (int): The index of the current batch in the train loop.
+ data_batch (dict or tuple or list, optional): Data from dataloader.
+ outputs (dict, optional): Outputs from model.
+ """
+ if self.every_n_train_iters(runner, self.interval):
+ assert torch.isfinite(outputs['loss']),\
+ runner.logger.info('loss become infinite or NaN!')
+```
+
+我们只需将钩子的配置传给执行器的 `custom_hooks` 的参数,执行器初始化的时候会注册钩子,
+
+```python
+from mmengine.runner import Runner
+
+custom_hooks = dict(
+ dict(type='CheckInvalidLossHook', interval=50)
+)
+runner = Runner(custom_hooks=custom_hooks, ...) # 实例化执行器,主要完成环境的初始化以及各种模块的构建
+runner.train() # 执行器开始训练
+```
+
+便会在每次模型前向计算后检查损失值。
+
+注意,自定义钩子的优先级默认为 `NORMAL (50)`,如果想改变钩子的优先级,则可以在配置中设置 priority 字段。
+
+```python
+custom_hooks = dict(
+ dict(type='CheckInvalidLossHook', interval=50, priority='ABOVE_NORMAL')
+)
+```
+
+也可以在定义类时给定优先级
+
+```python
+@HOOKS.register_module()
+class CheckInvalidLossHook(Hook):
+
+ priority = 'ABOVE_NORMAL'
+```
+
+你可能还想阅读[钩子的设计](../design/hook.md)或者[钩子的 API 文档](mmengine.hooks)。
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/model.md b/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/model.md
new file mode 100644
index 0000000000000000000000000000000000000000..94474de1b5d7f065ca878eadce850c26aff138be
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/model.md
@@ -0,0 +1,197 @@
+# 模型(Model)
+
+## Runner 与 model
+
+在 [Runner 教程的基本数据流](./runner.md#基本数据流)中我们提到,DataLoader、model 和 evaluator 之间的数据流通遵循了一些规则,我们先来回顾一下基本数据流的伪代码:
+
+```python
+# 训练过程
+for data_batch in train_dataloader:
+ data_batch = model.data_preprocessor(data_batch, training=True)
+ if isinstance(data_batch, dict):
+ losses = model(**data_batch, mode='loss')
+ elif isinstance(data_batch, (list, tuple)):
+ losses = model(*data_batch, mode='loss')
+ else:
+ raise TypeError()
+# 验证过程
+for data_batch in val_dataloader:
+ data_batch = model.data_preprocessor(data_batch, training=False)
+ if isinstance(data_batch, dict):
+ outputs = model(**data_batch, mode='predict')
+ elif isinstance(data_batch, (list, tuple)):
+ outputs = model(**data_batch, mode='predict')
+ else:
+ raise TypeError()
+ evaluator.process(data_samples=outputs, data_batch=data_batch)
+metrics = evaluator.evaluate(len(val_dataloader.dataset))
+```
+
+在 Runner 的教程中,我们简单介绍了模型和前后组件之间的数据流通关系,提到了 `data_preprocessor` 的概念,对 model 有了一定的了解。然而在 Runner 实际运行的过程中,模型的功能和调用关系,其复杂程度远超上述伪代码。为了让你能够不感知模型和外部组件的复杂关系,进而聚焦精力到算法本身,我们设计了 [BaseModel](mmengine.model.BaseModel)。大多数情况下你只需要让 model 继承 `BaseModel`,并按照要求实现 `forward` 接口,就能完成训练、测试、验证的逻辑。
+
+在继续阅读模型教程之前,我们先抛出两个问题,希望你在阅读完 model 教程后能够找到相应的答案:
+
+1. 我们在什么位置更新模型参数?如果我有一些非常复杂的参数更新逻辑,又该如何实现?
+2. 为什么要有 data_preprocessor 的概念?它又可以实现哪些功能?
+
+## 接口约定
+
+在训练深度学习任务时,我们通常需要定义一个模型来实现算法的主体。在基于 MMEngine 开发时,定义的模型由执行器管理,且需要实现 `train_step`、`val_step` 和 `test_step` 方法。
+对于检测、识别、分割一类的深度学习任务,上述方法通常为标准的流程,例如在 `train_step` 里更新参数,返回损失;`val_step` 和 `test_step` 返回预测结果。因此 MMEngine 抽象出模型基类 [BaseModel](mmengine.model.BaseModel),实现了上述接口的标准流程。
+
+得益于 `BaseModel` 我们只需要让模型继承自模型基类,并按照一定的规范实现 `forward`,就能让模型在执行器中运行起来。
+
+```{note}
+模型基类继承自[模块基类](../advanced_tutorials/initialize.md),能够通过配置 `init_cfg` 灵活地选择初始化方式。
+```
+
+[**forward**](mmengine.model.BaseModel.forward): `forward` 的入参需通常需要和 [DataLoader](https://pytorch.org/tutorials/beginner/basics/data_tutorial.html) 的输出保持一致 (自定义[数据预处理器](#数据预处理器datapreprocessor)除外),如果 `DataLoader` 返回元组类型的数据 `data`,`forward` 需要能够接受 `*data` 的解包后的参数;如果返回字典类型的数据 `data`,`forward` 需要能够接受 `**data` 解包后的参数。 `mode` 参数用于控制 forward 的返回结果:
+
+- `mode='loss'`:`loss` 模式通常在训练阶段启用,并返回一个损失字典。损失字典的 key-value 分别为损失名和可微的 `torch.Tensor`。字典中记录的损失会被用于更新参数和记录日志。模型基类会在 `train_step` 方法中调用该模式的 `forward`。
+- `mode='predict'`: `predict` 模式通常在验证、测试阶段启用,并返回列表/元组形式的预测结果,预测结果需要和 [process](mmengine.evaluator.Evaluator.process) 接口的参数相匹配。OpenMMLab 系列算法对 `predict` 模式的输出有着更加严格的约定,需要输出列表形式的[数据元素](../advanced_tutorials/data_element.md)。模型基类会在 `val_step`,`test_step` 方法中调用该模式的 `forward`。
+- `mode='tensor'`:`tensor` 和 `predict` 模式均返回模型的前向推理结果,区别在于 `tensor` 模式下,`forward` 会返回未经后处理的张量,例如返回未经非极大值抑制(nms)处理的检测结果,返回未经 `argmax` 处理的分类结果。我们可以基于 `tensor` 模式的结果进行自定义的后处理。
+
+[**train_step**](mmengine.model.BaseModel.train_step): 执行 `forward` 方法的 `loss` 分支,得到损失字典。模型基类基于[优化器封装](./optim_wrapper.md) 实现了标准的梯度计算、参数更新、梯度清零流程。其等效伪代码如下:
+
+```python
+def train_step(self, data, optim_wrapper):
+ data = self.data_preprocessor(data, training=True) # 按下不表,详见数据与处理器一节
+ loss = self(**data, mode='loss') # loss 模式,返回损失字典,假设 data 是字典,使用 ** 进行解析。事实上 train_step 兼容 tuple 和 dict 类型的输入。
+ parsed_losses, log_vars = self.parse_losses() # 解析损失字典,返回可以 backward 的损失以及可以被日志记录的损失
+ optim_wrapper.update_params(parsed_losses) # 更新参数
+ return log_vars
+```
+
+[**val_step**](mmengine.model.BaseModel.val_step): 执行 `forward` 方法的 `predict` 分支,返回预测结果:
+
+```python
+def val_step(self, data, optim_wrapper):
+ data = self.data_preprocessor(data, training=False)
+ outputs = self(**data, mode='predict') # 预测模式,返回预测结果
+ return outputs
+```
+
+[**test_step**](mmengine.model.BaseModel.test_step): 同 `val_step`
+
+看到这我们就可以给出一份 **基本数据流伪代码 plus**:
+
+```python
+# 训练过程
+for data_batch in train_dataloader:
+ loss_dict = model.train_step(data_batch)
+# 验证过程
+for data_batch in val_dataloader:
+ preds = model.test_step(data_batch)
+ evaluator.process(data_samples=outputs, data_batch=data_batch)
+metrics = evaluator.evaluate(len(val_dataloader.dataset))
+```
+
+没错,抛开 Hook 不谈,[loop](mmengine.runner.loop) 调用 model 的过程和上述代码一模一样!看到这,我们再回过头去看 [15 分钟上手 MMEngine](../get_started/15_minutes.md) 里的模型定义部分,就有一种看山不是山的感觉:
+
+```python
+import torch.nn.functional as F
+import torchvision
+from mmengine.model import BaseModel
+
+class MMResNet50(BaseModel):
+ def __init__(self):
+ super().__init__()
+ self.resnet = torchvision.models.resnet50()
+
+ def forward(self, imgs, labels, mode):
+ x = self.resnet(imgs)
+ if mode == 'loss':
+ return {'loss': F.cross_entropy(x, labels)}
+ elif mode == 'predict':
+ return x, labels
+
+ # 下面的 3 个方法已在 BaseModel 实现,这里列出是为了
+ # 解释调用过程
+ def train_step(self, data, optim_wrapper):
+ data = self.data_preprocessor(data)
+ loss = self(*data, mode='loss') # CIFAR10 返回 tuple,因此用 * 解包
+ parsed_losses, log_vars = self.parse_losses()
+ optim_wrapper.update_params(parsed_losses)
+ return log_vars
+
+ def val_step(self, data, optim_wrapper):
+ data = self.data_preprocessor(data)
+ outputs = self(*data, mode='predict')
+ return outputs
+
+ def test_step(self, data, optim_wrapper):
+ data = self.data_preprocessor(data)
+ outputs = self(*data, mode='predict')
+ return outputs
+```
+
+看到这里,相信你对数据流有了更加深刻的理解,也能够回答 [Runner 与 model](#runner-与-model) 里提到的第一个问题:
+
+`BaseModel.train_step` 里实现了默认的参数更新逻辑,如果我们想实现自定义的参数更新流程,可以重写 `train_step` 方法。但是需要注意的是,我们需要保证 `train_step` 最后能够返回损失字典。
+
+## 数据预处理器(DataPreprocessor)
+
+如果你的电脑配有 GPU(或其他能够加速训练的硬件,如 MPS、IPU 等),并且运行了 [15 分钟上手 MMEngine](../get_started/15_minutes.md) 的代码示例,你会发现程序是在 GPU 上运行的,那么 `MMEngine` 是在何时把数据和模型从 CPU 搬运到 GPU 的呢?
+
+事实上,执行器会在构造阶段将模型搬运到指定设备,而数据则会在上一节提到的 `self.data_preprocessor` 这一行搬运到指定设备,进一步将处理好的数据传给模型。看到这里相信你会疑惑:
+
+1. `MMResNet50` 并没有配置 `data_preprocessor`,为什么却可以访问到 `data_preprocessor`,并且把数据搬运到 GPU?
+
+2. 为什么不直接在模型里调用 `data.to(device)` 搬运数据,而需要有 `data_preprocessor` 这一层抽象?它又能实现哪些功能?
+
+首先回答第一个问题:`MMResNet50` 继承了 `BaseModel`。在执行 `super().__init__` 时,如果不传入任何参数,会构造一个默认的 `BaseDataPreprocessor`,其等效简易实现如下:
+
+```python
+class BaseDataPreprocessor(nn.Module):
+ def forward(self, data, training=True): # 先忽略 training 参数
+ # 假设 data 是 CIFAR10 返回的 tuple 类型数据,事实上
+ # BaseDataPreprocessor 可以处理任意类型的数
+ # BaseDataPreprocessor 同样可以把数据搬运到多种设备,这边方便
+ # 起见写成 .cuda()
+ return tuple(_data.cuda() for _data in data)
+```
+
+`BaseDataPreprocessor` 会在训练过程中,将各种类型的数据搬运到指定设备。
+
+在回答第二个问题之前,我们不妨先再思考几个问题
+
+1. 数据归一化操作应该在哪里进行,[transform](../advanced_tutorials/data_transform.md) 还是 model?
+
+ 听上去好像都挺合理,放在 transform 里可以利用 Dataloader 的多进程加速,放在 model 里可以搬运到 GPU 上,利用GPU 资源加速归一化。然而在我们纠结 CPU 归一化快还是 GPU 归一化快的时候,CPU 到 GPU 的数据搬运耗时相较于前者,可算的上是“降维打击”。
+ 事实上对于归一化这类计算量较低的操作,其耗时会远低于数据搬运,因此优化数据搬运的效率就显得更加重要。设想一下,如果我能够在数据仍处于 uint8 时、归一化之前将其搬运到指定设备上(归一化后的 float 型数据大小是 unit8 的 4 倍),就能降低带宽,大大提升数据搬运的效率。这种“滞后”归一化的行为,也是我们设计数据预处理器(data preprocessor) 的主要原因之一。数据预处理器会先搬运数据,再做归一化,提升数据搬运的效率。
+
+2. 我们应该如何实现 MixUp、Mosaic 一类的数据增强?
+
+ 尽管看上去 MixUp 和 Mosaic 只是一种特殊的数据变换,按理说应该在 transform 里实现。考虑到这两种增强会涉及到“将多张图片融合成一张图片”的操作,在 transform 里实现他们的难度就会很大,因为目前 transform 的范式是对一张图片做各种增强,我们很难在一个 transform 里去额外读取其他图片(transform 里无法访问到 dataset)。然而如果基于 Dataloader 采样得到的 `batch_data` 去实现 Mosaic 或者 Mixup,事情就会变得非常简单,因为这个时候我们能够同时访问多张图片,可以轻而易举的完成图片融合的操作:
+
+ ```python
+ class MixUpDataPreprocessor(nn.Module):
+ def __init__(self, num_class, alpha):
+ self.alpha = alpha
+
+ def forward(self, data, training=True):
+ data = tuple(_data.cuda() for _data in data)
+ # 验证阶段无需进行 MixUp 数据增强
+ if not training:
+ return data
+
+ label = F.one_hot(label) # label 转 onehot 编码
+ batch_size = len(label)
+ index = torch.randperm(batch_size) # 计算用于叠加的图片数
+ img, label = data
+ lam = np.random.beta(self.alpha, self.alpha) # 融合因子
+
+ # 原图和标签的 MixUp.
+ img = lam * img + (1 - lam) * img[index, :]
+ label = lam * batch_scores + (1 - lam) * batch_scores[index, :]
+ # 由于此时返回的是 onehot 编码的 label,model 的 forward 也需要做相应调整
+ return tuple(img, label)
+ ```
+
+ 因此,除了数据搬运和归一化,`data_preprocessor` 另一大功能就是数据批增强(BatchAugmentation)。数据预处理器的模块化也能帮助我们实现算法和数据增强之间的自由组合。
+
+3. 如果 DataLoader 的输出和模型的输入类型不匹配怎么办,是修改 DataLoader 还是修改模型接口?
+
+ 答案是都不合适。理想的解决方案是我们能够在不破坏模型和数据已有接口的情况下完成适配。这个时候数据预处理器也能承担类型转换的工作,例如将传入的 data 从 `tuple` 转换成指定字段的 `dict`。
+
+看到这里,相信你已经能够理解数据预处理器存在的合理性,并且也能够自信地回答教程最初提出的两个问题!但是你可能还会疑惑 `train_step` 接口中传入的 `optim_wrapper` 又是什么,`test_step` 和 `val_step` 返回的结果和 evaluator 又有怎样的关系,这些问题会在[模型精度评测教程](./evaluation.md)和[优化器封装](./optim_wrapper.md)得到解答。
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/optim_wrapper.md b/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/optim_wrapper.md
new file mode 100644
index 0000000000000000000000000000000000000000..20fb968473d39e1939e02cd8e0feee9fe617bcc2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/optim_wrapper.md
@@ -0,0 +1,502 @@
+# 优化器封装(OptimWrapper)
+
+在[执行器教程](./runner.md)和[模型教程](./model.md)中,我们或多或少地提到了优化器封装(OptimWrapper)的概念,但是却没有介绍为什么我们需要优化器封装,相比于 Pytorch 原生的优化器,优化器封装又有怎样的优势,这些问题会在本教程中得到一一解答。我们将通过对比的方式帮助大家理解,优化器封装的优势,以及如何使用它。
+
+优化器封装顾名思义,是 Pytorch 原生优化器(Optimizer)高级抽象,它在增加了更多功能的同时,提供了一套统一的接口。优化器封装支持不同的训练策略,包括混合精度训练、梯度累加和梯度截断。我们可以根据需求选择合适的训练策略。优化器封装还定义了一套标准的参数更新流程,用户可以基于这一套流程,实现同一套代码,不同训练策略的切换。
+
+## 优化器封装 vs 优化器
+
+这里我们分别基于 Pytorch 内置的优化器和 MMEngine 的优化器封装进行单精度训练、混合精度训练和梯度累加,对比二者实现上的区别。
+
+### 训练模型
+
+**1.1 基于 Pytorch 的 SGD 优化器实现单精度训练**
+
+```python
+import torch
+from torch.optim import SGD
+import torch.nn as nn
+import torch.nn.functional as F
+
+inputs = [torch.zeros(10, 1, 1)] * 10
+targets = [torch.ones(10, 1, 1)] * 10
+model = nn.Linear(1, 1)
+optimizer = SGD(model.parameters(), lr=0.01)
+optimizer.zero_grad()
+
+for input, target in zip(inputs, targets):
+ output = model(input)
+ loss = F.l1_loss(output, target)
+ loss.backward()
+ optimizer.step()
+ optimizer.zero_grad()
+```
+
+**1.2 使用 MMEngine 的优化器封装实现单精度训练**
+
+```python
+from mmengine.optim import OptimWrapper
+
+optim_wrapper = OptimWrapper(optimizer=optimizer)
+
+for input, target in zip(inputs, targets):
+ output = model(input)
+ loss = F.l1_loss(output, target)
+ optim_wrapper.update_params(loss)
+```
+
+
+
+优化器封装的 `update_params` 实现了标准的梯度计算、参数更新和梯度清零流程,可以直接用来更新模型参数。
+
+**2.1 基于 Pytorch 的 SGD 优化器实现混合精度训练**
+
+```python
+from torch.cuda.amp import autocast
+
+model = model.cuda()
+inputs = [torch.zeros(10, 1, 1, 1)] * 10
+targets = [torch.ones(10, 1, 1, 1)] * 10
+
+for input, target in zip(inputs, targets):
+ with autocast():
+ output = model(input.cuda())
+ loss = F.l1_loss(output, target.cuda())
+ loss.backward()
+ optimizer.step()
+ optimizer.zero_grad()
+```
+
+**2.2 基于 MMEngine 的 优化器封装实现混合精度训练**
+
+```python
+from mmengine.optim import AmpOptimWrapper
+
+optim_wrapper = AmpOptimWrapper(optimizer=optimizer)
+
+for input, target in zip(inputs, targets):
+ with optim_wrapper.optim_context(model):
+ output = model(input.cuda())
+ loss = F.l1_loss(output, target.cuda())
+ optim_wrapper.update_params(loss)
+```
+
+
+
+开启混合精度训练需要使用 `AmpOptimWrapper`,他的 optim_context 接口类似 `autocast`,会开启混合精度训练的上下文。除此之外他还能加速分布式训练时的梯度累加,这个我们会在下一个示例中介绍。
+
+**3.1 基于 Pytorch 的 SGD 优化器实现混合精度训练和梯度累加**
+
+```python
+for idx, (input, target) in enumerate(zip(inputs, targets)):
+ with autocast():
+ output = model(input.cuda())
+ loss = F.l1_loss(output, target.cuda())
+ loss.backward()
+ if idx % 2 == 0:
+ optimizer.step()
+ optimizer.zero_grad()
+```
+
+**3.2 基于 MMEngine 的优化器封装实现混合精度训练和梯度累加**
+
+```python
+optim_wrapper = AmpOptimWrapper(optimizer=optimizer, accumulative_counts=2)
+
+for input, target in zip(inputs, targets):
+ with optim_wrapper.optim_context(model):
+ output = model(input.cuda())
+ loss = F.l1_loss(output, target.cuda())
+ optim_wrapper.update_params(loss)
+```
+
+
+
+我们只需要配置 `accumulative_counts` 参数,并调用 `update_params` 接口就能实现梯度累加的功能。除此之外,分布式训练情况下,如果我们配置梯度累加的同时开启了 `optim_wrapper` 上下文,可以避免梯度累加阶段不必要的梯度同步。
+
+优化器封装同样提供了更细粒度的接口,方便用户实现一些自定义的参数更新逻辑:
+
+- `backward`:传入损失,用于计算参数梯度。
+- `step`:同 `optimizer.step`,用于更新参数。
+- `zero_grad`:同 `optimizer.zero_grad`,用于参数的梯度。
+
+我们可以使用上述接口实现和 Pytorch 优化器相同的参数更新逻辑:
+
+```python
+for idx, (input, target) in enumerate(zip(inputs, targets)):
+ optimizer.zero_grad()
+ with optim_wrapper.optim_context(model):
+ output = model(input.cuda())
+ loss = F.l1_loss(output, target.cuda())
+ optim_wrapper.backward(loss)
+ if idx % 2 == 0:
+ optim_wrapper.step()
+ optim_wrapper.zero_grad()
+```
+
+我们同样可以为优化器封装配置梯度裁减策略:
+
+```python
+# 基于 torch.nn.utils.clip_grad_norm_ 对梯度进行裁减
+optim_wrapper = AmpOptimWrapper(
+ optimizer=optimizer, clip_grad=dict(max_norm=1))
+
+# 基于 torch.nn.utils.clip_grad_value_ 对梯度进行裁减
+optim_wrapper = AmpOptimWrapper(
+ optimizer=optimizer, clip_grad=dict(clip_value=0.2))
+```
+
+### 获取学习率/动量
+
+优化器封装提供了 `get_lr` 和 `get_momentum` 接口用于获取优化器的一个参数组的学习率:
+
+```python
+import torch.nn as nn
+from torch.optim import SGD
+
+from mmengine.optim import OptimWrapper
+
+model = nn.Linear(1, 1)
+optimizer = SGD(model.parameters(), lr=0.01)
+optim_wrapper = OptimWrapper(optimizer)
+
+print(optimizer.param_groups[0]['lr']) # 0.01
+print(optimizer.param_groups[0]['momentum']) # 0
+print(optim_wrapper.get_lr()) # {'lr': [0.01]}
+print(optim_wrapper.get_momentum()) # {'momentum': [0]}
+```
+
+```
+0.01
+0
+{'lr': [0.01]}
+{'momentum': [0]}
+```
+
+### 导出/加载状态字典
+
+优化器封装和优化器一样,提供了 `state_dict` 和 `load_state_dict` 接口,用于导出/加载优化器状态,对于 `AmpOptimWrapper`,优化器封装还会额外导出混合精度训练相关的参数:
+
+```python
+import torch.nn as nn
+from torch.optim import SGD
+from mmengine.optim import OptimWrapper, AmpOptimWrapper
+
+model = nn.Linear(1, 1)
+optimizer = SGD(model.parameters(), lr=0.01)
+
+optim_wrapper = OptimWrapper(optimizer=optimizer)
+amp_optim_wrapper = AmpOptimWrapper(optimizer=optimizer)
+
+# 导出状态字典
+optim_state_dict = optim_wrapper.state_dict()
+amp_optim_state_dict = amp_optim_wrapper.state_dict()
+
+print(optim_state_dict)
+print(amp_optim_state_dict)
+optim_wrapper_new = OptimWrapper(optimizer=optimizer)
+amp_optim_wrapper_new = AmpOptimWrapper(optimizer=optimizer)
+
+# 加载状态字典
+amp_optim_wrapper_new.load_state_dict(amp_optim_state_dict)
+optim_wrapper_new.load_state_dict(optim_state_dict)
+```
+
+```
+{'state': {}, 'param_groups': [{'lr': 0.01, 'momentum': 0, 'dampening': 0, 'weight_decay': 0, 'nesterov': False, 'maximize': False, 'foreach': None, 'params': [0, 1]}]}
+{'state': {}, 'param_groups': [{'lr': 0.01, 'momentum': 0, 'dampening': 0, 'weight_decay': 0, 'nesterov': False, 'maximize': False, 'foreach': None, 'params': [0, 1]}], 'loss_scaler': {'scale': 65536.0, 'growth_factor': 2.0, 'backoff_factor': 0.5, 'growth_interval': 2000, '_growth_tracker': 0}}
+```
+
+### 使用多个优化器
+
+考虑到生成对抗网络之类的算法通常需要使用多个优化器来训练生成器和判别器,因此优化器封装提供了优化器封装的容器类:`OptimWrapperDict` 来管理多个优化器封装。`OptimWrapperDict` 以字典的形式存储优化器封装,并允许用户像字典一样访问、遍历其中的元素,即优化器封装实例。
+
+与普通的优化器封装不同,`OptimWrapperDict` 没有实现 `update_params`、 `optim_context`, `backward`、`step` 等方法,无法被直接用于训练模型。我们建议直接访问 `OptimWrapperDict` 管理的优化器实例,来实现参数更新逻辑。
+
+你或许会好奇,既然 `OptimWrapperDict` 没有训练的功能,那为什么不直接使用 `dict` 来管理多个优化器?事实上,`OptimWrapperDict` 的核心功能是支持批量导出/加载所有优化器封装的状态字典;支持获取多个优化器封装的学习率、动量。如果没有 `OptimWrapperDict`,`MMEngine` 就需要在很多位置对优化器封装的类型做 `if else` 判断,以获取所有优化器封装的状态。
+
+```python
+from torch.optim import SGD
+import torch.nn as nn
+
+from mmengine.optim import OptimWrapper, OptimWrapperDict
+
+gen = nn.Linear(1, 1)
+disc = nn.Linear(1, 1)
+optimizer_gen = SGD(gen.parameters(), lr=0.01)
+optimizer_disc = SGD(disc.parameters(), lr=0.01)
+
+optim_wapper_gen = OptimWrapper(optimizer=optimizer_gen)
+optim_wapper_disc = OptimWrapper(optimizer=optimizer_disc)
+optim_dict = OptimWrapperDict(gen=optim_wapper_gen, disc=optim_wapper_disc)
+
+print(optim_dict.get_lr()) # {'gen.lr': [0.01], 'disc.lr': [0.01]}
+print(optim_dict.get_momentum()) # {'gen.momentum': [0], 'disc.momentum': [0]}
+```
+
+```
+{'gen.lr': [0.01], 'disc.lr': [0.01]}
+{'gen.momentum': [0], 'disc.momentum': [0]}
+```
+
+如上例所示,`OptimWrapperDict` 可以非常方便的导出所有优化器封装的学习率和动量,同样的,优化器封装也能够导出/加载所有优化器封装的状态字典。
+
+### 在[执行器](./runner.md)中配置优化器封装
+
+优化器封装需要接受 `optimizer` 参数,因此我们首先需要为优化器封装配置 `optimizer`。MMEngine 会自动将 PyTorch 中的所有优化器都添加进 `OPTIMIZERS` 注册表中,用户可以用字典的形式来指定优化器,所有支持的优化器见 [PyTorch 优化器列表](https://pytorch.org/docs/stable/optim.html#algorithms)。
+
+以配置一个 SGD 优化器封装为例:
+
+```python
+optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
+optim_wrapper = dict(type='OptimWrapper', optimizer=optimizer)
+```
+
+这样我们就配置好了一个优化器类型为 SGD 的优化器封装,学习率、动量等参数如配置所示。考虑到 `OptimWrapper` 为标准的单精度训练,因此我们也可以不配置 `type` 字段:
+
+```python
+optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
+optim_wrapper = dict(optimizer=optimizer)
+```
+
+要想开启混合精度训练和梯度累加,需要将 `type` 切换成 `AmpOptimWrapper`,并指定 `accumulative_counts` 参数:
+
+```python
+optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
+optim_wrapper = dict(type='AmpOptimWrapper', optimizer=optimizer, accumulative_counts=2)
+```
+
+```{note}
+如果你是第一次阅读 MMEngine 的教程文档,并且尚未了解[配置类](../advanced_tutorials/config.md)、[注册器](../advanced_tutorials/registry.md) 等概念,建议可以先跳过以下进阶教程,先去阅读其他文档。当然了,如果你已经具备了这些储备知识,我们强烈建议阅读进阶教程,在进阶教程中,我们将学会:
+
+1. 如何在配置文件中定制化地在优化器中配置模型参数的学习率、衰减系数等。
+2. 如何自定义一个优化器构造策略,实现真正意义上的“优化器配置自由”。
+
+除了配置类和注册器等前置知识,我们建议在开始进阶教程之前,先深入了解 Pytorch 原生优化器构造时的 params 参数。
+```
+
+## 进阶配置
+
+PyTorch 的优化器支持对模型中的不同参数设置不同的超参数,例如对一个分类模型的骨干(backbone)和分类头(head)设置不同的学习率:
+
+```python
+from torch.optim import SGD
+import torch.nn as nn
+
+model = nn.ModuleDict(dict(backbone=nn.Linear(1, 1), head=nn.Linear(1, 1)))
+optimizer = SGD([{'params': model.backbone.parameters()},
+ {'params': model.head.parameters(), 'lr': 1e-3}],
+ lr=0.01,
+ momentum=0.9)
+```
+
+上面的例子中,模型的骨干部分使用了 0.01 学习率,而模型的头部则使用了 1e-3 学习率。用户可以将模型的不同部分参数和对应的超参组成一个字典的列表传给优化器,来实现对模型优化的细粒度调整。
+
+在 MMEngine 中,我们通过优化器封装构造器(optimizer wrapper constructor),让用户能够直接通过设置优化器封装配置文件中的 `paramwise_cfg` 字段而非修改代码来实现对模型的不同部分设置不同的超参。
+
+### 为不同类型的参数设置不同的超参系数
+
+MMEngine 提供的默认优化器封装构造器支持对模型中不同类型的参数设置不同的超参系数。例如,我们可以在 `paramwise_cfg` 中设置 `norm_decay_mult=0`,从而将正则化层(normalization layer)的权重(weight)和偏置(bias)的权值衰减系数(weight decay)设置为 0,来实现 [Bag of Tricks](https://arxiv.org/abs/1812.01187) 论文中提到的不对正则化层进行权值衰减的技巧。
+
+具体示例如下,我们将 `ToyModel` 中所有正则化层(`head.bn`)的权重衰减系数设置为 0:
+
+```python
+from mmengine.optim import build_optim_wrapper
+from collections import OrderedDict
+
+class ToyModel(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.backbone = nn.ModuleDict(
+ dict(layer0=nn.Linear(1, 1), layer1=nn.Linear(1, 1)))
+ self.head = nn.Sequential(
+ OrderedDict(
+ linear=nn.Linear(1, 1),
+ bn=nn.BatchNorm1d(1)))
+
+
+optim_wrapper = dict(
+ optimizer=dict(type='SGD', lr=0.01, weight_decay=0.0001),
+ paramwise_cfg=dict(norm_decay_mult=0))
+optimizer = build_optim_wrapper(ToyModel(), optim_wrapper)
+```
+
+```
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.bias:lr=0.01
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.bias:weight_decay=0.0001
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer1.bias:lr=0.01
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer1.bias:weight_decay=0.0001
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.linear.bias:lr=0.01
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.linear.bias:weight_decay=0.0001
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.bn.weight:weight_decay=0.0
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.bn.bias:weight_decay=0.0
+```
+
+除了可以对正则化层的权重衰减进行配置外,MMEngine 的默认优化器封装构造器的 `paramwise_cfg` 还支持对更多不同类型的参数设置超参系数,支持的配置如下:
+
+`lr_mult`:所有参数的学习率系数
+
+`decay_mult`:所有参数的衰减系数
+
+`bias_lr_mult`:偏置的学习率系数(不包括正则化层的偏置以及可变形卷积的 offset)
+
+`bias_decay_mult`:偏置的权值衰减系数(不包括正则化层的偏置以及可变形卷积的 offset)
+
+`norm_decay_mult`:正则化层权重和偏置的权值衰减系数
+
+`flat_decay_mult`:一维参数的权值衰减系数
+
+`dwconv_decay_mult`:Depth-wise 卷积的权值衰减系数
+
+`bypass_duplicate`:是否跳过重复的参数,默认为 `False`
+
+`dcn_offset_lr_mult`:可变形卷积(Deformable Convolution)的学习率系数
+
+### 为模型不同部分的参数设置不同的超参系数
+
+此外,与上文 PyTorch 的示例一样,在 MMEngine 中我们也同样可以对模型中的任意模块设置不同的超参,只需要在 `paramwise_cfg` 中设置 `custom_keys` 即可。
+
+例如我们想将 `backbone.layer0` 所有参数的学习率设置为 0,衰减系数设置为 0,`backbone` 其余子模块的学习率设置为 0.01;`head` 所有参数的学习率设置为 0.001,可以这样配置:
+
+```python
+optim_wrapper = dict(
+ optimizer=dict(type='SGD', lr=0.01, weight_decay=0.0001),
+ paramwise_cfg=dict(
+ custom_keys={
+ 'backbone.layer0': dict(lr_mult=0, decay_mult=0),
+ 'backbone': dict(lr_mult=1),
+ 'head': dict(lr_mult=0.1)
+ }))
+optimizer = build_optim_wrapper(ToyModel(), optim_wrapper)
+```
+
+```
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.weight:lr=0.0
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.weight:weight_decay=0.0
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.weight:lr_mult=0
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.weight:decay_mult=0
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.bias:lr=0.0
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.bias:weight_decay=0.0
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.bias:lr_mult=0
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer0.bias:decay_mult=0
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer1.weight:lr=0.01
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer1.weight:weight_decay=0.0001
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer1.weight:lr_mult=1
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer1.bias:lr=0.01
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer1.bias:weight_decay=0.0001
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- backbone.layer1.bias:lr_mult=1
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.linear.weight:lr=0.001
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.linear.weight:weight_decay=0.0001
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.linear.weight:lr_mult=0.1
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.linear.bias:lr=0.001
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.linear.bias:weight_decay=0.0001
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.linear.bias:lr_mult=0.1
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.bn.weight:lr=0.001
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.bn.weight:weight_decay=0.0001
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.bn.weight:lr_mult=0.1
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.bn.bias:lr=0.001
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.bn.bias:weight_decay=0.0001
+08/23 22:02:43 - mmengine - INFO - paramwise_options -- head.bn.bias:lr_mult=0.1
+```
+
+上例中,模型的状态字典的 `key` 如下:
+
+```python
+for name, val in ToyModel().named_parameters():
+ print(name)
+```
+
+```
+backbone.layer0.weight
+backbone.layer0.bias
+backbone.layer1.weight
+backbone.layer1.bias
+head.linear.weight
+head.linear.bias
+head.bn.weight
+head.bn.bias
+```
+
+custom_keys 中每一个字段的含义如下:
+
+1. `'backbone': dict(lr_mult=1)`:将名字前缀为 `backbone` 的参数的学习率系数设置为 1
+2. `'backbone.layer0': dict(lr_mult=0, decay_mult=0)`:将名字前缀为 `backbone.layer0` 的参数学习率系数设置为 0,衰减系数设置为 0,该配置优先级比第一条高
+3. `'head': dict(lr_mult=0.1)`:将名字前缀为 `head` 的参数的学习率系数设置为 0.1
+
+### 自定义优化器构造策略
+
+与 MMEngine 中的其他模块一样,优化器封装构造器也同样由[注册表](../advanced_tutorial/registry.md)管理。我们可以通过实现自定义的优化器封装构造器来实现自定义的超参设置策略。
+
+例如,我们想实现一个叫做 `LayerDecayOptimWrapperConstructor` 的优化器封装构造器,能够对模型不同深度的层自动设置递减的学习率:
+
+```python
+from mmengine.optim import DefaultOptimWrapperConstructor
+from mmengine.registry import OPTIM_WRAPPER_CONSTRUCTORS
+from mmengine.logging import print_log
+
+
+@OPTIM_WRAPPER_CONSTRUCTORS.register_module(force=True)
+class LayerDecayOptimWrapperConstructor(DefaultOptimWrapperConstructor):
+
+ def __init__(self, optim_wrapper_cfg, paramwise_cfg=None):
+ super().__init__(optim_wrapper_cfg, paramwise_cfg=None)
+ self.decay_factor = paramwise_cfg.get('decay_factor', 0.5)
+
+ super().__init__(optim_wrapper_cfg, paramwise_cfg)
+
+ def add_params(self, params, module, prefix='' ,lr=None):
+ if lr is None:
+ lr = self.base_lr
+
+ for name, param in module.named_parameters(recurse=False):
+ param_group = dict()
+ param_group['params'] = [param]
+ param_group['lr'] = lr
+ params.append(param_group)
+ full_name = f'{prefix}.{name}' if prefix else name
+ print_log(f'{full_name} : lr={lr}', logger='current')
+
+ for name, module in module.named_children():
+ chiled_prefix = f'{prefix}.{name}' if prefix else name
+ self.add_params(
+ params, module, chiled_prefix, lr=lr * self.decay_factor)
+
+
+class ToyModel(nn.Module):
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.layer = nn.ModuleDict(dict(linear=nn.Linear(1, 1)))
+ self.linear = nn.Linear(1, 1)
+
+
+model = ToyModel()
+
+optim_wrapper = dict(
+ optimizer=dict(type='SGD', lr=0.01, weight_decay=0.0001),
+ paramwise_cfg=dict(decay_factor=0.5),
+ constructor='LayerDecayOptimWrapperConstructor')
+
+optimizer = build_optim_wrapper(model, optim_wrapper)
+```
+
+```
+08/23 22:20:26 - mmengine - INFO - layer.linear.weight : lr=0.0025
+08/23 22:20:26 - mmengine - INFO - layer.linear.bias : lr=0.0025
+08/23 22:20:26 - mmengine - INFO - linear.weight : lr=0.005
+08/23 22:20:26 - mmengine - INFO - linear.bias : lr=0.005
+```
+
+`add_params` 被第一次调用时,`params` 参数为空列表(`list`),`module` 为模型(`model`)。详细的重载规则参考[优化器封装构造器文档](mmengine.optim.DefaultOptimWrapperConstructor)。
+
+类似地,如果想构造多个优化器,也需要实现自定义的构造器:
+
+```python
+@OPTIM_WRAPPER_CONSTRUCTORS.register_module()
+class MultipleOptimiWrapperConstructor:
+ ...
+```
+
+### 在训练过程中调整超参
+
+优化器中的超参数在构造时只能设置为一个定值,仅仅使用优化器封装,并不能在训练过程中调整学习率等参数。在 MMEngine 中,我们实现了参数调度器(Parameter Scheduler),以便能够在训练过程中调整参数。关于参数调度器的用法请见[优化器参数调整策略](./param_scheduler.md)
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/param_scheduler.md b/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/param_scheduler.md
new file mode 100644
index 0000000000000000000000000000000000000000..e18cb6aa4610f074c16e851c4d9eaa466230d773
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/param_scheduler.md
@@ -0,0 +1,214 @@
+# 优化器参数调整策略(Parameter Scheduler)
+
+在模型训练过程中,我们往往不是采用固定的优化参数,例如学习率等,会随着训练轮数的增加进行调整。最简单常见的学习率调整策略就是阶梯式下降,例如每隔一段时间将学习率降低为原来的几分之一。PyTorch 中有学习率调度器 LRScheduler 来对各种不同的学习率调整方式进行抽象,但支持仍然比较有限,在 MMEngine 中,我们对其进行了拓展,实现了更通用的[参数调度器](mmengine.optim._ParamScheduler),可以对学习率、动量等优化器相关的参数进行调整,并且支持多个调度器进行组合,应用更复杂的调度策略。
+
+## 参数调度器的使用
+
+我们先简单介绍一下如何使用 PyTorch 内置的学习率调度器来进行学习率的调整:
+
+
+如何使用 PyTorch 内置的学习率调度器调整学习率
+
+下面是参考 [PyTorch 官方文档](https://pytorch.org/docs/stable/optim.html) 实现的一个例子,我们构造一个 [ExponentialLR](mmengine.optim.ExponentialLR),并且在每个 epoch 结束后调用 `scheduler.step()`,实现了随 epoch 指数下降的学习率调整策略。
+
+```python
+import torch
+from torch.optim import SGD
+from torch.optim.lr_scheduler import ExponentialLR
+
+model = torch.nn.Linear(1, 1)
+dataset = [torch.randn((1, 1, 1)) for _ in range(20)]
+optimizer = SGD(model, 0.1)
+scheduler = ExponentialLR(optimizer, gamma=0.9)
+
+for epoch in range(10):
+ for data in dataset:
+ optimizer.zero_grad()
+ output = model(data)
+ loss = 1 - output
+ loss.backward()
+ optimizer.step()
+ scheduler.step()
+```
+
+
+
+在 `mmengine.optim.scheduler` 中,我们支持大部分 PyTorch 中的学习率调度器,例如 `ExponentialLR`,`LinearLR`,`StepLR`,`MultiStepLR` 等,使用方式也基本一致,所有支持的调度器见[调度器接口文档](https://mmengine.readthedocs.io/zh_CN/latest/api/optim.html#scheduler)。同时增加了对动量的调整,在类名中将 `LR` 替换成 `Momentum` 即可,例如 `ExponentialMomentum`,`LinearMomentum`。更进一步地,我们实现了通用的参数调度器 ParamScheduler,用于调整优化器的中的其他参数,包括 weight_decay 等。这个特性可以很方便地配置一些新算法中复杂的调整策略。
+
+和 PyTorch 文档中所给示例不同,MMEngine 中通常不需要手动来实现训练循环以及调用 `optimizer.step()`,而是在执行器(Runner)中对训练流程进行自动管理,同时通过 `ParamSchedulerHook` 来控制参数调度器的执行。
+
+### 使用单一的学习率调度器
+
+如果整个训练过程只需要使用一个学习率调度器, 那么和 PyTorch 自带的学习率调度器没有差异。
+
+```python
+# 基于手动构建学习率调度器的例子
+from torch.optim import SGD
+from mmengine.runner import Runner
+from mmengine.optim.scheduler import MultiStepLR
+
+optimizer = SGD(model.parameters(), lr=0.01, momentum=0.9)
+param_scheduler = MultiStepLR(optimizer, milestones=[8, 11], gamma=0.1)
+
+runner = Runner(
+ model=model,
+ optim_wrapper=dict(
+ optimizer=optimizer),
+ param_scheduler=param_scheduler,
+ ...
+ )
+```
+
+
+
+如果配合注册器和配置文件使用的话,我们可以设置配置文件中的 `param_scheduler` 字段来指定调度器, 执行器(Runner)会根据此字段以及执行器中的优化器自动构建学习率调度器:
+
+```python
+# 在配置文件中设置学习率调度器字段
+param_scheduler = dict(type='MultiStepLR', by_epoch=True, milestones=[8, 11], gamma=0.1)
+```
+
+注意这里增加了初始化参数 `by_epoch`,控制的是学习率调整频率,当其为 True 时表示按轮次(epoch)调整,为 False 时表示按迭代次数(iteration)调整,默认值为 True。在上面的例子中,表示按照轮次进行调整,此时其他参数的单位均为 epoch,例如 `milestones` 中的 \[8, 11\] 表示第 8 和 11 轮次结束时,学习率将会被调整为上一轮次的 0.1 倍。
+
+当修改了学习率调整频率后,调度器中与计数相关设置的含义也会相应被改变。当 `by_epoch=True` 时,milestones 中的数字表示在哪些轮次进行学习率衰减,而当 `by_epoch=False` 时则表示在进行到第几次迭代时进行学习率衰减。下面是一个按照迭代次数进行调整的例子,在第 600 和 800 次迭代结束时,学习率将会被调整为原来的 0.1 倍。
+
+```python
+param_scheduler = dict(type='MultiStepLR', by_epoch=False, milestones=[600, 800], gamma=0.1)
+```
+
+
+
+若用户希望在配置调度器时按轮次填写参数的同时使用基于迭代的更新频率,MMEngine 的调度器也提供了自动换算的方式。用户可以调用 `build_iter_from_epoch` 方法,并提供每个训练轮次的迭代次数,即可构造按迭代次数更新的调度器对象:
+
+```python
+epoch_length = len(train_dataloader)
+param_scheduler = MultiStepLR.build_iter_from_epoch(optimizer, milestones=[8, 11], gamma=0.1, epoch_length=epoch_length)
+```
+
+如果使用配置文件构建调度器,只需要在配置中加入 `convert_to_iter_based=True`,执行器会自动调用 `build_iter_from_epoch` 将基于轮次的配置文件转换为基于迭代次数的调度器对象:
+
+```python
+param_scheduler = dict(type='MultiStepLR', by_epoch=True, milestones=[8, 11], gamma=0.1, convert_to_iter_based=True)
+```
+
+为了能直观感受这两种模式的区别,我们这里再举一个例子。下面是一个按轮次更新的余弦退火(CosineAnnealing)学习率调度器,学习率仅在每个轮次结束后被修改:
+
+```python
+param_scheduler = dict(type='CosineAnnealingLR', by_epoch=True, T_max=12)
+```
+
+
+
+而在使用自动换算后,学习率会在每次迭代后被修改。从下图可以看出,学习率的变化更为平滑。
+
+```python
+param_scheduler = dict(type='CosineAnnealingLR', by_epoch=True, T_max=12, convert_to_iter_based=True)
+```
+
+
+
+### 组合多个学习率调度器(以学习率预热为例)
+
+有些算法在训练过程中,并不是自始至终按照某个调度策略进行学习率调整的。最常见的例子是学习率预热,比如在训练刚开始的若干迭代次数使用线性的调整策略将学习率从一个较小的值增长到正常,然后按照另外的调整策略进行正常训练。
+
+MMEngine 支持组合多个调度器一起使用,只需将配置文件中的 `scheduler` 字段修改为一组调度器配置的列表,SchedulerStepHook 可以自动对调度器列表进行处理。下面的例子便实现了学习率预热。
+
+```python
+param_scheduler = [
+ # 线性学习率预热调度器
+ dict(type='LinearLR',
+ start_factor=0.001,
+ by_epoch=False, # 按迭代更新学习率
+ begin=0,
+ end=50), # 预热前 50 次迭代
+ # 主学习率调度器
+ dict(type='MultiStepLR',
+ by_epoch=True, # 按轮次更新学习率
+ milestones=[8, 11],
+ gamma=0.1)
+]
+```
+
+
+
+注意这里增加了 `begin` 和 `end` 参数,这两个参数指定了调度器的**生效区间**。生效区间通常只在多个调度器组合时才需要去设置,使用单个调度器时可以忽略。当指定了 `begin` 和 `end` 参数时,表示该调度器只在 \[begin, end) 区间内生效,其单位是由 `by_epoch` 参数决定。上述例子中预热阶段 `LinearLR` 的 `by_epoch` 为 False,表示该调度器只在前 50 次迭代生效,超过 50 次迭代后此调度器不再生效,由第二个调度器来控制学习率,即 `MultiStepLR`。在组合不同调度器时,各调度器的 `by_epoch` 参数不必相同。
+
+这里再举一个例子:
+
+```python
+param_scheduler = [
+ # 在 [0, 100) 迭代时使用线性学习率
+ dict(type='LinearLR',
+ start_factor=0.001,
+ by_epoch=False,
+ begin=0,
+ end=100),
+ # 在 [100, 900) 迭代时使用余弦学习率
+ dict(type='CosineAnnealingLR',
+ T_max=800,
+ by_epoch=False,
+ begin=100,
+ end=900)
+]
+```
+
+
+
+上述例子表示在训练的前 100 次迭代时使用线性的学习率预热,然后在第 100 到第 900 次迭代时使用周期为 800 的余弦退火学习率调度器使学习率按照余弦函数逐渐下降为 0 。
+
+我们可以组合任意多个调度器,既可以使用 MMEngine 中已经支持的调度器,也可以实现自定义的调度器。
+如果相邻两个调度器的生效区间没有紧邻,而是有一段区间没有被覆盖,那么这段区间的学习率维持不变。而如果两个调度器的生效区间发生了重叠,则对多组调度器叠加使用,学习率的调整会按照调度器配置文件中的顺序触发(行为与 PyTorch 中 [`ChainedScheduler`](https://pytorch.org/docs/stable/generated/torch.optim.lr_scheduler.ChainedScheduler.html#chainedscheduler) 一致)。
+在一般情况下,我们推荐用户在训练的不同阶段使用不同的学习率调度策略来避免调度器的生效区间发生重叠。如果确实需要将两个调度器叠加使用,则需要十分小心,避免学习率的调整与预期不符。
+
+## 如何调整其他参数
+
+### 动量
+
+和学习率一样, 动量也是优化器参数组中一组可以调度的参数。 动量调度器(momentum scheduler)的使用方法和学习率调度器完全一样。同样也只需要将动量调度器的配置添加进配置文件中的 `param_scheduler` 字段的列表中即可。
+
+示例:
+
+```python
+param_scheduler = [
+ # the lr scheduler
+ dict(type='LinearLR', ...),
+ # 动量调度器
+ dict(type='LinearMomentum',
+ start_factor=0.001,
+ by_epoch=False,
+ begin=0,
+ end=1000)
+]
+```
+
+### 通用的参数调度器
+
+MMEngine 还提供了一组通用的参数调度器用于调度优化器的 `param_groups` 中的其他参数,将学习率调度器类名中的 `LR` 改为 `Param` 即可,例如 `LinearParamScheduler`。用户可以通过设置参数调度器的 `param_name` 变量来选择想要调度的参数。
+
+下面是一个通过自定义参数名来调度的例子:
+
+```python
+param_scheduler = [
+ dict(type='LinearParamScheduler',
+ param_name='lr', # 调度 `optimizer.param_groups` 中名为 'lr' 的变量
+ start_factor=0.001,
+ by_epoch=False,
+ begin=0,
+ end=1000)
+]
+```
+
+这里设置的参数名是 `lr`,因此这个调度器的作用等同于直接使用学习率调度器 `LinearLRScheduler`。
+
+除了动量之外,用户也可以对 `optimizer.param_groups` 中的其他参数名进行调度,可调度的参数取决于所使用的优化器。例如,当使用带 `weight_decay` 的 SGD 优化器时,可以按照以下示例对调整 `weight_decay`:
+
+```python
+param_scheduler = [
+ dict(type='LinearParamScheduler',
+ param_name='weight_decay', # 调度 `optimizer.param_groups` 中名为 'weight_decay' 的变量
+ start_factor=0.001,
+ by_epoch=False,
+ begin=0,
+ end=1000)
+]
+```
diff --git a/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/runner.md b/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/runner.md
new file mode 100644
index 0000000000000000000000000000000000000000..83d2fcf8c1781178046caa71fdbb02635fb13cd6
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/docs/zh_cn/tutorials/runner.md
@@ -0,0 +1,522 @@
+# 执行器(Runner)
+
+欢迎来到 MMEngine 用户界面的核心——执行器!
+
+作为 MMEngine 中的“集大成者”,执行器涵盖了整个框架的方方面面,肩负着串联所有组件的重要责任;因此,其中的代码和实现逻辑需要兼顾各种情景,相对庞大复杂。但是**不用担心**!在这篇教程中,我们将隐去繁杂的细节,速览执行器常用的接口、功能、示例,为你呈现一个清晰易懂的用户界面。阅读完本篇教程,你将会:
+
+- 掌握执行器的常见参数与使用方式
+- 了解执行器的最佳实践——配置文件的写法
+- 了解执行器基本数据流与简要执行逻辑
+- 亲身感受使用执行器的优越性(也许)
+
+## 执行器示例
+
+使用执行器构建属于你自己的训练流程,通常有两种开始方式:
+
+- 参考 [API 文档](mmengine.runner.Runner),逐项确认和配置参数
+- 在已有配置(如 [15 分钟上手](../get_started/15_minutes.md)或 [MMDet](https://github.com/open-mmlab/mmdetection) 等下游算法库)的基础上,进行定制化修改
+
+两种方式各有利弊。使用前者,初学者很容易迷失在茫茫多的参数项中不知所措;而使用后者,一份过度精简或过度详细的参考配置都不利于初学者快速找到所需内容。
+
+解决上述问题的关键在于,把执行器作为备忘录:掌握其中最常用的部分,并在有特殊需求时聚焦感兴趣的部分,其余部分使用缺省值。下面我们将通过一个适合初学者参考的例子,说明其中最常用的参数,并为一些不常用参数给出进阶指引。
+
+### 面向初学者的示例代码
+
+```{hint}
+我们希望你在本教程中更多地关注整体结构,而非具体模块的实现。这种“自顶向下”的思考方式是我们所倡导的。别担心,之后你将有充足的机会和指引,聚焦于自己想要改进的模块
+```
+
+
+运行下面的示例前,请先执行本段代码准备模型、数据集与评测指标;但是在本教程中,暂时无需关注它们的具体实现
+
+```python
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.utils.data import Dataset
+
+from mmengine.model import BaseModel
+from mmengine.evaluator import BaseMetric
+from mmengine.registry import MODELS, DATASETS, METRICS
+
+
+@MODELS.register_module()
+class MyAwesomeModel(BaseModel):
+ def __init__(self, layers=4, activation='relu') -> None:
+ super().__init__()
+ if activation == 'relu':
+ act_type = nn.ReLU
+ elif activation == 'silu':
+ act_type = nn.SiLU
+ elif activation == 'none':
+ act_type = nn.Identity
+ else:
+ raise NotImplementedError
+ sequence = [nn.Linear(2, 64), act_type()]
+ for _ in range(layers-1):
+ sequence.extend([nn.Linear(64, 64), act_type()])
+ self.mlp = nn.Sequential(*sequence)
+ self.classifier = nn.Linear(64, 2)
+
+ def forward(self, data, labels, mode):
+ x = self.mlp(data)
+ x = self.classifier(x)
+ if mode == 'tensor':
+ return x
+ elif mode == 'predict':
+ return F.softmax(x, dim=1), labels
+ elif mode == 'loss':
+ return {'loss': F.cross_entropy(x, labels)}
+
+
+@DATASETS.register_module()
+class MyDataset(Dataset):
+ def __init__(self, is_train, size):
+ self.is_train = is_train
+ if self.is_train:
+ torch.manual_seed(0)
+ self.labels = torch.randint(0, 2, (size,))
+ else:
+ torch.manual_seed(3407)
+ self.labels = torch.randint(0, 2, (size,))
+ r = 3 * (self.labels+1) + torch.randn(self.labels.shape)
+ theta = torch.rand(self.labels.shape) * 2 * torch.pi
+ self.data = torch.vstack([r*torch.cos(theta), r*torch.sin(theta)]).T
+
+ def __getitem__(self, index):
+ return self.data[index], self.labels[index]
+
+ def __len__(self):
+ return len(self.data)
+
+
+@METRICS.register_module()
+class Accuracy(BaseMetric):
+ def __init__(self):
+ super().__init__()
+
+ def process(self, data_batch, data_samples):
+ score, gt = data_samples
+ self.results.append({
+ 'batch_size': len(gt),
+ 'correct': (score.argmax(dim=1) == gt).sum().cpu(),
+ })
+
+ def compute_metrics(self, results):
+ total_correct = sum(r['correct'] for r in results)
+ total_size = sum(r['batch_size'] for r in results)
+ return dict(accuracy=100*total_correct/total_size)
+```
+
+
+
+
+点击展开一段长长的示例代码。做好准备
+
+```python
+from torch.utils.data import DataLoader, default_collate
+from torch.optim import Adam
+from mmengine.runner import Runner
+
+
+runner = Runner(
+ # 你的模型
+ model=MyAwesomeModel(
+ layers=2,
+ activation='relu'),
+ # 模型检查点、日志等都将存储在工作路径中
+ work_dir='exp/my_awesome_model',
+
+ # 训练所用数据
+ train_dataloader=DataLoader(
+ dataset=MyDataset(
+ is_train=True,
+ size=10000),
+ shuffle=True,
+ collate_fn=default_collate,
+ batch_size=64,
+ pin_memory=True,
+ num_workers=2),
+ # 训练相关配置
+ train_cfg=dict(
+ by_epoch=True, # 根据 epoch 计数而非 iteration
+ max_epochs=10,
+ val_begin=2, # 从第 2 个 epoch 开始验证
+ val_interval=1), # 每隔 1 个 epoch 进行一次验证
+
+ # 优化器封装,MMEngine 中的新概念,提供更丰富的优化选择。
+ # 通常使用默认即可,可缺省。有特殊需求可查阅文档更换,如
+ # 'AmpOptimWrapper' 开启混合精度训练
+ optim_wrapper=dict(
+ optimizer=dict(
+ type=Adam,
+ lr=0.001)),
+ # 参数调度器,用于在训练中调整学习率/动量等参数
+ param_scheduler=dict(
+ type='MultiStepLR',
+ by_epoch=True,
+ milestones=[4, 8],
+ gamma=0.1),
+
+ # 验证所用数据
+ val_dataloader=DataLoader(
+ dataset=MyDataset(
+ is_train=False,
+ size=1000),
+ shuffle=False,
+ collate_fn=default_collate,
+ batch_size=1000,
+ pin_memory=True,
+ num_workers=2),
+ # 验证相关配置,通常为空即可
+ val_cfg=dict(),
+ # 验证指标与验证器封装,可自由实现与配置
+ val_evaluator=dict(type=Accuracy),
+
+ # 以下为其他进阶配置,无特殊需要时尽量缺省
+ # 钩子属于进阶用法,如无特殊需要,尽量缺省
+ default_hooks=dict(
+ # 最常用的默认钩子,可修改保存 checkpoint 的间隔
+ checkpoint=dict(type='CheckpointHook', interval=1)),
+
+ # `luancher` 与 `env_cfg` 共同构成分布式训练环境配置
+ launcher='none',
+ env_cfg=dict(
+ cudnn_benchmark=False, # 是否使用 cudnn_benchmark
+ backend='nccl', # 分布式通信后端
+ mp_cfg=dict(mp_start_method='fork')), # 多进程设置
+ log_level='INFO',
+
+ # 加载权重的路径 (None 表示不加载)
+ load_from=None
+ # 从加载的权重文件中恢复训练
+ resume=False
+)
+
+# 开始训练你的模型吧
+runner.train()
+```
+
+
+
+### 示例代码讲解
+
+真是一段长长的代码!但是如果你通读了上述样例,即使不了解实现细节,你也一定大体理解了这个训练流程,并感叹于执行器代码的紧凑与可读性(也许)。这也是 MMEngine 所期望的:结构化、模块化、标准化的训练流程,使得复现更加可靠、对比更加清晰。
+
+上述例子可能会让你产生如下问题:
+
+
+参数项实在是太多了!
+
+不用担心,正如我们前面所说,**把执行器作为备忘录**。执行器涵盖了方方面面,防止你漏掉重要内容,但是这并不意味着你需要配置所有参数。如[15分钟上手](../get_started/15_minutes.md)中的极简例子(甚至,舍去 `val_evaluator` `val_dataloader` 和 `val_cfg`)也可以正常运行。所有的参数由你的需求驱动,不关注的内容往往缺省值也可以工作得很好。
+
+
+
+
+为什么有些传入参数是 dict?
+
+是的,这与 MMEngine 的风格相关。在 MMEngine 中我们提供了两种不同风格的执行器构建方式:a)基于手动构建的,以及 b)基于注册机制的。如果你感到迷惑,下面的例子将给出一个对比:
+
+```python
+from mmengine.model import BaseModel
+from mmengine.runner import Runner
+from mmengine.registry import MODELS # 模型根注册器,你的自定义模型需要注册到这个根注册器中
+
+@MODELS.register_module() # 用于注册的装饰器
+class MyAwesomeModel(BaseModel): # 你的自定义模型
+ def __init__(self, layers=18, activation='silu'):
+ ...
+
+# 基于注册机制的例子
+runner = Runner(
+ model=dict(
+ type='MyAwesomeModel',
+ layers=50,
+ activation='relu'),
+ ...
+)
+
+# 基于手动构建的例子
+model = MyAwesomeModel(layers=18, activation='relu')
+runner = Runner(
+ model=model,
+ ...
+)
+```
+
+类似上述例子,执行器中的参数大多同时支持两种输入类型。以上两种写法基本是等价的,区别在于:前者以 `dict` 作为输入时,该模块会在**需要时在执行器内部**被构建;而后者是构建完成后传递给执行器。如果你对于注册机制并不了解,下面的示意图展示了它的核心思想:注册器维护着**模块的构建方式**和它的**名字**之间的映射。如果你在使用中发现问题,或者想要进一步了解完整用法,我们推荐阅读[注册器(Registry)](../advanced_tutorials/registry.md)文档。
+
+
+
+看到这你可能仍然很疑惑,为什么我要传入字典让 Runner 来构建实例,这样又有什么好处?如果你有产生这样的疑问,那我们就会很自豪的回答:“当然!(没有好处)”。事实上,基于注册机制的构建方式只有在结合配置文件时才会发挥它的最大优势。这里直接传入字典的写法也并非使用执行器的最佳实践。在这里,我们希望你能够通过这个例子读懂并习惯这种写法,方便理解我们马上将要讲到的执行器最佳实践——配置文件。敬请期待!
+
+如果你作为初学者无法立刻理解,使用*手动构建的方式*依然不失为一种好选择,甚至在小规模使用、试错和调试时是一种更加推荐的方式,因为对于 IDE 更加友好。但我们也希望你能够读懂并习惯基于注册机制的写法,并且在后续教程中不会因此而产生不必要的混淆和疑惑。
+
+
+
+
+我应该去哪里找到 xxx 参数的可能配置选项?
+
+你可以在对应模块的教程中找到丰富的说明和示例,你也可以在 [API 文档](mmengine.runner.Runner) 中找到 `Runner` 的所有参数。如果上述两种方式都无法解决你的疑问,你随时可以在我们的[讨论区](https://github.com/open-mmlab/mmengine/discussions)中发起话题,帮助我们更好地改进文档。
+
+
+
+
+我来自 MMDet/MMCls...下游库,为什么例子写法与我接触的不同?
+
+OpenMMLab 下游库广泛采用了配置文件的方式。我们将在下个章节,基于上述示例稍微变换,从而展示配置文件——MMEngine 中执行器的最佳实践——的用法。
+
+
+
+## 执行器最佳实践——配置文件
+
+MMEngine 提供了一套支持 `Python` 语法的、功能强大的配置文件系统。你可以从之前的示例代码中**近乎**(我们将在下面说明)无缝地转换到配置文件。下面给出一段示例代码:
+
+```python
+# 以下代码存放在 example_config.py 文件中
+# 基本拷贝自上面的示例,并将每项结尾的逗号删去
+model = dict(type='MyAwesomeModel',
+ layers=2,
+ activation='relu')
+work_dir = 'exp/my_awesome_model'
+
+train_dataloader = dict(
+ dataset=dict(type='MyDataset',
+ is_train=True,
+ size=10000),
+ sampler=dict(
+ type='DefaultSampler',
+ shuffle=True),
+ collate_fn=dict(type='default_collate'),
+ batch_size=64,
+ pin_memory=True,
+ num_workers=2)
+train_cfg = dict(
+ by_epoch=True,
+ max_epochs=10,
+ val_begin=2,
+ val_interval=1)
+optim_wrapper = dict(
+ optimizer=dict(
+ type='Adam',
+ lr=0.001))
+param_scheduler = dict(
+ type='MultiStepLR',
+ by_epoch=True,
+ milestones=[4, 8],
+ gamma=0.1)
+
+val_dataloader = dict(
+ dataset=dict(type='MyDataset',
+ is_train=False,
+ size=1000),
+ sampler=dict(
+ type='DefaultSampler',
+ shuffle=False),
+ collate_fn=dict(type='default_collate'),
+ batch_size=1000,
+ pin_memory=True,
+ num_workers=2)
+val_cfg = dict()
+val_evaluator = dict(type='Accuracy')
+
+default_hooks = dict(
+ checkpoint=dict(type='CheckpointHook', interval=1))
+launcher = 'none'
+env_cfg = dict(
+ cudnn_benchmark=False,
+ backend='nccl',
+ mp_cfg=dict(mp_start_method='fork'))
+log_level = 'INFO'
+load_from = None
+resume = False
+```
+
+此时,我们只需要在训练代码中加载配置,然后运行即可
+
+```python
+from mmengine.config import Config
+from mmengine.runner import Runner
+config = Config.fromfile('example_config.py')
+runner = Runner.from_cfg(config)
+runner.train()
+```
+
+```{note}
+虽然是 `Python` 语法,但合法的配置文件需要满足以下条件:所有的变量必须是**基本类型**(例如 `str` `dict` `int`等)。因此,配置文件系统高度依赖于注册机制,以实现从基本类型到其他类型(如 `nn.Module`)的构建。
+```
+
+```{note}
+使用配置文件时,你通常不需要手动注册所有模块。例如,`torch.optim` 中的所有优化器(如 `Adam` `SGD`等)都已经在 `mmengine.optim` 中注册完成。使用时的经验法则是:尝试直接使用 `PyTorch` 中的组件,只有当出现报错时再手动注册。
+```
+
+```{note}
+当使用配置文件写法时,你的自定义模块的实现代码通常存放在独立文件中,可能并未被正确注册,进而导致构建失败。我们推荐你阅读[注册器](./registry.md)文档中 `custom_imports` 相关的内容以更好地使用配置文件系统。
+```
+
+```{warning}
+虽然与示例中的写法一致,但 `from_cfg` 与 `__init__` 的缺省值处理可能存在些微不同,例如 `env_cfg` 参数。
+```
+
+执行器配置文件已经在 OpenMMLab 的众多下游库(MMCls,MMDet...)中被广泛使用,并成为事实标准与最佳实践。配置文件的功能远不止如此,如果你对于继承、覆写等进阶功能感兴趣,请参考[配置(Config)](../advanced_tutorials/config.md)文档。
+
+## 基本数据流
+
+```{hint}
+在本章节中,我们将会介绍执行器内部各模块之间的数据传递流向与格式约定。如果你还没有基于 MMEngine 构建一个训练流程,本章节的部分内容可能会比较抽象、枯燥;你也可以暂时跳过,并在将来有需要时结合实践进行阅读。
+```
+
+接下来,我们将**稍微**深入执行器的内部,结合图示来理清其中数据的流向与格式约定。
+
+
+
+上图是执行器的**基本**数据流,其中虚线边框、灰色填充的不同形状代表不同的数据格式,实线方框代表模块或方法。由于 MMEngine 强大的灵活性与可扩展性,你总可以继承某些关键基类并重载其中的方法,因此上图并不总是成立。只有当你没有自定义 `Runner` 或 `TrainLoop` ,并且你的自定义模型没有重载 `train_step`、`val_step` 与 `test_step` 方法时上图才会成立(而这在检测、分割等任务上是常见的,参考[模型](./model.md)教程)。
+
+
+可以确切地说明图中传递的每项数据的具体类型吗?
+
+很遗憾,这一点无法做到。虽然 MMEngine 做了大量类型注释,但 `Python` 是一门高度动态化的编程语言,同时以数据为核心的深度学习系统也需要足够的灵活性来处理纷繁复杂的数据源,你有充分的自由决定何时需要(有时是必须)打破类型约定。因此,在你自定义某一或某几个模块(如 `val_evaluator` )时,你需要确保它的输入与上游(如 `model` 的输出)兼容,同时输出可以被下游解析。MMEngine 将处理数据的灵活性交给了用户,因而也需要用户保证数据流的兼容性——当然,实际上手后会发现,这一点并不十分困难。
+
+数据一致性的考验一直存在于深度学习领域,MMEngine 也在尝试用自己的方式改进。如果你有兴趣,可以参考[数据集基类](../advanced_tutorials/basedataset.md)与[抽象数据接口](../advanced_tutorials/data_element.md)文档——但是**请注意,它们主要面向进阶用户**。
+
+
+
+
+dataloader、model 和 evaluator 之间的数据格式是如何约定的?
+
+针对图中所展示的基本数据流,上述三个模块之间的数据传递可以用如下伪代码表示
+
+```python
+# 训练过程
+for data_batch in train_dataloader:
+ data_batch = data_preprocessor(data_batch)
+ if isinstance(data_batch, dict):
+ losses = model.forward(**data_batch, mode='loss')
+ elif isinstance(data_batch, (list, tuple)):
+ losses = model.forward(*data_batch, mode='loss')
+ else:
+ raise TypeError()
+
+# 验证过程
+for data_batch in val_dataloader:
+ data_batch = data_preprocessor(data_batch)
+ if isinstance(data_batch, dict):
+ outputs = model.forward(**data_batch, mode='predict')
+ elif isinstance(data_batch, (list, tuple)):
+ outputs = model.forward(**data_batch, mode='predict')
+ else:
+ raise TypeError()
+ evaluator.process(data_samples=outputs, data_batch=data_batch)
+metrics = evaluator.evaluate(len(val_dataloader.dataset))
+```
+
+上述伪代码的关键点在于:
+
+- data_preprocessor 的输出需要经过解包后传递给 model
+- evaluator 的 `data_samples` 参数接收模型的预测结果,而 `data_batch` 参数接收 dataloader 的原始数据
+
+
+
+
+什么是 data_preprocessor?我可以用它做裁减缩放等图像预处理吗?
+
+虽然图中的 data preprocessor 与 model 是分离的,但在实际中前者是后者的一部分,因此可以在[模型](./model.md)文档中的数据处理器章节找到。
+
+通常来说,数据处理器不需要额外关注和指定,默认的数据处理器只会自动将数据搬运到 GPU 中。但是,如果你的模型与数据加载器的数据格式不匹配,你也可以自定义一个数据处理器来进行格式转换。
+
+裁减缩放等图像预处理更推荐在[数据变换](../advanced_tutorials/data_transform.md)中进行,但如果是 batch 相关的数据处理(如 batch-resize 等),可以在这里实现。
+
+
+
+
+为什么 model 产生了 3 个不同的输出? loss、predict、tensor 是什么含义?
+
+[15 分钟上手](../get_started/15_minutes.md)对此有一定的描述,你需要在自定义模型的 `forward` 函数中实现 3 条数据通路,适配训练、验证等不同需求。[模型](./model.md)文档中对此有详细解释。
+
+
+
+
+我可以看出红线是训练流程,蓝线是验证/测试流程,但绿线是什么?
+
+在目前的执行器流程中,`'tensor'` 模式的输出并未被使用,大多数情况下用户无需实现。但一些情况下输出中间结果可以方便地进行 debug
+
+
+
+
+如果我重载了 train_step 等方法,上图会完全失效吗?
+
+默认的 `train_step`、`val_step`、`test_step` 的行为,覆盖了从数据进入 `data preprocessor` 到 `model` 输出 `loss`、`predict` 结果的这一段流程,不影响其余部分。
+
+
+
+## 为什么使用执行器(可选)
+
+```{hint}
+这一部分内容并不能教会你如何使用执行器乃至整个 MMEngine,如果你正在被雇主/教授/DDL催促着几个小时内拿出成果,那这部分可能无法帮助到你,请随意跳过。但我们仍强烈推荐抽出时间阅读本章节,这可以帮助你更好地理解并使用 MMEngine
+```
+
+
+放轻松,接下来是闲聊时间
+
+恭喜你通关了执行器!这真是一篇长长的、但还算有趣(希望如此)的教程。无论如何,请相信这些都是为了让你更加**轻松**——不论是本篇教程、执行器,还是 MMEngine。
+
+执行器是 MMEngine 中所有模块的“管理者”。所有的独立模块——不论是模型、数据集这些看得见摸的着的,还是日志记录、分布式训练、随机种子等相对隐晦的——都在执行器中被统一调度、产生关联。事物之间的关系是复杂的,但执行器为你处理了一切,并提供了一个清晰易懂的配置式接口。这样做的好处主要有:
+
+1. 你可以轻易地在已搭建流程上修改/添加所需配置,而不会搅乱整个代码。也许你起初只有单卡训练,但你随时可以添加1、2行的分布式配置,切换到多卡甚至多机训练
+2. 你可以享受 MMEngine 不断引入的新特性,而不必担心后向兼容性。混合精度训练、可视化、崭新的分布式训练方式、多种设备后端……我们会在保证后向兼容性的前提下不断吸收社区的优秀建议与前沿技术,并以简洁明了的方式提供给你
+3. 你可以集中关注并实现自己的惊人想法,而不必受限于其他恼人的、不相关的细节。执行器的缺省值会为你处理绝大多数的情况
+
+所以,MMEngine 与执行器会确实地让你更加轻松。只要花费一点点努力完成迁移,你的代码与实验会随着 MMEngine 的发展而与时俱进;如果再花费一点努力,MMEngine 的配置系统可以让你更加高效地管理数据、模型、实验。便利性与可靠性,这些正是我们努力的目标。
+
+蓝色药丸,还是红色药丸——你准备好加入吗?
+
+
+
+## 下一步的建议
+
+如果你想要进一步地:
+
+
+实现自己的模型结构
+
+参考[模型(Model)](./model.md)
+
+
+
+
+使用自己的数据集
+
+参考[数据集(Dataset)与数据加载器(DataLoader)](./dataset.md)
+
+
+
+
+更换模型评测/验证指标
+
+参考[模型精度评测(Evaluation)](./evaluation.md)
+
+
+
+
+调整优化器封装(如开启混合精度训练、梯度累积等)与更换优化器
+
+参考[优化器封装(OptimWrapper)](./optim_wrapper.md)
+
+
+
+
+动态调整学习率等参数(如 warmup )
+
+参考[优化器参数调整策略(Parameter Scheduler)](./param_scheduler.md)
+
+
+
+
+其他
+
+- 左侧的“常用功能”中包含更多常用的与新特性的示例代码可供参考
+- “进阶教程”中有更多面向资深开发者的内容,可以更加灵活地配置训练流程、日志、可视化等
+- 如果以上所有内容都无法实现你的新想法,那么[钩子(Hook)](./hook.md)值得一试
+- 欢迎在我们的 [讨论版](https://github.com/open-mmlab/mmengine/discussions) 中发起话题求助!
+
+
diff --git a/testbed/open-mmlab__mmengine/examples/distributed_training.py b/testbed/open-mmlab__mmengine/examples/distributed_training.py
new file mode 100644
index 0000000000000000000000000000000000000000..7030a9f4d828c0b665a6cf7a8b05cd3705d54394
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/examples/distributed_training.py
@@ -0,0 +1,101 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import argparse
+
+import torch.nn.functional as F
+import torchvision
+import torchvision.transforms as transforms
+from torch.optim import SGD
+
+from mmengine.evaluator import BaseMetric
+from mmengine.model import BaseModel
+from mmengine.runner import Runner
+
+
+class MMResNet50(BaseModel):
+
+ def __init__(self):
+ super().__init__()
+ self.resnet = torchvision.models.resnet50()
+
+ def forward(self, imgs, labels, mode):
+ x = self.resnet(imgs)
+ if mode == 'loss':
+ return {'loss': F.cross_entropy(x, labels)}
+ elif mode == 'predict':
+ return x, labels
+
+
+class Accuracy(BaseMetric):
+
+ def process(self, data_batch, data_samples):
+ score, gt = data_samples
+ self.results.append({
+ 'batch_size': len(gt),
+ 'correct': (score.argmax(dim=1) == gt).sum().cpu(),
+ })
+
+ def compute_metrics(self, results):
+ total_correct = sum(item['correct'] for item in results)
+ total_size = sum(item['batch_size'] for item in results)
+ return dict(accuracy=100 * total_correct / total_size)
+
+
+def parse_args():
+ parser = argparse.ArgumentParser(description='Distributed Training')
+ parser.add_argument(
+ '--launcher',
+ choices=['none', 'pytorch', 'slurm', 'mpi'],
+ default='none',
+ help='job launcher')
+ parser.add_argument('--local_rank', type=int, default=0)
+
+ args = parser.parse_args()
+ return args
+
+
+def main():
+ args = parse_args()
+ norm_cfg = dict(mean=[0.491, 0.482, 0.447], std=[0.202, 0.199, 0.201])
+ train_set = torchvision.datasets.CIFAR10(
+ 'data/cifar10',
+ train=True,
+ download=True,
+ transform=transforms.Compose([
+ transforms.RandomCrop(32, padding=4),
+ transforms.RandomHorizontalFlip(),
+ transforms.ToTensor(),
+ transforms.Normalize(**norm_cfg)
+ ]))
+ valid_set = torchvision.datasets.CIFAR10(
+ 'data/cifar10',
+ train=False,
+ download=True,
+ transform=transforms.Compose(
+ [transforms.ToTensor(),
+ transforms.Normalize(**norm_cfg)]))
+ train_dataloader = dict(
+ batch_size=32,
+ dataset=train_set,
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ collate_fn=dict(type='default_collate'))
+ val_dataloader = dict(
+ batch_size=32,
+ dataset=valid_set,
+ sampler=dict(type='DefaultSampler', shuffle=False),
+ collate_fn=dict(type='default_collate'))
+ runner = Runner(
+ model=MMResNet50(),
+ work_dir='./work_dir',
+ train_dataloader=train_dataloader,
+ optim_wrapper=dict(optimizer=dict(type=SGD, lr=0.001, momentum=0.9)),
+ train_cfg=dict(by_epoch=True, max_epochs=2, val_interval=1),
+ val_dataloader=val_dataloader,
+ val_cfg=dict(),
+ val_evaluator=dict(type=Accuracy),
+ launcher=args.launcher,
+ )
+ runner.train()
+
+
+if __name__ == '__main__':
+ main()
diff --git a/testbed/open-mmlab__mmengine/mmengine/__init__.py b/testbed/open-mmlab__mmengine/mmengine/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a436c950e8ffa39af69304efc180a1ebcaceb582
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/__init__.py
@@ -0,0 +1,8 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+# flake8: noqa
+from .config import *
+from .fileio import *
+from .logging import *
+from .registry import *
+from .utils import *
+from .version import __version__, version_info
diff --git a/testbed/open-mmlab__mmengine/mmengine/config/__init__.py b/testbed/open-mmlab__mmengine/mmengine/config/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..abf09ab2f2ddefac91f3bc9fcc35035c7281297d
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/config/__init__.py
@@ -0,0 +1,4 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .config import Config, ConfigDict, DictAction
+
+__all__ = ['Config', 'ConfigDict', 'DictAction']
diff --git a/testbed/open-mmlab__mmengine/mmengine/config/config.py b/testbed/open-mmlab__mmengine/mmengine/config/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a81797880341be098abc5c9f1bcc06e4db78a43
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/config/config.py
@@ -0,0 +1,1038 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import ast
+import copy
+import os
+import os.path as osp
+import platform
+import shutil
+import tempfile
+import types
+import uuid
+import warnings
+from argparse import Action, ArgumentParser, Namespace
+from collections import abc
+from pathlib import Path
+from typing import Any, Optional, Sequence, Tuple, Union
+
+from addict import Dict
+from yapf.yapflib.yapf_api import FormatCode
+
+from mmengine.fileio import dump, load
+from mmengine.logging import print_log
+from mmengine.utils import (check_file_exist, get_installed_path,
+ import_modules_from_strings, is_installed)
+from .utils import (RemoveAssignFromAST, _get_external_cfg_base_path,
+ _get_external_cfg_path, _get_package_and_cfg_path)
+
+BASE_KEY = '_base_'
+DELETE_KEY = '_delete_'
+DEPRECATION_KEY = '_deprecation_'
+RESERVED_KEYS = ['filename', 'text', 'pretty_text']
+
+if platform.system() == 'Windows':
+ import regex as re
+else:
+ import re # type: ignore
+
+
+class ConfigDict(Dict):
+ """A dictionary for config which has the same interface as python's built-
+ in dictionary and can be used as a normal dictionary.
+
+ The Config class would transform the nested fields (dictionary-like fields)
+ in config file into ``ConfigDict``.
+ """
+
+ def __missing__(self, name):
+ raise KeyError(name)
+
+ def __getattr__(self, name):
+ try:
+ value = super().__getattr__(name)
+ except KeyError:
+ raise AttributeError(f"'{self.__class__.__name__}' object has no "
+ f"attribute '{name}'")
+ except Exception as e:
+ raise e
+ else:
+ return value
+
+
+def add_args(parser: ArgumentParser,
+ cfg: dict,
+ prefix: str = '') -> ArgumentParser:
+ """Add config fields into argument parser.
+
+ Args:
+ parser (ArgumentParser): Argument parser.
+ cfg (dict): Config dictionary.
+ prefix (str, optional): Prefix of parser argument.
+ Defaults to ''.
+
+ Returns:
+ ArgumentParser: Argument parser containing config fields.
+ """
+ for k, v in cfg.items():
+ if isinstance(v, str):
+ parser.add_argument('--' + prefix + k)
+ elif isinstance(v, bool):
+ parser.add_argument('--' + prefix + k, action='store_true')
+ elif isinstance(v, int):
+ parser.add_argument('--' + prefix + k, type=int)
+ elif isinstance(v, float):
+ parser.add_argument('--' + prefix + k, type=float)
+ elif isinstance(v, dict):
+ add_args(parser, v, prefix + k + '.')
+ elif isinstance(v, abc.Iterable):
+ parser.add_argument(
+ '--' + prefix + k, type=type(next(iter(v))), nargs='+')
+ else:
+ print_log(
+ f'cannot parse key {prefix + k} of type {type(v)}',
+ logger='current')
+ return parser
+
+
+class Config:
+ """A facility for config and config files.
+
+ It supports common file formats as configs: python/json/yaml.
+ ``Config.fromfile`` can parse a dictionary from a config file, then
+ build a ``Config`` instance with the dictionary.
+ The interface is the same as a dict object and also allows access config
+ values as attributes.
+
+ Args:
+ cfg_dict (dict, optional): A config dictionary. Defaults to None.
+ cfg_text (str, optional): Text of config. Defaults to None.
+ filename (str or Path, optional): Name of config file.
+ Defaults to None.
+
+ Examples:
+ >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1])))
+ >>> cfg.a
+ 1
+ >>> cfg.b
+ {'b1': [0, 1]}
+ >>> cfg.b.b1
+ [0, 1]
+ >>> cfg = Config.fromfile('tests/data/config/a.py')
+ >>> cfg.filename
+ "/home/username/projects/mmengine/tests/data/config/a.py"
+ >>> cfg.item4
+ 'test'
+ >>> cfg
+ "Config [path: /home/username/projects/mmengine/tests/data/config/a.py]
+ :"
+ "{'item1': [1, 2], 'item2': {'a': 0}, 'item3': True, 'item4': 'test'}"
+ """
+
+ def __init__(self,
+ cfg_dict: dict = None,
+ cfg_text: Optional[str] = None,
+ filename: Optional[Union[str, Path]] = None):
+ filename = str(filename) if isinstance(filename, Path) else filename
+ if cfg_dict is None:
+ cfg_dict = dict()
+ elif not isinstance(cfg_dict, dict):
+ raise TypeError('cfg_dict must be a dict, but '
+ f'got {type(cfg_dict)}')
+ for key in cfg_dict:
+ if key in RESERVED_KEYS:
+ raise KeyError(f'{key} is reserved for config file')
+
+ super().__setattr__('_cfg_dict', ConfigDict(cfg_dict))
+ super().__setattr__('_filename', filename)
+ if cfg_text:
+ text = cfg_text
+ elif filename:
+ with open(filename, encoding='utf-8') as f:
+ text = f.read()
+ else:
+ text = ''
+ super().__setattr__('_text', text)
+
+ @staticmethod
+ def fromfile(filename: Union[str, Path],
+ use_predefined_variables: bool = True,
+ import_custom_modules: bool = True) -> 'Config':
+ """Build a Config instance from config file.
+
+ Args:
+ filename (str or Path): Name of config file.
+ use_predefined_variables (bool, optional): Whether to use
+ predefined variables. Defaults to True.
+ import_custom_modules (bool, optional): Whether to support
+ importing custom modules in config. Defaults to True.
+
+ Returns:
+ Config: Config instance built from config file.
+ """
+ filename = str(filename) if isinstance(filename, Path) else filename
+ cfg_dict, cfg_text = Config._file2dict(filename,
+ use_predefined_variables)
+ if import_custom_modules and cfg_dict.get('custom_imports', None):
+ try:
+ import_modules_from_strings(**cfg_dict['custom_imports'])
+ except ImportError as e:
+ raise ImportError('Failed to custom import!') from e
+ return Config(cfg_dict, cfg_text=cfg_text, filename=filename)
+
+ @staticmethod
+ def fromstring(cfg_str: str, file_format: str) -> 'Config':
+ """Build a Config instance from config text.
+
+ Args:
+ cfg_str (str): Config text.
+ file_format (str): Config file format corresponding to the
+ config str. Only py/yml/yaml/json type are supported now!
+
+ Returns:
+ Config: Config object generated from ``cfg_str``.
+ """
+ if file_format not in ['.py', '.json', '.yaml', '.yml']:
+ raise OSError('Only py/yml/yaml/json type are supported now!')
+ if file_format != '.py' and 'dict(' in cfg_str:
+ # check if users specify a wrong suffix for python
+ warnings.warn(
+ 'Please check "file_format", the file format may be .py')
+
+ # A temporary file can not be opened a second time on Windows.
+ # See https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile for more details. # noqa
+ # `temp_file` is opened first in `tempfile.NamedTemporaryFile` and
+ # second in `Config.from_file`.
+ # In addition, a named temporary file will be removed after closed.
+ # As a workaround we set `delete=False` and close the temporary file
+ # before opening again.
+
+ with tempfile.NamedTemporaryFile(
+ 'w', encoding='utf-8', suffix=file_format,
+ delete=False) as temp_file:
+ temp_file.write(cfg_str)
+
+ cfg = Config.fromfile(temp_file.name)
+ os.remove(temp_file.name) # manually delete the temporary file
+ return cfg
+
+ @staticmethod
+ def _validate_py_syntax(filename: str):
+ """Validate syntax of python config.
+
+ Args:
+ filename (str): Filename of python config file.
+ """
+ with open(filename, encoding='utf-8') as f:
+ content = f.read()
+ try:
+ ast.parse(content)
+ except SyntaxError as e:
+ raise SyntaxError('There are syntax errors in config '
+ f'file {filename}: {e}')
+
+ @staticmethod
+ def _substitute_predefined_vars(filename: str, temp_config_name: str):
+ """Substitute predefined variables in config with actual values.
+
+ Sometimes we want some variables in the config to be related to the
+ current path or file name, etc.
+
+ Here is an example of a typical usage scenario. When training a model,
+ we define a working directory in the config that save the models and
+ logs. For different configs, we expect to define different working
+ directories. A common way for users is to use the config file name
+ directly as part of the working directory name, e.g. for the config
+ ``config_setting1.py``, the working directory is
+ ``. /work_dir/config_setting1``.
+
+ This can be easily achieved using predefined variables, which can be
+ written in the config `config_setting1.py` as follows
+
+ .. code-block:: python
+
+ work_dir = '. /work_dir/{{ fileBasenameNoExtension }}'
+
+
+ Here `{{ fileBasenameNoExtension }}` indicates the file name of the
+ config (without the extension), and when the config class reads the
+ config file, it will automatically parse this double-bracketed string
+ to the corresponding actual value.
+
+ .. code-block:: python
+
+ cfg = Config.fromfile('. /config_setting1.py')
+ cfg.work_dir # ". /work_dir/config_setting1"
+
+
+ For details, Please refer to docs/zh_cn/advanced_tutorials/config.md .
+
+ Args:
+ filename (str): Filename of config.
+ temp_config_name (str): Temporary filename to save substituted
+ config.
+ """
+ file_dirname = osp.dirname(filename)
+ file_basename = osp.basename(filename)
+ file_basename_no_extension = osp.splitext(file_basename)[0]
+ file_extname = osp.splitext(filename)[1]
+ support_templates = dict(
+ fileDirname=file_dirname,
+ fileBasename=file_basename,
+ fileBasenameNoExtension=file_basename_no_extension,
+ fileExtname=file_extname)
+ with open(filename, encoding='utf-8') as f:
+ config_file = f.read()
+ for key, value in support_templates.items():
+ regexp = r'\{\{\s*' + str(key) + r'\s*\}\}'
+ value = value.replace('\\', '/')
+ config_file = re.sub(regexp, value, config_file)
+ with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file:
+ tmp_config_file.write(config_file)
+
+ @staticmethod
+ def _pre_substitute_base_vars(filename: str,
+ temp_config_name: str) -> dict:
+ """Preceding step for substituting variables in base config with actual
+ value.
+
+ Args:
+ filename (str): Filename of config.
+ temp_config_name (str): Temporary filename to save substituted
+ config.
+
+ Returns:
+ dict: A dictionary contains variables in base config.
+ """
+ with open(filename, encoding='utf-8') as f:
+ config_file = f.read()
+ base_var_dict = {}
+ regexp = r'\{\{\s*' + BASE_KEY + r'\.([\w\.]+)\s*\}\}'
+ base_vars = set(re.findall(regexp, config_file))
+ for base_var in base_vars:
+ randstr = f'_{base_var}_{uuid.uuid4().hex.lower()[:6]}'
+ base_var_dict[randstr] = base_var
+ regexp = r'\{\{\s*' + BASE_KEY + r'\.' + base_var + r'\s*\}\}'
+ config_file = re.sub(regexp, f'"{randstr}"', config_file)
+ with open(temp_config_name, 'w', encoding='utf-8') as tmp_config_file:
+ tmp_config_file.write(config_file)
+ return base_var_dict
+
+ @staticmethod
+ def _substitute_base_vars(cfg: Any, base_var_dict: dict,
+ base_cfg: dict) -> Any:
+ """Substitute base variables from strings to their actual values.
+
+ Args:
+ Any : Config dictionary.
+ base_var_dict (dict): A dictionary contains variables in base
+ config.
+ base_cfg (dict): Base config dictionary.
+
+ Returns:
+ Any : A dictionary with origin base variables
+ substituted with actual values.
+ """
+ cfg = copy.deepcopy(cfg)
+
+ if isinstance(cfg, dict):
+ for k, v in cfg.items():
+ if isinstance(v, str) and v in base_var_dict:
+ new_v = base_cfg
+ for new_k in base_var_dict[v].split('.'):
+ new_v = new_v[new_k]
+ cfg[k] = new_v
+ elif isinstance(v, (list, tuple, dict)):
+ cfg[k] = Config._substitute_base_vars(
+ v, base_var_dict, base_cfg)
+ elif isinstance(cfg, tuple):
+ cfg = tuple(
+ Config._substitute_base_vars(c, base_var_dict, base_cfg)
+ for c in cfg)
+ elif isinstance(cfg, list):
+ cfg = [
+ Config._substitute_base_vars(c, base_var_dict, base_cfg)
+ for c in cfg
+ ]
+ elif isinstance(cfg, str) and cfg in base_var_dict:
+ new_v = base_cfg
+ for new_k in base_var_dict[cfg].split('.'):
+ new_v = new_v[new_k]
+ cfg = new_v
+
+ return cfg
+
+ @staticmethod
+ def _file2dict(filename: str,
+ use_predefined_variables: bool = True) -> Tuple[dict, str]:
+ """Transform file to variables dictionary.
+
+ Args:
+ filename (str): Name of config file.
+ use_predefined_variables (bool, optional): Whether to use
+ predefined variables. Defaults to True.
+
+ Returns:
+ Tuple[dict, str]: Variables dictionary and text of Config.
+ """
+ filename = osp.abspath(osp.expanduser(filename))
+ check_file_exist(filename)
+ fileExtname = osp.splitext(filename)[1]
+ if fileExtname not in ['.py', '.json', '.yaml', '.yml']:
+ raise OSError('Only py/yml/yaml/json type are supported now!')
+
+ with tempfile.TemporaryDirectory() as temp_config_dir:
+ temp_config_file = tempfile.NamedTemporaryFile(
+ dir=temp_config_dir, suffix=fileExtname)
+ if platform.system() == 'Windows':
+ temp_config_file.close()
+
+ # Substitute predefined variables
+ if use_predefined_variables:
+ Config._substitute_predefined_vars(filename,
+ temp_config_file.name)
+ else:
+ shutil.copyfile(filename, temp_config_file.name)
+ # Substitute base variables from placeholders to strings
+ base_var_dict = Config._pre_substitute_base_vars(
+ temp_config_file.name, temp_config_file.name)
+
+ # Handle base files
+ base_cfg_dict = ConfigDict()
+ cfg_text_list = list()
+ for base_cfg_path in Config._get_base_files(temp_config_file.name):
+ base_cfg_path, scope = Config._get_cfg_path(
+ base_cfg_path, filename)
+ _cfg_dict, _cfg_text = Config._file2dict(base_cfg_path)
+ cfg_text_list.append(_cfg_text)
+ duplicate_keys = base_cfg_dict.keys() & _cfg_dict.keys()
+ if len(duplicate_keys) > 0:
+ raise KeyError('Duplicate key is not allowed among bases. '
+ f'Duplicate keys: {duplicate_keys}')
+
+ # _dict_to_config_dict will do the following things:
+ # 1. Recursively converts ``dict`` to :obj:`ConfigDict`.
+ # 2. Set `_scope_` for the outer dict variable for the base
+ # config.
+ # 3. Set `scope` attribute for each base variable. Different
+ # from `_scope_`, `scope` is not a key of base dict,
+ # `scope` attribute will be parsed to key `_scope_` by
+ # function `_parse_scope` only if the base variable is
+ # accessed by the current config.
+ _cfg_dict = Config._dict_to_config_dict(_cfg_dict, scope)
+ base_cfg_dict.update(_cfg_dict)
+
+ if filename.endswith('.py'):
+ with open(temp_config_file.name, encoding='utf-8') as f:
+ codes = ast.parse(f.read())
+ codes = RemoveAssignFromAST(BASE_KEY).visit(codes)
+ codeobj = compile(codes, '', mode='exec')
+ # Support load global variable in nested function of the
+ # config.
+ global_locals_var = {'_base_': base_cfg_dict}
+ ori_keys = set(global_locals_var.keys())
+ eval(codeobj, global_locals_var, global_locals_var)
+ cfg_dict = {
+ key: value
+ for key, value in global_locals_var.items()
+ if (key not in ori_keys and not key.startswith('__'))
+ }
+ elif filename.endswith(('.yml', '.yaml', '.json')):
+ cfg_dict = load(temp_config_file.name)
+ # close temp file
+ for key, value in list(cfg_dict.items()):
+ if isinstance(value, (types.FunctionType, types.ModuleType)):
+ cfg_dict.pop(key)
+ temp_config_file.close()
+
+ # If the current config accesses a base variable of base
+ # configs, The ``scope`` attribute of corresponding variable
+ # will be converted to the `_scope_`.
+ Config._parse_scope(cfg_dict)
+
+ # check deprecation information
+ if DEPRECATION_KEY in cfg_dict:
+ deprecation_info = cfg_dict.pop(DEPRECATION_KEY)
+ warning_msg = f'The config file {filename} will be deprecated ' \
+ 'in the future.'
+ if 'expected' in deprecation_info:
+ warning_msg += f' Please use {deprecation_info["expected"]} ' \
+ 'instead.'
+ if 'reference' in deprecation_info:
+ warning_msg += ' More information can be found at ' \
+ f'{deprecation_info["reference"]}'
+ warnings.warn(warning_msg, DeprecationWarning)
+
+ cfg_text = filename + '\n'
+ with open(filename, encoding='utf-8') as f:
+ # Setting encoding explicitly to resolve coding issue on windows
+ cfg_text += f.read()
+
+ # Substitute base variables from strings to their actual values
+ cfg_dict = Config._substitute_base_vars(cfg_dict, base_var_dict,
+ base_cfg_dict)
+ cfg_dict.pop(BASE_KEY, None)
+
+ cfg_dict = Config._merge_a_into_b(cfg_dict, base_cfg_dict)
+ cfg_dict = {
+ k: v
+ for k, v in cfg_dict.items() if not k.startswith('__')
+ }
+
+ # merge cfg_text
+ cfg_text_list.append(cfg_text)
+ cfg_text = '\n'.join(cfg_text_list)
+
+ return cfg_dict, cfg_text
+
+ @staticmethod
+ def _dict_to_config_dict(cfg: dict,
+ scope: Optional[str] = None,
+ has_scope=True):
+ """Recursively converts ``dict`` to :obj:`ConfigDict`.
+
+ Args:
+ cfg (dict): Config dict.
+ scope (str, optional): Scope of instance.
+ has_scope (bool): Whether to add `_scope_` key to config dict.
+
+ Returns:
+ ConfigDict: Converted dict.
+ """
+ # Only the outer dict with key `type` should have the key `_scope_`.
+ if isinstance(cfg, dict):
+ if has_scope and 'type' in cfg:
+ has_scope = False
+ if scope is not None and cfg.get('_scope_', None) is None:
+ cfg._scope_ = scope # type: ignore
+ cfg = ConfigDict(cfg)
+ dict.__setattr__(cfg, 'scope', scope)
+ for key, value in cfg.items():
+ cfg[key] = Config._dict_to_config_dict(
+ value, scope=scope, has_scope=has_scope)
+ elif isinstance(cfg, tuple):
+ cfg = tuple(
+ Config._dict_to_config_dict(_cfg, scope, has_scope=has_scope)
+ for _cfg in cfg)
+ elif isinstance(cfg, list):
+ cfg = [
+ Config._dict_to_config_dict(_cfg, scope, has_scope=has_scope)
+ for _cfg in cfg
+ ]
+ return cfg
+
+ @staticmethod
+ def _parse_scope(cfg: dict) -> None:
+ """Adds ``_scope_`` to :obj:`ConfigDict` instance, which means a base
+ variable.
+
+ If the config dict already has the scope, scope will not be
+ overwritten.
+
+ Args:
+ cfg (dict): Config needs to be parsed with scope.
+ """
+ if isinstance(cfg, ConfigDict):
+ cfg._scope_ = cfg.scope
+ elif isinstance(cfg, (tuple, list)):
+ [Config._parse_scope(value) for value in cfg]
+ else:
+ return
+
+ @staticmethod
+ def _get_base_files(filename: str) -> list:
+ """Get the base config file.
+
+ Args:
+ filename (str): The config file.
+
+ Raises:
+ TypeError: Name of config file.
+
+ Returns:
+ list: A list of base config.
+ """
+ file_format = filename.partition('.')[-1]
+ if file_format == 'py':
+ Config._validate_py_syntax(filename)
+ with open(filename, encoding='utf-8') as f:
+ codes = ast.parse(f.read()).body
+
+ def is_base_line(c):
+ return (isinstance(c, ast.Assign)
+ and isinstance(c.targets[0], ast.Name)
+ and c.targets[0].id == BASE_KEY)
+
+ base_code = next((c for c in codes if is_base_line(c)), None)
+ if base_code is not None:
+ base_code = ast.Expression( # type: ignore
+ body=base_code.value) # type: ignore
+ base_files = eval(compile(base_code, '', mode='eval'))
+ else:
+ base_files = []
+ elif file_format in ('yml', 'yaml', 'json'):
+ import mmengine
+ cfg_dict = mmengine.load(filename)
+ base_files = cfg_dict.get(BASE_KEY, [])
+ else:
+ raise TypeError('The config type should be py, json, yaml or '
+ f'yml, but got {file_format}')
+ base_files = base_files if isinstance(base_files,
+ list) else [base_files]
+ return base_files
+
+ @staticmethod
+ def _get_cfg_path(cfg_path: str,
+ filename: str) -> Tuple[str, Optional[str]]:
+ """Get the config path from the current or external package.
+
+ Args:
+ cfg_path (str): Relative path of config.
+ filename (str): The config file being parsed.
+
+ Returns:
+ Tuple[str, str or None]: Path and scope of config. If the config
+ is not an external config, the scope will be `None`.
+ """
+ if '::' in cfg_path:
+ # `cfg_path` startswith '::' means an external config path.
+ # Get package name and relative config path.
+ scope = cfg_path.partition('::')[0]
+ package, cfg_path = _get_package_and_cfg_path(cfg_path)
+
+ if not is_installed(package):
+ raise ModuleNotFoundError(
+ f'{package} is not installed, please install {package} '
+ f'manually')
+
+ # Get installed package path.
+ package_path = get_installed_path(package)
+ try:
+ # Get config path from meta file.
+ cfg_path = _get_external_cfg_path(package_path, cfg_path)
+ except ValueError:
+ # Since base config does not have a metafile, it should be
+ # concatenated with package path and relative config path.
+ cfg_path = _get_external_cfg_base_path(package_path, cfg_path)
+ except FileNotFoundError as e:
+ raise e
+ return cfg_path, scope
+ else:
+ # Get local config path.
+ cfg_dir = osp.dirname(filename)
+ cfg_path = osp.join(cfg_dir, cfg_path)
+ return cfg_path, None
+
+ @staticmethod
+ def _merge_a_into_b(a: dict,
+ b: dict,
+ allow_list_keys: bool = False) -> dict:
+ """merge dict ``a`` into dict ``b`` (non-inplace).
+
+ Values in ``a`` will overwrite ``b``. ``b`` is copied first to avoid
+ in-place modifications.
+
+ Args:
+ a (dict): The source dict to be merged into ``b``.
+ b (dict): The origin dict to be fetch keys from ``a``.
+ allow_list_keys (bool): If True, int string keys (e.g. '0', '1')
+ are allowed in source ``a`` and will replace the element of the
+ corresponding index in b if b is a list. Defaults to False.
+
+ Returns:
+ dict: The modified dict of ``b`` using ``a``.
+
+ Examples:
+ # Normally merge a into b.
+ >>> Config._merge_a_into_b(
+ ... dict(obj=dict(a=2)), dict(obj=dict(a=1)))
+ {'obj': {'a': 2}}
+
+ # Delete b first and merge a into b.
+ >>> Config._merge_a_into_b(
+ ... dict(obj=dict(_delete_=True, a=2)), dict(obj=dict(a=1)))
+ {'obj': {'a': 2}}
+
+ # b is a list
+ >>> Config._merge_a_into_b(
+ ... {'0': dict(a=2)}, [dict(a=1), dict(b=2)], True)
+ [{'a': 2}, {'b': 2}]
+ """
+ b = b.copy()
+ for k, v in a.items():
+ if allow_list_keys and k.isdigit() and isinstance(b, list):
+ k = int(k)
+ if len(b) <= k:
+ raise KeyError(f'Index {k} exceeds the length of list {b}')
+ b[k] = Config._merge_a_into_b(v, b[k], allow_list_keys)
+ elif isinstance(v, dict):
+ if k in b and not v.pop(DELETE_KEY, False):
+ allowed_types: Union[Tuple, type] = (
+ dict, list) if allow_list_keys else dict
+ if not isinstance(b[k], allowed_types):
+ raise TypeError(
+ f'{k}={v} in child config cannot inherit from '
+ f'base because {k} is a dict in the child config '
+ f'but is of type {type(b[k])} in base config. '
+ f'You may set `{DELETE_KEY}=True` to ignore the '
+ f'base config.')
+ b[k] = Config._merge_a_into_b(v, b[k], allow_list_keys)
+ else:
+ b[k] = ConfigDict(v)
+ else:
+ b[k] = v
+ return b
+
+ @staticmethod
+ def auto_argparser(description=None):
+ """Generate argparser from config file automatically (experimental)"""
+ partial_parser = ArgumentParser(description=description)
+ partial_parser.add_argument('config', help='config file path')
+ cfg_file = partial_parser.parse_known_args()[0].config
+ cfg = Config.fromfile(cfg_file)
+ parser = ArgumentParser(description=description)
+ parser.add_argument('config', help='config file path')
+ add_args(parser, cfg)
+ return parser, cfg
+
+ @property
+ def filename(self) -> str:
+ """get file name of config."""
+ return self._filename
+
+ @property
+ def text(self) -> str:
+ """get config text."""
+ return self._text
+
+ @property
+ def pretty_text(self) -> str:
+ """get formatted python config text."""
+
+ indent = 4
+
+ def _indent(s_, num_spaces):
+ s = s_.split('\n')
+ if len(s) == 1:
+ return s_
+ first = s.pop(0)
+ s = [(num_spaces * ' ') + line for line in s]
+ s = '\n'.join(s)
+ s = first + '\n' + s
+ return s
+
+ def _format_basic_types(k, v, use_mapping=False):
+ if isinstance(v, str):
+ v_str = repr(v)
+ else:
+ v_str = str(v)
+
+ if use_mapping:
+ k_str = f"'{k}'" if isinstance(k, str) else str(k)
+ attr_str = f'{k_str}: {v_str}'
+ else:
+ attr_str = f'{str(k)}={v_str}'
+ attr_str = _indent(attr_str, indent)
+
+ return attr_str
+
+ def _format_list(k, v, use_mapping=False):
+ # check if all items in the list are dict
+ if all(isinstance(_, dict) for _ in v):
+ v_str = '[\n'
+ v_str += '\n'.join(
+ f'dict({_indent(_format_dict(v_), indent)}),'
+ for v_ in v).rstrip(',')
+ if use_mapping:
+ k_str = f"'{k}'" if isinstance(k, str) else str(k)
+ attr_str = f'{k_str}: {v_str}'
+ else:
+ attr_str = f'{str(k)}={v_str}'
+ attr_str = _indent(attr_str, indent) + ']'
+ else:
+ attr_str = _format_basic_types(k, v, use_mapping)
+ return attr_str
+
+ def _contain_invalid_identifier(dict_str):
+ contain_invalid_identifier = False
+ for key_name in dict_str:
+ contain_invalid_identifier |= \
+ (not str(key_name).isidentifier())
+ return contain_invalid_identifier
+
+ def _format_dict(input_dict, outest_level=False):
+ r = ''
+ s = []
+
+ use_mapping = _contain_invalid_identifier(input_dict)
+ if use_mapping:
+ r += '{'
+ for idx, (k, v) in enumerate(input_dict.items()):
+ is_last = idx >= len(input_dict) - 1
+ end = '' if outest_level or is_last else ','
+ if isinstance(v, dict):
+ v_str = '\n' + _format_dict(v)
+ if use_mapping:
+ k_str = f"'{k}'" if isinstance(k, str) else str(k)
+ attr_str = f'{k_str}: dict({v_str}'
+ else:
+ attr_str = f'{str(k)}=dict({v_str}'
+ attr_str = _indent(attr_str, indent) + ')' + end
+ elif isinstance(v, list):
+ attr_str = _format_list(k, v, use_mapping) + end
+ else:
+ attr_str = _format_basic_types(k, v, use_mapping) + end
+
+ s.append(attr_str)
+ r += '\n'.join(s)
+ if use_mapping:
+ r += '}'
+ return r
+
+ cfg_dict = self._cfg_dict.to_dict()
+ text = _format_dict(cfg_dict, outest_level=True)
+ # copied from setup.cfg
+ yapf_style = dict(
+ based_on_style='pep8',
+ blank_line_before_nested_class_or_def=True,
+ split_before_expression_after_opening_paren=True)
+ text, _ = FormatCode(text, style_config=yapf_style, verify=True)
+
+ return text
+
+ def __repr__(self):
+ return f'Config (path: {self.filename}): {self._cfg_dict.__repr__()}'
+
+ def __len__(self):
+ return len(self._cfg_dict)
+
+ def __getattr__(self, name: str) -> Any:
+ return getattr(self._cfg_dict, name)
+
+ def __getitem__(self, name):
+ return self._cfg_dict.__getitem__(name)
+
+ def __setattr__(self, name, value):
+ if isinstance(value, dict):
+ value = ConfigDict(value)
+ self._cfg_dict.__setattr__(name, value)
+
+ def __setitem__(self, name, value):
+ if isinstance(value, dict):
+ value = ConfigDict(value)
+ self._cfg_dict.__setitem__(name, value)
+
+ def __iter__(self):
+ return iter(self._cfg_dict)
+
+ def __getstate__(self) -> Tuple[dict, Optional[str], Optional[str]]:
+ return (self._cfg_dict, self._filename, self._text)
+
+ def __deepcopy__(self, memo):
+ cls = self.__class__
+ other = cls.__new__(cls)
+ memo[id(self)] = other
+
+ for key, value in self.__dict__.items():
+ super(Config, other).__setattr__(key, copy.deepcopy(value, memo))
+
+ return other
+
+ def __copy__(self):
+ cls = self.__class__
+ other = cls.__new__(cls)
+ other.__dict__.update(self.__dict__)
+
+ return other
+
+ def __setstate__(self, state: Tuple[dict, Optional[str], Optional[str]]):
+ _cfg_dict, _filename, _text = state
+ super().__setattr__('_cfg_dict', _cfg_dict)
+ super().__setattr__('_filename', _filename)
+ super().__setattr__('_text', _text)
+
+ def dump(self, file: Optional[Union[str, Path]] = None):
+ """Dump config to file or return config text.
+
+ Args:
+ file (str or Path, optional): If not specified, then the object
+ is dumped to a str, otherwise to a file specified by the filename.
+ Defaults to None.
+
+ Returns:
+ str or None: Config text.
+ """
+ file = str(file) if isinstance(file, Path) else file
+ cfg_dict = super().__getattribute__('_cfg_dict').to_dict()
+ if file is None:
+ if self.filename is None or self.filename.endswith('.py'):
+ return self.pretty_text
+ else:
+ file_format = self.filename.split('.')[-1]
+ return dump(cfg_dict, file_format=file_format)
+ elif file.endswith('.py'):
+ with open(file, 'w', encoding='utf-8') as f:
+ f.write(self.pretty_text)
+ else:
+ file_format = file.split('.')[-1]
+ return dump(cfg_dict, file=file, file_format=file_format)
+
+ def merge_from_dict(self,
+ options: dict,
+ allow_list_keys: bool = True) -> None:
+ """Merge list into cfg_dict.
+
+ Merge the dict parsed by MultipleKVAction into this cfg.
+
+ Args:
+ options (dict): dict of configs to merge from.
+ allow_list_keys (bool): If True, int string keys (e.g. '0', '1')
+ are allowed in ``options`` and will replace the element of the
+ corresponding index in the config if the config is a list.
+ Defaults to True.
+
+ Examples:
+ >>> from mmengine import Config
+ >>> # Merge dictionary element
+ >>> options = {'model.backbone.depth': 50, 'model.backbone.with_cp': True}
+ >>> cfg = Config(dict(model=dict(backbone=dict(type='ResNet'))))
+ >>> cfg.merge_from_dict(options)
+ >>> cfg._cfg_dict
+ {'model': {'backbone': {'type': 'ResNet', 'depth': 50, 'with_cp': True}}}
+ >>> # Merge list element
+ >>> cfg = Config(
+ >>> dict(pipeline=[dict(type='LoadImage'),
+ >>> dict(type='LoadAnnotations')]))
+ >>> options = dict(pipeline={'0': dict(type='SelfLoadImage')})
+ >>> cfg.merge_from_dict(options, allow_list_keys=True)
+ >>> cfg._cfg_dict
+ {'pipeline': [{'type': 'SelfLoadImage'}, {'type': 'LoadAnnotations'}]}
+ """ # noqa: E501
+ option_cfg_dict: dict = {}
+ for full_key, v in options.items():
+ d = option_cfg_dict
+ key_list = full_key.split('.')
+ for subkey in key_list[:-1]:
+ d.setdefault(subkey, ConfigDict())
+ d = d[subkey]
+ subkey = key_list[-1]
+ d[subkey] = v
+
+ cfg_dict = super().__getattribute__('_cfg_dict')
+ super().__setattr__(
+ '_cfg_dict',
+ Config._merge_a_into_b(
+ option_cfg_dict, cfg_dict, allow_list_keys=allow_list_keys))
+
+
+class DictAction(Action):
+ """
+ argparse action to split an argument into KEY=VALUE form
+ on the first = and append to a dictionary. List options can
+ be passed as comma separated values, i.e 'KEY=V1,V2,V3', or with explicit
+ brackets, i.e. 'KEY=[V1,V2,V3]'. It also support nested brackets to build
+ list/tuple values. e.g. 'KEY=[(V1,V2),(V3,V4)]'
+ """
+
+ @staticmethod
+ def _parse_int_float_bool(val: str) -> Union[int, float, bool, Any]:
+ """parse int/float/bool value in the string."""
+ try:
+ return int(val)
+ except ValueError:
+ pass
+ try:
+ return float(val)
+ except ValueError:
+ pass
+ if val.lower() in ['true', 'false']:
+ return True if val.lower() == 'true' else False
+ if val == 'None':
+ return None
+ return val
+
+ @staticmethod
+ def _parse_iterable(val: str) -> Union[list, tuple, Any]:
+ """Parse iterable values in the string.
+
+ All elements inside '()' or '[]' are treated as iterable values.
+
+ Args:
+ val (str): Value string.
+
+ Returns:
+ list | tuple | Any: The expanded list or tuple from the string,
+ or single value if no iterable values are found.
+
+ Examples:
+ >>> DictAction._parse_iterable('1,2,3')
+ [1, 2, 3]
+ >>> DictAction._parse_iterable('[a, b, c]')
+ ['a', 'b', 'c']
+ >>> DictAction._parse_iterable('[(1, 2, 3), [a, b], c]')
+ [(1, 2, 3), ['a', 'b'], 'c']
+ """
+
+ def find_next_comma(string):
+ """Find the position of next comma in the string.
+
+ If no ',' is found in the string, return the string length. All
+ chars inside '()' and '[]' are treated as one element and thus ','
+ inside these brackets are ignored.
+ """
+ assert (string.count('(') == string.count(')')) and (
+ string.count('[') == string.count(']')), \
+ f'Imbalanced brackets exist in {string}'
+ end = len(string)
+ for idx, char in enumerate(string):
+ pre = string[:idx]
+ # The string before this ',' is balanced
+ if ((char == ',') and (pre.count('(') == pre.count(')'))
+ and (pre.count('[') == pre.count(']'))):
+ end = idx
+ break
+ return end
+
+ # Strip ' and " characters and replace whitespace.
+ val = val.strip('\'\"').replace(' ', '')
+ is_tuple = False
+ if val.startswith('(') and val.endswith(')'):
+ is_tuple = True
+ val = val[1:-1]
+ elif val.startswith('[') and val.endswith(']'):
+ val = val[1:-1]
+ elif ',' not in val:
+ # val is a single value
+ return DictAction._parse_int_float_bool(val)
+
+ values = []
+ while len(val) > 0:
+ comma_idx = find_next_comma(val)
+ element = DictAction._parse_iterable(val[:comma_idx])
+ values.append(element)
+ val = val[comma_idx + 1:]
+
+ if is_tuple:
+ return tuple(values)
+
+ return values
+
+ def __call__(self,
+ parser: ArgumentParser,
+ namespace: Namespace,
+ values: Union[str, Sequence[Any], None],
+ option_string: str = None):
+ """Parse Variables in string and add them into argparser.
+
+ Args:
+ parser (ArgumentParser): Argument parser.
+ namespace (Namespace): Argument namespace.
+ values (Union[str, Sequence[Any], None]): Argument string.
+ option_string (list[str], optional): Option string.
+ Defaults to None.
+ """
+ # Copied behavior from `argparse._ExtendAction`.
+ options = copy.copy(getattr(namespace, self.dest, None) or {})
+ if values is not None:
+ for kv in values:
+ key, val = kv.split('=', maxsplit=1)
+ options[key] = self._parse_iterable(val)
+ setattr(namespace, self.dest, options)
diff --git a/testbed/open-mmlab__mmengine/mmengine/config/utils.py b/testbed/open-mmlab__mmengine/mmengine/config/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ff0b01de1a01aadd8e8762c6bf1cd651f24b42b
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/config/utils.py
@@ -0,0 +1,138 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import ast
+import os.path as osp
+import re
+import warnings
+from typing import Tuple
+
+from mmengine.fileio import load
+from mmengine.utils import check_file_exist
+
+PKG2PROJECT = {
+ 'mmcls': 'mmcls',
+ 'mmdet': 'mmdet',
+ 'mmdet3d': 'mmdet3d',
+ 'mmseg': 'mmsegmentation',
+ 'mmaction2': 'mmaction2',
+ 'mmtrack': 'mmtrack',
+ 'mmpose': 'mmpose',
+ 'mmedit': 'mmedit',
+ 'mmocr': 'mmocr',
+ 'mmgen': 'mmgen',
+ 'mmfewshot': 'mmfewshot',
+ 'mmrazor': 'mmrazor',
+ 'mmflow': 'mmflow',
+ 'mmhuman3d': 'mmhuman3d',
+ 'mmrotate': 'mmrotate',
+ 'mmselfsup': 'mmselfsup',
+ 'mmyolo': 'mmyolo',
+}
+
+
+def _get_cfg_metainfo(package_path: str, cfg_path: str) -> dict:
+ """Get target meta information from all 'metafile.yml' defined in `mode-
+ index.yml` of external package.
+
+ Args:
+ package_path (str): Path of external package.
+ cfg_path (str): Name of experiment config.
+
+ Returns:
+ dict: Meta information of target experiment.
+ """
+ meta_index_path = osp.join(package_path, '.mim', 'model-index.yml')
+ meta_index = load(meta_index_path)
+ cfg_dict = dict()
+ for meta_path in meta_index['Import']:
+ meta_path = osp.join(package_path, '.mim', meta_path)
+ cfg_meta = load(meta_path)
+ for model_cfg in cfg_meta['Models']:
+ if 'Config' not in model_cfg:
+ warnings.warn(f'There is not `Config` define in {model_cfg}')
+ continue
+ cfg_name = model_cfg['Config'].partition('/')[-1]
+ # Some config could have multiple weights, we only pick the
+ # first one.
+ if cfg_name in cfg_dict:
+ continue
+ cfg_dict[cfg_name] = model_cfg
+ if cfg_path not in cfg_dict:
+ raise ValueError(f'Expected configs: {cfg_dict.keys()}, but got '
+ f'{cfg_path}')
+ return cfg_dict[cfg_path]
+
+
+def _get_external_cfg_path(package_path: str, cfg_file: str) -> str:
+ """Get config path of external package.
+
+ Args:
+ package_path (str): Path of external package.
+ cfg_file (str): Name of experiment config.
+
+ Returns:
+ str: Absolute config path from external package.
+ """
+ cfg_file = cfg_file.split('.')[0]
+ model_cfg = _get_cfg_metainfo(package_path, cfg_file)
+ cfg_path = osp.join(package_path, model_cfg['Config'])
+ check_file_exist(cfg_path)
+ return cfg_path
+
+
+def _get_external_cfg_base_path(package_path: str, cfg_name: str) -> str:
+ """Get base config path of external package.
+
+ Args:
+ package_path (str): Path of external package.
+ cfg_name (str): External relative config path with 'package::'.
+
+ Returns:
+ str: Absolute config path from external package.
+ """
+ cfg_path = osp.join(package_path, '.mim', 'configs', cfg_name)
+ check_file_exist(cfg_path)
+ return cfg_path
+
+
+def _get_package_and_cfg_path(cfg_path: str) -> Tuple[str, str]:
+ """Get package name and relative config path.
+
+ Args:
+ cfg_path (str): External relative config path with 'package::'.
+
+ Returns:
+ Tuple[str, str]: Package name and config path.
+ """
+ if re.match(r'\w*::\w*/\w*', cfg_path) is None:
+ raise ValueError(
+ '`_get_package_and_cfg_path` is used for get external package, '
+ 'please specify the package name and relative config path, just '
+ 'like `mmdet::faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py`')
+ package_cfg = cfg_path.split('::')
+ if len(package_cfg) > 2:
+ raise ValueError('`::` should only be used to separate package and '
+ 'config name, but found multiple `::` in '
+ f'{cfg_path}')
+ package, cfg_path = package_cfg
+ assert package in PKG2PROJECT, 'mmengine does not support to load ' \
+ f'{package} config.'
+ package = PKG2PROJECT[package]
+ return package, cfg_path
+
+
+class RemoveAssignFromAST(ast.NodeTransformer):
+ """Remove Assign node if the target's name match the key.
+
+ Args:
+ key (str): The target name of the Assign node.
+ """
+
+ def __init__(self, key):
+ self.key = key
+
+ def visit_Assign(self, node):
+ if (isinstance(node.targets[0], ast.Name)
+ and node.targets[0].id == self.key):
+ return None
+ else:
+ return node
diff --git a/testbed/open-mmlab__mmengine/mmengine/dataset/__init__.py b/testbed/open-mmlab__mmengine/mmengine/dataset/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c58ef983f4af79aa1f29a24e42f4d20f1089b133
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/dataset/__init__.py
@@ -0,0 +1,12 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .base_dataset import BaseDataset, Compose, force_full_init
+from .dataset_wrapper import ClassBalancedDataset, ConcatDataset, RepeatDataset
+from .sampler import DefaultSampler, InfiniteSampler
+from .utils import (COLLATE_FUNCTIONS, default_collate, pseudo_collate,
+ worker_init_fn)
+
+__all__ = [
+ 'BaseDataset', 'Compose', 'force_full_init', 'ClassBalancedDataset',
+ 'ConcatDataset', 'RepeatDataset', 'DefaultSampler', 'InfiniteSampler',
+ 'worker_init_fn', 'pseudo_collate', 'COLLATE_FUNCTIONS', 'default_collate'
+]
diff --git a/testbed/open-mmlab__mmengine/mmengine/dataset/base_dataset.py b/testbed/open-mmlab__mmengine/mmengine/dataset/base_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..8fd01a077334d954d45916ae604506c6037a0085
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/dataset/base_dataset.py
@@ -0,0 +1,822 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import functools
+import gc
+import os.path as osp
+import pickle
+import warnings
+from typing import Any, Callable, List, Optional, Sequence, Tuple, Union
+
+import numpy as np
+from torch.utils.data import Dataset
+
+from mmengine.fileio import list_from_file, load
+from mmengine.registry import TRANSFORMS
+from mmengine.utils import is_abs
+
+
+class Compose:
+ """Compose multiple transforms sequentially.
+
+ Args:
+ transforms (Sequence[dict, callable], optional): Sequence of transform
+ object or config dict to be composed.
+ """
+
+ def __init__(self, transforms: Optional[Sequence[Union[dict, Callable]]]):
+ self.transforms: List[Callable] = []
+
+ if transforms is None:
+ transforms = []
+
+ for transform in transforms:
+ # `Compose` can be built with config dict with type and
+ # corresponding arguments.
+ if isinstance(transform, dict):
+ transform = TRANSFORMS.build(transform)
+ if not callable(transform):
+ raise TypeError(f'transform should be a callable object, '
+ f'but got {type(transform)}')
+ self.transforms.append(transform)
+ elif callable(transform):
+ self.transforms.append(transform)
+ else:
+ raise TypeError(
+ f'transform must be a callable object or dict, '
+ f'but got {type(transform)}')
+
+ def __call__(self, data: dict) -> Optional[dict]:
+ """Call function to apply transforms sequentially.
+
+ Args:
+ data (dict): A result dict contains the data to transform.
+
+ Returns:
+ dict: Transformed data.
+ """
+ for t in self.transforms:
+ data = t(data)
+ # The transform will return None when it failed to load images or
+ # cannot find suitable augmentation parameters to augment the data.
+ # Here we simply return None if the transform returns None and the
+ # dataset will handle it by randomly selecting another data sample.
+ if data is None:
+ return None
+ return data
+
+ def __repr__(self):
+ """Print ``self.transforms`` in sequence.
+
+ Returns:
+ str: Formatted string.
+ """
+ format_string = self.__class__.__name__ + '('
+ for t in self.transforms:
+ format_string += '\n'
+ format_string += f' {t}'
+ format_string += '\n)'
+ return format_string
+
+
+def force_full_init(old_func: Callable) -> Any:
+ """Those methods decorated by ``force_full_init`` will be forced to call
+ ``full_init`` if the instance has not been fully initiated.
+
+ Args:
+ old_func (Callable): Decorated function, make sure the first arg is an
+ instance with ``full_init`` method.
+
+ Returns:
+ Any: Depends on old_func.
+ """
+
+ @functools.wraps(old_func)
+ def wrapper(obj: object, *args, **kwargs):
+ # The instance must have `full_init` method.
+ if not hasattr(obj, 'full_init'):
+ raise AttributeError(f'{type(obj)} does not have full_init '
+ 'method.')
+ # If instance does not have `_fully_initialized` attribute or
+ # `_fully_initialized` is False, call `full_init` and set
+ # `_fully_initialized` to True
+ if not getattr(obj, '_fully_initialized', False):
+ warnings.warn('Attribute `_fully_initialized` is not defined in '
+ f'{type(obj)} or `type(obj)._fully_initialized is '
+ 'False, `full_init` will be called and '
+ f'{type(obj)}._fully_initialized will be set to '
+ 'True')
+ obj.full_init() # type: ignore
+ obj._fully_initialized = True # type: ignore
+
+ return old_func(obj, *args, **kwargs)
+
+ return wrapper
+
+
+class BaseDataset(Dataset):
+ r"""BaseDataset for open source projects in OpenMMLab.
+
+ The annotation format is shown as follows.
+
+ .. code-block:: none
+
+ {
+ "metainfo":
+ {
+ "dataset_type": "test_dataset",
+ "task_name": "test_task"
+ },
+ "data_list":
+ [
+ {
+ "img_path": "test_img.jpg",
+ "height": 604,
+ "width": 640,
+ "instances":
+ [
+ {
+ "bbox": [0, 0, 10, 20],
+ "bbox_label": 1,
+ "mask": [[0,0],[0,10],[10,20],[20,0]],
+ "extra_anns": [1,2,3]
+ },
+ {
+ "bbox": [10, 10, 110, 120],
+ "bbox_label": 2,
+ "mask": [[10,10],[10,110],[110,120],[120,10]],
+ "extra_anns": [4,5,6]
+ }
+ ]
+ },
+ ]
+ }
+
+ Args:
+ ann_file (str): Annotation file path. Defaults to ''.
+ metainfo (dict, optional): Meta information for dataset, such as class
+ information. Defaults to None.
+ data_root (str): The root directory for ``data_prefix`` and
+ ``ann_file``. Defaults to ''.
+ data_prefix (dict): Prefix for training data. Defaults to
+ dict(img_path='').
+ filter_cfg (dict, optional): Config for filter data. Defaults to None.
+ indices (int or Sequence[int], optional): Support using first few
+ data in annotation file to facilitate training/testing on a smaller
+ dataset. Defaults to None which means using all ``data_infos``.
+ serialize_data (bool, optional): Whether to hold memory using
+ serialized objects, when enabled, data loader workers can use
+ shared RAM from master process instead of making a copy. Defaults
+ to True.
+ pipeline (list, optional): Processing pipeline. Defaults to [].
+ test_mode (bool, optional): ``test_mode=True`` means in test phase.
+ Defaults to False.
+ lazy_init (bool, optional): Whether to load annotation during
+ instantiation. In some cases, such as visualization, only the meta
+ information of the dataset is needed, which is not necessary to
+ load annotation file. ``Basedataset`` can skip load annotations to
+ save time by set ``lazy_init=True``. Defaults to False.
+ max_refetch (int, optional): If ``Basedataset.prepare_data`` get a
+ None img. The maximum extra number of cycles to get a valid
+ image. Defaults to 1000.
+
+ Note:
+ BaseDataset collects meta information from ``annotation file`` (the
+ lowest priority), ``BaseDataset.METAINFO``(medium) and ``metainfo
+ parameter`` (highest) passed to constructors. The lower priority meta
+ information will be overwritten by higher one.
+
+ Note:
+ Dataset wrapper such as ``ConcatDataset``, ``RepeatDataset`` .etc.
+ should not inherit from ``BaseDataset`` since ``get_subset`` and
+ ``get_subset_`` could produce ambiguous meaning sub-dataset which
+ conflicts with original dataset.
+
+ Examples:
+ >>> # Assume the annotation file is given above.
+ >>> class CustomDataset(BaseDataset):
+ >>> METAINFO: dict = dict(task_name='custom_task',
+ >>> dataset_type='custom_type')
+ >>> metainfo=dict(task_name='custom_task_name')
+ >>> custom_dataset = CustomDataset(
+ >>> 'path/to/ann_file',
+ >>> metainfo=metainfo)
+ >>> # meta information of annotation file will be overwritten by
+ >>> # `CustomDataset.METAINFO`. The merged meta information will
+ >>> # further be overwritten by argument `metainfo`.
+ >>> custom_dataset.metainfo
+ {'task_name': custom_task_name, dataset_type: custom_type}
+ """
+
+ METAINFO: dict = dict()
+ _fully_initialized: bool = False
+
+ def __init__(self,
+ ann_file: str = '',
+ metainfo: Optional[dict] = None,
+ data_root: str = '',
+ data_prefix: dict = dict(img_path=''),
+ filter_cfg: Optional[dict] = None,
+ indices: Optional[Union[int, Sequence[int]]] = None,
+ serialize_data: bool = True,
+ pipeline: List[Union[dict, Callable]] = [],
+ test_mode: bool = False,
+ lazy_init: bool = False,
+ max_refetch: int = 1000):
+
+ self.data_root = data_root
+ self.data_prefix = copy.copy(data_prefix)
+ self.ann_file = ann_file
+ self.filter_cfg = copy.deepcopy(filter_cfg)
+ self._indices = indices
+ self.serialize_data = serialize_data
+ self.test_mode = test_mode
+ self.max_refetch = max_refetch
+ self.data_list: List[dict] = []
+ self.data_bytes: np.ndarray
+
+ # Set meta information.
+ self._metainfo = self._load_metainfo(copy.deepcopy(metainfo))
+
+ # Join paths.
+ self._join_prefix()
+
+ # Build pipeline.
+ self.pipeline = Compose(pipeline)
+ # Full initialize the dataset.
+ if not lazy_init:
+ self.full_init()
+
+ @force_full_init
+ def get_data_info(self, idx: int) -> dict:
+ """Get annotation by index and automatically call ``full_init`` if the
+ dataset has not been fully initialized.
+
+ Args:
+ idx (int): The index of data.
+
+ Returns:
+ dict: The idx-th annotation of the dataset.
+ """
+ if self.serialize_data:
+ start_addr = 0 if idx == 0 else self.data_address[idx - 1].item()
+ end_addr = self.data_address[idx].item()
+ bytes = memoryview(
+ self.data_bytes[start_addr:end_addr]) # type: ignore
+ data_info = pickle.loads(bytes) # type: ignore
+ else:
+ data_info = copy.deepcopy(self.data_list[idx])
+ # Some codebase needs `sample_idx` of data information. Here we convert
+ # the idx to a positive number and save it in data information.
+ if idx >= 0:
+ data_info['sample_idx'] = idx
+ else:
+ data_info['sample_idx'] = len(self) + idx
+
+ return data_info
+
+ def full_init(self):
+ """Load annotation file and set ``BaseDataset._fully_initialized`` to
+ True.
+
+ If ``lazy_init=False``, ``full_init`` will be called during the
+ instantiation and ``self._fully_initialized`` will be set to True. If
+ ``obj._fully_initialized=False``, the class method decorated by
+ ``force_full_init`` will call ``full_init`` automatically.
+
+ Several steps to initialize annotation:
+
+ - load_data_list: Load annotations from annotation file.
+ - filter data information: Filter annotations according to
+ filter_cfg.
+ - slice_data: Slice dataset according to ``self._indices``
+ - serialize_data: Serialize ``self.data_list`` if
+ ``self.serialize_data`` is True.
+ """
+ if self._fully_initialized:
+ return
+ # load data information
+ self.data_list = self.load_data_list()
+ # filter illegal data, such as data that has no annotations.
+ self.data_list = self.filter_data()
+ # Get subset data according to indices.
+ if self._indices is not None:
+ self.data_list = self._get_unserialized_subset(self._indices)
+
+ # serialize data_list
+ if self.serialize_data:
+ self.data_bytes, self.data_address = self._serialize_data()
+
+ self._fully_initialized = True
+
+ @property
+ def metainfo(self) -> dict:
+ """Get meta information of dataset.
+
+ Returns:
+ dict: meta information collected from ``BaseDataset.METAINFO``,
+ annotation file and metainfo argument during instantiation.
+ """
+ return copy.deepcopy(self._metainfo)
+
+ def parse_data_info(self, raw_data_info: dict) -> Union[dict, List[dict]]:
+ """Parse raw annotation to target format.
+
+ This method should return dict or list of dict. Each dict or list
+ contains the data information of a training sample. If the protocol of
+ the sample annotations is changed, this function can be overridden to
+ update the parsing logic while keeping compatibility.
+
+ Args:
+ raw_data_info (dict): Raw data information load from ``ann_file``
+
+ Returns:
+ list or list[dict]: Parsed annotation.
+ """
+ for prefix_key, prefix in self.data_prefix.items():
+ assert prefix_key in raw_data_info, (
+ f'raw_data_info: {raw_data_info} dose not contain prefix key'
+ f'{prefix_key}, please check your data_prefix.')
+ raw_data_info[prefix_key] = osp.join(prefix,
+ raw_data_info[prefix_key])
+ return raw_data_info
+
+ def filter_data(self) -> List[dict]:
+ """Filter annotations according to filter_cfg. Defaults return all
+ ``data_list``.
+
+ If some ``data_list`` could be filtered according to specific logic,
+ the subclass should override this method.
+
+ Returns:
+ list[int]: Filtered results.
+ """
+ return self.data_list
+
+ def get_cat_ids(self, idx: int) -> List[int]:
+ """Get category ids by index. Dataset wrapped by ClassBalancedDataset
+ must implement this method.
+
+ The ``ClassBalancedDataset`` requires a subclass which implements this
+ method.
+
+ Args:
+ idx (int): The index of data.
+
+ Returns:
+ list[int]: All categories in the image of specified index.
+ """
+ raise NotImplementedError(f'{type(self)} must implement `get_cat_ids` '
+ 'method')
+
+ def __getitem__(self, idx: int) -> dict:
+ """Get the idx-th image and data information of dataset after
+ ``self.pipeline``, and ``full_init`` will be called if the dataset has
+ not been fully initialized.
+
+ During training phase, if ``self.pipeline`` get ``None``,
+ ``self._rand_another`` will be called until a valid image is fetched or
+ the maximum limit of refetech is reached.
+
+ Args:
+ idx (int): The index of self.data_list.
+
+ Returns:
+ dict: The idx-th image and data information of dataset after
+ ``self.pipeline``.
+ """
+ # Performing full initialization by calling `__getitem__` will consume
+ # extra memory. If a dataset is not fully initialized by setting
+ # `lazy_init=True` and then fed into the dataloader. Different workers
+ # will simultaneously read and parse the annotation. It will cost more
+ # time and memory, although this may work. Therefore, it is recommended
+ # to manually call `full_init` before dataset fed into dataloader to
+ # ensure all workers use shared RAM from master process.
+ if not self._fully_initialized:
+ warnings.warn(
+ 'Please call `full_init()` method manually to accelerate '
+ 'the speed.')
+ self.full_init()
+
+ if self.test_mode:
+ data = self.prepare_data(idx)
+ if data is None:
+ raise Exception('Test time pipline should not get `None` '
+ 'data_sample')
+ return data
+
+ for _ in range(self.max_refetch + 1):
+ data = self.prepare_data(idx)
+ # Broken images or random augmentations may cause the returned data
+ # to be None
+ if data is None:
+ idx = self._rand_another()
+ continue
+ return data
+
+ raise Exception(f'Cannot find valid image after {self.max_refetch}! '
+ 'Please check your image path and pipeline')
+
+ def load_data_list(self) -> List[dict]:
+ """Load annotations from an annotation file named as ``self.ann_file``
+
+ If the annotation file does not follow `OpenMMLab 2.0 format dataset
+ `_ .
+ The subclass must override this method for load annotations. The meta
+ information of annotation file will be overwritten :attr:`METAINFO`
+ and ``metainfo`` argument of constructor.
+
+ Returns:
+ list[dict]: A list of annotation.
+ """ # noqa: E501
+ # `self.ann_file` denotes the absolute annotation file path if
+ # `self.root=None` or relative path if `self.root=/path/to/data/`.
+ annotations = load(self.ann_file)
+ if not isinstance(annotations, dict):
+ raise TypeError(f'The annotations loaded from annotation file '
+ f'should be a dict, but got {type(annotations)}!')
+ if 'data_list' not in annotations or 'metainfo' not in annotations:
+ raise ValueError('Annotation must have data_list and metainfo '
+ 'keys')
+ metainfo = annotations['metainfo']
+ raw_data_list = annotations['data_list']
+
+ # Meta information load from annotation file will not influence the
+ # existed meta information load from `BaseDataset.METAINFO` and
+ # `metainfo` arguments defined in constructor.
+ for k, v in metainfo.items():
+ self._metainfo.setdefault(k, v)
+
+ # load and parse data_infos.
+ data_list = []
+ for raw_data_info in raw_data_list:
+ # parse raw data information to target format
+ data_info = self.parse_data_info(raw_data_info)
+ if isinstance(data_info, dict):
+ # For image tasks, `data_info` should information if single
+ # image, such as dict(img_path='xxx', width=360, ...)
+ data_list.append(data_info)
+ elif isinstance(data_info, list):
+ # For video tasks, `data_info` could contain image
+ # information of multiple frames, such as
+ # [dict(video_path='xxx', timestamps=...),
+ # dict(video_path='xxx', timestamps=...)]
+ for item in data_info:
+ if not isinstance(item, dict):
+ raise TypeError('data_info must be list of dict, but '
+ f'got {type(item)}')
+ data_list.extend(data_info)
+ else:
+ raise TypeError('data_info should be a dict or list of dict, '
+ f'but got {type(data_info)}')
+
+ return data_list
+
+ @classmethod
+ def _load_metainfo(cls, metainfo: dict = None) -> dict:
+ """Collect meta information from the dictionary of meta.
+
+ Args:
+ metainfo (dict): Meta information dict. If ``metainfo``
+ contains existed filename, it will be parsed by
+ ``list_from_file``.
+
+ Returns:
+ dict: Parsed meta information.
+ """
+ # avoid `cls.METAINFO` being overwritten by `metainfo`
+ cls_metainfo = copy.deepcopy(cls.METAINFO)
+ if metainfo is None:
+ return cls_metainfo
+ if not isinstance(metainfo, dict):
+ raise TypeError(
+ f'metainfo should be a dict, but got {type(metainfo)}')
+
+ for k, v in metainfo.items():
+ if isinstance(v, str):
+ # If type of value is string, and can be loaded from
+ # corresponding backend. it means the file name of meta file.
+ try:
+ cls_metainfo[k] = list_from_file(v)
+ except (TypeError, FileNotFoundError):
+ warnings.warn(f'{v} is not a meta file, simply parsed as '
+ 'meta information')
+ cls_metainfo[k] = v
+ else:
+ cls_metainfo[k] = v
+ return cls_metainfo
+
+ def _join_prefix(self):
+ """Join ``self.data_root`` with ``self.data_prefix`` and
+ ``self.ann_file``.
+
+ Examples:
+ >>> # self.data_prefix contains relative paths
+ >>> self.data_root = 'a/b/c'
+ >>> self.data_prefix = dict(img='d/e/')
+ >>> self.ann_file = 'f'
+ >>> self._join_prefix()
+ >>> self.data_prefix
+ dict(img='a/b/c/d/e')
+ >>> self.ann_file
+ 'a/b/c/f'
+ >>> # self.data_prefix contains absolute paths
+ >>> self.data_root = 'a/b/c'
+ >>> self.data_prefix = dict(img='/d/e/')
+ >>> self.ann_file = 'f'
+ >>> self._join_prefix()
+ >>> self.data_prefix
+ dict(img='/d/e')
+ >>> self.ann_file
+ 'a/b/c/f'
+ """
+ # Automatically join annotation file path with `self.root` if
+ # `self.ann_file` is not an absolute path.
+ if not is_abs(self.ann_file) and self.ann_file:
+ self.ann_file = osp.join(self.data_root, self.ann_file)
+ # Automatically join data directory with `self.root` if path value in
+ # `self.data_prefix` is not an absolute path.
+ for data_key, prefix in self.data_prefix.items():
+ if isinstance(prefix, str):
+ if not is_abs(prefix):
+ self.data_prefix[data_key] = osp.join(
+ self.data_root, prefix)
+ else:
+ self.data_prefix[data_key] = prefix
+ else:
+ raise TypeError('prefix should be a string, but got '
+ f'{type(prefix)}')
+
+ @force_full_init
+ def get_subset_(self, indices: Union[Sequence[int], int]) -> None:
+ """The in-place version of ``get_subset `` to convert dataset to a
+ subset of original dataset.
+
+ This method will convert the original dataset to a subset of dataset.
+ If type of indices is int, ``get_subset_`` will return a subdataset
+ which contains the first or last few data information according to
+ indices is positive or negative. If type of indices is a sequence of
+ int, the subdataset will extract the data information according to
+ the index given in indices.
+
+ Examples:
+ >>> dataset = BaseDataset('path/to/ann_file')
+ >>> len(dataset)
+ 100
+ >>> dataset.get_subset_(90)
+ >>> len(dataset)
+ 90
+ >>> # if type of indices is sequence, extract the corresponding
+ >>> # index data information
+ >>> dataset.get_subset_([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
+ >>> len(dataset)
+ 10
+ >>> dataset.get_subset_(-3)
+ >>> len(dataset) # Get the latest few data information.
+ 3
+
+ Args:
+ indices (int or Sequence[int]): If type of indices is int, indices
+ represents the first or last few data of dataset according to
+ indices is positive or negative. If type of indices is
+ Sequence, indices represents the target data information
+ index of dataset.
+ """
+ # Get subset of data from serialized data or data information sequence
+ # according to `self.serialize_data`.
+ if self.serialize_data:
+ self.data_bytes, self.data_address = \
+ self._get_serialized_subset(indices)
+ else:
+ self.data_list = self._get_unserialized_subset(indices)
+
+ @force_full_init
+ def get_subset(self, indices: Union[Sequence[int], int]) -> 'BaseDataset':
+ """Return a subset of dataset.
+
+ This method will return a subset of original dataset. If type of
+ indices is int, ``get_subset_`` will return a subdataset which
+ contains the first or last few data information according to
+ indices is positive or negative. If type of indices is a sequence of
+ int, the subdataset will extract the information according to the index
+ given in indices.
+
+ Examples:
+ >>> dataset = BaseDataset('path/to/ann_file')
+ >>> len(dataset)
+ 100
+ >>> subdataset = dataset.get_subset(90)
+ >>> len(sub_dataset)
+ 90
+ >>> # if type of indices is list, extract the corresponding
+ >>> # index data information
+ >>> subdataset = dataset.get_subset([0, 1, 2, 3, 4, 5, 6, 7,
+ >>> 8, 9])
+ >>> len(sub_dataset)
+ 10
+ >>> subdataset = dataset.get_subset(-3)
+ >>> len(subdataset) # Get the latest few data information.
+ 3
+
+ Args:
+ indices (int or Sequence[int]): If type of indices is int, indices
+ represents the first or last few data of dataset according to
+ indices is positive or negative. If type of indices is
+ Sequence, indices represents the target data information
+ index of dataset.
+
+ Returns:
+ BaseDataset: A subset of dataset.
+ """
+ # Get subset of data from serialized data or data information list
+ # according to `self.serialize_data`. Since `_get_serialized_subset`
+ # will recalculate the subset data information,
+ # `_copy_without_annotation` will copy all attributes except data
+ # information.
+ sub_dataset = self._copy_without_annotation()
+ # Get subset of dataset with serialize and unserialized data.
+ if self.serialize_data:
+ data_bytes, data_address = \
+ self._get_serialized_subset(indices)
+ sub_dataset.data_bytes = data_bytes.copy()
+ sub_dataset.data_address = data_address.copy()
+ else:
+ data_list = self._get_unserialized_subset(indices)
+ sub_dataset.data_list = copy.deepcopy(data_list)
+ return sub_dataset
+
+ def _get_serialized_subset(self, indices: Union[Sequence[int], int]) \
+ -> Tuple[np.ndarray, np.ndarray]:
+ """Get subset of serialized data information list.
+
+ Args:
+ indices (int or Sequence[int]): If type of indices is int,
+ indices represents the first or last few data of serialized
+ data information list. If type of indices is Sequence, indices
+ represents the target data information index which consist of
+ subset data information.
+
+ Returns:
+ Tuple[np.ndarray, np.ndarray]: subset of serialized data
+ information.
+ """
+ sub_data_bytes: Union[List, np.ndarray]
+ sub_data_address: Union[List, np.ndarray]
+ if isinstance(indices, int):
+ if indices >= 0:
+ assert indices < len(self.data_address), \
+ f'{indices} is out of dataset length({len(self)}'
+ # Return the first few data information.
+ end_addr = self.data_address[indices - 1].item() \
+ if indices > 0 else 0
+ # Slicing operation of `np.ndarray` does not trigger a memory
+ # copy.
+ sub_data_bytes = self.data_bytes[:end_addr]
+ # Since the buffer size of first few data information is not
+ # changed,
+ sub_data_address = self.data_address[:indices]
+ else:
+ assert -indices <= len(self.data_address), \
+ f'{indices} is out of dataset length({len(self)}'
+ # Return the last few data information.
+ ignored_bytes_size = self.data_address[indices - 1]
+ start_addr = self.data_address[indices - 1].item()
+ sub_data_bytes = self.data_bytes[start_addr:]
+ sub_data_address = self.data_address[indices:]
+ sub_data_address = sub_data_address - ignored_bytes_size
+ elif isinstance(indices, Sequence):
+ sub_data_bytes = []
+ sub_data_address = []
+ for idx in indices:
+ assert len(self) > idx >= -len(self)
+ start_addr = 0 if idx == 0 else \
+ self.data_address[idx - 1].item()
+ end_addr = self.data_address[idx].item()
+ # Get data information by address.
+ sub_data_bytes.append(self.data_bytes[start_addr:end_addr])
+ # Get data information size.
+ sub_data_address.append(end_addr - start_addr)
+ # Handle indices is an empty list.
+ if sub_data_bytes:
+ sub_data_bytes = np.concatenate(sub_data_bytes)
+ sub_data_address = np.cumsum(sub_data_address)
+ else:
+ sub_data_bytes = np.array([])
+ sub_data_address = np.array([])
+ else:
+ raise TypeError('indices should be a int or sequence of int, '
+ f'but got {type(indices)}')
+ return sub_data_bytes, sub_data_address # type: ignore
+
+ def _get_unserialized_subset(self, indices: Union[Sequence[int],
+ int]) -> list:
+ """Get subset of data information list.
+
+ Args:
+ indices (int or Sequence[int]): If type of indices is int,
+ indices represents the first or last few data of data
+ information. If indices of indices is Sequence, indices
+ represents the target data information index which consist
+ of subset data information.
+
+ Returns:
+ Tuple[np.ndarray, np.ndarray]: subset of data information.
+ """
+ if isinstance(indices, int):
+ if indices >= 0:
+ # Return the first few data information.
+ sub_data_list = self.data_list[:indices]
+ else:
+ # Return the last few data information.
+ sub_data_list = self.data_list[indices:]
+ elif isinstance(indices, Sequence):
+ # Return the data information according to given indices.
+ sub_data_list = []
+ for idx in indices:
+ sub_data_list.append(self.data_list[idx])
+ else:
+ raise TypeError('indices should be a int or sequence of int, '
+ f'but got {type(indices)}')
+ return sub_data_list
+
+ def _serialize_data(self) -> Tuple[np.ndarray, np.ndarray]:
+ """Serialize ``self.data_list`` to save memory when launching multiple
+ workers in data loading. This function will be called in ``full_init``.
+
+ Hold memory using serialized objects, and data loader workers can use
+ shared RAM from master process instead of making a copy.
+
+ Returns:
+ Tuple[np.ndarray, np.ndarray]: Serialized result and corresponding
+ address.
+ """
+
+ def _serialize(data):
+ buffer = pickle.dumps(data, protocol=4)
+ return np.frombuffer(buffer, dtype=np.uint8)
+
+ # Serialize data information list avoid making multiple copies of
+ # `self.data_list` when iterate `import torch.utils.data.dataloader`
+ # with multiple workers.
+ data_list = [_serialize(x) for x in self.data_list]
+ address_list = np.asarray([len(x) for x in data_list], dtype=np.int64)
+ data_address: np.ndarray = np.cumsum(address_list)
+ # TODO Check if np.concatenate is necessary
+ data_bytes = np.concatenate(data_list)
+ # Empty cache for preventing making multiple copies of
+ # `self.data_info` when loading data multi-processes.
+ self.data_list.clear()
+ gc.collect()
+ return data_bytes, data_address
+
+ def _rand_another(self) -> int:
+ """Get random index.
+
+ Returns:
+ int: Random index from 0 to ``len(self)-1``
+ """
+ return np.random.randint(0, len(self))
+
+ def prepare_data(self, idx) -> Any:
+ """Get data processed by ``self.pipeline``.
+
+ Args:
+ idx (int): The index of ``data_info``.
+
+ Returns:
+ Any: Depends on ``self.pipeline``.
+ """
+ data_info = self.get_data_info(idx)
+ return self.pipeline(data_info)
+
+ @force_full_init
+ def __len__(self) -> int:
+ """Get the length of filtered dataset and automatically call
+ ``full_init`` if the dataset has not been fully init.
+
+ Returns:
+ int: The length of filtered dataset.
+ """
+ if self.serialize_data:
+ return len(self.data_address)
+ else:
+ return len(self.data_list)
+
+ def _copy_without_annotation(self, memo=dict()) -> 'BaseDataset':
+ """Deepcopy for all attributes other than ``data_list``,
+ ``data_address`` and ``data_bytes``.
+
+ Args:
+ memo: Memory dict which used to reconstruct complex object
+ correctly.
+ """
+ cls = self.__class__
+ other = cls.__new__(cls)
+ memo[id(self)] = other
+
+ for key, value in self.__dict__.items():
+ if key in ['data_list', 'data_address', 'data_bytes']:
+ continue
+ super(BaseDataset, other).__setattr__(key,
+ copy.deepcopy(value, memo))
+
+ return other
diff --git a/testbed/open-mmlab__mmengine/mmengine/dataset/dataset_wrapper.py b/testbed/open-mmlab__mmengine/mmengine/dataset/dataset_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..db7be63be512f96ca41936633b423b834e9cb6b5
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/dataset/dataset_wrapper.py
@@ -0,0 +1,503 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import bisect
+import copy
+import math
+import warnings
+from collections import defaultdict
+from typing import List, Sequence, Tuple, Union
+
+from torch.utils.data.dataset import ConcatDataset as _ConcatDataset
+
+from mmengine.registry import DATASETS
+from .base_dataset import BaseDataset, force_full_init
+
+
+@DATASETS.register_module()
+class ConcatDataset(_ConcatDataset):
+ """A wrapper of concatenated dataset.
+
+ Same as ``torch.utils.data.dataset.ConcatDataset`` and support lazy_init.
+
+ Note:
+ ``ConcatDataset`` should not inherit from ``BaseDataset`` since
+ ``get_subset`` and ``get_subset_`` could produce ambiguous meaning
+ sub-dataset which conflicts with original dataset. If you want to use
+ a sub-dataset of ``ConcatDataset``, you should set ``indices``
+ arguments for wrapped dataset which inherit from ``BaseDataset``.
+
+ Args:
+ datasets (Sequence[BaseDataset] or Sequence[dict]): A list of datasets
+ which will be concatenated.
+ lazy_init (bool, optional): Whether to load annotation during
+ instantiation. Defaults to False.
+ ignore_keys (List[str] or str): Ignore the keys that can be
+ unequal in `dataset.metainfo`. Defaults to None.
+ `New in version 0.3.0.`
+ """
+
+ def __init__(self,
+ datasets: Sequence[Union[BaseDataset, dict]],
+ lazy_init: bool = False,
+ ignore_keys: Union[str, List[str], None] = None):
+ self.datasets: List[BaseDataset] = []
+ for i, dataset in enumerate(datasets):
+ if isinstance(dataset, dict):
+ self.datasets.append(DATASETS.build(dataset))
+ elif isinstance(dataset, BaseDataset):
+ self.datasets.append(dataset)
+ else:
+ raise TypeError(
+ 'elements in datasets sequence should be config or '
+ f'`BaseDataset` instance, but got {type(dataset)}')
+ if ignore_keys is None:
+ self.ignore_keys = []
+ elif isinstance(ignore_keys, str):
+ self.ignore_keys = [ignore_keys]
+ elif isinstance(ignore_keys, list):
+ self.ignore_keys = ignore_keys
+ else:
+ raise TypeError('ignore_keys should be a list or str, '
+ f'but got {type(ignore_keys)}')
+
+ meta_keys: set = set()
+ for dataset in self.datasets:
+ meta_keys |= dataset.metainfo.keys()
+ # Only use metainfo of first dataset.
+ self._metainfo = self.datasets[0].metainfo
+ for i, dataset in enumerate(self.datasets, 1):
+ for key in meta_keys:
+ if key in self.ignore_keys:
+ continue
+ if key not in dataset.metainfo:
+ raise ValueError(
+ f'{key} does not in the meta information of '
+ f'the {i}-th dataset')
+ if self._metainfo[key] != dataset.metainfo[key]:
+ raise ValueError(
+ f'The meta information of the {i}-th dataset does not '
+ 'match meta information of the first dataset')
+
+ self._fully_initialized = False
+ if not lazy_init:
+ self.full_init()
+
+ @property
+ def metainfo(self) -> dict:
+ """Get the meta information of the first dataset in ``self.datasets``.
+
+ Returns:
+ dict: Meta information of first dataset.
+ """
+ # Prevent `self._metainfo` from being modified by outside.
+ return copy.deepcopy(self._metainfo)
+
+ def full_init(self):
+ """Loop to ``full_init`` each dataset."""
+ if self._fully_initialized:
+ return
+ for d in self.datasets:
+ d.full_init()
+ # Get the cumulative sizes of `self.datasets`. For example, the length
+ # of `self.datasets` is [2, 3, 4], the cumulative sizes is [2, 5, 9]
+ super().__init__(self.datasets)
+ self._fully_initialized = True
+
+ @force_full_init
+ def _get_ori_dataset_idx(self, idx: int) -> Tuple[int, int]:
+ """Convert global idx to local index.
+
+ Args:
+ idx (int): Global index of ``RepeatDataset``.
+
+ Returns:
+ Tuple[int, int]: The index of ``self.datasets`` and the local
+ index of data.
+ """
+ if idx < 0:
+ if -idx > len(self):
+ raise ValueError(
+ f'absolute value of index({idx}) should not exceed dataset'
+ f'length({len(self)}).')
+ idx = len(self) + idx
+ # Get `dataset_idx` to tell idx belongs to which dataset.
+ dataset_idx = bisect.bisect_right(self.cumulative_sizes, idx)
+ # Get the inner index of single dataset.
+ if dataset_idx == 0:
+ sample_idx = idx
+ else:
+ sample_idx = idx - self.cumulative_sizes[dataset_idx - 1]
+
+ return dataset_idx, sample_idx
+
+ @force_full_init
+ def get_data_info(self, idx: int) -> dict:
+ """Get annotation by index.
+
+ Args:
+ idx (int): Global index of ``ConcatDataset``.
+
+ Returns:
+ dict: The idx-th annotation of the datasets.
+ """
+ dataset_idx, sample_idx = self._get_ori_dataset_idx(idx)
+ return self.datasets[dataset_idx].get_data_info(sample_idx)
+
+ @force_full_init
+ def __len__(self):
+ return super().__len__()
+
+ def __getitem__(self, idx):
+ if not self._fully_initialized:
+ warnings.warn('Please call `full_init` method manually to '
+ 'accelerate the speed.')
+ self.full_init()
+ dataset_idx, sample_idx = self._get_ori_dataset_idx(idx)
+ return self.datasets[dataset_idx][sample_idx]
+
+ def get_subset_(self, indices: Union[List[int], int]) -> None:
+ """Not supported in ``ConcatDataset`` for the ambiguous meaning of sub-
+ dataset."""
+ raise NotImplementedError(
+ '`ConcatDataset` dose not support `get_subset` and '
+ '`get_subset_` interfaces because this will lead to ambiguous '
+ 'implementation of some methods. If you want to use `get_subset` '
+ 'or `get_subset_` interfaces, please use them in the wrapped '
+ 'dataset first and then use `ConcatDataset`.')
+
+ def get_subset(self, indices: Union[List[int], int]) -> 'BaseDataset':
+ """Not supported in ``ConcatDataset`` for the ambiguous meaning of sub-
+ dataset."""
+ raise NotImplementedError(
+ '`ConcatDataset` dose not support `get_subset` and '
+ '`get_subset_` interfaces because this will lead to ambiguous '
+ 'implementation of some methods. If you want to use `get_subset` '
+ 'or `get_subset_` interfaces, please use them in the wrapped '
+ 'dataset first and then use `ConcatDataset`.')
+
+
+@DATASETS.register_module()
+class RepeatDataset:
+ """A wrapper of repeated dataset.
+
+ The length of repeated dataset will be `times` larger than the original
+ dataset. This is useful when the data loading time is long but the dataset
+ is small. Using RepeatDataset can reduce the data loading time between
+ epochs.
+
+ Note:
+ ``RepeatDataset`` should not inherit from ``BaseDataset`` since
+ ``get_subset`` and ``get_subset_`` could produce ambiguous meaning
+ sub-dataset which conflicts with original dataset. If you want to use
+ a sub-dataset of ``RepeatDataset``, you should set ``indices``
+ arguments for wrapped dataset which inherit from ``BaseDataset``.
+
+ Args:
+ dataset (BaseDataset or dict): The dataset to be repeated.
+ times (int): Repeat times.
+ lazy_init (bool): Whether to load annotation during
+ instantiation. Defaults to False.
+ """
+
+ def __init__(self,
+ dataset: Union[BaseDataset, dict],
+ times: int,
+ lazy_init: bool = False):
+ self.dataset: BaseDataset
+ if isinstance(dataset, dict):
+ self.dataset = DATASETS.build(dataset)
+ elif isinstance(dataset, BaseDataset):
+ self.dataset = dataset
+ else:
+ raise TypeError(
+ 'elements in datasets sequence should be config or '
+ f'`BaseDataset` instance, but got {type(dataset)}')
+ self.times = times
+ self._metainfo = self.dataset.metainfo
+
+ self._fully_initialized = False
+ if not lazy_init:
+ self.full_init()
+
+ @property
+ def metainfo(self) -> dict:
+ """Get the meta information of the repeated dataset.
+
+ Returns:
+ dict: The meta information of repeated dataset.
+ """
+ return copy.deepcopy(self._metainfo)
+
+ def full_init(self):
+ """Loop to ``full_init`` each dataset."""
+ if self._fully_initialized:
+ return
+
+ self.dataset.full_init()
+ self._ori_len = len(self.dataset)
+ self._fully_initialized = True
+
+ @force_full_init
+ def _get_ori_dataset_idx(self, idx: int) -> int:
+ """Convert global index to local index.
+
+ Args:
+ idx: Global index of ``RepeatDataset``.
+
+ Returns:
+ idx (int): Local index of data.
+ """
+ return idx % self._ori_len
+
+ @force_full_init
+ def get_data_info(self, idx: int) -> dict:
+ """Get annotation by index.
+
+ Args:
+ idx (int): Global index of ``ConcatDataset``.
+
+ Returns:
+ dict: The idx-th annotation of the datasets.
+ """
+ sample_idx = self._get_ori_dataset_idx(idx)
+ return self.dataset.get_data_info(sample_idx)
+
+ def __getitem__(self, idx):
+ if not self._fully_initialized:
+ warnings.warn('Please call `full_init` method manually to '
+ 'accelerate the speed.')
+ self.full_init()
+
+ sample_idx = self._get_ori_dataset_idx(idx)
+ return self.dataset[sample_idx]
+
+ @force_full_init
+ def __len__(self):
+ return self.times * self._ori_len
+
+ def get_subset_(self, indices: Union[List[int], int]) -> None:
+ """Not supported in ``RepeatDataset`` for the ambiguous meaning of sub-
+ dataset."""
+ raise NotImplementedError(
+ '`RepeatDataset` dose not support `get_subset` and '
+ '`get_subset_` interfaces because this will lead to ambiguous '
+ 'implementation of some methods. If you want to use `get_subset` '
+ 'or `get_subset_` interfaces, please use them in the wrapped '
+ 'dataset first and then use `RepeatDataset`.')
+
+ def get_subset(self, indices: Union[List[int], int]) -> 'BaseDataset':
+ """Not supported in ``RepeatDataset`` for the ambiguous meaning of sub-
+ dataset."""
+ raise NotImplementedError(
+ '`RepeatDataset` dose not support `get_subset` and '
+ '`get_subset_` interfaces because this will lead to ambiguous '
+ 'implementation of some methods. If you want to use `get_subset` '
+ 'or `get_subset_` interfaces, please use them in the wrapped '
+ 'dataset first and then use `RepeatDataset`.')
+
+
+@DATASETS.register_module()
+class ClassBalancedDataset:
+ """A wrapper of class balanced dataset.
+
+ Suitable for training on class imbalanced datasets like LVIS. Following
+ the sampling strategy in the `paper `_,
+ in each epoch, an image may appear multiple times based on its
+ "repeat factor".
+ The repeat factor for an image is a function of the frequency the rarest
+ category labeled in that image. The "frequency of category c" in [0, 1]
+ is defined by the fraction of images in the training set (without repeats)
+ in which category c appears.
+ The dataset needs to instantiate :meth:`get_cat_ids` to support
+ ClassBalancedDataset.
+
+ The repeat factor is computed as followed.
+
+ 1. For each category c, compute the fraction # of images
+ that contain it: :math:`f(c)`
+ 2. For each category c, compute the category-level repeat factor:
+ :math:`r(c) = max(1, sqrt(t/f(c)))`
+ 3. For each image I, compute the image-level repeat factor:
+ :math:`r(I) = max_{c in I} r(c)`
+
+ Note:
+ ``ClassBalancedDataset`` should not inherit from ``BaseDataset``
+ since ``get_subset`` and ``get_subset_`` could produce ambiguous
+ meaning sub-dataset which conflicts with original dataset. If you
+ want to use a sub-dataset of ``ClassBalancedDataset``, you should set
+ ``indices`` arguments for wrapped dataset which inherit from
+ ``BaseDataset``.
+
+ Args:
+ dataset (BaseDataset or dict): The dataset to be repeated.
+ oversample_thr (float): frequency threshold below which data is
+ repeated. For categories with ``f_c >= oversample_thr``, there is
+ no oversampling. For categories with ``f_c < oversample_thr``, the
+ degree of oversampling following the square-root inverse frequency
+ heuristic above.
+ lazy_init (bool, optional): whether to load annotation during
+ instantiation. Defaults to False
+ """
+
+ def __init__(self,
+ dataset: Union[BaseDataset, dict],
+ oversample_thr: float,
+ lazy_init: bool = False):
+ if isinstance(dataset, dict):
+ self.dataset = DATASETS.build(dataset)
+ elif isinstance(dataset, BaseDataset):
+ self.dataset = dataset
+ else:
+ raise TypeError(
+ 'elements in datasets sequence should be config or '
+ f'`BaseDataset` instance, but got {type(dataset)}')
+ self.oversample_thr = oversample_thr
+ self._metainfo = self.dataset.metainfo
+
+ self._fully_initialized = False
+ if not lazy_init:
+ self.full_init()
+
+ @property
+ def metainfo(self) -> dict:
+ """Get the meta information of the repeated dataset.
+
+ Returns:
+ dict: The meta information of repeated dataset.
+ """
+ return copy.deepcopy(self._metainfo)
+
+ def full_init(self):
+ """Loop to ``full_init`` each dataset."""
+ if self._fully_initialized:
+ return
+
+ self.dataset.full_init()
+ # Get repeat factors for each image.
+ repeat_factors = self._get_repeat_factors(self.dataset,
+ self.oversample_thr)
+ # Repeat dataset's indices according to repeat_factors. For example,
+ # if `repeat_factors = [1, 2, 3]`, and the `len(dataset) == 3`,
+ # the repeated indices will be [1, 2, 2, 3, 3, 3].
+ repeat_indices = []
+ for dataset_index, repeat_factor in enumerate(repeat_factors):
+ repeat_indices.extend([dataset_index] * math.ceil(repeat_factor))
+ self.repeat_indices = repeat_indices
+
+ self._fully_initialized = True
+
+ def _get_repeat_factors(self, dataset: BaseDataset,
+ repeat_thr: float) -> List[float]:
+ """Get repeat factor for each images in the dataset.
+
+ Args:
+ dataset (BaseDataset): The dataset.
+ repeat_thr (float): The threshold of frequency. If an image
+ contains the categories whose frequency below the threshold,
+ it would be repeated.
+
+ Returns:
+ List[float]: The repeat factors for each images in the dataset.
+ """
+ # 1. For each category c, compute the fraction # of images
+ # that contain it: f(c)
+ category_freq: defaultdict = defaultdict(float)
+ num_images = len(dataset)
+ for idx in range(num_images):
+ cat_ids = set(self.dataset.get_cat_ids(idx))
+ for cat_id in cat_ids:
+ category_freq[cat_id] += 1
+ for k, v in category_freq.items():
+ assert v > 0, f'caterogy {k} does not contain any images'
+ category_freq[k] = v / num_images
+
+ # 2. For each category c, compute the category-level repeat factor:
+ # r(c) = max(1, sqrt(t/f(c)))
+ category_repeat = {
+ cat_id: max(1.0, math.sqrt(repeat_thr / cat_freq))
+ for cat_id, cat_freq in category_freq.items()
+ }
+
+ # 3. For each image I and its labels L(I), compute the image-level
+ # repeat factor:
+ # r(I) = max_{c in L(I)} r(c)
+ repeat_factors = []
+ for idx in range(num_images):
+ cat_ids = set(self.dataset.get_cat_ids(idx))
+ if len(cat_ids) != 0:
+ repeat_factor = max(
+ {category_repeat[cat_id]
+ for cat_id in cat_ids})
+ repeat_factors.append(repeat_factor)
+
+ return repeat_factors
+
+ @force_full_init
+ def _get_ori_dataset_idx(self, idx: int) -> int:
+ """Convert global index to local index.
+
+ Args:
+ idx (int): Global index of ``RepeatDataset``.
+
+ Returns:
+ int: Local index of data.
+ """
+ return self.repeat_indices[idx]
+
+ @force_full_init
+ def get_cat_ids(self, idx: int) -> List[int]:
+ """Get category ids of class balanced dataset by index.
+
+ Args:
+ idx (int): Index of data.
+
+ Returns:
+ List[int]: All categories in the image of specified index.
+ """
+ sample_idx = self._get_ori_dataset_idx(idx)
+ return self.dataset.get_cat_ids(sample_idx)
+
+ @force_full_init
+ def get_data_info(self, idx: int) -> dict:
+ """Get annotation by index.
+
+ Args:
+ idx (int): Global index of ``ConcatDataset``.
+
+ Returns:
+ dict: The idx-th annotation of the dataset.
+ """
+ sample_idx = self._get_ori_dataset_idx(idx)
+ return self.dataset.get_data_info(sample_idx)
+
+ def __getitem__(self, idx):
+ warnings.warn('Please call `full_init` method manually to '
+ 'accelerate the speed.')
+ if not self._fully_initialized:
+ self.full_init()
+
+ ori_index = self._get_ori_dataset_idx(idx)
+ return self.dataset[ori_index]
+
+ @force_full_init
+ def __len__(self):
+ return len(self.repeat_indices)
+
+ def get_subset_(self, indices: Union[List[int], int]) -> None:
+ """Not supported in ``ClassBalancedDataset`` for the ambiguous meaning
+ of sub-dataset."""
+ raise NotImplementedError(
+ '`ClassBalancedDataset` dose not support `get_subset` and '
+ '`get_subset_` interfaces because this will lead to ambiguous '
+ 'implementation of some methods. If you want to use `get_subset` '
+ 'or `get_subset_` interfaces, please use them in the wrapped '
+ 'dataset first and then use `ClassBalancedDataset`.')
+
+ def get_subset(self, indices: Union[List[int], int]) -> 'BaseDataset':
+ """Not supported in ``ClassBalancedDataset`` for the ambiguous meaning
+ of sub-dataset."""
+ raise NotImplementedError(
+ '`ClassBalancedDataset` dose not support `get_subset` and '
+ '`get_subset_` interfaces because this will lead to ambiguous '
+ 'implementation of some methods. If you want to use `get_subset` '
+ 'or `get_subset_` interfaces, please use them in the wrapped '
+ 'dataset first and then use `ClassBalancedDataset`.')
diff --git a/testbed/open-mmlab__mmengine/mmengine/dataset/sampler.py b/testbed/open-mmlab__mmengine/mmengine/dataset/sampler.py
new file mode 100644
index 0000000000000000000000000000000000000000..95e8e2da6b3d8c44d9423eeedef8a168df9742ca
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/dataset/sampler.py
@@ -0,0 +1,165 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import itertools
+import math
+from typing import Iterator, Optional, Sized
+
+import torch
+from torch.utils.data import Sampler
+
+from mmengine.dist import get_dist_info, sync_random_seed
+from mmengine.registry import DATA_SAMPLERS
+
+
+@DATA_SAMPLERS.register_module()
+class DefaultSampler(Sampler):
+ """The default data sampler for both distributed and non-distributed
+ environment.
+
+ It has several differences from the PyTorch ``DistributedSampler`` as
+ below:
+
+ 1. This sampler supports non-distributed environment.
+
+ 2. The round up behaviors are a little different.
+
+ - If ``round_up=True``, this sampler will add extra samples to make the
+ number of samples is evenly divisible by the world size. And
+ this behavior is the same as the ``DistributedSampler`` with
+ ``drop_last=False``.
+ - If ``round_up=False``, this sampler won't remove or add any samples
+ while the ``DistributedSampler`` with ``drop_last=True`` will remove
+ tail samples.
+
+ Args:
+ dataset (Sized): The dataset.
+ shuffle (bool): Whether shuffle the dataset or not. Defaults to True.
+ seed (int, optional): Random seed used to shuffle the sampler if
+ :attr:`shuffle=True`. This number should be identical across all
+ processes in the distributed group. Defaults to None.
+ round_up (bool): Whether to add extra samples to make the number of
+ samples evenly divisible by the world size. Defaults to True.
+ """
+
+ def __init__(self,
+ dataset: Sized,
+ shuffle: bool = True,
+ seed: Optional[int] = None,
+ round_up: bool = True) -> None:
+ rank, world_size = get_dist_info()
+ self.rank = rank
+ self.world_size = world_size
+
+ self.dataset = dataset
+ self.shuffle = shuffle
+ if seed is None:
+ seed = sync_random_seed()
+ self.seed = seed
+ self.epoch = 0
+ self.round_up = round_up
+
+ if self.round_up:
+ self.num_samples = math.ceil(len(self.dataset) / world_size)
+ self.total_size = self.num_samples * self.world_size
+ else:
+ self.num_samples = math.ceil(
+ (len(self.dataset) - rank) / world_size)
+ self.total_size = len(self.dataset)
+
+ def __iter__(self) -> Iterator[int]:
+ """Iterate the indices."""
+ # deterministically shuffle based on epoch and seed
+ if self.shuffle:
+ g = torch.Generator()
+ g.manual_seed(self.seed + self.epoch)
+ indices = torch.randperm(len(self.dataset), generator=g).tolist()
+ else:
+ indices = torch.arange(len(self.dataset)).tolist()
+
+ # add extra samples to make it evenly divisible
+ if self.round_up:
+ indices = (
+ indices *
+ int(self.total_size / len(indices) + 1))[:self.total_size]
+
+ # subsample
+ indices = indices[self.rank:self.total_size:self.world_size]
+
+ return iter(indices)
+
+ def __len__(self) -> int:
+ """The number of samples in this rank."""
+ return self.num_samples
+
+ def set_epoch(self, epoch: int) -> None:
+ """Sets the epoch for this sampler.
+
+ When :attr:`shuffle=True`, this ensures all replicas use a different
+ random ordering for each epoch. Otherwise, the next iteration of this
+ sampler will yield the same ordering.
+
+ Args:
+ epoch (int): Epoch number.
+ """
+ self.epoch = epoch
+
+
+@DATA_SAMPLERS.register_module()
+class InfiniteSampler(Sampler):
+ """It's designed for iteration-based runner and yields a mini-batch indices
+ each time.
+
+ The implementation logic is referred to
+ https://github.com/facebookresearch/detectron2/blob/main/detectron2/data/samplers/distributed_sampler.py
+
+ Args:
+ dataset (Sized): The dataset.
+ shuffle (bool): Whether shuffle the dataset or not. Defaults to True.
+ seed (int, optional): Random seed. If None, set a random seed.
+ Defaults to None.
+ """ # noqa: W605
+
+ def __init__(self,
+ dataset: Sized,
+ shuffle: bool = True,
+ seed: Optional[int] = None) -> None:
+ rank, world_size = get_dist_info()
+ self.rank = rank
+ self.world_size = world_size
+
+ self.dataset = dataset
+ self.world_size = world_size
+ self.rank = rank
+ self.shuffle = shuffle
+ if seed is None:
+ seed = sync_random_seed()
+ self.seed = seed
+ self.size = len(dataset)
+ self.indices = self._indices_of_rank()
+
+ def _infinite_indices(self) -> Iterator[int]:
+ """Infinitely yield a sequence of indices."""
+ g = torch.Generator()
+ g.manual_seed(self.seed)
+ while True:
+ if self.shuffle:
+ yield from torch.randperm(self.size, generator=g).tolist()
+
+ else:
+ yield from torch.arange(self.size).tolist()
+
+ def _indices_of_rank(self) -> Iterator[int]:
+ """Slice the infinite indices by rank."""
+ yield from itertools.islice(self._infinite_indices(), self.rank, None,
+ self.world_size)
+
+ def __iter__(self) -> Iterator[int]:
+ """Iterate the indices."""
+ yield from self.indices
+
+ def __len__(self) -> int:
+ """Length of base dataset."""
+ return self.size
+
+ def set_epoch(self, epoch: int) -> None:
+ """Not supported in iteration-based runner."""
+ pass
diff --git a/testbed/open-mmlab__mmengine/mmengine/dataset/utils.py b/testbed/open-mmlab__mmengine/mmengine/dataset/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c91e52bb8cbc8e0ed5d3b508c6b7de6008a93473
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/dataset/utils.py
@@ -0,0 +1,157 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import random
+from typing import Any, Mapping, Sequence
+
+import numpy as np
+import torch
+from torch.utils.data._utils.collate import \
+ default_collate as torch_default_collate
+
+from mmengine.registry import Registry
+from mmengine.structures import BaseDataElement
+
+COLLATE_FUNCTIONS = Registry('Collate Functions')
+
+
+def worker_init_fn(worker_id: int, num_workers: int, rank: int,
+ seed: int) -> None:
+ """This function will be called on each worker subprocess after seeding and
+ before data loading.
+
+ Args:
+ worker_id (int): Worker id in [0, num_workers - 1].
+ num_workers (int): How many subprocesses to use for data loading.
+ rank (int): Rank of process in distributed environment. If in
+ non-distributed environment, it is a constant number `0`.
+ seed (int): Random seed.
+ """
+ # The seed of each worker equals to
+ # num_worker * rank + worker_id + user_seed
+ worker_seed = num_workers * rank + worker_id + seed
+ np.random.seed(worker_seed)
+ random.seed(worker_seed)
+ torch.manual_seed(worker_seed)
+
+
+@COLLATE_FUNCTIONS.register_module()
+def pseudo_collate(data_batch: Sequence) -> Any:
+ """Convert list of data sampled from dataset into a batch of data, of which
+ type consistent with the type of each data_itement in ``data_batch``.
+
+ The default behavior of dataloader is to merge a list of samples to form
+ a mini-batch of Tensor(s). However, in MMEngine, ``pseudo_collate``
+ will not stack tensors to batch tensors, and convert int, float, ndarray to
+ tensors.
+
+ This code is referenced from:
+ `Pytorch default_collate `_.
+
+ Args:
+ data_batch (Sequence): Batch of data from dataloader.
+
+ Returns:
+ Any: Transversed Data in the same format as the data_itement of
+ ``data_batch``.
+ """ # noqa: E501
+ data_item = data_batch[0]
+ data_item_type = type(data_item)
+ if isinstance(data_item, (str, bytes)):
+ return data_batch
+ elif isinstance(data_item, tuple) and hasattr(data_item, '_fields'):
+ # named tuple
+ return data_item_type(*(pseudo_collate(samples)
+ for samples in zip(*data_batch)))
+ elif isinstance(data_item, Sequence):
+ # check to make sure that the data_itements in batch have
+ # consistent size
+ it = iter(data_batch)
+ data_item_size = len(next(it))
+ if not all(len(data_item) == data_item_size for data_item in it):
+ raise RuntimeError(
+ 'each data_itement in list of batch should be of equal size')
+ transposed = list(zip(*data_batch))
+
+ if isinstance(data_item, tuple):
+ return [pseudo_collate(samples)
+ for samples in transposed] # Compat with Pytorch.
+ else:
+ try:
+ return data_item_type(
+ [pseudo_collate(samples) for samples in transposed])
+ except TypeError:
+ # The sequence type may not support `__init__(iterable)`
+ # (e.g., `range`).
+ return [pseudo_collate(samples) for samples in transposed]
+ elif isinstance(data_item, Mapping):
+ return data_item_type({
+ key: pseudo_collate([d[key] for d in data_batch])
+ for key in data_item
+ })
+ else:
+ return data_batch
+
+
+@COLLATE_FUNCTIONS.register_module()
+def default_collate(data_batch: Sequence) -> Any:
+ """Convert list of data sampled from dataset into a batch of data, of which
+ type consistent with the type of each data_itement in ``data_batch``.
+
+ Different from :func:`pseudo_collate`, ``default_collate`` will stack
+ tensor contained in ``data_batch`` into a batched tensor with the
+ first dimension batch size, and then move input tensor to the target
+ device.
+
+ Different from ``default_collate`` in pytorch, ``default_collate`` will
+ not process ``BaseDataElement``.
+
+ This code is referenced from:
+ `Pytorch default_collate `_.
+
+ Note:
+ ``default_collate`` only accept input tensor with the same shape.
+
+ Args:
+ data_batch (Sequence): Data sampled from dataset.
+
+ Returns:
+ Any: Data in the same format as the data_itement of ``data_batch``, of which
+ tensors have been stacked, and ndarray, int, float have been
+ converted to tensors.
+ """ # noqa: E501
+ data_item = data_batch[0]
+ data_item_type = type(data_item)
+
+ if isinstance(data_item, (BaseDataElement, str, bytes)):
+ return data_batch
+ elif isinstance(data_item, tuple) and hasattr(data_item, '_fields'):
+ # named_tuple
+ return data_item_type(*(default_collate(samples)
+ for samples in zip(*data_batch)))
+ elif isinstance(data_item, Sequence):
+ # check to make sure that the data_itements in batch have
+ # consistent size
+ it = iter(data_batch)
+ data_item_size = len(next(it))
+ if not all(len(data_item) == data_item_size for data_item in it):
+ raise RuntimeError(
+ 'each data_itement in list of batch should be of equal size')
+ transposed = list(zip(*data_batch))
+
+ if isinstance(data_item, tuple):
+ return [default_collate(samples)
+ for samples in transposed] # Compat with Pytorch.
+ else:
+ try:
+ return data_item_type(
+ [default_collate(samples) for samples in transposed])
+ except TypeError:
+ # The sequence type may not support `__init__(iterable)`
+ # (e.g., `range`).
+ return [default_collate(samples) for samples in transposed]
+ elif isinstance(data_item, Mapping):
+ return data_item_type({
+ key: default_collate([d[key] for d in data_batch])
+ for key in data_item
+ })
+ else:
+ return torch_default_collate(data_batch)
diff --git a/testbed/open-mmlab__mmengine/mmengine/device/__init__.py b/testbed/open-mmlab__mmengine/mmengine/device/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6b9d0afdfecc712c85d797b82fd3e501a23b89e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/device/__init__.py
@@ -0,0 +1,8 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .utils import (get_device, get_max_cuda_memory, is_cuda_available,
+ is_mlu_available, is_mps_available, is_npu_available)
+
+__all__ = [
+ 'get_max_cuda_memory', 'get_device', 'is_cuda_available',
+ 'is_mlu_available', 'is_mps_available', 'is_npu_available'
+]
diff --git a/testbed/open-mmlab__mmengine/mmengine/device/utils.py b/testbed/open-mmlab__mmengine/mmengine/device/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a31af549be57995eea660fee0f8eb21db9bdc44
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/device/utils.py
@@ -0,0 +1,72 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from typing import Optional
+
+import torch
+
+
+def get_max_cuda_memory(device: Optional[torch.device] = None) -> int:
+ """Returns the maximum GPU memory occupied by tensors in megabytes (MB) for
+ a given device. By default, this returns the peak allocated memory since
+ the beginning of this program.
+
+ Args:
+ device (torch.device, optional): selected device. Returns
+ statistic for the current device, given by
+ :func:`~torch.cuda.current_device`, if ``device`` is None.
+ Defaults to None.
+
+ Returns:
+ int: The maximum GPU memory occupied by tensors in megabytes
+ for a given device.
+ """
+ mem = torch.cuda.max_memory_allocated(device=device)
+ mem_mb = torch.tensor([int(mem) // (1024 * 1024)],
+ dtype=torch.int,
+ device=device)
+ torch.cuda.reset_peak_memory_stats()
+ return int(mem_mb.item())
+
+
+def is_cuda_available() -> bool:
+ """Returns True if cuda devices exist."""
+ return torch.cuda.is_available()
+
+
+def is_npu_available() -> bool:
+ """Returns True if Ascend PyTorch and npu devices exist."""
+ try:
+ import torch_npu # noqa: F401
+ except Exception:
+ return False
+ return hasattr(torch, 'npu') and torch.npu.is_available()
+
+
+def is_mlu_available() -> bool:
+ """Returns True if Cambricon PyTorch and mlu devices exist."""
+ return hasattr(torch, 'is_mlu_available') and torch.is_mlu_available()
+
+
+def is_mps_available() -> bool:
+ """Return True if mps devices exist.
+
+ It's specialized for mac m1 chips and require torch version 1.12 or higher.
+ """
+ return hasattr(torch.backends, 'mps') and torch.backends.mps.is_available()
+
+
+def get_device() -> str:
+ """Returns the currently existing device type.
+
+ Returns:
+ str: cuda | npu | mlu | mps | cpu.
+ """
+ if is_npu_available():
+ return 'npu'
+ elif is_cuda_available():
+ return 'cuda'
+ elif is_mlu_available():
+ return 'mlu'
+ elif is_mps_available():
+ return 'mps'
+ else:
+ return 'cpu'
diff --git a/testbed/open-mmlab__mmengine/mmengine/dist/__init__.py b/testbed/open-mmlab__mmengine/mmengine/dist/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..48d7d4f9ed90526892d98ef7298b9805851322e5
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/dist/__init__.py
@@ -0,0 +1,21 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .dist import (all_gather_object, all_reduce, all_gather, all_reduce_dict,
+ collect_results, gather, broadcast, gather_object,
+ sync_random_seed, broadcast_object_list,
+ collect_results_cpu, collect_results_gpu, all_reduce_params)
+from .utils import (get_dist_info, init_dist, init_local_group, get_backend,
+ get_world_size, get_rank, get_local_size, get_local_rank,
+ is_main_process, master_only, barrier, get_local_group,
+ is_distributed, get_default_group, get_data_device,
+ get_comm_device, cast_data_device)
+
+__all__ = [
+ 'all_gather_object', 'all_reduce', 'all_gather', 'all_reduce_dict',
+ 'collect_results', 'collect_results_cpu', 'collect_results_gpu', 'gather',
+ 'broadcast', 'gather_object', 'sync_random_seed', 'broadcast_object_list',
+ 'get_dist_info', 'init_dist', 'init_local_group', 'get_backend',
+ 'get_world_size', 'get_rank', 'get_local_size', 'get_local_group',
+ 'get_local_rank', 'is_main_process', 'master_only', 'barrier',
+ 'is_distributed', 'get_default_group', 'all_reduce_params',
+ 'get_data_device', 'get_comm_device', 'cast_data_device'
+]
diff --git a/testbed/open-mmlab__mmengine/mmengine/dist/dist.py b/testbed/open-mmlab__mmengine/mmengine/dist/dist.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e320e38485787e9914ac672027f13805e9a39ce
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/dist/dist.py
@@ -0,0 +1,1147 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os.path as osp
+import pickle
+import shutil
+import tempfile
+from collections import OrderedDict
+from typing import Any, Dict, Generator, List, Optional, Tuple, Union
+
+import numpy as np
+import torch
+from torch import Tensor
+from torch import distributed as torch_dist
+from torch._utils import (_flatten_dense_tensors, _take_tensors,
+ _unflatten_dense_tensors)
+from torch.distributed import ProcessGroup
+
+import mmengine
+from .utils import (get_world_size, get_rank, get_backend, get_dist_info,
+ get_default_group, barrier, get_data_device,
+ get_comm_device, cast_data_device)
+from mmengine.utils import digit_version
+from mmengine.utils.dl_utils import TORCH_VERSION
+from mmengine.device import is_npu_available
+
+
+def _get_reduce_op(name: str) -> torch_dist.ReduceOp:
+ op_mappings = {
+ 'sum': torch_dist.ReduceOp.SUM,
+ 'product': torch_dist.ReduceOp.PRODUCT,
+ 'min': torch_dist.ReduceOp.MIN,
+ 'max': torch_dist.ReduceOp.MAX,
+ 'band': torch_dist.ReduceOp.BAND,
+ 'bor': torch_dist.ReduceOp.BOR,
+ 'bxor': torch_dist.ReduceOp.BXOR,
+ }
+
+ if name.lower() not in op_mappings:
+ raise ValueError(
+ f'reduce op should be one of {op_mappings.keys()}, bug got {name}')
+
+ return op_mappings[name.lower()]
+
+
+def all_reduce(data: Tensor,
+ op: str = 'sum',
+ group: Optional[ProcessGroup] = None) -> None:
+ """Reduces the tensor data across all machines in such a way that all get
+ the final result.
+
+ After the call ``data`` is going to be bitwise identical in all
+ processes.
+
+ Note:
+ Calling ``all_reduce`` in non-distributed environment does nothing.
+
+ Args:
+ data (Tensor): Input and output of the collective. The function
+ operates in-place.
+ op (str): Operation to reduce data. Defaults to 'sum'. Optional values
+ are 'sum', 'mean' and 'produce', 'min', 'max', 'band', 'bor' and
+ 'bxor'.
+ group (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+
+ Examples:
+ >>> import torch
+ >>> import mmengine.dist as dist
+
+ >>> # non-distributed environment
+ >>> data = torch.arange(2, dtype=torch.int64)
+ >>> dist.all_reduce(data)
+ >>> data
+ tensor([0, 1])
+
+ >>> # distributed environment
+ >>> # We have 2 process groups, 2 ranks.
+ >>> data = torch.arange(2, dtype=torch.int64) + 1 + 2 * rank
+ >>> data
+ tensor([1, 2]) # Rank 0
+ tensor([3, 4]) # Rank 1
+ >>> dist.all_reduce(data, op=dist.ReduceOp.SUM)
+ >>> data
+ tensor([4, 6]) # Rank 0
+ tensor([4, 6]) # Rank 1
+ """
+ world_size = get_world_size(group)
+ if world_size > 1:
+ if group is None:
+ group = get_default_group()
+
+ input_device = get_data_device(data)
+ backend_device = get_comm_device(group)
+ data_on_device = cast_data_device(data, backend_device)
+
+ # pytorch does not support 'mean' operation so we fall back to support
+ # it with 'sum' operation.
+ if op.lower() == 'mean':
+ torch_dist.all_reduce(data_on_device, _get_reduce_op('sum'), group)
+
+ # use true_divide to handle torch1.6.0 throws an RuntimeError when
+ # the type of `data_on_device` is int64
+ data_on_device = torch.true_divide(data_on_device, world_size)
+ else:
+ torch_dist.all_reduce(data_on_device, _get_reduce_op(op), group)
+
+ cast_data_device(data_on_device, input_device, out=data)
+
+
+def all_gather(data: Tensor,
+ group: Optional[ProcessGroup] = None) -> List[Tensor]:
+ """Gather data from the whole group in a list.
+
+ Note:
+ Calling ``all_gather`` in non-distributed environment does nothing
+ and just returns a list containing :attr:`data` itself.
+
+ Note:
+ Unlike PyTorch ``torch.distributed.all_gather``, :meth:`all_gather` in
+ MMEngine does not pass in an empty list ``gather_list`` and returns
+ the ``gather_list`` directly, which is more convenient. The difference
+ between their interfaces is as below:
+
+ - MMEngine: all_gather(data, group) -> gather_list
+ - PyTorch: all_gather(gather_list, data, group) -> None
+
+ Args:
+ data (Tensor): Tensor to be gathered.
+ group (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+
+ Returns:
+ list[Tensor]: Return a list containing data from the whole group if
+ in distributed environment, otherwise a list only containing
+ :attr:`data` itself.
+
+ Examples:
+ >>> import torch
+ >>> import mmengine.dist as dist
+
+ >>> # non-distributed environment
+ >>> data = torch.arange(2, dtype=torch.int64)
+ >>> data
+ tensor([0, 1])
+ >>> output = dist.all_gather(data)
+ >>> output
+ [tensor([0, 1])]
+
+ >>> # distributed environment
+ >>> # We have 2 process groups, 2 ranks.
+ >>> data = torch.arange(2, dtype=torch.int64) + 1 + 2 * rank
+ >>> data
+ tensor([1, 2]) # Rank 0
+ tensor([3, 4]) # Rank 1
+ >>> output = dist.all_gather(data)
+ >>> output
+ [tensor([1, 2]), tensor([3, 4])] # Rank 0
+ [tensor([1, 2]), tensor([3, 4])] # Rank 1
+ """
+ world_size = get_world_size(group)
+ if world_size == 1:
+ return [data]
+
+ if group is None:
+ group = get_default_group()
+
+ input_device = get_data_device(data)
+ backend_device = get_comm_device(group)
+ data_on_device = cast_data_device(data, backend_device)
+
+ gather_list = [
+ torch.empty_like(data, device=backend_device)
+ for _ in range(world_size)
+ ]
+
+ torch_dist.all_gather(gather_list, data_on_device, group)
+
+ return cast_data_device(gather_list, input_device) # type: ignore
+
+
+def gather(data: Tensor,
+ dst: int = 0,
+ group: Optional[ProcessGroup] = None) -> List[Optional[Tensor]]:
+ """Gather data from the whole group to ``dst`` process.
+
+ Note:
+ Calling ``gather`` in non-distributed environment dose nothing
+ and just returns a list containing :attr:`data` itself.
+
+ Note:
+ ``NCCL`` backend does not support ``gather``.
+
+ Note:
+ Unlike PyTorch ``torch.distributed.gather``, :meth:`gather` in
+ MMEngine does not pass in an empty list ``gather_list`` and returns
+ the ``gather_list`` directly, which is more convenient. The difference
+ between their interfaces is as below:
+
+ - MMEngine: gather(data, dst, group) -> gather_list
+ - PyTorch: gather(data, gather_list, dst, group) -> None
+
+ Args:
+ data (Tensor): Tensor to be gathered. CUDA tensor is not supported.
+ dst (int): Destination rank. Defaults to 0.
+ group (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+
+ Returns:
+ list[Tensor]: ``dst`` process will get a list of tensor gathering from
+ the whole group. Other process will get a empty list. If in
+ non-distributed environment, just return a list containing
+ :attr:`data` itself.
+
+ Examples:
+ >>> import torch
+ >>> import mmengine.dist as dist
+
+ >>> # non-distributed environment
+ >>> data = torch.arange(2, dtype=torch.int64)
+ >>> data
+ tensor([0, 1])
+ >>> output = dist.gather(data)
+ >>> output
+ [tensor([0, 1])]
+
+ >>> # distributed environment
+ >>> # We have 2 process groups, 2 ranks.
+ >>> data = torch.arange(2, dtype=torch.int64) + 1 + 2 * rank
+ >>> data
+ tensor([1, 2]) # Rank 0
+ tensor([3, 4]) # Rank 1
+ >>> output = dist.gather(data)
+ >>> output
+ [tensor([1, 2]), tensor([3, 4])] # Rank 0
+ [] # Rank 1
+ """
+ world_size = get_world_size(group)
+ if world_size == 1:
+ return [data]
+
+ if group is None:
+ group = get_default_group()
+
+ input_device = get_data_device(data)
+ backend_device = get_comm_device(group)
+
+ if get_rank(group) == dst:
+ gather_list = [
+ torch.empty_like(data, device=backend_device)
+ for _ in range(world_size)
+ ]
+ else:
+ gather_list = []
+
+ torch_dist.gather(data, gather_list, dst, group)
+
+ if get_rank(group) == dst:
+ return cast_data_device(gather_list, input_device) # type: ignore
+ else:
+ return gather_list
+
+
+def broadcast(data: Tensor,
+ src: int = 0,
+ group: Optional[ProcessGroup] = None) -> None:
+ """Broadcast the data from ``src`` process to the whole group.
+
+ ``data`` must have the same number of elements in all processes
+ participating in the collective.
+
+ Note:
+ Calling ``broadcast`` in non-distributed environment does nothing.
+
+ Args:
+ data (Tensor): Data to be sent if ``src`` is the rank of current
+ process, and data to be used to save received data otherwise.
+ src (int): Source rank. Defaults to 0.
+ group (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+
+ Examples:
+ >>> import torch
+ >>> import mmengine.dist as dist
+
+ >>> # non-distributed environment
+ >>> data = torch.arange(2, dtype=torch.int64)
+ >>> data
+ tensor([0, 1])
+ >>> dist.broadcast(data)
+ >>> data
+ tensor([0, 1])
+
+ >>> # distributed environment
+ >>> # We have 2 process groups, 2 ranks.
+ >>> data = torch.arange(2, dtype=torch.int64) + 1 + 2 * rank
+ >>> data
+ tensor([1, 2]) # Rank 0
+ tensor([3, 4]) # Rank 1
+ >>> dist.broadcast(data)
+ >>> data
+ tensor([1, 2]) # Rank 0
+ tensor([1, 2]) # Rank 1
+ """
+ if get_world_size(group) > 1:
+ if group is None:
+ group = get_default_group()
+
+ input_device = get_data_device(data)
+ backend_device = get_comm_device(group)
+ data_on_device = cast_data_device(data, backend_device)
+
+ torch_dist.broadcast(data_on_device, src, group)
+
+ if get_rank(group) != src:
+ cast_data_device(data_on_device, input_device, data)
+
+
+def sync_random_seed(group: Optional[ProcessGroup] = None) -> int:
+ """Synchronize a random seed to all processes.
+
+ In distributed sampling, different ranks should sample non-overlapped
+ data in the dataset. Therefore, this function is used to make sure that
+ each rank shuffles the data indices in the same order based
+ on the same seed. Then different ranks could use different indices
+ to select non-overlapped data from the same data list.
+
+ Args:
+ group (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+
+ Returns:
+ int: Random seed.
+
+ Examples:
+ >>> import torch
+ >>> import mmengine.dist as dist
+
+ >>> # non-distributed environment
+ >>> seed = dist.sync_random_seed()
+ >>> seed # which a random number
+ 587791752
+
+ >>> distributed environment
+ >>> # We have 2 process groups, 2 ranks.
+ >>> seed = dist.sync_random_seed()
+ >>> seed
+ 587791752 # Rank 0
+ 587791752 # Rank 1
+ """
+ seed = np.random.randint(2**31)
+ if get_world_size(group) == 1:
+ return seed
+
+ if group is None:
+ group = get_default_group()
+
+ backend_device = get_comm_device(group)
+
+ if get_rank(group) == 0:
+ random_num = torch.tensor(seed, dtype=torch.int32).to(backend_device)
+ else:
+ random_num = torch.tensor(0, dtype=torch.int32).to(backend_device)
+
+ torch_dist.broadcast(random_num, src=0, group=group)
+
+ return random_num.item()
+
+
+def _object_to_tensor(obj: Any) -> Tuple[Tensor, Tensor]:
+ """Serialize picklable python object to tensor."""
+ byte_storage = torch.ByteStorage.from_buffer(pickle.dumps(obj))
+ # Do not replace `torch.ByteTensor` or `torch.LongTensor` with torch.tensor
+ # and specifying dtype. Otherwise, it will cause 100X slowdown.
+ # See: https://github.com/pytorch/pytorch/issues/65696
+ byte_tensor = torch.ByteTensor(byte_storage)
+ local_size = torch.LongTensor([byte_tensor.numel()])
+ return byte_tensor, local_size
+
+
+def _tensor_to_object(tensor: Tensor, tensor_size: int) -> Any:
+ """Deserialize tensor to picklable python object."""
+ buf = tensor.cpu().numpy().tobytes()[:tensor_size]
+ return pickle.loads(buf)
+
+
+def _broadcast_object_list(object_list: List[Any],
+ src: int = 0,
+ group: Optional[ProcessGroup] = None) -> None:
+ """Broadcast picklable objects in ``object_list`` to the whole group.
+
+ Similar to :func:`broadcast`, but Python objects can be passed in. Note
+ that all objects in ``object_list`` must be picklable in order to be
+ broadcasted.
+ """
+ if torch_dist.distributed_c10d._rank_not_in_group(group):
+ return
+
+ my_rank = get_rank()
+ # Serialize object_list elements to tensors on src rank.
+ if my_rank == src:
+ tensor_list, size_list = zip(
+ *[_object_to_tensor(obj) for obj in object_list])
+ object_sizes_tensor = torch.cat(size_list)
+ else:
+ object_sizes_tensor = torch.empty(len(object_list), dtype=torch.long)
+
+ # Current device selection.
+ # To preserve backwards compatibility, ``device`` is ``None`` by default.
+ # in which case we run current logic of device selection, i.e.
+ # ``current_device`` is CUDA if backend is NCCL otherwise CPU device. In
+ # the case it is not ``None`` we move the size and object tensors to be
+ # broadcasted to this device.
+ group_backend = get_backend(group)
+ is_nccl_backend = group_backend == torch_dist.Backend.NCCL
+ current_device = torch.device('cpu')
+ is_hccl_backend = group_backend == 'hccl'
+ if is_hccl_backend:
+ current_device = torch.npu.current_device()
+ object_sizes_tensor = object_sizes_tensor.to(current_device)
+ elif is_nccl_backend:
+ # See note about using torch.cuda.current_device() here in
+ # docstring. We cannot simply use my_rank since rank == device is
+ # not necessarily true.
+ current_device = torch.device('cuda', torch.cuda.current_device())
+ object_sizes_tensor = object_sizes_tensor.to(current_device)
+
+ # Broadcast object sizes
+ torch_dist.broadcast(object_sizes_tensor, src=src, group=group)
+
+ # Concatenate and broadcast serialized object tensors
+ if my_rank == src:
+ object_tensor = torch.cat(tensor_list)
+ else:
+ object_tensor = torch.empty(
+ torch.sum(object_sizes_tensor).int().item(),
+ dtype=torch.uint8,
+ )
+
+ if is_nccl_backend or is_hccl_backend:
+ object_tensor = object_tensor.to(current_device)
+ torch_dist.broadcast(object_tensor, src=src, group=group)
+ # Deserialize objects using their stored sizes.
+ offset = 0
+ if my_rank != src:
+ for i, obj_size in enumerate(object_sizes_tensor):
+ obj_view = object_tensor[offset:offset + obj_size]
+ obj_view = obj_view.type(torch.uint8)
+ if obj_view.device != torch.device('cpu'):
+ obj_view = obj_view.cpu()
+ offset += obj_size
+ object_list[i] = _tensor_to_object(obj_view, obj_size)
+
+
+def broadcast_object_list(data: List[Any],
+ src: int = 0,
+ group: Optional[ProcessGroup] = None) -> None:
+ """Broadcasts picklable objects in ``object_list`` to the whole group.
+ Similar to :func:`broadcast`, but Python objects can be passed in. Note
+ that all objects in ``object_list`` must be picklable in order to be
+ broadcasted.
+
+ Note:
+ Calling ``broadcast_object_list`` in non-distributed environment does
+ nothing.
+
+ Args:
+ data (List[Any]): List of input objects to broadcast.
+ Each object must be picklable. Only objects on the ``src`` rank
+ will be broadcast, but each rank must provide lists of equal sizes.
+ src (int): Source rank from which to broadcast ``object_list``.
+ group: (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Default is ``None``.
+ device (``torch.device``, optional): If not None, the objects are
+ serialized and converted to tensors which are moved to the
+ ``device`` before broadcasting. Default is ``None``.
+
+ Note:
+ For NCCL-based process groups, internal tensor representations of
+ objects must be moved to the GPU device before communication starts.
+ In this case, the used device is given by
+ ``torch.cuda.current_device()`` and it is the user's responsibility to
+ ensure that this is correctly set so that each rank has an individual
+ GPU, via ``torch.cuda.set_device()``.
+
+ Examples:
+ >>> import torch
+ >>> import mmengine.dist as dist
+
+ >>> # non-distributed environment
+ >>> data = ['foo', 12, {1: 2}]
+ >>> dist.broadcast_object_list(data)
+ >>> data
+ ['foo', 12, {1: 2}]
+
+ >>> # distributed environment
+ >>> # We have 2 process groups, 2 ranks.
+ >>> if dist.get_rank() == 0:
+ >>> # Assumes world_size of 3.
+ >>> data = ["foo", 12, {1: 2}] # any picklable object
+ >>> else:
+ >>> data = [None, None, None]
+ >>> dist.broadcast_object_list(data)
+ >>> data
+ ["foo", 12, {1: 2}] # Rank 0
+ ["foo", 12, {1: 2}] # Rank 1
+ """
+ assert isinstance(data, list)
+
+ if get_world_size(group) > 1:
+ if group is None:
+ group = get_default_group()
+
+ if digit_version(TORCH_VERSION) >= digit_version(
+ '1.8.0') and not is_npu_available():
+ torch_dist.broadcast_object_list(data, src, group)
+ else:
+ _broadcast_object_list(data, src, group)
+
+
+def all_reduce_dict(data: Dict[str, Tensor],
+ op: str = 'sum',
+ group: Optional[ProcessGroup] = None) -> None:
+ """Reduces the dict across all machines in such a way that all get the
+ final result.
+
+ The code is modified from https://github.com/Megvii-
+ BaseDetection/YOLOX/blob/main/yolox/utils/allreduce_norm.py.
+
+ Args:
+ data (dict[str, Tensor]): Data to be reduced.
+ op (str): Operation to reduce data. Defaults to 'sum'. Optional values
+ are 'sum', 'mean' and 'produce', 'min', 'max', 'band', 'bor' and
+ 'bxor'.
+ group (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+
+ Examples:
+ >>> import torch
+ >>> import mmengine.dist as dist
+
+ >>> # non-distributed environment
+ >>> data = {
+ 'key1': torch.arange(2, dtype=torch.int64),
+ 'key2': torch.arange(3, dtype=torch.int64)
+ }
+ >>> dist.all_reduce_dict(data)
+ >>> data
+ {'key1': tensor([0, 1]), 'key2': tensor([0, 1, 2])}
+
+ >>> # distributed environment
+ >>> # We have 2 process groups, 2 ranks.
+ >>> data = {
+ 'key1': torch.arange(2, dtype=torch.int64),
+ 'key2': torch.arange(3, dtype=torch.int64)
+ }
+ >>> dist.all_reduce_dict(data)
+ >>> data
+ {'key1': tensor([0, 2]), 'key2': tensor([0, 2, 4])} # Rank 0
+ {'key1': tensor([0, 2]), 'key2': tensor([0, 2, 4])} # Rank 1
+ """
+ assert isinstance(data, dict)
+
+ world_size = get_world_size(group)
+ if world_size > 1:
+
+ if group is None:
+ group = get_default_group()
+
+ # ensure keys are consistent across processes
+ keys = sorted(data.keys())
+ tensor_shapes = [data[k].shape for k in keys]
+ tensor_sizes = [data[k].numel() for k in keys]
+
+ if digit_version(TORCH_VERSION) == digit_version('1.5.0'):
+ # `torch.cat` in torch1.5 can not concatenate different types so
+ # we fallback to convert them all to float type.
+ flatten_tensor = torch.cat(
+ [data[k].flatten().float() for k in keys])
+ else:
+ flatten_tensor = torch.cat([data[k].flatten() for k in keys])
+
+ all_reduce(flatten_tensor, op=op, group=group)
+
+ split_tensors = [
+ x.reshape(shape) for x, shape in zip(
+ torch.split(flatten_tensor, tensor_sizes), tensor_shapes)
+ ]
+
+ for k, v in zip(keys, split_tensors):
+ data[k] = v
+
+
+def _all_gather_object(object_list: List[Any],
+ obj: Any,
+ group: Optional[ProcessGroup] = None) -> None:
+ """Gather picklable objects from the whole group into a list.
+
+ Similar to :func:`all_gather`, but Python objects can be passed in.
+ Note that the object must be picklable in order to be gathered.
+
+ Args:
+ object_list (list[Any]): Output list. It should be correctly sized as
+ the size of the group for this collective and will contain the
+ output.
+ object (Any): Pickable Python object to be broadcast from current
+ process.
+ group (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+
+ Returns:
+ None. If the calling rank is part of this group, the output of the
+ collective will be populated into the input ``object_list``. If the
+ calling rank is not part of the group, the passed in ``object_list``
+ will be unmodified.
+ """
+ if torch_dist.distributed_c10d._rank_not_in_group(group):
+ return
+
+ input_tensor, local_size = _object_to_tensor(obj)
+ group_backend = get_backend(group)
+ current_device = torch.device('cpu')
+ is_nccl_backend = group_backend == torch_dist.Backend.NCCL
+ if is_nccl_backend:
+ # See note about using torch.cuda.current_device() here in docstring.
+ # We cannot simply use my_rank since rank == device is not necessarily
+ # true.
+ current_device = torch.device('cuda', torch.cuda.current_device())
+ input_tensor = input_tensor.to(current_device)
+ local_size = local_size.to(current_device)
+ # Gather all local sizes. This is so that we can find the max size, and
+ # index until the correct size when deserializing the tensors.
+ group_size = get_world_size(group=group)
+ object_sizes_tensor = torch.zeros(
+ group_size, dtype=torch.long, device=current_device)
+ object_size_list = [
+ object_sizes_tensor[i].unsqueeze(dim=0) for i in range(group_size)
+ ]
+ # Allgather tensor sizes
+ torch_dist.all_gather(object_size_list, local_size, group=group)
+ max_object_size = int(max(object_size_list).item())
+ # Resize tensor to max size across all ranks.
+ input_tensor.resize_(max_object_size)
+ coalesced_output_tensor = torch.empty(
+ max_object_size * group_size, dtype=torch.uint8, device=current_device)
+ # Output tensors are nonoverlapping views of coalesced_output_tensor
+ output_tensors = [
+ coalesced_output_tensor[max_object_size * i:max_object_size * (i + 1)]
+ for i in range(group_size)
+ ]
+ torch_dist.all_gather(output_tensors, input_tensor, group=group)
+ # Deserialize outputs back to object.
+ for i, tensor in enumerate(output_tensors):
+ tensor = tensor.type(torch.uint8)
+ if tensor.device != torch.device('cpu'):
+ tensor = tensor.cpu()
+ tensor_size = object_size_list[i]
+ object_list[i] = _tensor_to_object(tensor, tensor_size)
+
+
+def all_gather_object(data: Any,
+ group: Optional[ProcessGroup] = None) -> List[Any]:
+ """Gather picklable objects from the whole group into a list. Similar to
+ :func:`all_gather`, but Python objects can be passed in. Note that the
+ object must be picklable in order to be gathered.
+
+ Note:
+ Calling ``all_gather_object`` in non-distributed environment does
+ nothing and just returns a list containing :attr:`data` itself.
+
+ Note:
+ Unlike PyTorch ``torch.distributed.all_gather_object``,
+ :meth:`all_gather_object` in MMEngine does not pass in an empty list
+ ``gather_list`` and returns the ``gather_list`` directly, which is
+ more convenient. The difference between their interfaces is as below:
+
+ - MMEngine: all_gather_object(data, group) -> gather_list
+ - PyTorch: all_gather_object(gather_list, data, group) -> None
+
+ Args:
+ data (Any): Pickable Python object to be broadcast from current
+ process.
+ group (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+
+ Returns:
+ list[Tensor]: Return a list containing data from the whole group if
+ in distributed environment, otherwise a list only containing
+ :attr:`data` itself.
+
+ Note:
+ For NCCL-based process groups, internal tensor representations
+ of objects must be moved to the GPU device before communication starts.
+ In this case, the used device is given by
+ ``torch.cuda.current_device()`` and it is the user's responsibility to
+ ensure that this is correctly set so that each rank has an individual
+ GPU, via ``torch.cuda.set_device()``.
+
+ Examples:
+ >>> import torch
+ >>> import mmengine.dist as dist
+
+ >>> # non-distributed environment
+ >>> data = ['foo', 12, {1: 2}] # any picklable object
+ >>> gather_objects = dist.all_gather_object(data[dist.get_rank()])
+ >>> output
+ ['foo']
+
+ >>> # distributed environment
+ >>> # We have 3 process groups, 3 ranks.
+ >>> output = dist.all_gather_object(data[dist.get_rank()])
+ >>> output
+ ['foo', 12, {1: 2}] # Rank 0
+ ['foo', 12, {1: 2}] # Rank 1
+ ['foo', 12, {1: 2}] # Rank 2
+ """
+ world_size = get_world_size(group)
+ if world_size == 1:
+ return [data]
+
+ if group is None:
+ group = get_default_group()
+
+ gather_list = [None] * world_size
+
+ if digit_version(TORCH_VERSION) >= digit_version('1.8.0'):
+ torch_dist.all_gather_object(gather_list, data, group)
+ else:
+ _all_gather_object(gather_list, data, group)
+
+ return gather_list
+
+
+def _validate_output_list_for_rank(my_rank: int, dst: int,
+ gather_list: Optional[list]) -> None:
+ """Validate whether ``gather_list`` is None in non-dst ranks."""
+ if dst == my_rank:
+ if not gather_list:
+ raise ValueError(
+ 'Argument ``gather_list`` must be specified on destination '
+ 'rank.')
+ elif gather_list:
+ raise ValueError('Argument ``gather_list`` must NOT be specified '
+ 'on non-destination ranks.')
+
+
+def _gather_object(obj: Any,
+ object_gather_list=None,
+ dst: int = 0,
+ group: Optional[ProcessGroup] = None) -> None:
+ """Gathers picklable objects from the whole group in a single process.
+
+ Similar to :func:`gather`, but Python objects can be passed in. Note that
+ the object must be picklable in order to be gathered.
+
+ Args:
+ obj (Any): Input object. Must be picklable.
+ object_gather_list (list[Any], optional): Output list. On the ``dst``
+ rank, it should be correctly sized as the size of the group for
+ this collective and will contain the output. Must be ``None`` on
+ non-dst ranks. Defaults to None.
+ dst (int): Destination rank. Defaults to 0.
+ group: (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+ """
+ if torch_dist.distributed_c10d._rank_not_in_group(group):
+ return
+
+ # Ensure object_gather_list is specified appopriately.
+ my_rank = get_rank()
+ _validate_output_list_for_rank(my_rank, dst, object_gather_list)
+ input_tensor, local_size = _object_to_tensor(obj)
+ group_backend = get_backend(group)
+ current_device = torch.device('cpu')
+ is_nccl_backend = group_backend == torch_dist.Backend.NCCL
+ if is_nccl_backend:
+ current_device = torch.device('cuda', torch.cuda.current_device())
+ input_tensor = input_tensor.to(current_device)
+ local_size = local_size.to(current_device)
+ # Gather all local sizes. This is so that we can find the max size, and
+ # index until the correct size when deserializing the tensors.
+ group_size = get_world_size(group=group)
+ object_sizes_tensor = torch.zeros(
+ group_size, dtype=torch.long, device=current_device)
+ object_size_list = [
+ object_sizes_tensor[i].unsqueeze(dim=0) for i in range(group_size)
+ ]
+ # Allgather tensor sizes. An all-gather is needed here despite this being a
+ # gather, since each rank needs to broadcast a tensor of the same (maximal)
+ # size.
+ torch_dist.all_gather(object_size_list, local_size, group=group)
+ max_object_size = int(max(object_size_list).item())
+ # Resize tensor to max size across all ranks.
+ input_tensor.resize_(max_object_size)
+ # Avoid populating output tensors if the result won't be gathered on this
+ # rank.
+ if my_rank == dst:
+ coalesced_output_tensor = torch.empty(
+ max_object_size * group_size,
+ dtype=torch.uint8,
+ device=current_device)
+ # Output tensors are nonoverlapping views of coalesced_output_tensor
+ output_tensors = [
+ coalesced_output_tensor[max_object_size * i:max_object_size *
+ (i + 1)] for i in range(group_size)
+ ]
+ # All ranks call gather with equal-sized tensors.
+ torch_dist.gather(
+ input_tensor,
+ gather_list=output_tensors if my_rank == dst else None,
+ dst=dst,
+ group=group,
+ )
+ if my_rank != dst:
+ return
+ for i, tensor in enumerate(output_tensors):
+ tensor = tensor.type(torch.uint8)
+ tensor_size = object_size_list[i]
+ object_gather_list[i] = _tensor_to_object(tensor, tensor_size)
+
+
+def gather_object(data: Any,
+ dst: int = 0,
+ group: Optional[ProcessGroup] = None) -> Optional[List[Any]]:
+ """Gathers picklable objects from the whole group in a single process.
+ Similar to :func:`gather`, but Python objects can be passed in. Note that
+ the object must be picklable in order to be gathered.
+
+ Note:
+ ``NCCL backend`` does not support ``gather_object``.
+
+ Note:
+ Unlike PyTorch ``torch.distributed.gather_object``,
+ :meth:`gather_object` in MMEngine does not pass in an empty list
+ ``gather_list`` and returns the ``gather_list`` directly, which is
+ more convenient. The difference between their interfaces is as below:
+
+ - MMEngine: gather_object(data, dst, group) -> gather_list
+ - PyTorch: gather_object(data, gather_list, data, group) -> None
+
+ Args:
+ data (Any): Input object. Must be picklable.
+ dst (int): Destination rank. Defaults to 0.
+ group: (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+
+ Returns:
+ list[Any]. On the ``dst`` rank, return ``gather_list`` which contains
+ the output of the collective.
+
+ Examples:
+ >>> import torch
+ >>> import mmengine.dist as dist
+
+ >>> # non-distributed environment
+ >>> data = ['foo', 12, {1: 2}] # any picklable object
+ >>> gather_objects = dist.gather_object(data[dist.get_rank()])
+ >>> output
+ ['foo']
+
+ >>> # distributed environment
+ >>> # We have 3 process groups, 3 ranks.
+ >>> dist.gather_object(gather_objects[dist.get_rank()], dst=0)
+ >>> output
+ ['foo', 12, {1: 2}] # Rank 0
+ None # Rank 1
+ None # Rank 2
+ """
+ world_size = get_world_size(group)
+ if world_size == 1:
+ return [data]
+
+ if group is None:
+ group = get_default_group()
+
+ gather_list = [None] * world_size if get_rank(group) == dst else None
+
+ if digit_version(TORCH_VERSION) >= digit_version('1.8.0'):
+ torch_dist.gather_object(data, gather_list, dst, group)
+ else:
+ _gather_object(data, gather_list, dst, group)
+
+ return gather_list
+
+
+def collect_results(results: list,
+ size: int,
+ device: str = 'cpu',
+ tmpdir: Optional[str] = None) -> Optional[list]:
+ """Collected results in distributed environments.
+
+ Args:
+ results (list[object]): Result list containing result parts to be
+ collected. Each item of ``result_part`` should be a picklable
+ object.
+ size (int): Size of the results, commonly equal to length of
+ the results.
+ device (str): Device name. Optional values are 'cpu' and 'gpu'.
+ tmpdir (str | None): Temporal directory for collected results to
+ store. If set to None, it will create a temporal directory for it.
+ ``tmpdir`` should be None when device is 'gpu'. Defaults to None.
+
+ Returns:
+ list or None: The collected results.
+
+ Examples:
+ >>> # distributed environment
+ >>> # We have 2 process groups, 2 ranks.
+ >>> import mmengine.dist as dist
+ >>> if dist.get_rank() == 0:
+ data = ['foo', {1: 2}]
+ else:
+ data = [24, {'a': 'b'}]
+ >>> size = 4
+ >>> output = dist.collect_results(data, size, device='cpu')
+ >>> output
+ ['foo', 24, {1: 2}, {'a': 'b'}] # rank 0
+ None # rank 1
+ """
+ if device not in ['gpu', 'cpu']:
+ raise NotImplementedError(
+ f"device must be 'cpu' or 'gpu', but got {device}")
+
+ if device == 'gpu':
+ assert tmpdir is None, 'tmpdir should be None when device is "gpu"'
+ return collect_results_gpu(results, size)
+ else:
+ return collect_results_cpu(results, size, tmpdir)
+
+
+def collect_results_cpu(result_part: list,
+ size: int,
+ tmpdir: Optional[str] = None) -> Optional[list]:
+ """Collect results under cpu mode.
+
+ On cpu mode, this function will save the results on different gpus to
+ ``tmpdir`` and collect them by the rank 0 worker.
+
+ Args:
+ result_part (list): Result list containing result parts
+ to be collected. Each item of ``result_part`` should be a picklable
+ object.
+ size (int): Size of the results, commonly equal to length of
+ the results.
+ tmpdir (str | None): Temporal directory for collected results to
+ store. If set to None, it will create a random temporal directory
+ for it. Defaults to None.
+
+ Returns:
+ list or None: The collected results.
+
+ Examples:
+ >>> # distributed environment
+ >>> # We have 2 process groups, 2 ranks.
+ >>> import mmengine.dist as dist
+ >>> if dist.get_rank() == 0:
+ data = ['foo', {1: 2}]
+ else:
+ data = [24, {'a': 'b'}]
+ >>> size = 4
+ >>> output = dist.collect_results_cpu(data, size)
+ >>> output
+ ['foo', 24, {1: 2}, {'a': 'b'}] # rank 0
+ None # rank 1
+ """
+ rank, world_size = get_dist_info()
+ if world_size == 1:
+ return result_part[:size]
+
+ # create a tmp dir if it is not specified
+ if tmpdir is None:
+ MAX_LEN = 512
+ # 32 is whitespace
+ dir_tensor = torch.full((MAX_LEN, ), 32, dtype=torch.uint8)
+ if rank == 0:
+ mmengine.mkdir_or_exist('.dist_test')
+ tmpdir = tempfile.mkdtemp(dir='.dist_test')
+ tmpdir = torch.tensor(
+ bytearray(tmpdir.encode()), dtype=torch.uint8)
+ dir_tensor[:len(tmpdir)] = tmpdir
+ broadcast(dir_tensor, 0)
+ tmpdir = dir_tensor.numpy().tobytes().decode().rstrip()
+ else:
+ mmengine.mkdir_or_exist(tmpdir)
+
+ # dump the part result to the dir
+ with open(osp.join(tmpdir, f'part_{rank}.pkl'), 'wb') as f: # type: ignore
+ pickle.dump(result_part, f, protocol=2)
+
+ barrier()
+
+ # collect all parts
+ if rank != 0:
+ return None
+ else:
+ # load results of all parts from tmp dir
+ part_list = []
+ for i in range(world_size):
+ path = osp.join(tmpdir, f'part_{i}.pkl') # type: ignore
+ with open(path, 'rb') as f:
+ part_list.append(pickle.load(f))
+ # sort the results
+ ordered_results = []
+ for res in zip(*part_list):
+ ordered_results.extend(list(res))
+ # the dataloader may pad some samples
+ ordered_results = ordered_results[:size]
+ # remove tmp dir
+ shutil.rmtree(tmpdir) # type: ignore
+ return ordered_results
+
+
+def collect_results_gpu(result_part: list, size: int) -> Optional[list]:
+ """Collect results under gpu mode.
+
+ On gpu mode, this function will encode results to gpu tensors and use gpu
+ communication for results collection.
+
+ Args:
+ result_part (list[object]): Result list containing result parts
+ to be collected. Each item of ``result_part`` should be a picklable
+ object.
+ size (int): Size of the results, commonly equal to length of
+ the results.
+
+ Returns:
+ list or None: The collected results.
+
+ Examples:
+ >>> # distributed environment
+ >>> # We have 2 process groups, 2 ranks.
+ >>> import mmengine.dist as dist
+ >>> if dist.get_rank() == 0:
+ data = ['foo', {1: 2}]
+ else:
+ data = [24, {'a': 'b'}]
+ >>> size = 4
+ >>> output = dist.collect_results_gpu(data, size)
+ >>> output
+ ['foo', 24, {1: 2}, {'a': 'b'}] # rank 0
+ None # rank 1
+ """
+ rank, world_size = get_dist_info()
+ if world_size == 1:
+ return result_part[:size]
+
+ # gather all result part. Note that NCCL does not support gather so use
+ # all_gather_object instead.
+ part_list = all_gather_object(result_part)
+
+ if rank == 0:
+ # sort the results
+ ordered_results = []
+ for res in zip(*part_list):
+ ordered_results.extend(list(res))
+ # the dataloader may pad some samples
+ ordered_results = ordered_results[:size]
+ return ordered_results
+ else:
+ return None
+
+
+def _all_reduce_coalesced(tensors: List[torch.Tensor],
+ bucket_size_mb: int = -1,
+ op: str = 'sum',
+ group: Optional[ProcessGroup] = None) -> None:
+ """All-reduce a sequence of tensors as a whole.
+
+ Args:
+ tensors (List[torch.Tensor]): A sequence of tensors to be
+ all-reduced.
+ bucket_size_mb (int): The limit of each chunk in megabytes
+ for grouping tensors into chunks. Defaults to -1.
+ op (str): Operation to reduce data. Defaults to 'sum'. Optional values
+ are 'sum', 'mean' and 'produce', 'min', 'max', 'band', 'bor' and
+ 'bxor'.
+ group (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+ """
+ if bucket_size_mb > 0:
+ bucket_size_bytes = bucket_size_mb * 1024 * 1024
+ buckets = _take_tensors(tensors, bucket_size_bytes)
+ else:
+ buckets = OrderedDict()
+ for tensor in tensors:
+ tp = tensor.type()
+ if tp not in buckets:
+ buckets[tp] = []
+ buckets[tp].append(tensor)
+ buckets = buckets.values()
+
+ for bucket in buckets:
+ flat_tensors = _flatten_dense_tensors(bucket)
+ all_reduce(flat_tensors, op=op, group=group)
+ for tensor, synced in zip(
+ bucket, _unflatten_dense_tensors(flat_tensors, bucket)):
+ tensor.copy_(synced)
+
+
+def all_reduce_params(params: Union[List, Generator[torch.Tensor, None, None]],
+ coalesce: bool = True,
+ bucket_size_mb: int = -1,
+ op: str = 'sum',
+ group: Optional[ProcessGroup] = None) -> None:
+ """All-reduce parameters.
+
+ Args:
+ params (List or Generator[torch.Tensor, None, None]): List of
+ parameters or buffers of a model.
+ coalesce (bool, optional): Whether to reduce parameters as a whole.
+ Defaults to True.
+ bucket_size_mb (int, optional): Size of bucket, the unit is MB.
+ Defaults to -1.
+ op (str): Operation to reduce data. Defaults to 'sum'. Optional values
+ are 'sum', 'mean' and 'produce', 'min', 'max', 'band', 'bor' and
+ 'bxor'.
+ group (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+
+ Examples:
+ >>> import torch
+ >>> import mmengine.dist as dist
+
+ >>> # non-distributed environment
+ >>> data = [torch.arange(2), torch.arange(3)]
+ >>> dist.all_reduce_params(data)
+ >>> data
+ [tensor([0, 1]), tensor([0, 1, 2])]
+
+ >>> # distributed environment
+ >>> # We have 2 process groups, 2 ranks.
+ >>> if dist.get_rank() == 0:
+ ... data = [torch.tensor([1, 2]), torch.tensor([3, 4])]
+ ... else:
+ ... data = [torch.tensor([2, 3]), torch.tensor([4, 5])]
+
+ >>> dist.all_reduce_params(data)
+ >>> data
+ [torch.tensor([3, 5]), torch.tensor([7, 9])]
+ """
+ world_size = get_world_size(group)
+ if world_size == 1:
+ return
+ params_data = [param.data for param in params]
+ if coalesce:
+ _all_reduce_coalesced(params_data, bucket_size_mb, op=op, group=group)
+ else:
+ for tensor in params_data:
+ all_reduce(tensor, op=op, group=group)
diff --git a/testbed/open-mmlab__mmengine/mmengine/dist/utils.py b/testbed/open-mmlab__mmengine/mmengine/dist/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5ec3cf51d482f93b690e7e7a21d6a638c611a56
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/dist/utils.py
@@ -0,0 +1,539 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import functools
+import os
+import subprocess
+from typing import Callable, Optional, Tuple, Union
+
+import numpy as np
+import torch
+import torch.multiprocessing as mp
+from torch import Tensor
+from torch import distributed as torch_dist
+from torch.distributed import ProcessGroup
+from mmengine.device import is_mlu_available, is_npu_available
+
+from collections.abc import Iterable, Mapping
+
+_LOCAL_PROCESS_GROUP = None
+
+
+def is_distributed() -> bool:
+ """Return True if distributed environment has been initialized."""
+ return torch_dist.is_available() and torch_dist.is_initialized()
+
+
+def get_local_group() -> Optional[ProcessGroup]:
+ """Return local process group."""
+ if not is_distributed():
+ return None
+
+ if _LOCAL_PROCESS_GROUP is None:
+ raise RuntimeError('Local process group is not created, please use '
+ '`init_local_group` to setup local process group.')
+
+ return _LOCAL_PROCESS_GROUP
+
+
+def get_default_group() -> Optional[ProcessGroup]:
+ """Return default process group."""
+
+ return torch_dist.distributed_c10d._get_default_group()
+
+
+def init_dist(launcher, backend='nccl', **kwargs) -> None:
+ """Initialize distributed environment.
+
+ Args:
+ launcher (str): Way to launcher multi processes. Supported launchers
+ are 'pytorch', 'mpi' and 'slurm'.
+ backend (str): Communication Backends. Supported backends are 'nccl',
+ 'gloo' and 'mpi'. Defaults to 'nccl'.
+ **kwargs: keyword arguments are passed to ``init_process_group``.
+ """
+ if mp.get_start_method(allow_none=True) is None:
+ mp.set_start_method('spawn')
+ if launcher == 'pytorch':
+ _init_dist_pytorch(backend, **kwargs)
+ elif launcher == 'mpi':
+ _init_dist_mpi(backend, **kwargs)
+ elif launcher == 'slurm':
+ _init_dist_slurm(backend, **kwargs)
+ else:
+ raise ValueError(f'Invalid launcher type: {launcher}')
+
+
+def _init_dist_pytorch(backend, **kwargs) -> None:
+ """Initialize distributed environment with PyTorch launcher.
+
+ Args:
+ backend (str): Backend of torch.distributed. Supported backends are
+ 'nccl', 'gloo' and 'mpi'. Defaults to 'nccl'.
+ **kwargs: keyword arguments are passed to ``init_process_group``.
+ """
+ # TODO: use local_rank instead of rank % num_gpus
+ rank = int(os.environ['RANK'])
+ if is_mlu_available():
+ import torch_mlu # noqa: F401
+ torch.mlu.set_device(rank)
+ torch_dist.init_process_group(
+ backend='cncl',
+ rank=rank,
+ world_size=int(os.environ['WORLD_SIZE']),
+ **kwargs)
+ elif is_npu_available():
+ import torch_npu # noqa: F401
+ torch.npu.set_device(rank)
+ torch_dist.init_process_group(
+ backend='hccl',
+ rank=rank,
+ world_size=int(os.environ['WORLD_SIZE']),
+ **kwargs)
+ else:
+ num_gpus = torch.cuda.device_count()
+ torch.cuda.set_device(rank % num_gpus)
+ torch_dist.init_process_group(backend=backend, **kwargs)
+
+
+def _init_dist_mpi(backend, **kwargs) -> None:
+ """Initialize distributed environment with MPI launcher.
+
+ Args:
+ backend (str): Backend of torch.distributed. Supported backends are
+ 'nccl', 'gloo' and 'mpi'. Defaults to 'nccl'.
+ **kwargs: keyword arguments are passed to ``init_process_group``.
+ """
+ if backend == 'smddp':
+ try:
+ import smdistributed.dataparallel.torch.torch_smddp # noqa: F401
+ except ModuleNotFoundError as e:
+ raise ModuleNotFoundError(
+ 'Please use an Amazon SageMaker DLC to access smdistributed: '
+ 'https://github.com/aws/deep-learning-containers/blob/master'
+ '/available_images.md#sagemaker-framework-containers'
+ '-sm-support-only') from e
+ local_rank = int(os.environ['OMPI_COMM_WORLD_LOCAL_RANK'])
+ torch.cuda.set_device(local_rank)
+ if 'MASTER_PORT' not in os.environ:
+ # 29500 is torch.distributed default port
+ os.environ['MASTER_PORT'] = '29500'
+ if 'MASTER_ADDR' not in os.environ:
+ raise KeyError('The environment variable MASTER_ADDR is not set')
+ os.environ['WORLD_SIZE'] = os.environ['OMPI_COMM_WORLD_SIZE']
+ os.environ['RANK'] = os.environ['OMPI_COMM_WORLD_RANK']
+ torch_dist.init_process_group(backend=backend, **kwargs)
+
+
+def _init_dist_slurm(backend, port=None) -> None:
+ """Initialize slurm distributed training environment.
+
+ If argument ``port`` is not specified, then the master port will be system
+ environment variable ``MASTER_PORT``. If ``MASTER_PORT`` is not in system
+ environment variable, then a default port ``29500`` will be used.
+
+ Args:
+ backend (str): Backend of torch.distributed.
+ port (int, optional): Master port. Defaults to None.
+ """
+ proc_id = int(os.environ['SLURM_PROCID'])
+ ntasks = int(os.environ['SLURM_NTASKS'])
+ node_list = os.environ['SLURM_NODELIST']
+ num_gpus = torch.cuda.device_count()
+ torch.cuda.set_device(proc_id % num_gpus)
+ addr = subprocess.getoutput(
+ f'scontrol show hostname {node_list} | head -n1')
+ # specify master port
+ if port is not None:
+ os.environ['MASTER_PORT'] = str(port)
+ elif 'MASTER_PORT' in os.environ:
+ pass # use MASTER_PORT in the environment variable
+ else:
+ # 29500 is torch.distributed default port
+ os.environ['MASTER_PORT'] = '29500'
+ # use MASTER_ADDR in the environment variable if it already exists
+ if 'MASTER_ADDR' not in os.environ:
+ os.environ['MASTER_ADDR'] = addr
+ os.environ['WORLD_SIZE'] = str(ntasks)
+ os.environ['LOCAL_RANK'] = str(proc_id % num_gpus)
+ os.environ['RANK'] = str(proc_id)
+ torch_dist.init_process_group(backend=backend)
+
+
+def init_local_group(node_rank: int, num_gpus_per_node: int):
+ """Setup the local process group.
+
+ Setup a process group which only includes processes that on the same
+ machine as the current process.
+
+ The code is modified from
+ https://github.com/facebookresearch/detectron2/blob/main/detectron2/engine/launch.py
+
+ Args:
+ node_rank (int): Rank of machines used for training.
+ num_gpus_per_node (int): Number of gpus used for training in a single
+ machine.
+ """ # noqa: W501
+ global _LOCAL_PROCESS_GROUP
+ assert _LOCAL_PROCESS_GROUP is None
+
+ ranks = list(
+ range(node_rank * num_gpus_per_node,
+ (node_rank + 1) * num_gpus_per_node))
+ _LOCAL_PROCESS_GROUP = torch_dist.new_group(ranks)
+
+
+def get_backend(group: Optional[ProcessGroup] = None) -> Optional[str]:
+ """Return the backend of the given process group.
+
+ Note:
+ Calling ``get_backend`` in non-distributed environment will return
+ None.
+
+ Args:
+ group (ProcessGroup, optional): The process group to work on. The
+ default is the general main process group. If another specific
+ group is specified, the calling process must be part of
+ :attr:`group`. Defaults to None.
+
+ Returns:
+ str or None: Return the backend of the given process group as a lower
+ case string if in distributed environment, otherwise None.
+ """
+ if is_distributed():
+ # handle low versions of torch like 1.5.0 which does not support
+ # passing in None for group argument
+ if group is None:
+ group = get_default_group()
+ return torch_dist.get_backend(group)
+ else:
+ return None
+
+
+def get_world_size(group: Optional[ProcessGroup] = None) -> int:
+ """Return the number of the given process group.
+
+ Note:
+ Calling ``get_world_size`` in non-distributed environment will return
+ 1.
+
+ Args:
+ group (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+
+ Returns:
+ int: Return the number of processes of the given process group if in
+ distributed environment, otherwise 1.
+ """
+ if is_distributed():
+ # handle low versions of torch like 1.5.0 which does not support
+ # passing in None for group argument
+ if group is None:
+ group = get_default_group()
+ return torch_dist.get_world_size(group)
+ else:
+ return 1
+
+
+def get_rank(group: Optional[ProcessGroup] = None) -> int:
+ """Return the rank of the given process group.
+
+ Rank is a unique identifier assigned to each process within a distributed
+ process group. They are always consecutive integers ranging from 0 to
+ ``world_size``.
+
+ Note:
+ Calling ``get_rank`` in non-distributed environment will return 0.
+
+ Args:
+ group (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+
+ Returns:
+ int: Return the rank of the process group if in distributed
+ environment, otherwise 0.
+ """
+
+ if is_distributed():
+ # handle low versions of torch like 1.5.0 which does not support
+ # passing in None for group argument
+ if group is None:
+ group = get_default_group()
+ return torch_dist.get_rank(group)
+ else:
+ return 0
+
+
+def get_local_size() -> int:
+ """Return the number of the current node.
+
+ Returns:
+ int: Return the number of processes in the current node if in
+ distributed environment, otherwise 1.
+ """
+ if not is_distributed():
+ return 1
+
+ if _LOCAL_PROCESS_GROUP is None:
+ raise RuntimeError('Local process group is not created, please use '
+ '`init_local_group` to setup local process group.')
+
+ return torch_dist.get_world_size(_LOCAL_PROCESS_GROUP)
+
+
+def get_local_rank() -> int:
+ """Return the rank of current process in the current node.
+
+ Returns:
+ int: Return the rank of current process in the current node if in
+ distributed environment, otherwise 0
+ """
+ if not is_distributed():
+ return 0
+
+ if _LOCAL_PROCESS_GROUP is None:
+ raise RuntimeError('Local process group is not created, please use '
+ '`init_local_group` to setup local process group.')
+
+ return torch_dist.get_rank(_LOCAL_PROCESS_GROUP)
+
+
+def get_dist_info(group: Optional[ProcessGroup] = None) -> Tuple[int, int]:
+ """Get distributed information of the given process group.
+
+ Note:
+ Calling ``get_dist_info`` in non-distributed environment will return
+ (0, 1).
+
+ Args:
+ group (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+
+ Returns:
+ tuple[int, int]: Return a tuple containing the ``rank`` and
+ ``world_size``.
+ """
+ world_size = get_world_size(group)
+ rank = get_rank(group)
+ return rank, world_size
+
+
+def is_main_process(group: Optional[ProcessGroup] = None) -> bool:
+ """Whether the current rank of the given process group is equal to 0.
+
+ Args:
+ group (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+
+ Returns:
+ bool: Return True if the current rank of the given process group is
+ equal to 0, otherwise False.
+ """
+ return get_rank(group) == 0
+
+
+def master_only(func: Callable) -> Callable:
+ """Decorate those methods which should be executed in master process.
+
+ Args:
+ func (callable): Function to be decorated.
+
+ Returns:
+ callable: Return decorated function.
+ """
+
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ if is_main_process():
+ return func(*args, **kwargs)
+
+ return wrapper
+
+
+def barrier(group: Optional[ProcessGroup] = None) -> None:
+ """Synchronize all processes from the given process group.
+
+ This collective blocks processes until the whole group enters this
+ function.
+
+ Note:
+ Calling ``barrier`` in non-distributed environment will do nothing.
+
+ Args:
+ group (ProcessGroup, optional): The process group to work on. If None,
+ the default process group will be used. Defaults to None.
+ """
+ if is_distributed():
+ # handle low versions of torch like 1.5.0 which does not support
+ # passing in None for group argument
+ if group is None:
+ group = get_default_group()
+ torch_dist.barrier(group)
+
+
+def get_data_device(data: Union[Tensor, Mapping, Iterable]) -> torch.device:
+ """Return the device of ``data``.
+
+ If ``data`` is a sequence of Tensor, all items in ``data`` should have a
+ same device type.
+
+ If ``data`` is a dict whose values are Tensor, all values should have a
+ same device type.
+
+ Args:
+ data (Tensor or Sequence or dict): Inputs to be inferred the device.
+
+ Returns:
+ torch.device: The device of ``data``.
+
+ Examples:
+ >>> import torch
+ >>> from mmengine.dist import cast_data_device
+ >>> # data is a Tensor
+ >>> data = torch.tensor([0, 1])
+ >>> get_data_device(data)
+ device(type='cpu')
+ >>> # data is a list of Tensor
+ >>> data = [torch.tensor([0, 1]), torch.tensor([2, 3])]
+ >>> get_data_device(data)
+ device(type='cpu')
+ >>> # data is a dict
+ >>> data = {'key1': torch.tensor([0, 1]), 'key2': torch.tensor([0, 1])}
+ >>> get_data_device(data)
+ device(type='cpu')
+ """
+ if isinstance(data, Tensor):
+ return data.device
+ elif isinstance(data, Mapping):
+ pre = None
+ for v in data.values():
+ cur = get_data_device(v)
+ if pre is None:
+ pre = cur
+ else:
+ if cur != pre:
+ raise ValueError(
+ 'device type in data should be consistent, but got '
+ f'{cur} and {pre}')
+ if pre is None:
+ raise ValueError('data should not be empty.')
+ return pre
+ elif isinstance(data, Iterable) and not isinstance(data, str):
+ pre = None
+ for item in data:
+ cur = get_data_device(item)
+ if pre is None:
+ pre = cur
+ else:
+ if cur != pre:
+ raise ValueError(
+ 'device type in data should be consistent, but got '
+ f'{cur} and {pre}')
+ if pre is None:
+ raise ValueError('data should not be empty.')
+ return pre
+ else:
+ raise TypeError('data should be a Tensor, sequence of tensor or dict, '
+ f'but got {data}')
+
+
+def get_comm_device(group: Optional[ProcessGroup] = None) -> torch.device:
+ """Return the device for communication among groups.
+
+ Args:
+ group (ProcessGroup, optional): The process group to work on.
+
+ Returns:
+ torch.device: The device of backend.
+ """
+ backend = get_backend(group)
+ if backend == 'hccl':
+ import torch_npu # noqa: F401
+ return torch.device('npu', torch.npu.current_device())
+ elif backend == torch_dist.Backend.NCCL:
+ return torch.device('cuda', torch.cuda.current_device())
+ elif backend == 'cncl':
+ import torch_mlu # noqa: F401
+ return torch.device('mlu', torch.mlu.current_device())
+ elif backend == 'smddp':
+ return torch.device('cuda', torch.cuda.current_device())
+ else:
+ # GLOO and MPI backends use cpu device by default
+ return torch.device('cpu')
+
+
+def cast_data_device(
+ data: Union[Tensor, Mapping, Iterable],
+ device: torch.device,
+ out: Optional[Union[Tensor, Mapping, Iterable]] = None
+) -> Union[Tensor, Mapping, Iterable]:
+ """Recursively convert Tensor in ``data`` to ``device``.
+
+ If ``data`` has already on the ``device``, it will not be casted again.
+
+ Args:
+ data (Tensor or list or dict): Inputs to be casted.
+ device (torch.device): Destination device type.
+ out (Tensor or list or dict, optional): If ``out`` is specified, its
+ value will be equal to ``data``. Defaults to None.
+
+ Returns:
+ Tensor or list or dict: ``data`` was casted to ``device``.
+ """
+ if out is not None:
+ if type(data) != type(out):
+ raise TypeError(
+ 'out should be the same type with data, but got data is '
+ f'{type(data)} and out is {type(data)}')
+
+ if isinstance(out, set):
+ raise TypeError('out should not be a set')
+
+ if isinstance(data, Tensor):
+ if get_data_device(data) == device:
+ data_on_device = data
+ else:
+ data_on_device = data.to(device)
+
+ if out is not None:
+ # modify the value of out inplace
+ out.copy_(data_on_device) # type: ignore
+
+ return data_on_device
+ elif isinstance(data, Mapping):
+ data_on_device = {}
+ if out is not None:
+ data_len = len(data)
+ out_len = len(out) # type: ignore
+ if data_len != out_len:
+ raise ValueError('length of data and out should be same, '
+ f'but got {data_len} and {out_len}')
+
+ for k, v in data.items():
+ data_on_device[k] = cast_data_device(v, device,
+ out[k]) # type: ignore
+ else:
+ for k, v in data.items():
+ data_on_device[k] = cast_data_device(v, device)
+
+ if len(data_on_device) == 0:
+ raise ValueError('data should not be empty')
+
+ # To ensure the type of output as same as input, we use `type(data)`
+ # to wrap the output
+ return type(data)(data_on_device) # type: ignore
+ elif isinstance(data, Iterable) and not isinstance(
+ data, str) and not isinstance(data, np.ndarray):
+ data_on_device = []
+ if out is not None:
+ for v1, v2 in zip(data, out):
+ data_on_device.append(cast_data_device(v1, device, v2))
+ else:
+ for v in data:
+ data_on_device.append(cast_data_device(v, device))
+
+ if len(data_on_device) == 0:
+ raise ValueError('data should not be empty')
+
+ return type(data)(data_on_device) # type: ignore
+ else:
+ raise TypeError('data should be a Tensor, list of tensor or dict, '
+ f'but got {data}')
diff --git a/testbed/open-mmlab__mmengine/mmengine/evaluator/__init__.py b/testbed/open-mmlab__mmengine/mmengine/evaluator/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6bc78425e2a3194bdaa4da29e6b3e238237fafa
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/evaluator/__init__.py
@@ -0,0 +1,6 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .evaluator import Evaluator
+from .metric import BaseMetric, DumpResults
+from .utils import get_metric_value
+
+__all__ = ['BaseMetric', 'Evaluator', 'get_metric_value', 'DumpResults']
diff --git a/testbed/open-mmlab__mmengine/mmengine/evaluator/evaluator.py b/testbed/open-mmlab__mmengine/mmengine/evaluator/evaluator.py
new file mode 100644
index 0000000000000000000000000000000000000000..930ce930286a6bdcf4d0eac7cb79a961f3587a14
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/evaluator/evaluator.py
@@ -0,0 +1,135 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from typing import Any, Iterator, List, Optional, Sequence, Union
+
+from mmengine.dataset import pseudo_collate
+from mmengine.registry import EVALUATOR, METRICS
+from mmengine.structures import BaseDataElement
+from .metric import BaseMetric
+
+
+@EVALUATOR.register_module()
+class Evaluator:
+ """Wrapper class to compose multiple :class:`BaseMetric` instances.
+
+ Args:
+ metrics (dict or BaseMetric or Sequence): The config of metrics.
+ """
+
+ def __init__(self, metrics: Union[dict, BaseMetric, Sequence]):
+ self._dataset_meta: Optional[dict] = None
+ if not isinstance(metrics, Sequence):
+ metrics = [metrics]
+ self.metrics: List[BaseMetric] = []
+ for metric in metrics:
+ if isinstance(metric, dict):
+ self.metrics.append(METRICS.build(metric))
+ else:
+ self.metrics.append(metric)
+
+ @property
+ def dataset_meta(self) -> Optional[dict]:
+ """Optional[dict]: Meta info of the dataset."""
+ return self._dataset_meta
+
+ @dataset_meta.setter
+ def dataset_meta(self, dataset_meta: dict) -> None:
+ """Set the dataset meta info to the evaluator and it's metrics."""
+ self._dataset_meta = dataset_meta
+ for metric in self.metrics:
+ metric.dataset_meta = dataset_meta
+
+ def process(self,
+ data_samples: Sequence[BaseDataElement],
+ data_batch: Optional[Any] = None):
+ """Convert ``BaseDataSample`` to dict and invoke process method of each
+ metric.
+
+ Args:
+ data_samples (Sequence[BaseDataElement]): predictions of the model,
+ and the ground truth of the validation set.
+ data_batch (Any, optional): A batch of data from the dataloader.
+ """
+ _data_samples = []
+ for data_sample in data_samples:
+ if isinstance(data_sample, BaseDataElement):
+ _data_samples.append(data_sample.to_dict())
+ else:
+ _data_samples.append(data_sample)
+
+ for metric in self.metrics:
+ metric.process(data_batch, _data_samples)
+
+ def evaluate(self, size: int) -> dict:
+ """Invoke ``evaluate`` method of each metric and collect the metrics
+ dictionary.
+
+ Args:
+ size (int): Length of the entire validation dataset. When batch
+ size > 1, the dataloader may pad some data samples to make
+ sure all ranks have the same length of dataset slice. The
+ ``collect_results`` function will drop the padded data based on
+ this size.
+
+ Returns:
+ dict: Evaluation results of all metrics. The keys are the names
+ of the metrics, and the values are corresponding results.
+ """
+ metrics = {}
+ for metric in self.metrics:
+ _results = metric.evaluate(size)
+
+ # Check metric name conflicts
+ for name in _results.keys():
+ if name in metrics:
+ raise ValueError(
+ 'There are multiple evaluation results with the same '
+ f'metric name {name}. Please make sure all metrics '
+ 'have different prefixes.')
+
+ metrics.update(_results)
+ return metrics
+
+ def offline_evaluate(self,
+ data_samples: Sequence,
+ data: Optional[Sequence] = None,
+ chunk_size: int = 1):
+ """Offline evaluate the dumped predictions on the given data .
+
+ Args:
+ data_samples (Sequence): All predictions and ground truth of the
+ model and the validation set.
+ data (Sequence, optional): All data of the validation set.
+ chunk_size (int): The number of data samples and predictions to be
+ processed in a batch.
+ """
+
+ # support chunking iterable objects
+ def get_chunks(seq: Iterator, chunk_size=1):
+ stop = False
+ while not stop:
+ chunk = []
+ for _ in range(chunk_size):
+ try:
+ chunk.append(next(seq))
+ except StopIteration:
+ stop = True
+ break
+ if chunk:
+ yield chunk
+
+ if data is not None:
+ assert len(data_samples) == len(data), (
+ 'data_samples and data should have the same length, but got '
+ f'data_samples length: {len(data_samples)} '
+ f'data length: {len(data)}')
+ data = get_chunks(iter(data), chunk_size)
+
+ size = 0
+ for output_chunk in get_chunks(iter(data_samples), chunk_size):
+ if data is not None:
+ data_chunk = pseudo_collate(next(data)) # type: ignore
+ else:
+ data_chunk = None
+ size += len(output_chunk)
+ self.process(output_chunk, data_chunk)
+ return self.evaluate(size)
diff --git a/testbed/open-mmlab__mmengine/mmengine/evaluator/metric.py b/testbed/open-mmlab__mmengine/mmengine/evaluator/metric.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7f7df5b7c1637c9fee9a27e0c47092b2e3e59de
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/evaluator/metric.py
@@ -0,0 +1,172 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import warnings
+from abc import ABCMeta, abstractmethod
+from typing import Any, List, Optional, Sequence, Union
+
+from torch import Tensor
+
+from mmengine.dist import (broadcast_object_list, collect_results,
+ is_main_process)
+from mmengine.fileio import dump
+from mmengine.logging import print_log
+from mmengine.registry import METRICS
+from mmengine.structures import BaseDataElement
+
+
+class BaseMetric(metaclass=ABCMeta):
+ """Base class for a metric.
+
+ The metric first processes each batch of data_samples and predictions,
+ and appends the processed results to the results list. Then it
+ collects all results together from all ranks if distributed training
+ is used. Finally, it computes the metrics of the entire dataset.
+
+ A subclass of class:`BaseMetric` should assign a meaningful value to the
+ class attribute `default_prefix`. See the argument `prefix` for details.
+
+ Args:
+ collect_device (str): Device name used for collecting results from
+ different ranks during distributed training. Must be 'cpu' or
+ 'gpu'. Defaults to 'cpu'.
+ prefix (str, optional): The prefix that will be added in the metric
+ names to disambiguate homonymous metrics of different evaluators.
+ If prefix is not provided in the argument, self.default_prefix
+ will be used instead. Default: None
+ """
+
+ default_prefix: Optional[str] = None
+
+ def __init__(self,
+ collect_device: str = 'cpu',
+ prefix: Optional[str] = None) -> None:
+ self._dataset_meta: Union[None, dict] = None
+ self.collect_device = collect_device
+ self.results: List[Any] = []
+ self.prefix = prefix or self.default_prefix
+ if self.prefix is None:
+ warnings.warn('The prefix is not set in metric class '
+ f'{self.__class__.__name__}.')
+
+ @property
+ def dataset_meta(self) -> Optional[dict]:
+ """Optional[dict]: Meta info of the dataset."""
+ return self._dataset_meta
+
+ @dataset_meta.setter
+ def dataset_meta(self, dataset_meta: dict) -> None:
+ """Set the dataset meta info to the metric."""
+ self._dataset_meta = dataset_meta
+
+ @abstractmethod
+ def process(self, data_batch: Any, data_samples: Sequence[dict]) -> None:
+ """Process one batch of data samples and predictions. The processed
+ results should be stored in ``self.results``, which will be used to
+ compute the metrics when all batches have been processed.
+
+ Args:
+ data_batch (Any): A batch of data from the dataloader.
+ data_samples (Sequence[dict]): A batch of outputs from
+ the model.
+ """
+
+ @abstractmethod
+ def compute_metrics(self, results: list) -> dict:
+ """Compute the metrics from processed results.
+
+ Args:
+ results (list): The processed results of each batch.
+
+ Returns:
+ dict: The computed metrics. The keys are the names of the metrics,
+ and the values are corresponding results.
+ """
+
+ def evaluate(self, size: int) -> dict:
+ """Evaluate the model performance of the whole dataset after processing
+ all batches.
+
+ Args:
+ size (int): Length of the entire validation dataset. When batch
+ size > 1, the dataloader may pad some data samples to make
+ sure all ranks have the same length of dataset slice. The
+ ``collect_results`` function will drop the padded data based on
+ this size.
+
+ Returns:
+ dict: Evaluation metrics dict on the val dataset. The keys are the
+ names of the metrics, and the values are corresponding results.
+ """
+ if len(self.results) == 0:
+ warnings.warn(
+ f'{self.__class__.__name__} got empty `self.results`. Please '
+ 'ensure that the processed results are properly added into '
+ '`self.results` in `process` method.')
+
+ results = collect_results(self.results, size, self.collect_device)
+
+ if is_main_process():
+ # cast all tensors in results list to cpu
+ results = _to_cpu(results)
+ _metrics = self.compute_metrics(results) # type: ignore
+ # Add prefix to metric names
+ if self.prefix:
+ _metrics = {
+ '/'.join((self.prefix, k)): v
+ for k, v in _metrics.items()
+ }
+ metrics = [_metrics]
+ else:
+ metrics = [None] # type: ignore
+
+ broadcast_object_list(metrics)
+
+ # reset the results list
+ self.results.clear()
+ return metrics[0]
+
+
+@METRICS.register_module()
+class DumpResults(BaseMetric):
+ """Dump model predictions to a pickle file for offline evaluation.
+
+ Args:
+ out_file_path (str): Path of the dumped file. Must end with '.pkl'
+ or '.pickle'.
+ collect_device (str): Device name used for collecting results from
+ different ranks during distributed training. Must be 'cpu' or
+ 'gpu'. Defaults to 'cpu'.
+ """
+
+ def __init__(self,
+ out_file_path: str,
+ collect_device: str = 'cpu') -> None:
+ super().__init__(collect_device=collect_device)
+ if not out_file_path.endswith(('.pkl', '.pickle')):
+ raise ValueError('The output file must be a pkl file.')
+ self.out_file_path = out_file_path
+
+ def process(self, data_batch: Any, predictions: Sequence[dict]) -> None:
+ """transfer tensors in predictions to CPU."""
+ self.results.extend(_to_cpu(predictions))
+
+ def compute_metrics(self, results: list) -> dict:
+ """dump the prediction results to a pickle file."""
+ dump(results, self.out_file_path)
+ print_log(
+ f'Results has been saved to {self.out_file_path}.',
+ logger='current')
+ return {}
+
+
+def _to_cpu(data: Any) -> Any:
+ """transfer all tensors and BaseDataElement to cpu."""
+ if isinstance(data, (Tensor, BaseDataElement)):
+ return data.to('cpu')
+ elif isinstance(data, list):
+ return [_to_cpu(d) for d in data]
+ elif isinstance(data, tuple):
+ return tuple(_to_cpu(d) for d in data)
+ elif isinstance(data, dict):
+ return {k: _to_cpu(v) for k, v in data.items()}
+ else:
+ return data
diff --git a/testbed/open-mmlab__mmengine/mmengine/evaluator/utils.py b/testbed/open-mmlab__mmengine/mmengine/evaluator/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..6981c881b95e1b6c6c859958a3b6f73049e2f2af
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/evaluator/utils.py
@@ -0,0 +1,38 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from typing import Any, Dict
+
+
+def get_metric_value(indicator: str, metrics: Dict) -> Any:
+ """Get the metric value specified by an indicator, which can be either a
+ metric name or a full name with evaluator prefix.
+
+ Args:
+ indicator (str): The metric indicator, which can be the metric name
+ (e.g. 'AP') or the full name with prefix (e.g. 'COCO/AP')
+ metrics (dict): The evaluation results output by the evaluator
+
+ Returns:
+ Any: The specified metric value
+ """
+
+ if '/' in indicator:
+ # The indicator is a full name
+ if indicator in metrics:
+ return metrics[indicator]
+ else:
+ raise ValueError(
+ f'The indicator "{indicator}" can not match any metric in '
+ f'{list(metrics.keys())}')
+ else:
+ # The indicator is metric name without prefix
+ matched = [k for k in metrics.keys() if k.split('/')[-1] == indicator]
+
+ if not matched:
+ raise ValueError(
+ f'The indicator {indicator} can not match any metric in '
+ f'{list(metrics.keys())}')
+ elif len(matched) > 1:
+ raise ValueError(f'The indicator "{indicator}" matches multiple '
+ f'metrics {matched}')
+ else:
+ return metrics[matched[0]]
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/__init__.py b/testbed/open-mmlab__mmengine/mmengine/fileio/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..81adcd4c02c96715825bf220794ac9e0b08019b9
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/__init__.py
@@ -0,0 +1,27 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .backends import (BaseStorageBackend, HTTPBackend, LmdbBackend,
+ LocalBackend, MemcachedBackend, PetrelBackend,
+ register_backend)
+from .file_client import FileClient, HardDiskBackend
+from .handlers import (BaseFileHandler, JsonHandler, PickleHandler,
+ YamlHandler, register_handler)
+from .io import (copy_if_symlink_fails, copyfile, copyfile_from_local,
+ copyfile_to_local, copytree, copytree_from_local,
+ copytree_to_local, dump, exists, generate_presigned_url, get,
+ get_file_backend, get_local_path, get_text, isdir, isfile,
+ join_path, list_dir_or_file, load, put, put_text, remove,
+ rmtree)
+from .parse import dict_from_file, list_from_file
+
+__all__ = [
+ 'BaseStorageBackend', 'FileClient', 'PetrelBackend', 'MemcachedBackend',
+ 'LmdbBackend', 'HardDiskBackend', 'LocalBackend', 'HTTPBackend',
+ 'copy_if_symlink_fails', 'copyfile', 'copyfile_from_local',
+ 'copyfile_to_local', 'copytree', 'copytree_from_local',
+ 'copytree_to_local', 'exists', 'generate_presigned_url', 'get',
+ 'get_file_backend', 'get_local_path', 'get_text', 'isdir', 'isfile',
+ 'join_path', 'list_dir_or_file', 'put', 'put_text', 'remove', 'rmtree',
+ 'load', 'dump', 'register_handler', 'BaseFileHandler', 'JsonHandler',
+ 'PickleHandler', 'YamlHandler', 'list_from_file', 'dict_from_file',
+ 'register_backend'
+]
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/backends/__init__.py b/testbed/open-mmlab__mmengine/mmengine/fileio/backends/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa0008977f765f059c2f727885b57716979c2f05
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/backends/__init__.py
@@ -0,0 +1,14 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .base import BaseStorageBackend
+from .http_backend import HTTPBackend
+from .lmdb_backend import LmdbBackend
+from .local_backend import LocalBackend
+from .memcached_backend import MemcachedBackend
+from .petrel_backend import PetrelBackend
+from .registry_utils import backends, prefix_to_backends, register_backend
+
+__all__ = [
+ 'BaseStorageBackend', 'LocalBackend', 'HTTPBackend', 'LmdbBackend',
+ 'MemcachedBackend', 'PetrelBackend', 'register_backend', 'backends',
+ 'prefix_to_backends'
+]
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/backends/base.py b/testbed/open-mmlab__mmengine/mmengine/fileio/backends/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ebabd3bb69e6e6d17eb8c6ded2eef578e1b9af1
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/backends/base.py
@@ -0,0 +1,36 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import warnings
+from abc import ABCMeta, abstractmethod
+
+
+class BaseStorageBackend(metaclass=ABCMeta):
+ """Abstract class of storage backends.
+
+ All backends need to implement two apis: :meth:`get()` and
+ :meth:`get_text()`.
+
+ - :meth:`get()` reads the file as a byte stream.
+ - :meth:`get_text()` reads the file as texts.
+ """
+
+ # a flag to indicate whether the backend can create a symlink for a file
+ # This attribute will be deprecated in future.
+ _allow_symlink = False
+
+ @property
+ def allow_symlink(self):
+ warnings.warn('allow_symlink will be deprecated in future',
+ DeprecationWarning)
+ return self._allow_symlink
+
+ @property
+ def name(self):
+ return self.__class__.__name__
+
+ @abstractmethod
+ def get(self, filepath):
+ pass
+
+ @abstractmethod
+ def get_text(self, filepath):
+ pass
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/backends/http_backend.py b/testbed/open-mmlab__mmengine/mmengine/fileio/backends/http_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3e65bbdbb6e4cb93b324951d9d2dd18c07bae64
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/backends/http_backend.py
@@ -0,0 +1,78 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import tempfile
+from contextlib import contextmanager
+from pathlib import Path
+from typing import Generator, Union
+from urllib.request import urlopen
+
+from .base import BaseStorageBackend
+
+
+class HTTPBackend(BaseStorageBackend):
+ """HTTP and HTTPS storage bachend."""
+
+ def get(self, filepath: str) -> bytes:
+ """Read bytes from a given ``filepath``.
+
+ Args:
+ filepath (str): Path to read data.
+
+ Returns:
+ bytes: Expected bytes object.
+
+ Examples:
+ >>> backend = HTTPBackend()
+ >>> backend.get('http://path/of/file')
+ b'hello world'
+ """
+ return urlopen(filepath).read()
+
+ def get_text(self, filepath, encoding='utf-8') -> str:
+ """Read text from a given ``filepath``.
+
+ Args:
+ filepath (str): Path to read data.
+ encoding (str): The encoding format used to open the ``filepath``.
+ Defaults to 'utf-8'.
+
+ Returns:
+ str: Expected text reading from ``filepath``.
+
+ Examples:
+ >>> backend = HTTPBackend()
+ >>> backend.get_text('http://path/of/file')
+ 'hello world'
+ """
+ return urlopen(filepath).read().decode(encoding)
+
+ @contextmanager
+ def get_local_path(
+ self, filepath: str) -> Generator[Union[str, Path], None, None]:
+ """Download a file from ``filepath`` to a local temporary directory,
+ and return the temporary path.
+
+ ``get_local_path`` is decorated by :meth:`contxtlib.contextmanager`. It
+ can be called with ``with`` statement, and when exists from the
+ ``with`` statement, the temporary path will be released.
+
+ Args:
+ filepath (str): Download a file from ``filepath``.
+
+ Yields:
+ Iterable[str]: Only yield one temporary path.
+
+ Examples:
+ >>> backend = HTTPBackend()
+ >>> # After existing from the ``with`` clause,
+ >>> # the path will be removed
+ >>> with backend.get_local_path('http://path/of/file') as path:
+ ... # do something here
+ """
+ try:
+ f = tempfile.NamedTemporaryFile(delete=False)
+ f.write(self.get(filepath))
+ f.close()
+ yield f.name
+ finally:
+ os.remove(f.name)
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/backends/lmdb_backend.py b/testbed/open-mmlab__mmengine/mmengine/fileio/backends/lmdb_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb47923e56a43529cd28ce7aa3bc9404875c2fd7
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/backends/lmdb_backend.py
@@ -0,0 +1,82 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from pathlib import Path
+from typing import Union
+
+from .base import BaseStorageBackend
+
+
+class LmdbBackend(BaseStorageBackend):
+ """Lmdb storage backend.
+
+ Args:
+ db_path (str): Lmdb database path.
+ readonly (bool): Lmdb environment parameter. If True, disallow any
+ write operations. Defaults to True.
+ lock (bool): Lmdb environment parameter. If False, when concurrent
+ access occurs, do not lock the database. Defaults to False.
+ readahead (bool): Lmdb environment parameter. If False, disable the OS
+ filesystem readahead mechanism, which may improve random read
+ performance when a database is larger than RAM. Defaults to False.
+ **kwargs: Keyword arguments passed to `lmdb.open`.
+
+ Attributes:
+ db_path (str): Lmdb database path.
+ """
+
+ def __init__(self,
+ db_path,
+ readonly=True,
+ lock=False,
+ readahead=False,
+ **kwargs):
+ try:
+ import lmdb # noqa: F401
+ except ImportError:
+ raise ImportError(
+ 'Please run "pip install lmdb" to enable LmdbBackend.')
+
+ self.db_path = str(db_path)
+ self.readonly = readonly
+ self.lock = lock
+ self.readahead = readahead
+ self.kwargs = kwargs
+ self._client = None
+
+ def get(self, filepath: Union[str, Path]) -> bytes:
+ """Get values according to the filepath.
+
+ Args:
+ filepath (str or Path): Here, filepath is the lmdb key.
+
+ Returns:
+ bytes: Expected bytes object.
+
+ Examples:
+ >>> backend = LmdbBackend('path/to/lmdb')
+ >>> backend.get('key')
+ b'hello world'
+ """
+ if self._client is None:
+ self._client = self._get_client()
+
+ filepath = str(filepath)
+ with self._client.begin(write=False) as txn:
+ value_buf = txn.get(filepath.encode('ascii'))
+ return value_buf
+
+ def get_text(self, filepath, encoding=None):
+ raise NotImplementedError
+
+ def _get_client(self):
+ import lmdb
+
+ return lmdb.open(
+ self.db_path,
+ readonly=self.readonly,
+ lock=self.lock,
+ readahead=self.readahead,
+ **self.kwargs)
+
+ def __del__(self):
+ if self._client is not None:
+ self._client.close()
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/backends/local_backend.py b/testbed/open-mmlab__mmengine/mmengine/fileio/backends/local_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c6c7774fa87cf845b2bae2563ab9cc16be8c6d3
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/backends/local_backend.py
@@ -0,0 +1,543 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import os.path as osp
+import shutil
+from contextlib import contextmanager
+from pathlib import Path
+from typing import Generator, Iterator, Optional, Tuple, Union
+
+import mmengine
+from .base import BaseStorageBackend
+
+
+class LocalBackend(BaseStorageBackend):
+ """Raw local storage backend."""
+
+ _allow_symlink = True
+
+ def get(self, filepath: Union[str, Path]) -> bytes:
+ """Read bytes from a given ``filepath`` with 'rb' mode.
+
+ Args:
+ filepath (str or Path): Path to read data.
+
+ Returns:
+ bytes: Expected bytes object.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> filepath = '/path/of/file'
+ >>> backend.get(filepath)
+ b'hello world'
+ """
+ with open(filepath, 'rb') as f:
+ value = f.read()
+ return value
+
+ def get_text(self,
+ filepath: Union[str, Path],
+ encoding: str = 'utf-8') -> str:
+ """Read text from a given ``filepath`` with 'r' mode.
+
+ Args:
+ filepath (str or Path): Path to read data.
+ encoding (str): The encoding format used to open the ``filepath``.
+ Defaults to 'utf-8'.
+
+ Returns:
+ str: Expected text reading from ``filepath``.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> filepath = '/path/of/file'
+ >>> backend.get_text(filepath)
+ 'hello world'
+ """
+ with open(filepath, encoding=encoding) as f:
+ text = f.read()
+ return text
+
+ def put(self, obj: bytes, filepath: Union[str, Path]) -> None:
+ """Write bytes to a given ``filepath`` with 'wb' mode.
+
+ Note:
+ ``put`` will create a directory if the directory of
+ ``filepath`` does not exist.
+
+ Args:
+ obj (bytes): Data to be written.
+ filepath (str or Path): Path to write data.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> filepath = '/path/of/file'
+ >>> backend.put(b'hello world', filepath)
+ """
+ mmengine.mkdir_or_exist(osp.dirname(filepath))
+ with open(filepath, 'wb') as f:
+ f.write(obj)
+
+ def put_text(self,
+ obj: str,
+ filepath: Union[str, Path],
+ encoding: str = 'utf-8') -> None:
+ """Write text to a given ``filepath`` with 'w' mode.
+
+ Note:
+ ``put_text`` will create a directory if the directory of
+ ``filepath`` does not exist.
+
+ Args:
+ obj (str): Data to be written.
+ filepath (str or Path): Path to write data.
+ encoding (str): The encoding format used to open the ``filepath``.
+ Defaults to 'utf-8'.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> filepath = '/path/of/file'
+ >>> backend.put_text('hello world', filepath)
+ """
+ mmengine.mkdir_or_exist(osp.dirname(filepath))
+ with open(filepath, 'w', encoding=encoding) as f:
+ f.write(obj)
+
+ def exists(self, filepath: Union[str, Path]) -> bool:
+ """Check whether a file path exists.
+
+ Args:
+ filepath (str or Path): Path to be checked whether exists.
+
+ Returns:
+ bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> filepath = '/path/of/file'
+ >>> backend.exists(filepath)
+ True
+ """
+ return osp.exists(filepath)
+
+ def isdir(self, filepath: Union[str, Path]) -> bool:
+ """Check whether a file path is a directory.
+
+ Args:
+ filepath (str or Path): Path to be checked whether it is a
+ directory.
+
+ Returns:
+ bool: Return ``True`` if ``filepath`` points to a directory,
+ ``False`` otherwise.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> filepath = '/path/of/dir'
+ >>> backend.isdir(filepath)
+ True
+ """
+ return osp.isdir(filepath)
+
+ def isfile(self, filepath: Union[str, Path]) -> bool:
+ """Check whether a file path is a file.
+
+ Args:
+ filepath (str or Path): Path to be checked whether it is a file.
+
+ Returns:
+ bool: Return ``True`` if ``filepath`` points to a file, ``False``
+ otherwise.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> filepath = '/path/of/file'
+ >>> backend.isfile(filepath)
+ True
+ """
+ return osp.isfile(filepath)
+
+ def join_path(self, filepath: Union[str, Path],
+ *filepaths: Union[str, Path]) -> str:
+ """Concatenate all file paths.
+
+ Join one or more filepath components intelligently. The return value
+ is the concatenation of filepath and any members of *filepaths.
+
+ Args:
+ filepath (str or Path): Path to be concatenated.
+
+ Returns:
+ str: The result of concatenation.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> filepath1 = '/path/of/dir1'
+ >>> filepath2 = 'dir2'
+ >>> filepath3 = 'path/of/file'
+ >>> backend.join_path(filepath1, filepath2, filepath3)
+ '/path/of/dir/dir2/path/of/file'
+ """
+ # TODO, if filepath or filepaths are Path, should return Path
+ return osp.join(filepath, *filepaths)
+
+ @contextmanager
+ def get_local_path(
+ self,
+ filepath: Union[str, Path],
+ ) -> Generator[Union[str, Path], None, None]:
+ """Only for unified API and do nothing.
+
+ Args:
+ filepath (str or Path): Path to be read data.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> with backend.get_local_path('s3://bucket/abc.jpg') as path:
+ ... # do something here
+ """
+ yield filepath
+
+ def copyfile(
+ self,
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ ) -> str:
+ """Copy a file src to dst and return the destination file.
+
+ src and dst should have the same prefix. If dst specifies a directory,
+ the file will be copied into dst using the base filename from src. If
+ dst specifies a file that already exists, it will be replaced.
+
+ Args:
+ src (str or Path): A file to be copied.
+ dst (str or Path): Copy file to dst.
+
+ Returns:
+ str: The destination file.
+
+ Raises:
+ SameFileError: If src and dst are the same file, a SameFileError
+ will be raised.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> # dst is a file
+ >>> src = '/path/of/file'
+ >>> dst = '/path1/of/file1'
+ >>> # src will be copied to '/path1/of/file1'
+ >>> backend.copyfile(src, dst)
+ '/path1/of/file1'
+
+ >>> # dst is a directory
+ >>> dst = '/path1/of/dir'
+ >>> # src will be copied to '/path1/of/dir/file'
+ >>> backend.copyfile(src, dst)
+ '/path1/of/dir/file'
+ """
+ return shutil.copy(src, dst)
+
+ def copytree(
+ self,
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ ) -> str:
+ """Recursively copy an entire directory tree rooted at src to a
+ directory named dst and return the destination directory.
+
+ src and dst should have the same prefix and dst must not already exist.
+
+ TODO: Whether to support dirs_exist_ok parameter.
+
+ Args:
+ src (str or Path): A directory to be copied.
+ dst (str or Path): Copy directory to dst.
+
+ Returns:
+ str: The destination directory.
+
+ Raises:
+ FileExistsError: If dst had already existed, a FileExistsError will
+ be raised.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> src = '/path/of/dir1'
+ >>> dst = '/path/of/dir2'
+ >>> backend.copytree(src, dst)
+ '/path/of/dir2'
+ """
+ return shutil.copytree(src, dst)
+
+ def copyfile_from_local(
+ self,
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ ) -> str:
+ """Copy a local file src to dst and return the destination file. Same
+ as :meth:`copyfile`.
+
+ Args:
+ src (str or Path): A local file to be copied.
+ dst (str or Path): Copy file to dst.
+
+ Returns:
+ str: If dst specifies a directory, the file will be copied into dst
+ using the base filename from src.
+
+ Raises:
+ SameFileError: If src and dst are the same file, a SameFileError
+ will be raised.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> # dst is a file
+ >>> src = '/path/of/file'
+ >>> dst = '/path1/of/file1'
+ >>> # src will be copied to '/path1/of/file1'
+ >>> backend.copyfile_from_local(src, dst)
+ '/path1/of/file1'
+
+ >>> # dst is a directory
+ >>> dst = '/path1/of/dir'
+ >>> # src will be copied to
+ >>> backend.copyfile_from_local(src, dst)
+ '/path1/of/dir/file'
+ """
+ return self.copyfile(src, dst)
+
+ def copytree_from_local(
+ self,
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ ) -> str:
+ """Recursively copy an entire directory tree rooted at src to a
+ directory named dst and return the destination directory. Same as
+ :meth:`copytree`.
+
+ Args:
+ src (str or Path): A local directory to be copied.
+ dst (str or Path): Copy directory to dst.
+
+ Returns:
+ str: The destination directory.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> src = '/path/of/dir1'
+ >>> dst = '/path/of/dir2'
+ >>> backend.copytree_from_local(src, dst)
+ '/path/of/dir2'
+ """
+ return self.copytree(src, dst)
+
+ def copyfile_to_local(
+ self,
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ ) -> str:
+ """Copy the file src to local dst and return the destination file. Same
+ as :meth:`copyfile`.
+
+ If dst specifies a directory, the file will be copied into dst using
+ the base filename from src. If dst specifies a file that already
+ exists, it will be replaced.
+
+ Args:
+ src (str or Path): A file to be copied.
+ dst (str or Path): Copy file to to local dst.
+
+ Returns:
+ str: If dst specifies a directory, the file will be copied into dst
+ using the base filename from src.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> # dst is a file
+ >>> src = '/path/of/file'
+ >>> dst = '/path1/of/file1'
+ >>> # src will be copied to '/path1/of/file1'
+ >>> backend.copyfile_to_local(src, dst)
+ '/path1/of/file1'
+
+ >>> # dst is a directory
+ >>> dst = '/path1/of/dir'
+ >>> # src will be copied to
+ >>> backend.copyfile_to_local(src, dst)
+ '/path1/of/dir/file'
+ """
+ return self.copyfile(src, dst)
+
+ def copytree_to_local(
+ self,
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ ) -> str:
+ """Recursively copy an entire directory tree rooted at src to a local
+ directory named dst and return the destination directory.
+
+ Args:
+ src (str or Path): A directory to be copied.
+ dst (str or Path): Copy directory to local dst.
+ backend_args (dict, optional): Arguments to instantiate the
+ preifx of uri corresponding backend. Defaults to None.
+
+ Returns:
+ str: The destination directory.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> src = '/path/of/dir1'
+ >>> dst = '/path/of/dir2'
+ >>> backend.copytree_from_local(src, dst)
+ '/path/of/dir2'
+ """
+ return self.copytree(src, dst)
+
+ def remove(self, filepath: Union[str, Path]) -> None:
+ """Remove a file.
+
+ Args:
+ filepath (str or Path): Path to be removed.
+
+ Raises:
+ IsADirectoryError: If filepath is a directory, an IsADirectoryError
+ will be raised.
+ FileNotFoundError: If filepath does not exist, an FileNotFoundError
+ will be raised.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> filepath = '/path/of/file'
+ >>> backend.remove(filepath)
+ """
+ if not self.exists(filepath):
+ raise FileNotFoundError(f'filepath {filepath} does not exist')
+
+ if self.isdir(filepath):
+ raise IsADirectoryError('filepath should be a file')
+
+ os.remove(filepath)
+
+ def rmtree(self, dir_path: Union[str, Path]) -> None:
+ """Recursively delete a directory tree.
+
+ Args:
+ dir_path (str or Path): A directory to be removed.
+
+ Examples:
+ >>> dir_path = '/path/of/dir'
+ >>> backend.rmtree(dir_path)
+ """
+ shutil.rmtree(dir_path)
+
+ def copy_if_symlink_fails(
+ self,
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ ) -> bool:
+ """Create a symbolic link pointing to src named dst.
+
+ If failed to create a symbolic link pointing to src, directly copy src
+ to dst instead.
+
+ Args:
+ src (str or Path): Create a symbolic link pointing to src.
+ dst (str or Path): Create a symbolic link named dst.
+
+ Returns:
+ bool: Return True if successfully create a symbolic link pointing
+ to src. Otherwise, return False.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> src = '/path/of/file'
+ >>> dst = '/path1/of/file1'
+ >>> backend.copy_if_symlink_fails(src, dst)
+ True
+ >>> src = '/path/of/dir'
+ >>> dst = '/path1/of/dir1'
+ >>> backend.copy_if_symlink_fails(src, dst)
+ True
+ """
+ try:
+ os.symlink(src, dst)
+ return True
+ except Exception:
+ if self.isfile(src):
+ self.copyfile(src, dst)
+ else:
+ self.copytree(src, dst)
+ return False
+
+ def list_dir_or_file(self,
+ dir_path: Union[str, Path],
+ list_dir: bool = True,
+ list_file: bool = True,
+ suffix: Optional[Union[str, Tuple[str]]] = None,
+ recursive: bool = False) -> Iterator[str]:
+ """Scan a directory to find the interested directories or files in
+ arbitrary order.
+
+ Note:
+ :meth:`list_dir_or_file` returns the path relative to ``dir_path``.
+
+ Args:
+ dir_path (str or Path): Path of the directory.
+ list_dir (bool): List the directories. Defaults to True.
+ list_file (bool): List the path of files. Defaults to True.
+ suffix (str or tuple[str], optional): File suffix that we are
+ interested in. Defaults to None.
+ recursive (bool): If set to True, recursively scan the directory.
+ Defaults to False.
+
+ Yields:
+ Iterable[str]: A relative path to ``dir_path``.
+
+ Examples:
+ >>> backend = LocalBackend()
+ >>> dir_path = '/path/of/dir'
+ >>> # list those files and directories in current directory
+ >>> for file_path in backend.list_dir_or_file(dir_path):
+ ... print(file_path)
+ >>> # only list files
+ >>> for file_path in backend.list_dir_or_file(dir_path, list_dir=False):
+ ... print(file_path)
+ >>> # only list directories
+ >>> for file_path in backend.list_dir_or_file(dir_path, list_file=False):
+ ... print(file_path)
+ >>> # only list files ending with specified suffixes
+ >>> for file_path in backend.list_dir_or_file(dir_path, suffix='.txt'):
+ ... print(file_path)
+ >>> # list all files and directory recursively
+ >>> for file_path in backend.list_dir_or_file(dir_path, recursive=True):
+ ... print(file_path)
+ """ # noqa: E501
+ if list_dir and suffix is not None:
+ raise TypeError('`suffix` should be None when `list_dir` is True')
+
+ if (suffix is not None) and not isinstance(suffix, (str, tuple)):
+ raise TypeError('`suffix` must be a string or tuple of strings')
+
+ root = dir_path
+
+ def _list_dir_or_file(dir_path, list_dir, list_file, suffix,
+ recursive):
+ for entry in os.scandir(dir_path):
+ if not entry.name.startswith('.') and entry.is_file():
+ rel_path = osp.relpath(entry.path, root)
+ if (suffix is None
+ or rel_path.endswith(suffix)) and list_file:
+ yield rel_path
+ elif osp.isdir(entry.path):
+ if list_dir:
+ rel_dir = osp.relpath(entry.path, root)
+ yield rel_dir
+ if recursive:
+ yield from _list_dir_or_file(entry.path, list_dir,
+ list_file, suffix,
+ recursive)
+
+ return _list_dir_or_file(dir_path, list_dir, list_file, suffix,
+ recursive)
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/backends/memcached_backend.py b/testbed/open-mmlab__mmengine/mmengine/fileio/backends/memcached_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..2458e7c6ec3525ba0425370c3529c4403f726716
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/backends/memcached_backend.py
@@ -0,0 +1,58 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from pathlib import Path
+from typing import Union
+
+from .base import BaseStorageBackend
+
+
+class MemcachedBackend(BaseStorageBackend):
+ """Memcached storage backend.
+
+ Attributes:
+ server_list_cfg (str): Config file for memcached server list.
+ client_cfg (str): Config file for memcached client.
+ sys_path (str, optional): Additional path to be appended to `sys.path`.
+ Defaults to None.
+ """
+
+ def __init__(self, server_list_cfg, client_cfg, sys_path=None):
+ if sys_path is not None:
+ import sys
+ sys.path.append(sys_path)
+ try:
+ import mc
+ except ImportError:
+ raise ImportError(
+ 'Please install memcached to enable MemcachedBackend.')
+
+ self.server_list_cfg = server_list_cfg
+ self.client_cfg = client_cfg
+ self._client = mc.MemcachedClient.GetInstance(self.server_list_cfg,
+ self.client_cfg)
+ # mc.pyvector servers as a point which points to a memory cache
+ self._mc_buffer = mc.pyvector()
+
+ def get(self, filepath: Union[str, Path]):
+ """Get values according to the filepath.
+
+ Args:
+ filepath (str or Path): Path to read data.
+
+ Returns:
+ bytes: Expected bytes object.
+
+ Examples:
+ >>> server_list_cfg = '/path/of/server_list.conf'
+ >>> client_cfg = '/path/of/mc.conf'
+ >>> backend = MemcachedBackend(server_list_cfg, client_cfg)
+ >>> backend.get('/path/of/file')
+ b'hello world'
+ """
+ filepath = str(filepath)
+ import mc
+ self._client.Get(filepath, self._mc_buffer)
+ value_buf = mc.ConvertBuffer(self._mc_buffer)
+ return value_buf
+
+ def get_text(self, filepath, encoding=None):
+ raise NotImplementedError
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/backends/petrel_backend.py b/testbed/open-mmlab__mmengine/mmengine/fileio/backends/petrel_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..d662e697beba56c29c7118f0706e9831a0f1ae0e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/backends/petrel_backend.py
@@ -0,0 +1,771 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import os.path as osp
+import re
+import tempfile
+from contextlib import contextmanager
+from pathlib import Path
+from shutil import SameFileError
+from typing import Generator, Iterator, Optional, Tuple, Union
+
+import mmengine
+from mmengine.utils import has_method
+from .base import BaseStorageBackend
+
+
+class PetrelBackend(BaseStorageBackend):
+ """Petrel storage backend (for internal usage).
+
+ PetrelBackend supports reading and writing data to multiple clusters.
+ If the file path contains the cluster name, PetrelBackend will read data
+ from specified cluster or write data to it. Otherwise, PetrelBackend will
+ access the default cluster.
+
+ Args:
+ path_mapping (dict, optional): Path mapping dict from local path to
+ Petrel path. When ``path_mapping={'src': 'dst'}``, ``src`` in
+ ``filepath`` will be replaced by ``dst``. Defaults to None.
+ enable_mc (bool, optional): Whether to enable memcached support.
+ Defaults to True.
+ conf_path (str, optional): Config path of Petrel client. Default: None.
+ `New in version 0.3.3`.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> filepath1 = 'petrel://path/of/file'
+ >>> filepath2 = 'cluster-name:petrel://path/of/file'
+ >>> backend.get(filepath1) # get data from default cluster
+ >>> client.get(filepath2) # get data from 'cluster-name' cluster
+ """
+
+ def __init__(self,
+ path_mapping: Optional[dict] = None,
+ enable_mc: bool = True,
+ conf_path: Optional[str] = None):
+ try:
+ from petrel_client import client
+ except ImportError:
+ raise ImportError('Please install petrel_client to enable '
+ 'PetrelBackend.')
+
+ self._client = client.Client(conf_path=conf_path, enable_mc=enable_mc)
+ assert isinstance(path_mapping, dict) or path_mapping is None
+ self.path_mapping = path_mapping
+
+ def _map_path(self, filepath: Union[str, Path]) -> str:
+ """Map ``filepath`` to a string path whose prefix will be replaced by
+ :attr:`self.path_mapping`.
+
+ Args:
+ filepath (str or Path): Path to be mapped.
+ """
+ filepath = str(filepath)
+ if self.path_mapping is not None:
+ for k, v in self.path_mapping.items():
+ filepath = filepath.replace(k, v, 1)
+ return filepath
+
+ def _format_path(self, filepath: str) -> str:
+ """Convert a ``filepath`` to standard format of petrel oss.
+
+ If the ``filepath`` is concatenated by ``os.path.join``, in a Windows
+ environment, the ``filepath`` will be the format of
+ 's3://bucket_name\\image.jpg'. By invoking :meth:`_format_path`, the
+ above ``filepath`` will be converted to 's3://bucket_name/image.jpg'.
+
+ Args:
+ filepath (str): Path to be formatted.
+ """
+ return re.sub(r'\\+', '/', filepath)
+
+ def _replace_prefix(self, filepath: Union[str, Path]) -> str:
+ filepath = str(filepath)
+ return filepath.replace('petrel://', 's3://')
+
+ def get(self, filepath: Union[str, Path]) -> bytes:
+ """Read bytes from a given ``filepath`` with 'rb' mode.
+
+ Args:
+ filepath (str or Path): Path to read data.
+
+ Returns:
+ bytes: Return bytes read from filepath.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> filepath = 'petrel://path/of/file'
+ >>> backend.get(filepath)
+ b'hello world'
+ """
+ filepath = self._map_path(filepath)
+ filepath = self._format_path(filepath)
+ filepath = self._replace_prefix(filepath)
+ value = self._client.Get(filepath)
+ return value
+
+ def get_text(
+ self,
+ filepath: Union[str, Path],
+ encoding: str = 'utf-8',
+ ) -> str:
+ """Read text from a given ``filepath`` with 'r' mode.
+
+ Args:
+ filepath (str or Path): Path to read data.
+ encoding (str): The encoding format used to open the ``filepath``.
+ Defaults to 'utf-8'.
+
+ Returns:
+ str: Expected text reading from ``filepath``.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> filepath = 'petrel://path/of/file'
+ >>> backend.get_text(filepath)
+ 'hello world'
+ """
+ return str(self.get(filepath), encoding=encoding)
+
+ def put(self, obj: bytes, filepath: Union[str, Path]) -> None:
+ """Write bytes to a given ``filepath``.
+
+ Args:
+ obj (bytes): Data to be saved.
+ filepath (str or Path): Path to write data.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> filepath = 'petrel://path/of/file'
+ >>> backend.put(b'hello world', filepath)
+ """
+ filepath = self._map_path(filepath)
+ filepath = self._format_path(filepath)
+ filepath = self._replace_prefix(filepath)
+ self._client.put(filepath, obj)
+
+ def put_text(
+ self,
+ obj: str,
+ filepath: Union[str, Path],
+ encoding: str = 'utf-8',
+ ) -> None:
+ """Write text to a given ``filepath``.
+
+ Args:
+ obj (str): Data to be written.
+ filepath (str or Path): Path to write data.
+ encoding (str): The encoding format used to encode the ``obj``.
+ Defaults to 'utf-8'.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> filepath = 'petrel://path/of/file'
+ >>> backend.put_text('hello world', filepath)
+ """
+ self.put(bytes(obj, encoding=encoding), filepath)
+
+ def exists(self, filepath: Union[str, Path]) -> bool:
+ """Check whether a file path exists.
+
+ Args:
+ filepath (str or Path): Path to be checked whether exists.
+
+ Returns:
+ bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> filepath = 'petrel://path/of/file'
+ >>> backend.exists(filepath)
+ True
+ """
+ if not (has_method(self._client, 'contains')
+ and has_method(self._client, 'isdir')):
+ raise NotImplementedError(
+ 'Current version of Petrel Python SDK has not supported '
+ 'the `contains` and `isdir` methods, please use a higher'
+ 'version or dev branch instead.')
+
+ filepath = self._map_path(filepath)
+ filepath = self._format_path(filepath)
+ filepath = self._replace_prefix(filepath)
+ return self._client.contains(filepath) or self._client.isdir(filepath)
+
+ def isdir(self, filepath: Union[str, Path]) -> bool:
+ """Check whether a file path is a directory.
+
+ Args:
+ filepath (str or Path): Path to be checked whether it is a
+ directory.
+
+ Returns:
+ bool: Return ``True`` if ``filepath`` points to a directory,
+ ``False`` otherwise.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> filepath = 'petrel://path/of/dir'
+ >>> backend.isdir(filepath)
+ True
+ """
+ if not has_method(self._client, 'isdir'):
+ raise NotImplementedError(
+ 'Current version of Petrel Python SDK has not supported '
+ 'the `isdir` method, please use a higher version or dev'
+ ' branch instead.')
+
+ filepath = self._map_path(filepath)
+ filepath = self._format_path(filepath)
+ filepath = self._replace_prefix(filepath)
+ return self._client.isdir(filepath)
+
+ def isfile(self, filepath: Union[str, Path]) -> bool:
+ """Check whether a file path is a file.
+
+ Args:
+ filepath (str or Path): Path to be checked whether it is a file.
+
+ Returns:
+ bool: Return ``True`` if ``filepath`` points to a file, ``False``
+ otherwise.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> filepath = 'petrel://path/of/file'
+ >>> backend.isfile(filepath)
+ True
+ """
+ if not has_method(self._client, 'contains'):
+ raise NotImplementedError(
+ 'Current version of Petrel Python SDK has not supported '
+ 'the `contains` method, please use a higher version or '
+ 'dev branch instead.')
+
+ filepath = self._map_path(filepath)
+ filepath = self._format_path(filepath)
+ filepath = self._replace_prefix(filepath)
+ return self._client.contains(filepath)
+
+ def join_path(
+ self,
+ filepath: Union[str, Path],
+ *filepaths: Union[str, Path],
+ ) -> str:
+ """Concatenate all file paths.
+
+ Join one or more filepath components intelligently. The return value
+ is the concatenation of filepath and any members of *filepaths.
+
+ Args:
+ filepath (str or Path): Path to be concatenated.
+
+ Returns:
+ str: The result after concatenation.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> filepath = 'petrel://path/of/file'
+ >>> backend.join_path(filepath, 'another/path')
+ 'petrel://path/of/file/another/path'
+ >>> backend.join_path(filepath, '/another/path')
+ 'petrel://path/of/file/another/path'
+ """
+ filepath = self._format_path(self._map_path(filepath))
+ if filepath.endswith('/'):
+ filepath = filepath[:-1]
+ formatted_paths = [filepath]
+ for path in filepaths:
+ formatted_path = self._format_path(self._map_path(path))
+ formatted_paths.append(formatted_path.lstrip('/'))
+
+ return '/'.join(formatted_paths)
+
+ @contextmanager
+ def get_local_path(
+ self,
+ filepath: Union[str, Path],
+ ) -> Generator[Union[str, Path], None, None]:
+ """Download a file from ``filepath`` to a local temporary directory,
+ and return the temporary path.
+
+ ``get_local_path`` is decorated by :meth:`contxtlib.contextmanager`. It
+ can be called with ``with`` statement, and when exists from the
+ ``with`` statement, the temporary path will be released.
+
+ Args:
+ filepath (str or Path): Download a file from ``filepath``.
+
+ Yields:
+ Iterable[str]: Only yield one temporary path.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> # After existing from the ``with`` clause,
+ >>> # the path will be removed
+ >>> filepath = 'petrel://path/of/file'
+ >>> with backend.get_local_path(filepath) as path:
+ ... # do something here
+ """
+ assert self.isfile(filepath)
+ try:
+ f = tempfile.NamedTemporaryFile(delete=False)
+ f.write(self.get(filepath))
+ f.close()
+ yield f.name
+ finally:
+ os.remove(f.name)
+
+ def copyfile(
+ self,
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ ) -> str:
+ """Copy a file src to dst and return the destination file.
+
+ src and dst should have the same prefix. If dst specifies a directory,
+ the file will be copied into dst using the base filename from src. If
+ dst specifies a file that already exists, it will be replaced.
+
+ Args:
+ src (str or Path): A file to be copied.
+ dst (str or Path): Copy file to dst.
+
+ Returns:
+ str: The destination file.
+
+ Raises:
+ SameFileError: If src and dst are the same file, a SameFileError
+ will be raised.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> # dst is a file
+ >>> src = 'petrel://path/of/file'
+ >>> dst = 'petrel://path/of/file1'
+ >>> backend.copyfile(src, dst)
+ 'petrel://path/of/file1'
+
+ >>> # dst is a directory
+ >>> dst = 'petrel://path/of/dir'
+ >>> backend.copyfile(src, dst)
+ 'petrel://path/of/dir/file'
+ """
+ src = self._format_path(self._map_path(src))
+ dst = self._format_path(self._map_path(dst))
+ if self.isdir(dst):
+ dst = self.join_path(dst, src.split('/')[-1])
+
+ if src == dst:
+ raise SameFileError('src and dst should not be same')
+
+ self.put(self.get(src), dst)
+ return dst
+
+ def copytree(
+ self,
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ ) -> str:
+ """Recursively copy an entire directory tree rooted at src to a
+ directory named dst and return the destination directory.
+
+ src and dst should have the same prefix.
+
+ Args:
+ src (str or Path): A directory to be copied.
+ dst (str or Path): Copy directory to dst.
+ backend_args (dict, optional): Arguments to instantiate the
+ preifx of uri corresponding backend. Defaults to None.
+
+ Returns:
+ str: The destination directory.
+
+ Raises:
+ FileExistsError: If dst had already existed, a FileExistsError will
+ be raised.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> src = 'petrel://path/of/dir'
+ >>> dst = 'petrel://path/of/dir1'
+ >>> backend.copytree(src, dst)
+ 'petrel://path/of/dir1'
+ """
+ src = self._format_path(self._map_path(src))
+ dst = self._format_path(self._map_path(dst))
+
+ if self.exists(dst):
+ raise FileExistsError('dst should not exist')
+
+ for path in self.list_dir_or_file(src, list_dir=False, recursive=True):
+ src_path = self.join_path(src, path)
+ dst_path = self.join_path(dst, path)
+ self.put(self.get(src_path), dst_path)
+
+ return dst
+
+ def copyfile_from_local(
+ self,
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ ) -> str:
+ """Upload a local file src to dst and return the destination file.
+
+ Args:
+ src (str or Path): A local file to be copied.
+ dst (str or Path): Copy file to dst.
+ backend_args (dict, optional): Arguments to instantiate the
+ preifx of uri corresponding backend. Defaults to None.
+
+ Returns:
+ str: If dst specifies a directory, the file will be copied into dst
+ using the base filename from src.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> # dst is a file
+ >>> src = 'path/of/your/file'
+ >>> dst = 'petrel://path/of/file1'
+ >>> backend.copyfile_from_local(src, dst)
+ 'petrel://path/of/file1'
+
+ >>> # dst is a directory
+ >>> dst = 'petrel://path/of/dir'
+ >>> backend.copyfile_from_local(src, dst)
+ 'petrel://path/of/dir/file'
+ """
+ dst = self._format_path(self._map_path(dst))
+ if self.isdir(dst):
+ dst = self.join_path(dst, osp.basename(src))
+
+ with open(src, 'rb') as f:
+ self.put(f.read(), dst)
+
+ return dst
+
+ def copytree_from_local(
+ self,
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ ) -> str:
+ """Recursively copy an entire directory tree rooted at src to a
+ directory named dst and return the destination directory.
+
+ Args:
+ src (str or Path): A local directory to be copied.
+ dst (str or Path): Copy directory to dst.
+
+ Returns:
+ str: The destination directory.
+
+ Raises:
+ FileExistsError: If dst had already existed, a FileExistsError will
+ be raised.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> src = 'path/of/your/dir'
+ >>> dst = 'petrel://path/of/dir1'
+ >>> backend.copytree_from_local(src, dst)
+ 'petrel://path/of/dir1'
+ """
+ dst = self._format_path(self._map_path(dst))
+ if self.exists(dst):
+ raise FileExistsError('dst should not exist')
+
+ src = str(src)
+
+ for cur_dir, _, files in os.walk(src):
+ for f in files:
+ src_path = osp.join(cur_dir, f)
+ dst_path = self.join_path(dst, src_path.replace(src, ''))
+ self.copyfile_from_local(src_path, dst_path)
+
+ return dst
+
+ def copyfile_to_local(
+ self,
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ ) -> Union[str, Path]:
+ """Copy the file src to local dst and return the destination file.
+
+ If dst specifies a directory, the file will be copied into dst using
+ the base filename from src. If dst specifies a file that already
+ exists, it will be replaced.
+
+ Args:
+ src (str or Path): A file to be copied.
+ dst (str or Path): Copy file to to local dst.
+
+ Returns:
+ str: If dst specifies a directory, the file will be copied into dst
+ using the base filename from src.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> # dst is a file
+ >>> src = 'petrel://path/of/file'
+ >>> dst = 'path/of/your/file'
+ >>> backend.copyfile_to_local(src, dst)
+ 'path/of/your/file'
+
+ >>> # dst is a directory
+ >>> dst = 'path/of/your/dir'
+ >>> backend.copyfile_to_local(src, dst)
+ 'path/of/your/dir/file'
+ """
+ if osp.isdir(dst):
+ basename = osp.basename(src)
+ if isinstance(dst, str):
+ dst = osp.join(dst, basename)
+ else:
+ assert isinstance(dst, Path)
+ dst = dst / basename
+
+ with open(dst, 'wb') as f:
+ f.write(self.get(src))
+
+ return dst
+
+ def copytree_to_local(
+ self,
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ ) -> Union[str, Path]:
+ """Recursively copy an entire directory tree rooted at src to a local
+ directory named dst and return the destination directory.
+
+ Args:
+ src (str or Path): A directory to be copied.
+ dst (str or Path): Copy directory to local dst.
+ backend_args (dict, optional): Arguments to instantiate the
+ preifx of uri corresponding backend. Defaults to None.
+
+ Returns:
+ str: The destination directory.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> src = 'petrel://path/of/dir'
+ >>> dst = 'path/of/your/dir'
+ >>> backend.copytree_to_local(src, dst)
+ 'path/of/your/dir'
+ """
+ for path in self.list_dir_or_file(src, list_dir=False, recursive=True):
+ dst_path = osp.join(dst, path)
+ mmengine.mkdir_or_exist(osp.dirname(dst_path))
+ with open(dst_path, 'wb') as f:
+ f.write(self.get(self.join_path(src, path)))
+
+ return dst
+
+ def remove(self, filepath: Union[str, Path]) -> None:
+ """Remove a file.
+
+ Args:
+ filepath (str or Path): Path to be removed.
+
+ Raises:
+ FileNotFoundError: If filepath does not exist, an FileNotFoundError
+ will be raised.
+ IsADirectoryError: If filepath is a directory, an IsADirectoryError
+ will be raised.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> filepath = 'petrel://path/of/file'
+ >>> backend.remove(filepath)
+ """
+ if not has_method(self._client, 'delete'):
+ raise NotImplementedError(
+ 'Current version of Petrel Python SDK has not supported '
+ 'the `delete` method, please use a higher version or dev '
+ 'branch instead.')
+
+ if not self.exists(filepath):
+ raise FileNotFoundError(f'filepath {filepath} does not exist')
+
+ if self.isdir(filepath):
+ raise IsADirectoryError('filepath should be a file')
+
+ filepath = self._map_path(filepath)
+ filepath = self._format_path(filepath)
+ filepath = self._replace_prefix(filepath)
+ self._client.delete(filepath)
+
+ def rmtree(self, dir_path: Union[str, Path]) -> None:
+ """Recursively delete a directory tree.
+
+ Args:
+ dir_path (str or Path): A directory to be removed.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> dir_path = 'petrel://path/of/dir'
+ >>> backend.rmtree(dir_path)
+ """
+ for path in self.list_dir_or_file(
+ dir_path, list_dir=False, recursive=True):
+ filepath = self.join_path(dir_path, path)
+ self.remove(filepath)
+
+ def copy_if_symlink_fails(
+ self,
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ ) -> bool:
+ """Create a symbolic link pointing to src named dst.
+
+ Directly copy src to dst because PetrelBacekend does not support create
+ a symbolic link.
+
+ Args:
+ src (str or Path): A file or directory to be copied.
+ dst (str or Path): Copy a file or directory to dst.
+ backend_args (dict, optional): Arguments to instantiate the
+ preifx of uri corresponding backend. Defaults to None.
+
+ Returns:
+ bool: Return False because PetrelBackend does not support create
+ a symbolic link.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> src = 'petrel://path/of/file'
+ >>> dst = 'petrel://path/of/your/file'
+ >>> backend.copy_if_symlink_fails(src, dst)
+ False
+ >>> src = 'petrel://path/of/dir'
+ >>> dst = 'petrel://path/of/your/dir'
+ >>> backend.copy_if_symlink_fails(src, dst)
+ False
+ """
+ if self.isfile(src):
+ self.copyfile(src, dst)
+ else:
+ self.copytree(src, dst)
+ return False
+
+ def list_dir_or_file(self,
+ dir_path: Union[str, Path],
+ list_dir: bool = True,
+ list_file: bool = True,
+ suffix: Optional[Union[str, Tuple[str]]] = None,
+ recursive: bool = False) -> Iterator[str]:
+ """Scan a directory to find the interested directories or files in
+ arbitrary order.
+
+ Note:
+ Petrel has no concept of directories but it simulates the directory
+ hierarchy in the filesystem through public prefixes. In addition,
+ if the returned path ends with '/', it means the path is a public
+ prefix which is a logical directory.
+
+ Note:
+ :meth:`list_dir_or_file` returns the path relative to ``dir_path``.
+ In addition, the returned path of directory will not contains the
+ suffix '/' which is consistent with other backends.
+
+ Args:
+ dir_path (str | Path): Path of the directory.
+ list_dir (bool): List the directories. Defaults to True.
+ list_file (bool): List the path of files. Defaults to True.
+ suffix (str or tuple[str], optional): File suffix
+ that we are interested in. Defaults to None.
+ recursive (bool): If set to True, recursively scan the
+ directory. Defaults to False.
+
+ Yields:
+ Iterable[str]: A relative path to ``dir_path``.
+
+ Examples:
+ >>> backend = PetrelBackend()
+ >>> dir_path = 'petrel://path/of/dir'
+ >>> # list those files and directories in current directory
+ >>> for file_path in backend.list_dir_or_file(dir_path):
+ ... print(file_path)
+ >>> # only list files
+ >>> for file_path in backend.list_dir_or_file(dir_path, list_dir=False):
+ ... print(file_path)
+ >>> # only list directories
+ >>> for file_path in backend.list_dir_or_file(dir_path, list_file=False):
+ ... print(file_path)
+ >>> # only list files ending with specified suffixes
+ >>> for file_path in backend.list_dir_or_file(dir_path, suffix='.txt'):
+ ... print(file_path)
+ >>> # list all files and directory recursively
+ >>> for file_path in backend.list_dir_or_file(dir_path, recursive=True):
+ ... print(file_path)
+ """ # noqa: E501
+ if not has_method(self._client, 'list'):
+ raise NotImplementedError(
+ 'Current version of Petrel Python SDK has not supported '
+ 'the `list` method, please use a higher version or dev'
+ ' branch instead.')
+
+ dir_path = self._map_path(dir_path)
+ dir_path = self._format_path(dir_path)
+ dir_path = self._replace_prefix(dir_path)
+ if list_dir and suffix is not None:
+ raise TypeError(
+ '`list_dir` should be False when `suffix` is not None')
+
+ if (suffix is not None) and not isinstance(suffix, (str, tuple)):
+ raise TypeError('`suffix` must be a string or tuple of strings')
+
+ # Petrel's simulated directory hierarchy assumes that directory paths
+ # should end with `/`
+ if not dir_path.endswith('/'):
+ dir_path += '/'
+
+ root = dir_path
+
+ def _list_dir_or_file(dir_path, list_dir, list_file, suffix,
+ recursive):
+ for path in self._client.list(dir_path):
+ # the `self.isdir` is not used here to determine whether path
+ # is a directory, because `self.isdir` relies on
+ # `self._client.list`
+ if path.endswith('/'): # a directory path
+ next_dir_path = self.join_path(dir_path, path)
+ if list_dir:
+ # get the relative path and exclude the last
+ # character '/'
+ rel_dir = next_dir_path[len(root):-1]
+ yield rel_dir
+ if recursive:
+ yield from _list_dir_or_file(next_dir_path, list_dir,
+ list_file, suffix,
+ recursive)
+ else: # a file path
+ absolute_path = self.join_path(dir_path, path)
+ rel_path = absolute_path[len(root):]
+ if (suffix is None
+ or rel_path.endswith(suffix)) and list_file:
+ yield rel_path
+
+ return _list_dir_or_file(dir_path, list_dir, list_file, suffix,
+ recursive)
+
+ def generate_presigned_url(self,
+ url: str,
+ client_method: str = 'get_object',
+ expires_in: int = 3600) -> str:
+ """Generate the presigned url of video stream which can be passed to
+ mmcv.VideoReader. Now only work on Petrel backend.
+
+ Note:
+ Now only work on Petrel backend.
+
+ Args:
+ url (str): Url of video stream.
+ client_method (str): Method of client, 'get_object' or
+ 'put_object'. Default: 'get_object'.
+ expires_in (int): expires, in seconds. Default: 3600.
+
+ Returns:
+ str: Generated presigned url.
+ """
+ return self._client.generate_presigned_url(url, client_method,
+ expires_in)
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/backends/registry_utils.py b/testbed/open-mmlab__mmengine/mmengine/fileio/backends/registry_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4578a4ca76fb3f867b87c088407399bc5c700153
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/backends/registry_utils.py
@@ -0,0 +1,117 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import inspect
+from typing import Optional, Type, Union
+
+from .base import BaseStorageBackend
+from .http_backend import HTTPBackend
+from .lmdb_backend import LmdbBackend
+from .local_backend import LocalBackend
+from .memcached_backend import MemcachedBackend
+from .petrel_backend import PetrelBackend
+
+backends: dict = {}
+prefix_to_backends: dict = {}
+
+
+def _register_backend(name: str,
+ backend: Type[BaseStorageBackend],
+ force: bool = False,
+ prefixes: Union[str, list, tuple, None] = None):
+ """Register a backend.
+
+ Args:
+ name (str): The name of the registered backend.
+ backend (BaseStorageBackend): The backend class to be registered,
+ which must be a subclass of :class:`BaseStorageBackend`.
+ force (bool): Whether to override the backend if the name has already
+ been registered. Defaults to False.
+ prefixes (str or list[str] or tuple[str], optional): The prefix
+ of the registered storage backend. Defaults to None.
+ """
+ global backends, prefix_to_backends
+
+ if not isinstance(name, str):
+ raise TypeError('the backend name should be a string, '
+ f'but got {type(name)}')
+
+ if not inspect.isclass(backend):
+ raise TypeError(f'backend should be a class, but got {type(backend)}')
+ if not issubclass(backend, BaseStorageBackend):
+ raise TypeError(
+ f'backend {backend} is not a subclass of BaseStorageBackend')
+
+ if name in backends and not force:
+ raise ValueError(f'{name} is already registered as a storage backend, '
+ 'add "force=True" if you want to override it')
+ backends[name] = backend
+
+ if prefixes is not None:
+ if isinstance(prefixes, str):
+ prefixes = [prefixes]
+ else:
+ assert isinstance(prefixes, (list, tuple))
+
+ for prefix in prefixes:
+ if prefix in prefix_to_backends and not force:
+ raise ValueError(
+ f'{prefix} is already registered as a storage backend,'
+ ' add "force=True" if you want to override it')
+
+ prefix_to_backends[prefix] = backend
+
+
+def register_backend(name: str,
+ backend: Optional[Type[BaseStorageBackend]] = None,
+ force: bool = False,
+ prefixes: Union[str, list, tuple, None] = None):
+ """Register a backend.
+
+ Args:
+ name (str): The name of the registered backend.
+ backend (class, optional): The backend class to be registered,
+ which must be a subclass of :class:`BaseStorageBackend`.
+ When this method is used as a decorator, backend is None.
+ Defaults to None.
+ force (bool): Whether to override the backend if the name has already
+ been registered. Defaults to False.
+ prefixes (str or list[str] or tuple[str], optional): The prefix
+ of the registered storage backend. Defaults to None.
+
+ This method can be used as a normal method or a decorator.
+
+ Examples:
+
+ >>> class NewBackend(BaseStorageBackend):
+ ... def get(self, filepath):
+ ... return filepath
+ ...
+ ... def get_text(self, filepath):
+ ... return filepath
+ >>> register_backend('new', NewBackend)
+
+ >>> @register_backend('new')
+ ... class NewBackend(BaseStorageBackend):
+ ... def get(self, filepath):
+ ... return filepath
+ ...
+ ... def get_text(self, filepath):
+ ... return filepath
+ """
+ if backend is not None:
+ _register_backend(name, backend, force=force, prefixes=prefixes)
+ return
+
+ def _register(backend_cls):
+ _register_backend(name, backend_cls, force=force, prefixes=prefixes)
+ return backend_cls
+
+ return _register
+
+
+register_backend('local', LocalBackend, prefixes='')
+register_backend('memcached', MemcachedBackend)
+register_backend('lmdb', LmdbBackend)
+# To avoid breaking backward Compatibility, 's3' is also used as a
+# prefix for PetrelBackend
+register_backend('petrel', PetrelBackend, prefixes=['petrel', 's3'])
+register_backend('http', HTTPBackend, prefixes=['http', 'https'])
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/file_client.py b/testbed/open-mmlab__mmengine/mmengine/fileio/file_client.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f4a67160db3b451116724fb17946676903ff27c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/file_client.py
@@ -0,0 +1,456 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import inspect
+import warnings
+from contextlib import contextmanager
+from pathlib import Path
+from typing import Any, Generator, Iterator, Optional, Tuple, Union
+
+from mmengine.utils import is_filepath
+from .backends import (BaseStorageBackend, HTTPBackend, LmdbBackend,
+ LocalBackend, MemcachedBackend, PetrelBackend)
+
+
+class HardDiskBackend(LocalBackend):
+ """Raw hard disks storage backend."""
+
+ def __init__(self) -> None:
+ warnings.warn(
+ '"HardDiskBackend" is the alias of "LocalBackend" '
+ 'and the former will be deprecated in future.', DeprecationWarning)
+
+ @property
+ def name(self):
+ return self.__class__.__name__
+
+
+class FileClient:
+ """A general file client to access files in different backends.
+
+ The client loads a file or text in a specified backend from its path
+ and returns it as a binary or text file. There are two ways to choose a
+ backend, the name of backend and the prefix of path. Although both of them
+ can be used to choose a storage backend, ``backend`` has a higher priority
+ that is if they are all set, the storage backend will be chosen by the
+ backend argument. If they are all `None`, the disk backend will be chosen.
+ Note that It can also register other backend accessor with a given name,
+ prefixes, and backend class. In addition, We use the singleton pattern to
+ avoid repeated object creation. If the arguments are the same, the same
+ object will be returned.
+
+ Warning:
+ `FileClient` will be deprecated in future. Please use io functions
+ in https://mmengine.readthedocs.io/en/latest/api/fileio.html#file-io
+
+ Args:
+ backend (str, optional): The storage backend type. Options are "disk",
+ "memcached", "lmdb", "http" and "petrel". Default: None.
+ prefix (str, optional): The prefix of the registered storage backend.
+ Options are "s3", "http", "https". Default: None.
+
+ Examples:
+ >>> # only set backend
+ >>> file_client = FileClient(backend='petrel')
+ >>> # only set prefix
+ >>> file_client = FileClient(prefix='s3')
+ >>> # set both backend and prefix but use backend to choose client
+ >>> file_client = FileClient(backend='petrel', prefix='s3')
+ >>> # if the arguments are the same, the same object is returned
+ >>> file_client1 = FileClient(backend='petrel')
+ >>> file_client1 is file_client
+ True
+
+ Attributes:
+ client (:obj:`BaseStorageBackend`): The backend object.
+ """
+
+ _backends = {
+ 'disk': HardDiskBackend,
+ 'memcached': MemcachedBackend,
+ 'lmdb': LmdbBackend,
+ 'petrel': PetrelBackend,
+ 'http': HTTPBackend,
+ }
+
+ _prefix_to_backends: dict = {
+ 's3': PetrelBackend,
+ 'petrel': PetrelBackend,
+ 'http': HTTPBackend,
+ 'https': HTTPBackend,
+ }
+
+ _instances: dict = {}
+
+ client: Any
+
+ def __new__(cls, backend=None, prefix=None, **kwargs):
+ warnings.warn(
+ '"FileClient" will be deprecated in future. Please use io '
+ 'functions in '
+ 'https://mmengine.readthedocs.io/en/latest/api/fileio.html#file-io', # noqa: E501
+ DeprecationWarning)
+ if backend is None and prefix is None:
+ backend = 'disk'
+ if backend is not None and backend not in cls._backends:
+ raise ValueError(
+ f'Backend {backend} is not supported. Currently supported ones'
+ f' are {list(cls._backends.keys())}')
+ if prefix is not None and prefix not in cls._prefix_to_backends:
+ raise ValueError(
+ f'prefix {prefix} is not supported. Currently supported ones '
+ f'are {list(cls._prefix_to_backends.keys())}')
+
+ # concatenate the arguments to a unique key for determining whether
+ # objects with the same arguments were created
+ arg_key = f'{backend}:{prefix}'
+ for key, value in kwargs.items():
+ arg_key += f':{key}:{value}'
+
+ # if a backend was overridden, it will create a new object
+ if arg_key in cls._instances:
+ _instance = cls._instances[arg_key]
+ else:
+ # create a new object and put it to _instance
+ _instance = super().__new__(cls)
+ if backend is not None:
+ _instance.client = cls._backends[backend](**kwargs)
+ else:
+ _instance.client = cls._prefix_to_backends[prefix](**kwargs)
+
+ cls._instances[arg_key] = _instance
+
+ return _instance
+
+ @property
+ def name(self):
+ return self.client.name
+
+ @property
+ def allow_symlink(self):
+ return self.client.allow_symlink
+
+ @staticmethod
+ def parse_uri_prefix(uri: Union[str, Path]) -> Optional[str]:
+ """Parse the prefix of a uri.
+
+ Args:
+ uri (str | Path): Uri to be parsed that contains the file prefix.
+
+ Examples:
+ >>> FileClient.parse_uri_prefix('s3://path/of/your/file')
+ 's3'
+
+ Returns:
+ str | None: Return the prefix of uri if the uri contains '://' else
+ ``None``.
+ """
+ assert is_filepath(uri)
+ uri = str(uri)
+ if '://' not in uri:
+ return None
+ else:
+ prefix, _ = uri.split('://')
+ # In the case of PetrelBackend, the prefix may contains the cluster
+ # name like clusterName:s3
+ if ':' in prefix:
+ _, prefix = prefix.split(':')
+ return prefix
+
+ @classmethod
+ def infer_client(cls,
+ file_client_args: Optional[dict] = None,
+ uri: Optional[Union[str, Path]] = None) -> 'FileClient':
+ """Infer a suitable file client based on the URI and arguments.
+
+ Args:
+ file_client_args (dict, optional): Arguments to instantiate a
+ FileClient. Default: None.
+ uri (str | Path, optional): Uri to be parsed that contains the file
+ prefix. Default: None.
+
+ Examples:
+ >>> uri = 's3://path/of/your/file'
+ >>> file_client = FileClient.infer_client(uri=uri)
+ >>> file_client_args = {'backend': 'petrel'}
+ >>> file_client = FileClient.infer_client(file_client_args)
+
+ Returns:
+ FileClient: Instantiated FileClient object.
+ """
+ assert file_client_args is not None or uri is not None
+ if file_client_args is None:
+ file_prefix = cls.parse_uri_prefix(uri) # type: ignore
+ return cls(prefix=file_prefix)
+ else:
+ return cls(**file_client_args)
+
+ @classmethod
+ def _register_backend(cls, name, backend, force=False, prefixes=None):
+ if not isinstance(name, str):
+ raise TypeError('the backend name should be a string, '
+ f'but got {type(name)}')
+ if not inspect.isclass(backend):
+ raise TypeError(
+ f'backend should be a class but got {type(backend)}')
+ if not issubclass(backend, BaseStorageBackend):
+ raise TypeError(
+ f'backend {backend} is not a subclass of BaseStorageBackend')
+ if not force and name in cls._backends:
+ raise KeyError(
+ f'{name} is already registered as a storage backend, '
+ 'add "force=True" if you want to override it')
+
+ if name in cls._backends and force:
+ for arg_key, instance in list(cls._instances.items()):
+ if isinstance(instance.client, cls._backends[name]):
+ cls._instances.pop(arg_key)
+ cls._backends[name] = backend
+
+ if prefixes is not None:
+ if isinstance(prefixes, str):
+ prefixes = [prefixes]
+ else:
+ assert isinstance(prefixes, (list, tuple))
+ for prefix in prefixes:
+ if prefix not in cls._prefix_to_backends:
+ cls._prefix_to_backends[prefix] = backend
+ elif (prefix in cls._prefix_to_backends) and force:
+ overridden_backend = cls._prefix_to_backends[prefix]
+ for arg_key, instance in list(cls._instances.items()):
+ if isinstance(instance.client, overridden_backend):
+ cls._instances.pop(arg_key)
+ else:
+ raise KeyError(
+ f'{prefix} is already registered as a storage backend,'
+ ' add "force=True" if you want to override it')
+
+ @classmethod
+ def register_backend(cls, name, backend=None, force=False, prefixes=None):
+ """Register a backend to FileClient.
+
+ This method can be used as a normal class method or a decorator.
+
+ .. code-block:: python
+
+ class NewBackend(BaseStorageBackend):
+
+ def get(self, filepath):
+ return filepath
+
+ def get_text(self, filepath):
+ return filepath
+
+ FileClient.register_backend('new', NewBackend)
+
+ or
+
+ .. code-block:: python
+
+ @FileClient.register_backend('new')
+ class NewBackend(BaseStorageBackend):
+
+ def get(self, filepath):
+ return filepath
+
+ def get_text(self, filepath):
+ return filepath
+
+ Args:
+ name (str): The name of the registered backend.
+ backend (class, optional): The backend class to be registered,
+ which must be a subclass of :class:`BaseStorageBackend`.
+ When this method is used as a decorator, backend is None.
+ Defaults to None.
+ force (bool, optional): Whether to override the backend if the name
+ has already been registered. Defaults to False.
+ prefixes (str or list[str] or tuple[str], optional): The prefixes
+ of the registered storage backend. Default: None.
+ `New in version 1.3.15.`
+ """
+ if backend is not None:
+ cls._register_backend(
+ name, backend, force=force, prefixes=prefixes)
+ return
+
+ def _register(backend_cls):
+ cls._register_backend(
+ name, backend_cls, force=force, prefixes=prefixes)
+ return backend_cls
+
+ return _register
+
+ def get(self, filepath: Union[str, Path]) -> Union[bytes, memoryview]:
+ """Read data from a given ``filepath`` with 'rb' mode.
+
+ Note:
+ There are two types of return values for ``get``, one is ``bytes``
+ and the other is ``memoryview``. The advantage of using memoryview
+ is that you can avoid copying, and if you want to convert it to
+ ``bytes``, you can use ``.tobytes()``.
+
+ Args:
+ filepath (str or Path): Path to read data.
+
+ Returns:
+ bytes | memoryview: Expected bytes object or a memory view of the
+ bytes object.
+ """
+ return self.client.get(filepath)
+
+ def get_text(self, filepath: Union[str, Path], encoding='utf-8') -> str:
+ """Read data from a given ``filepath`` with 'r' mode.
+
+ Args:
+ filepath (str or Path): Path to read data.
+ encoding (str): The encoding format used to open the ``filepath``.
+ Default: 'utf-8'.
+
+ Returns:
+ str: Expected text reading from ``filepath``.
+ """
+ return self.client.get_text(filepath, encoding)
+
+ def put(self, obj: bytes, filepath: Union[str, Path]) -> None:
+ """Write data to a given ``filepath`` with 'wb' mode.
+
+ Note:
+ ``put`` should create a directory if the directory of ``filepath``
+ does not exist.
+
+ Args:
+ obj (bytes): Data to be written.
+ filepath (str or Path): Path to write data.
+ """
+ self.client.put(obj, filepath)
+
+ def put_text(self, obj: str, filepath: Union[str, Path]) -> None:
+ """Write data to a given ``filepath`` with 'w' mode.
+
+ Note:
+ ``put_text`` should create a directory if the directory of
+ ``filepath`` does not exist.
+
+ Args:
+ obj (str): Data to be written.
+ filepath (str or Path): Path to write data.
+ encoding (str, optional): The encoding format used to open the
+ `filepath`. Default: 'utf-8'.
+ """
+ self.client.put_text(obj, filepath)
+
+ def remove(self, filepath: Union[str, Path]) -> None:
+ """Remove a file.
+
+ Args:
+ filepath (str, Path): Path to be removed.
+ """
+ self.client.remove(filepath)
+
+ def exists(self, filepath: Union[str, Path]) -> bool:
+ """Check whether a file path exists.
+
+ Args:
+ filepath (str or Path): Path to be checked whether exists.
+
+ Returns:
+ bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise.
+ """
+ return self.client.exists(filepath)
+
+ def isdir(self, filepath: Union[str, Path]) -> bool:
+ """Check whether a file path is a directory.
+
+ Args:
+ filepath (str or Path): Path to be checked whether it is a
+ directory.
+
+ Returns:
+ bool: Return ``True`` if ``filepath`` points to a directory,
+ ``False`` otherwise.
+ """
+ return self.client.isdir(filepath)
+
+ def isfile(self, filepath: Union[str, Path]) -> bool:
+ """Check whether a file path is a file.
+
+ Args:
+ filepath (str or Path): Path to be checked whether it is a file.
+
+ Returns:
+ bool: Return ``True`` if ``filepath`` points to a file, ``False``
+ otherwise.
+ """
+ return self.client.isfile(filepath)
+
+ def join_path(self, filepath: Union[str, Path],
+ *filepaths: Union[str, Path]) -> str:
+ """Concatenate all file paths.
+
+ Join one or more filepath components intelligently. The return value
+ is the concatenation of filepath and any members of *filepaths.
+
+ Args:
+ filepath (str or Path): Path to be concatenated.
+
+ Returns:
+ str: The result of concatenation.
+ """
+ return self.client.join_path(filepath, *filepaths)
+
+ @contextmanager
+ def get_local_path(
+ self,
+ filepath: Union[str,
+ Path]) -> Generator[Union[str, Path], None, None]:
+ """Download data from ``filepath`` and write the data to local path.
+
+ ``get_local_path`` is decorated by :meth:`contxtlib.contextmanager`. It
+ can be called with ``with`` statement, and when exists from the
+ ``with`` statement, the temporary path will be released.
+
+ Note:
+ If the ``filepath`` is a local path, just return itself.
+
+ .. warning::
+ ``get_local_path`` is an experimental interface that may change in
+ the future.
+
+ Args:
+ filepath (str or Path): Path to be read data.
+
+ Examples:
+ >>> file_client = FileClient(prefix='s3')
+ >>> with file_client.get_local_path('s3://bucket/abc.jpg') as path:
+ ... # do something here
+
+ Yields:
+ Iterable[str]: Only yield one path.
+ """
+ with self.client.get_local_path(str(filepath)) as local_path:
+ yield local_path
+
+ def list_dir_or_file(self,
+ dir_path: Union[str, Path],
+ list_dir: bool = True,
+ list_file: bool = True,
+ suffix: Optional[Union[str, Tuple[str]]] = None,
+ recursive: bool = False) -> Iterator[str]:
+ """Scan a directory to find the interested directories or files in
+ arbitrary order.
+
+ Note:
+ :meth:`list_dir_or_file` returns the path relative to ``dir_path``.
+
+ Args:
+ dir_path (str | Path): Path of the directory.
+ list_dir (bool): List the directories. Default: True.
+ list_file (bool): List the path of files. Default: True.
+ suffix (str or tuple[str], optional): File suffix
+ that we are interested in. Default: None.
+ recursive (bool): If set to True, recursively scan the
+ directory. Default: False.
+
+ Yields:
+ Iterable[str]: A relative path to ``dir_path``.
+ """
+ yield from self.client.list_dir_or_file(dir_path, list_dir, list_file,
+ suffix, recursive)
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/__init__.py b/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..391a60c36b3cdf9070437c9d96e9c0bf23fac1a2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/__init__.py
@@ -0,0 +1,11 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .base import BaseFileHandler
+from .json_handler import JsonHandler
+from .pickle_handler import PickleHandler
+from .registry_utils import file_handlers, register_handler
+from .yaml_handler import YamlHandler
+
+__all__ = [
+ 'BaseFileHandler', 'JsonHandler', 'PickleHandler', 'YamlHandler',
+ 'register_handler', 'file_handlers'
+]
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/base.py b/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..288878bc57282fbb2f12b32290152ca8e9d3cab0
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/base.py
@@ -0,0 +1,30 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from abc import ABCMeta, abstractmethod
+
+
+class BaseFileHandler(metaclass=ABCMeta):
+ # `str_like` is a flag to indicate whether the type of file object is
+ # str-like object or bytes-like object. Pickle only processes bytes-like
+ # objects but json only processes str-like object. If it is str-like
+ # object, `StringIO` will be used to process the buffer.
+ str_like = True
+
+ @abstractmethod
+ def load_from_fileobj(self, file, **kwargs):
+ pass
+
+ @abstractmethod
+ def dump_to_fileobj(self, obj, file, **kwargs):
+ pass
+
+ @abstractmethod
+ def dump_to_str(self, obj, **kwargs):
+ pass
+
+ def load_from_path(self, filepath, mode='r', **kwargs):
+ with open(filepath, mode) as f:
+ return self.load_from_fileobj(f, **kwargs)
+
+ def dump_to_path(self, obj, filepath, mode='w', **kwargs):
+ with open(filepath, mode) as f:
+ self.dump_to_fileobj(obj, f, **kwargs)
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/json_handler.py b/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/json_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..18d4f15f74139d20adff18b20be5529c592a66b6
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/json_handler.py
@@ -0,0 +1,36 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import json
+
+import numpy as np
+
+from .base import BaseFileHandler
+
+
+def set_default(obj):
+ """Set default json values for non-serializable values.
+
+ It helps convert ``set``, ``range`` and ``np.ndarray`` data types to list.
+ It also converts ``np.generic`` (including ``np.int32``, ``np.float32``,
+ etc.) into plain numbers of plain python built-in types.
+ """
+ if isinstance(obj, (set, range)):
+ return list(obj)
+ elif isinstance(obj, np.ndarray):
+ return obj.tolist()
+ elif isinstance(obj, np.generic):
+ return obj.item()
+ raise TypeError(f'{type(obj)} is unsupported for json dump')
+
+
+class JsonHandler(BaseFileHandler):
+
+ def load_from_fileobj(self, file):
+ return json.load(file)
+
+ def dump_to_fileobj(self, obj, file, **kwargs):
+ kwargs.setdefault('default', set_default)
+ json.dump(obj, file, **kwargs)
+
+ def dump_to_str(self, obj, **kwargs):
+ kwargs.setdefault('default', set_default)
+ return json.dumps(obj, **kwargs)
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/pickle_handler.py b/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/pickle_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..073856fd25a731b42f3cd19269ad95744b20598f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/pickle_handler.py
@@ -0,0 +1,26 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import pickle
+
+from .base import BaseFileHandler
+
+
+class PickleHandler(BaseFileHandler):
+
+ str_like = False
+
+ def load_from_fileobj(self, file, **kwargs):
+ return pickle.load(file, **kwargs)
+
+ def load_from_path(self, filepath, **kwargs):
+ return super().load_from_path(filepath, mode='rb', **kwargs)
+
+ def dump_to_str(self, obj, **kwargs):
+ kwargs.setdefault('protocol', 2)
+ return pickle.dumps(obj, **kwargs)
+
+ def dump_to_fileobj(self, obj, file, **kwargs):
+ kwargs.setdefault('protocol', 2)
+ pickle.dump(obj, file, **kwargs)
+
+ def dump_to_path(self, obj, filepath, **kwargs):
+ super().dump_to_path(obj, filepath, mode='wb', **kwargs)
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/registry_utils.py b/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/registry_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..106fc881f2514dfcf5b31878e7eca34c7f1659ea
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/registry_utils.py
@@ -0,0 +1,42 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from mmengine.utils import is_list_of
+from .base import BaseFileHandler
+from .json_handler import JsonHandler
+from .pickle_handler import PickleHandler
+from .yaml_handler import YamlHandler
+
+file_handlers = {
+ 'json': JsonHandler(),
+ 'yaml': YamlHandler(),
+ 'yml': YamlHandler(),
+ 'pickle': PickleHandler(),
+ 'pkl': PickleHandler(),
+}
+
+
+def _register_handler(handler, file_formats):
+ """Register a handler for some file extensions.
+
+ Args:
+ handler (:obj:`BaseFileHandler`): Handler to be registered.
+ file_formats (str or list[str]): File formats to be handled by this
+ handler.
+ """
+ if not isinstance(handler, BaseFileHandler):
+ raise TypeError(
+ f'handler must be a child of BaseFileHandler, not {type(handler)}')
+ if isinstance(file_formats, str):
+ file_formats = [file_formats]
+ if not is_list_of(file_formats, str):
+ raise TypeError('file_formats must be a str or a list of str')
+ for ext in file_formats:
+ file_handlers[ext] = handler
+
+
+def register_handler(file_formats, **kwargs):
+
+ def wrap(cls):
+ _register_handler(cls(**kwargs), file_formats)
+ return cls
+
+ return wrap
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/yaml_handler.py b/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/yaml_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..22c2607ae43734f334bbfa83445b1409ef855433
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/handlers/yaml_handler.py
@@ -0,0 +1,25 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import yaml
+
+try:
+ from yaml import CDumper as Dumper # type: ignore
+ from yaml import CLoader as Loader # type: ignore
+except ImportError:
+ from yaml import Loader, Dumper # type: ignore
+
+from .base import BaseFileHandler # isort:skip
+
+
+class YamlHandler(BaseFileHandler):
+
+ def load_from_fileobj(self, file, **kwargs):
+ kwargs.setdefault('Loader', Loader)
+ return yaml.load(file, **kwargs)
+
+ def dump_to_fileobj(self, obj, file, **kwargs):
+ kwargs.setdefault('Dumper', Dumper)
+ yaml.dump(obj, file, **kwargs)
+
+ def dump_to_str(self, obj, **kwargs):
+ kwargs.setdefault('Dumper', Dumper)
+ return yaml.dump(obj, **kwargs)
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/io.py b/testbed/open-mmlab__mmengine/mmengine/fileio/io.py
new file mode 100644
index 0000000000000000000000000000000000000000..62f9a4ef7a422787831d47634f401dfdc5323593
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/io.py
@@ -0,0 +1,938 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+"""This module provides unified file I/O related functions, which support
+operating I/O with different file backends based on the specified filepath or
+backend_args.
+
+MMEngine currently supports five file backends:
+
+- LocalBackend
+- PetrelBackend
+- HTTPBackend
+- LmdbBackend
+- MemcacheBackend
+
+Note that this module provide a union of all of the above file backends so
+NotImplementedError will be raised if the interface in the file backend is not
+implemented.
+
+There are two ways to call a method of a file backend:
+
+- Initialize a file backend with ``get_file_backend`` and call its methods.
+- Directory call unified I/O functions, which will call ``get_file_backend``
+ first and then call the corresponding backend method.
+
+Examples:
+ >>> # Initialize a file backend and call its methods
+ >>> import mmengine.fileio as fileio
+ >>> backend = fileio.get_file_backend(backend_args={'backend': 'petrel'})
+ >>> backend.get('s3://path/of/your/file')
+
+ >>> # Directory call unified I/O functions
+ >>> fileio.get('s3://path/of/your/file')
+"""
+import json
+import warnings
+from contextlib import contextmanager
+from io import BytesIO, StringIO
+from pathlib import Path
+from typing import Generator, Iterator, Optional, Tuple, Union
+
+from mmengine.utils import is_filepath, is_str
+from .backends import backends, prefix_to_backends
+from .file_client import FileClient
+# file_handlers and register_handler had been moved to
+# mmengine/fileio/handlers/registry_utis. Import them
+# in this file to keep backward compatibility.
+from .handlers import file_handlers, register_handler # noqa: F401
+
+backend_instances: dict = {}
+
+
+def _parse_uri_prefix(uri: Union[str, Path]) -> str:
+ """Parse the prefix of uri.
+
+ Args:
+ uri (str or Path): Uri to be parsed that contains the file prefix.
+
+ Examples:
+ >>> _parse_uri_prefix('/home/path/of/your/file')
+ ''
+ >>> _parse_uri_prefix('s3://path/of/your/file')
+ 's3'
+ >>> _parse_uri_prefix('clusterName:s3://path/of/your/file')
+ 's3'
+
+ Returns:
+ str: Return the prefix of uri if the uri contains '://'. Otherwise,
+ return ''.
+ """
+ assert is_filepath(uri)
+ uri = str(uri)
+ # if uri does not contains '://', the uri will be handled by
+ # LocalBackend by default
+ if '://' not in uri:
+ return ''
+ else:
+ prefix, _ = uri.split('://')
+ # In the case of PetrelBackend, the prefix may contain the cluster
+ # name like clusterName:s3://path/of/your/file
+ if ':' in prefix:
+ _, prefix = prefix.split(':')
+ return prefix
+
+
+def _get_file_backend(prefix: str, backend_args: dict):
+ """Return a file backend based on the prefix or backend_args.
+
+ Args:
+ prefix (str): Prefix of uri.
+ backend_args (dict): Arguments to instantiate the corresponding
+ backend.
+ """
+ # backend name has a higher priority
+ if 'backend' in backend_args:
+ backend_name = backend_args.pop('backend')
+ backend = backends[backend_name](**backend_args)
+ else:
+ backend = prefix_to_backends[prefix](**backend_args)
+ return backend
+
+
+def get_file_backend(
+ uri: Union[str, Path, None] = None,
+ *,
+ backend_args: Optional[dict] = None,
+ enable_singleton: bool = False,
+):
+ """Return a file backend based on the prefix of uri or backend_args.
+
+ Args:
+ uri (str or Path): Uri to be parsed that contains the file prefix.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+ enable_singleton (bool): Whether to enable the singleton pattern.
+ If it is True, the backend created will be reused if the
+ signature is same with the previous one. Defaults to False.
+
+ Returns:
+ BaseStorageBackend: Instantiated Backend object.
+
+ Examples:
+ >>> # get file backend based on the prefix of uri
+ >>> uri = 's3://path/of/your/file'
+ >>> backend = get_file_backend(uri)
+ >>> # get file backend based on the backend_args
+ >>> backend = get_file_backend(backend_args={'backend': 'petrel'})
+ >>> # backend name has a higher priority if 'backend' in backend_args
+ >>> backend = get_file_backend(uri, backend_args={'backend': 'petrel'})
+ """
+ global backend_instances
+
+ if backend_args is None:
+ backend_args = {}
+
+ if uri is None and 'backend' not in backend_args:
+ raise ValueError(
+ 'uri should not be None when "backend" does not exist in '
+ 'backend_args')
+
+ if uri is not None:
+ prefix = _parse_uri_prefix(uri)
+ else:
+ prefix = ''
+
+ if enable_singleton:
+ # TODO: whether to pass sort_key to json.dumps
+ unique_key = f'{prefix}:{json.dumps(backend_args)}'
+ if unique_key in backend_instances:
+ return backend_instances[unique_key]
+
+ backend = _get_file_backend(prefix, backend_args)
+ backend_instances[unique_key] = backend
+ return backend
+ else:
+ backend = _get_file_backend(prefix, backend_args)
+ return backend
+
+
+def get(
+ filepath: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> bytes:
+ """Read bytes from a given ``filepath`` with 'rb' mode.
+
+ Args:
+ filepath (str or Path): Path to read data.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Returns:
+ bytes: Expected bytes object.
+
+ Examples:
+ >>> filepath = '/path/of/file'
+ >>> get(filepath)
+ b'hello world'
+ """
+ backend = get_file_backend(
+ filepath, backend_args=backend_args, enable_singleton=True)
+ return backend.get(filepath)
+
+
+def get_text(
+ filepath: Union[str, Path],
+ encoding='utf-8',
+ backend_args: Optional[dict] = None,
+) -> str:
+ """Read text from a given ``filepath`` with 'r' mode.
+
+ Args:
+ filepath (str or Path): Path to read data.
+ encoding (str): The encoding format used to open the ``filepath``.
+ Defaults to 'utf-8'.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Returns:
+ str: Expected text reading from ``filepath``.
+
+ Examples:
+ >>> filepath = '/path/of/file'
+ >>> get_text(filepath)
+ 'hello world'
+ """
+ backend = get_file_backend(
+ filepath, backend_args=backend_args, enable_singleton=True)
+ return backend.get_text(filepath, encoding)
+
+
+def put(
+ obj: bytes,
+ filepath: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> None:
+ """Write bytes to a given ``filepath`` with 'wb' mode.
+
+ Note:
+ ``put`` should create a directory if the directory of
+ ``filepath`` does not exist.
+
+ Args:
+ obj (bytes): Data to be written.
+ filepath (str or Path): Path to write data.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Examples:
+ >>> filepath = '/path/of/file'
+ >>> put(b'hello world', filepath)
+ """
+ backend = get_file_backend(
+ filepath, backend_args=backend_args, enable_singleton=True)
+ backend.put(obj, filepath)
+
+
+def put_text(
+ obj: str,
+ filepath: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> None:
+ """Write text to a given ``filepath`` with 'w' mode.
+
+ Note:
+ ``put_text`` should create a directory if the directory of
+ ``filepath`` does not exist.
+
+ Args:
+ obj (str): Data to be written.
+ filepath (str or Path): Path to write data.
+ encoding (str, optional): The encoding format used to open the
+ ``filepath``. Defaults to 'utf-8'.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Examples:
+ >>> filepath = '/path/of/file'
+ >>> put_text('hello world', filepath)
+ """
+ backend = get_file_backend(
+ filepath, backend_args=backend_args, enable_singleton=True)
+ backend.put_text(obj, filepath)
+
+
+def exists(
+ filepath: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> bool:
+ """Check whether a file path exists.
+
+ Args:
+ filepath (str or Path): Path to be checked whether exists.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Returns:
+ bool: Return ``True`` if ``filepath`` exists, ``False`` otherwise.
+
+ Examples:
+ >>> filepath = '/path/of/file'
+ >>> exists(filepath)
+ True
+ """
+ backend = get_file_backend(
+ filepath, backend_args=backend_args, enable_singleton=True)
+ return backend.exists(filepath)
+
+
+def isdir(
+ filepath: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> bool:
+ """Check whether a file path is a directory.
+
+ Args:
+ filepath (str or Path): Path to be checked whether it is a
+ directory.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Returns:
+ bool: Return ``True`` if ``filepath`` points to a directory,
+ ``False`` otherwise.
+
+ Examples:
+ >>> filepath = '/path/of/dir'
+ >>> isdir(filepath)
+ True
+ """
+ backend = get_file_backend(
+ filepath, backend_args=backend_args, enable_singleton=True)
+ return backend.isdir(filepath)
+
+
+def isfile(
+ filepath: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> bool:
+ """Check whether a file path is a file.
+
+ Args:
+ filepath (str or Path): Path to be checked whether it is a file.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Returns:
+ bool: Return ``True`` if ``filepath`` points to a file, ``False``
+ otherwise.
+
+ Examples:
+ >>> filepath = '/path/of/file'
+ >>> isfile(filepath)
+ True
+ """
+ backend = get_file_backend(
+ filepath, backend_args=backend_args, enable_singleton=True)
+ return backend.isfile(filepath)
+
+
+def join_path(
+ filepath: Union[str, Path],
+ *filepaths: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> Union[str, Path]:
+ """Concatenate all file paths.
+
+ Join one or more filepath components intelligently. The return value
+ is the concatenation of filepath and any members of *filepaths.
+
+ Args:
+ filepath (str or Path): Path to be concatenated.
+ *filepaths (str or Path): Other paths to be concatenated.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Returns:
+ str: The result of concatenation.
+
+ Examples:
+ >>> filepath1 = '/path/of/dir1'
+ >>> filepath2 = 'dir2'
+ >>> filepath3 = 'path/of/file'
+ >>> join_path(filepath1, filepath2, filepath3)
+ '/path/of/dir/dir2/path/of/file'
+ """
+ backend = get_file_backend(
+ filepath, backend_args=backend_args, enable_singleton=True)
+ return backend.join_path(filepath, *filepaths)
+
+
+@contextmanager
+def get_local_path(
+ filepath: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> Generator[Union[str, Path], None, None]:
+ """Download data from ``filepath`` and write the data to local path.
+
+ ``get_local_path`` is decorated by :meth:`contxtlib.contextmanager`. It
+ can be called with ``with`` statement, and when exists from the
+ ``with`` statement, the temporary path will be released.
+
+ Note:
+ If the ``filepath`` is a local path, just return itself and it will
+ not be released (removed).
+
+ Args:
+ filepath (str or Path): Path to be read data.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Yields:
+ Iterable[str]: Only yield one path.
+
+ Examples:
+ >>> with get_local_path('s3://bucket/abc.jpg') as path:
+ ... # do something here
+ """
+ backend = get_file_backend(
+ filepath, backend_args=backend_args, enable_singleton=True)
+ with backend.get_local_path(str(filepath)) as local_path:
+ yield local_path
+
+
+def copyfile(
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> Union[str, Path]:
+ """Copy a file src to dst and return the destination file.
+
+ src and dst should have the same prefix. If dst specifies a directory,
+ the file will be copied into dst using the base filename from src. If
+ dst specifies a file that already exists, it will be replaced.
+
+ Args:
+ src (str or Path): A file to be copied.
+ dst (str or Path): Copy file to dst.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Returns:
+ str: The destination file.
+
+ Raises:
+ SameFileError: If src and dst are the same file, a SameFileError will
+ be raised.
+
+ Examples:
+ >>> # dst is a file
+ >>> src = '/path/of/file'
+ >>> dst = '/path1/of/file1'
+ >>> # src will be copied to '/path1/of/file1'
+ >>> copyfile(src, dst)
+ '/path1/of/file1'
+
+ >>> # dst is a directory
+ >>> dst = '/path1/of/dir'
+ >>> # src will be copied to '/path1/of/dir/file'
+ >>> copyfile(src, dst)
+ '/path1/of/dir/file'
+ """
+ backend = get_file_backend(
+ src, backend_args=backend_args, enable_singleton=True)
+ return backend.copyfile(src, dst)
+
+
+def copytree(
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> Union[str, Path]:
+ """Recursively copy an entire directory tree rooted at src to a directory
+ named dst and return the destination directory.
+
+ src and dst should have the same prefix and dst must not already exist.
+
+ Args:
+ src (str or Path): A directory to be copied.
+ dst (str or Path): Copy directory to dst.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Returns:
+ str: The destination directory.
+
+ Raises:
+ FileExistsError: If dst had already existed, a FileExistsError will be
+ raised.
+
+ Examples:
+ >>> src = '/path/of/dir1'
+ >>> dst = '/path/of/dir2'
+ >>> copytree(src, dst)
+ '/path/of/dir2'
+ """
+ backend = get_file_backend(
+ src, backend_args=backend_args, enable_singleton=True)
+ return backend.copytree(src, dst)
+
+
+def copyfile_from_local(
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> Union[str, Path]:
+ """Copy a local file src to dst and return the destination file.
+
+ Note:
+ If the backend is the instance of LocalBackend, it does the same
+ thing with :func:`copyfile`.
+
+ Args:
+ src (str or Path): A local file to be copied.
+ dst (str or Path): Copy file to dst.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Returns:
+ str: If dst specifies a directory, the file will be copied into dst
+ using the base filename from src.
+
+ Examples:
+ >>> # dst is a file
+ >>> src = '/path/of/file'
+ >>> dst = 's3://openmmlab/mmengine/file1'
+ >>> # src will be copied to 's3://openmmlab/mmengine/file1'
+ >>> copyfile_from_local(src, dst)
+ s3://openmmlab/mmengine/file1
+
+ >>> # dst is a directory
+ >>> dst = 's3://openmmlab/mmengine'
+ >>> # src will be copied to 's3://openmmlab/mmengine/file''
+ >>> copyfile_from_local(src, dst)
+ 's3://openmmlab/mmengine/file'
+ """
+ backend = get_file_backend(
+ dst, backend_args=backend_args, enable_singleton=True)
+ return backend.copyfile_from_local(src, dst)
+
+
+def copytree_from_local(
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> Union[str, Path]:
+ """Recursively copy an entire directory tree rooted at src to a directory
+ named dst and return the destination directory.
+
+ Note:
+ If the backend is the instance of LocalBackend, it does the same
+ thing with :func:`copytree`.
+
+ Args:
+ src (str or Path): A local directory to be copied.
+ dst (str or Path): Copy directory to dst.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Returns:
+ str: The destination directory.
+
+ Examples:
+ >>> src = '/path/of/dir'
+ >>> dst = 's3://openmmlab/mmengine/dir'
+ >>> copyfile_from_local(src, dst)
+ 's3://openmmlab/mmengine/dir'
+ """
+ backend = get_file_backend(
+ dst, backend_args=backend_args, enable_singleton=True)
+ return backend.copytree_from_local(src, dst)
+
+
+def copyfile_to_local(
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> Union[str, Path]:
+ """Copy the file src to local dst and return the destination file.
+
+ If dst specifies a directory, the file will be copied into dst using
+ the base filename from src. If dst specifies a file that already
+ exists, it will be replaced.
+
+ Note:
+ If the backend is the instance of LocalBackend, it does the same
+ thing with :func:`copyfile`.
+
+ Args:
+ src (str or Path): A file to be copied.
+ dst (str or Path): Copy file to to local dst.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Returns:
+ str: If dst specifies a directory, the file will be copied into dst
+ using the base filename from src.
+
+ Examples:
+ >>> # dst is a file
+ >>> src = 's3://openmmlab/mmengine/file'
+ >>> dst = '/path/of/file'
+ >>> # src will be copied to '/path/of/file'
+ >>> copyfile_to_local(src, dst)
+ '/path/of/file'
+
+ >>> # dst is a directory
+ >>> dst = '/path/of/dir'
+ >>> # src will be copied to '/path/of/dir/file'
+ >>> copyfile_to_local(src, dst)
+ '/path/of/dir/file'
+ """
+ backend = get_file_backend(
+ dst, backend_args=backend_args, enable_singleton=True)
+ return backend.copyfile_to_local(src, dst)
+
+
+def copytree_to_local(
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> Union[str, Path]:
+ """Recursively copy an entire directory tree rooted at src to a local
+ directory named dst and return the destination directory.
+
+ Note:
+ If the backend is the instance of LocalBackend, it does the same
+ thing with :func:`copytree`.
+
+ Args:
+ src (str or Path): A directory to be copied.
+ dst (str or Path): Copy directory to local dst.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Returns:
+ str: The destination directory.
+
+ Examples:
+ >>> src = 's3://openmmlab/mmengine/dir'
+ >>> dst = '/path/of/dir'
+ >>> copytree_to_local(src, dst)
+ '/path/of/dir'
+ """
+ backend = get_file_backend(
+ dst, backend_args=backend_args, enable_singleton=True)
+ return backend.copytree_to_local(src, dst)
+
+
+def remove(
+ filepath: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> None:
+ """Remove a file.
+
+ Args:
+ filepath (str, Path): Path to be removed.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Raises:
+ FileNotFoundError: If filepath does not exist, an FileNotFoundError
+ will be raised.
+ IsADirectoryError: If filepath is a directory, an IsADirectoryError
+ will be raised.
+
+ Examples:
+ >>> filepath = '/path/of/file'
+ >>> remove(filepath)
+ """
+ backend = get_file_backend(
+ filepath, backend_args=backend_args, enable_singleton=True)
+ backend.remove(filepath)
+
+
+def rmtree(
+ dir_path: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> None:
+ """Recursively delete a directory tree.
+
+ Args:
+ dir_path (str or Path): A directory to be removed.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Examples:
+ >>> dir_path = '/path/of/dir'
+ >>> rmtree(dir_path)
+ """
+ backend = get_file_backend(
+ dir_path, backend_args=backend_args, enable_singleton=True)
+ backend.rmtree(dir_path)
+
+
+def copy_if_symlink_fails(
+ src: Union[str, Path],
+ dst: Union[str, Path],
+ backend_args: Optional[dict] = None,
+) -> bool:
+ """Create a symbolic link pointing to src named dst.
+
+ If failed to create a symbolic link pointing to src, directory copy src to
+ dst instead.
+
+ Args:
+ src (str or Path): Create a symbolic link pointing to src.
+ dst (str or Path): Create a symbolic link named dst.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Returns:
+ bool: Return True if successfully create a symbolic link pointing to
+ src. Otherwise, return False.
+
+ Examples:
+ >>> src = '/path/of/file'
+ >>> dst = '/path1/of/file1'
+ >>> copy_if_symlink_fails(src, dst)
+ True
+ >>> src = '/path/of/dir'
+ >>> dst = '/path1/of/dir1'
+ >>> copy_if_symlink_fails(src, dst)
+ True
+ """
+ backend = get_file_backend(
+ src, backend_args=backend_args, enable_singleton=True)
+ return backend.copy_if_symlink_fails(src, dst)
+
+
+def list_dir_or_file(
+ dir_path: Union[str, Path],
+ list_dir: bool = True,
+ list_file: bool = True,
+ suffix: Optional[Union[str, Tuple[str]]] = None,
+ recursive: bool = False,
+ backend_args: Optional[dict] = None,
+) -> Iterator[str]:
+ """Scan a directory to find the interested directories or files in
+ arbitrary order.
+
+ Note:
+ :meth:`list_dir_or_file` returns the path relative to ``dir_path``.
+
+ Args:
+ dir_path (str or Path): Path of the directory.
+ list_dir (bool): List the directories. Defaults to True.
+ list_file (bool): List the path of files. Defaults to True.
+ suffix (str or tuple[str], optional): File suffix that we are
+ interested in. Defaults to None.
+ recursive (bool): If set to True, recursively scan the directory.
+ Defaults to False.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Yields:
+ Iterable[str]: A relative path to ``dir_path``.
+
+ Examples:
+ >>> dir_path = '/path/of/dir'
+ >>> for file_path in list_dir_or_file(dir_path):
+ ... print(file_path)
+ >>> # list those files and directories in current directory
+ >>> for file_path in list_dir_or_file(dir_path):
+ ... print(file_path)
+ >>> # only list files
+ >>> for file_path in list_dir_or_file(dir_path, list_dir=False):
+ ... print(file_path)
+ >>> # only list directories
+ >>> for file_path in list_dir_or_file(dir_path, list_file=False):
+ ... print(file_path)
+ >>> # only list files ending with specified suffixes
+ >>> for file_path in list_dir_or_file(dir_path, suffix='.txt'):
+ ... print(file_path)
+ >>> # list all files and directory recursively
+ >>> for file_path in list_dir_or_file(dir_path, recursive=True):
+ ... print(file_path)
+ """
+ backend = get_file_backend(
+ dir_path, backend_args=backend_args, enable_singleton=True)
+ yield from backend.list_dir_or_file(dir_path, list_dir, list_file, suffix,
+ recursive)
+
+
+def generate_presigned_url(
+ url: str,
+ client_method: str = 'get_object',
+ expires_in: int = 3600,
+ backend_args: Optional[dict] = None,
+) -> str:
+ """Generate the presigned url of video stream which can be passed to
+ mmcv.VideoReader. Now only work on Petrel backend.
+
+ Note:
+ Now only work on Petrel backend.
+
+ Args:
+ url (str): Url of video stream.
+ client_method (str): Method of client, 'get_object' or
+ 'put_object'. Default: 'get_object'.
+ expires_in (int): expires, in seconds. Default: 3600.
+ backend_args (dict, optional): Arguments to instantiate the
+ corresponding backend. Defaults to None.
+
+ Returns:
+ str: Generated presigned url.
+ """
+ backend = get_file_backend(
+ url, backend_args=backend_args, enable_singleton=True)
+ return backend.generate_presigned_url(url, client_method, expires_in)
+
+
+def load(file,
+ file_format=None,
+ file_client_args=None,
+ backend_args=None,
+ **kwargs):
+ """Load data from json/yaml/pickle files.
+
+ This method provides a unified api for loading data from serialized files.
+
+ ``load`` supports loading data from serialized files those can be storaged
+ in different backends.
+
+ Args:
+ file (str or :obj:`Path` or file-like object): Filename or a file-like
+ object.
+ file_format (str, optional): If not specified, the file format will be
+ inferred from the file extension, otherwise use the specified one.
+ Currently supported formats include "json", "yaml/yml" and
+ "pickle/pkl".
+ file_client_args (dict, optional): Arguments to instantiate a
+ FileClient. See :class:`mmengine.fileio.FileClient` for details.
+ Defaults to None. It will be deprecated in future. Please use
+ ``backend_args`` instead.
+ backend_args (dict, optional): Arguments to instantiate the
+ preifx of uri corresponding backend. Defaults to None.
+ New in v0.2.0.
+
+ Examples:
+ >>> load('/path/of/your/file') # file is storaged in disk
+ >>> load('https://path/of/your/file') # file is storaged in Internet
+ >>> load('s3://path/of/your/file') # file is storaged in petrel
+
+ Returns:
+ The content from the file.
+ """
+ if isinstance(file, Path):
+ file = str(file)
+ if file_format is None and is_str(file):
+ file_format = file.split('.')[-1]
+ if file_format not in file_handlers:
+ raise TypeError(f'Unsupported format: {file_format}')
+
+ if file_client_args is not None:
+ warnings.warn(
+ '"file_client_args" will be deprecated in future. '
+ 'Please use "backend_args" instead', DeprecationWarning)
+ if backend_args is not None:
+ raise ValueError(
+ '"file_client_args and "backend_args" cannot be set at the '
+ 'same time.')
+
+ handler = file_handlers[file_format]
+ if is_str(file):
+ if file_client_args is not None:
+ file_client = FileClient.infer_client(file_client_args, file)
+ file_backend = file_client
+ else:
+ file_backend = get_file_backend(file, backend_args=backend_args)
+
+ if handler.str_like:
+ with StringIO(file_backend.get_text(file)) as f:
+ obj = handler.load_from_fileobj(f, **kwargs)
+ else:
+ with BytesIO(file_backend.get(file)) as f:
+ obj = handler.load_from_fileobj(f, **kwargs)
+ elif hasattr(file, 'read'):
+ obj = handler.load_from_fileobj(file, **kwargs)
+ else:
+ raise TypeError('"file" must be a filepath str or a file-object')
+ return obj
+
+
+def dump(obj,
+ file=None,
+ file_format=None,
+ file_client_args=None,
+ backend_args=None,
+ **kwargs):
+ """Dump data to json/yaml/pickle strings or files.
+
+ This method provides a unified api for dumping data as strings or to files,
+ and also supports custom arguments for each file format.
+
+ ``dump`` supports dumping data as strings or to files which is saved to
+ different backends.
+
+ Args:
+ obj (any): The python object to be dumped.
+ file (str or :obj:`Path` or file-like object, optional): If not
+ specified, then the object is dumped to a str, otherwise to a file
+ specified by the filename or file-like object.
+ file_format (str, optional): Same as :func:`load`.
+ file_client_args (dict, optional): Arguments to instantiate a
+ FileClient. See :class:`mmengine.fileio.FileClient` for details.
+ Defaults to None. It will be deprecated in future. Please use
+ ``backend_args`` instead.
+ backend_args (dict, optional): Arguments to instantiate the
+ preifx of uri corresponding backend. Defaults to None.
+ New in v0.2.0.
+
+ Examples:
+ >>> dump('hello world', '/path/of/your/file') # disk
+ >>> dump('hello world', 's3://path/of/your/file') # ceph or petrel
+
+ Returns:
+ bool: True for success, False otherwise.
+ """
+ if isinstance(file, Path):
+ file = str(file)
+ if file_format is None:
+ if is_str(file):
+ file_format = file.split('.')[-1]
+ elif file is None:
+ raise ValueError(
+ 'file_format must be specified since file is None')
+ if file_format not in file_handlers:
+ raise TypeError(f'Unsupported format: {file_format}')
+
+ if file_client_args is not None:
+ warnings.warn(
+ '"file_client_args" will be deprecated in future. '
+ 'Please use "backend_args" instead', DeprecationWarning)
+ if backend_args is not None:
+ raise ValueError(
+ '"file_client_args" and "backend_args" cannot be set at the '
+ 'same time.')
+
+ handler = file_handlers[file_format]
+ if file is None:
+ return handler.dump_to_str(obj, **kwargs)
+ elif is_str(file):
+ if file_client_args is not None:
+ file_client = FileClient.infer_client(file_client_args, file)
+ file_backend = file_client
+ else:
+ file_backend = get_file_backend(file, backend_args=backend_args)
+
+ if handler.str_like:
+ with StringIO() as f:
+ handler.dump_to_fileobj(obj, f, **kwargs)
+ file_backend.put_text(f.getvalue(), file)
+ else:
+ with BytesIO() as f:
+ handler.dump_to_fileobj(obj, f, **kwargs)
+ file_backend.put(f.getvalue(), file)
+ elif hasattr(file, 'write'):
+ handler.dump_to_fileobj(obj, file, **kwargs)
+ else:
+ raise TypeError('"file" must be a filename str or a file-object')
diff --git a/testbed/open-mmlab__mmengine/mmengine/fileio/parse.py b/testbed/open-mmlab__mmengine/mmengine/fileio/parse.py
new file mode 100644
index 0000000000000000000000000000000000000000..080ae023c26bce35d6de02e1993068bcd9982ea4
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/fileio/parse.py
@@ -0,0 +1,133 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import warnings
+from io import StringIO
+
+from .file_client import FileClient
+from .io import get_text
+
+
+def list_from_file(filename,
+ prefix='',
+ offset=0,
+ max_num=0,
+ encoding='utf-8',
+ file_client_args=None,
+ backend_args=None):
+ """Load a text file and parse the content as a list of strings.
+
+ ``list_from_file`` supports loading a text file which can be storaged in
+ different backends and parsing the content as a list for strings.
+
+ Args:
+ filename (str): Filename.
+ prefix (str): The prefix to be inserted to the beginning of each item.
+ offset (int): The offset of lines.
+ max_num (int): The maximum number of lines to be read,
+ zeros and negatives mean no limitation.
+ encoding (str): Encoding used to open the file. Defaults to utf-8.
+ file_client_args (dict, optional): Arguments to instantiate a
+ FileClient. See :class:`mmengine.fileio.FileClient` for details.
+ Defaults to None. It will be deprecated in future. Please use
+ ``backend_args`` instead.
+ backend_args (dict, optional): Arguments to instantiate the
+ preifx of uri corresponding backend. Defaults to None.
+ New in v0.2.0.
+
+ Examples:
+ >>> list_from_file('/path/of/your/file') # disk
+ ['hello', 'world']
+ >>> list_from_file('s3://path/of/your/file') # ceph or petrel
+ ['hello', 'world']
+
+ Returns:
+ list[str]: A list of strings.
+ """
+ if file_client_args is not None:
+ warnings.warn(
+ '"file_client_args" will be deprecated in future. '
+ 'Please use "backend_args" instead', DeprecationWarning)
+ if backend_args is not None:
+ raise ValueError(
+ '"file_client_args" and "backend_args" cannot be set at the '
+ 'same time.')
+ cnt = 0
+ item_list = []
+
+ if file_client_args is not None:
+ file_client = FileClient.infer_client(file_client_args, filename)
+ text = file_client.get_text(filename, encoding)
+ else:
+ text = get_text(filename, encoding, backend_args=backend_args)
+
+ with StringIO(text) as f:
+ for _ in range(offset):
+ f.readline()
+ for line in f:
+ if 0 < max_num <= cnt:
+ break
+ item_list.append(prefix + line.rstrip('\n\r'))
+ cnt += 1
+ return item_list
+
+
+def dict_from_file(filename,
+ key_type=str,
+ encoding='utf-8',
+ file_client_args=None,
+ backend_args=None):
+ """Load a text file and parse the content as a dict.
+
+ Each line of the text file will be two or more columns split by
+ whitespaces or tabs. The first column will be parsed as dict keys, and
+ the following columns will be parsed as dict values.
+
+ ``dict_from_file`` supports loading a text file which can be storaged in
+ different backends and parsing the content as a dict.
+
+ Args:
+ filename(str): Filename.
+ key_type(type): Type of the dict keys. str is user by default and
+ type conversion will be performed if specified.
+ encoding (str): Encoding used to open the file. Defaults to utf-8.
+ file_client_args (dict, optional): Arguments to instantiate a
+ FileClient. See :class:`mmengine.fileio.FileClient` for details.
+ Defaults to None. It will be deprecated in future. Please use
+ ``backend_args`` instead.
+ backend_args (dict, optional): Arguments to instantiate the
+ preifx of uri corresponding backend. Defaults to None.
+ New in v0.2.0.
+
+ Examples:
+ >>> dict_from_file('/path/of/your/file') # disk
+ {'key1': 'value1', 'key2': 'value2'}
+ >>> dict_from_file('s3://path/of/your/file') # ceph or petrel
+ {'key1': 'value1', 'key2': 'value2'}
+
+ Returns:
+ dict: The parsed contents.
+ """
+ if file_client_args is not None:
+ warnings.warn(
+ '"file_client_args" will be deprecated in future. '
+ 'Please use "backend_args" instead', DeprecationWarning)
+ if backend_args is not None:
+ raise ValueError(
+ '"file_client_args" and "backend_args" cannot be set at the '
+ 'same time.')
+
+ mapping = {}
+
+ if file_client_args is not None:
+ file_client = FileClient.infer_client(file_client_args, filename)
+ text = file_client.get_text(filename, encoding)
+ else:
+ text = get_text(filename, encoding, backend_args=backend_args)
+
+ with StringIO(text) as f:
+ for line in f:
+ items = line.rstrip('\n').split()
+ assert len(items) >= 2
+ key = key_type(items[0])
+ val = items[1:] if len(items) > 2 else items[1]
+ mapping[key] = val
+ return mapping
diff --git a/testbed/open-mmlab__mmengine/mmengine/hooks/__init__.py b/testbed/open-mmlab__mmengine/mmengine/hooks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe326332e2045ee6b9e9329b5eddb3073cf684aa
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hooks/__init__.py
@@ -0,0 +1,18 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .checkpoint_hook import CheckpointHook
+from .ema_hook import EMAHook
+from .empty_cache_hook import EmptyCacheHook
+from .hook import Hook
+from .iter_timer_hook import IterTimerHook
+from .logger_hook import LoggerHook
+from .naive_visualization_hook import NaiveVisualizationHook
+from .param_scheduler_hook import ParamSchedulerHook
+from .runtime_info_hook import RuntimeInfoHook
+from .sampler_seed_hook import DistSamplerSeedHook
+from .sync_buffer_hook import SyncBuffersHook
+
+__all__ = [
+ 'Hook', 'IterTimerHook', 'DistSamplerSeedHook', 'ParamSchedulerHook',
+ 'SyncBuffersHook', 'EmptyCacheHook', 'CheckpointHook', 'LoggerHook',
+ 'NaiveVisualizationHook', 'EMAHook', 'RuntimeInfoHook'
+]
diff --git a/testbed/open-mmlab__mmengine/mmengine/hooks/checkpoint_hook.py b/testbed/open-mmlab__mmengine/mmengine/hooks/checkpoint_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9aa1a35fccdda29364fe2f0ef40c8968400765d
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hooks/checkpoint_hook.py
@@ -0,0 +1,526 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os.path as osp
+import warnings
+from collections import OrderedDict
+from math import inf
+from pathlib import Path
+from typing import Callable, Dict, List, Optional, Sequence, Union
+
+from mmengine.dist import is_main_process
+from mmengine.fileio import FileClient, get_file_backend
+from mmengine.registry import HOOKS
+from mmengine.utils import is_list_of, is_seq_of
+from .hook import Hook
+
+DATA_BATCH = Optional[Union[dict, tuple, list]]
+
+
+@HOOKS.register_module()
+class CheckpointHook(Hook):
+ """Save checkpoints periodically.
+
+ Args:
+ interval (int): The saving period. If ``by_epoch=True``, interval
+ indicates epochs, otherwise it indicates iterations.
+ Defaults to -1, which means "never".
+ by_epoch (bool): Saving checkpoints by epoch or by iteration.
+ Defaults to True.
+ save_optimizer (bool): Whether to save optimizer state_dict in the
+ checkpoint. It is usually used for resuming experiments.
+ Defaults to True.
+ save_param_scheduler (bool): Whether to save param_scheduler state_dict
+ in the checkpoint. It is usually used for resuming experiments.
+ Defaults to True.
+ out_dir (str, Path, Optional): The root directory to save checkpoints.
+ If not specified, ``runner.work_dir`` will be used by default. If
+ specified, the ``out_dir`` will be the concatenation of ``out_dir``
+ and the last level directory of ``runner.work_dir``. For example,
+ if the input ``our_dir`` is ``./tmp`` and ``runner.work_dir`` is
+ ``./work_dir/cur_exp``, then the ckpt will be saved in
+ ``./tmp/cur_exp``. Defaults to None.
+ max_keep_ckpts (int): The maximum checkpoints to keep.
+ In some cases we want only the latest few checkpoints and would
+ like to delete old ones to save the disk space.
+ Defaults to -1, which means unlimited.
+ save_last (bool): Whether to force the last checkpoint to be
+ saved regardless of interval. Defaults to True.
+ save_best (str, List[str], optional): If a metric is specified, it
+ would measure the best checkpoint during evaluation. If a list of
+ metrics is passed, it would measure a group of best checkpoints
+ corresponding to the passed metrics. The information about best
+ checkpoint(s) would be saved in ``runner.message_hub`` to keep
+ best score value and best checkpoint path, which will be also
+ loaded when resuming checkpoint. Options are the evaluation metrics
+ on the test dataset. e.g., ``bbox_mAP``, ``segm_mAP`` for bbox
+ detection and instance segmentation. ``AR@100`` for proposal
+ recall. If ``save_best`` is ``auto``, the first key of the returned
+ ``OrderedDict`` result will be used. Defaults to None.
+ rule (str, List[str], optional): Comparison rule for best score. If
+ set to None, it will infer a reasonable rule. Keys such as 'acc',
+ 'top' .etc will be inferred by 'greater' rule. Keys contain 'loss'
+ will be inferred by 'less' rule. If ``save_best`` is a list of
+ metrics and ``rule`` is a str, all metrics in ``save_best`` will
+ share the comparison rule. If ``save_best`` and ``rule`` are both
+ lists, their length must be the same, and metrics in ``save_best``
+ will use the corresponding comparison rule in ``rule``. Options
+ are 'greater', 'less', None and list which contains 'greater' and
+ 'less'. Defaults to None.
+ greater_keys (List[str], optional): Metric keys that will be
+ inferred by 'greater' comparison rule. If ``None``,
+ _default_greater_keys will be used. Defaults to None.
+ less_keys (List[str], optional): Metric keys that will be
+ inferred by 'less' comparison rule. If ``None``, _default_less_keys
+ will be used. Defaults to None.
+ file_client_args (dict, optional): Arguments to instantiate a
+ FileClient. See :class:`mmengine.fileio.FileClient` for details.
+ Defaults to None. It will be deprecated in future. Please use
+ ``backend_args`` instead.
+ filename_tmpl (str, optional): String template to indicate checkpoint
+ name. If specified, must contain one and only one "{}", which will
+ be replaced with ``epoch + 1`` if ``by_epoch=True`` else
+ ``iteration + 1``.
+ Defaults to None, which means "epoch_{}.pth" or "iter_{}.pth"
+ accordingly.
+ backend_args (dict, optional): Arguments to instantiate the
+ preifx of uri corresponding backend. Defaults to None.
+ New in v0.2.0.
+
+ Examples:
+ >>> # Save best based on single metric
+ >>> CheckpointHook(interval=2, by_epoch=True, save_best='acc',
+ >>> rule='less')
+ >>> # Save best based on multi metrics with the same comparison rule
+ >>> CheckpointHook(interval=2, by_epoch=True,
+ >>> save_best=['acc', 'mIoU'], rule='greater')
+ >>> # Save best based on multi metrics with different comparison rule
+ >>> CheckpointHook(interval=2, by_epoch=True,
+ >>> save_best=['FID', 'IS'], rule=['less', 'greater'])
+ """
+ out_dir: str
+
+ priority = 'VERY_LOW'
+
+ # logic to save best checkpoints
+ # Since the key for determining greater or less is related to the
+ # downstream tasks, downstream repositories may need to overwrite
+ # the following inner variables accordingly.
+
+ rule_map = {'greater': lambda x, y: x > y, 'less': lambda x, y: x < y}
+ init_value_map = {'greater': -inf, 'less': inf}
+ _default_greater_keys = [
+ 'acc', 'top', 'AR@', 'auc', 'precision', 'mAP', 'mDice', 'mIoU',
+ 'mAcc', 'aAcc'
+ ]
+ _default_less_keys = ['loss']
+
+ def __init__(self,
+ interval: int = -1,
+ by_epoch: bool = True,
+ save_optimizer: bool = True,
+ save_param_scheduler: bool = True,
+ out_dir: Optional[Union[str, Path]] = None,
+ max_keep_ckpts: int = -1,
+ save_last: bool = True,
+ save_best: Union[str, List[str], None] = None,
+ rule: Union[str, List[str], None] = None,
+ greater_keys: Optional[Sequence[str]] = None,
+ less_keys: Optional[Sequence[str]] = None,
+ file_client_args: Optional[dict] = None,
+ filename_tmpl: Optional[str] = None,
+ backend_args: Optional[dict] = None,
+ **kwargs) -> None:
+ self.interval = interval
+ self.by_epoch = by_epoch
+ self.save_optimizer = save_optimizer
+ self.save_param_scheduler = save_param_scheduler
+ self.out_dir = out_dir # type: ignore
+ self.max_keep_ckpts = max_keep_ckpts
+ self.save_last = save_last
+ self.args = kwargs
+
+ if file_client_args is not None:
+ warnings.warn(
+ '"file_client_args" will be deprecated in future. '
+ 'Please use "backend_args" instead', DeprecationWarning)
+ if backend_args is not None:
+ raise ValueError(
+ '"file_client_args" and "backend_args" cannot be set '
+ 'at the same time.')
+
+ self.file_client_args = file_client_args
+ self.backend_args = backend_args
+
+ if filename_tmpl is None:
+ if self.by_epoch:
+ self.filename_tmpl = 'epoch_{}.pth'
+ else:
+ self.filename_tmpl = 'iter_{}.pth'
+ else:
+ self.filename_tmpl = filename_tmpl
+
+ # save best logic
+ assert (isinstance(save_best, str) or is_list_of(save_best, str)
+ or (save_best is None)), (
+ '"save_best" should be a str or list of str or None, '
+ f'but got {type(save_best)}')
+
+ if isinstance(save_best, list):
+ if 'auto' in save_best:
+ assert len(save_best) == 1, (
+ 'Only support one "auto" in "save_best" list.')
+ assert len(save_best) == len(
+ set(save_best)), ('Find duplicate element in "save_best".')
+ else:
+ # convert str to list[str]
+ if save_best is not None:
+ save_best = [save_best] # type: ignore # noqa: F401
+ self.save_best = save_best
+
+ # rule logic
+ assert (isinstance(rule, str) or is_list_of(rule, str)
+ or (rule is None)), (
+ '"rule" should be a str or list of str or None, '
+ f'but got {type(rule)}')
+ if isinstance(rule, list):
+ # check the length of rule list
+ assert len(rule) in [
+ 1,
+ len(self.save_best) # type: ignore
+ ], ('Number of "rule" must be 1 or the same as number of '
+ f'"save_best", but got {len(rule)}.')
+ else:
+ # convert str/None to list
+ rule = [rule] # type: ignore # noqa: F401
+
+ if greater_keys is None:
+ self.greater_keys = self._default_greater_keys
+ else:
+ if not isinstance(greater_keys, (list, tuple)):
+ greater_keys = (greater_keys, ) # type: ignore
+ assert is_seq_of(greater_keys, str)
+ self.greater_keys = greater_keys # type: ignore
+
+ if less_keys is None:
+ self.less_keys = self._default_less_keys
+ else:
+ if not isinstance(less_keys, (list, tuple)):
+ less_keys = (less_keys, ) # type: ignore
+ assert is_seq_of(less_keys, str)
+ self.less_keys = less_keys # type: ignore
+
+ if self.save_best is not None:
+ self.is_better_than: Dict[str, Callable] = dict()
+ self._init_rule(rule, self.save_best)
+ if len(self.key_indicators) == 1:
+ self.best_ckpt_path: Optional[str] = None
+ else:
+ self.best_ckpt_path_dict: Dict = dict()
+
+ def before_train(self, runner) -> None:
+ """Finish all operations, related to checkpoint.
+
+ This function will get the appropriate file client, and the directory
+ to save these checkpoints of the model.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ if self.out_dir is None:
+ self.out_dir = runner.work_dir
+
+ # If self.file_client_args is None, self.file_client will not
+ # used in CheckpointHook. To avoid breaking backward compatibility,
+ # it will not be removed util the release of MMEngine1.0
+ self.file_client = FileClient.infer_client(self.file_client_args,
+ self.out_dir)
+
+ if self.file_client_args is None:
+ self.file_backend = get_file_backend(
+ self.out_dir, backend_args=self.backend_args)
+ else:
+ self.file_backend = self.file_client
+
+ # if `self.out_dir` is not equal to `runner.work_dir`, it means that
+ # `self.out_dir` is set so the final `self.out_dir` is the
+ # concatenation of `self.out_dir` and the last level directory of
+ # `runner.work_dir`
+ if self.out_dir != runner.work_dir:
+ basename = osp.basename(runner.work_dir.rstrip(osp.sep))
+ self.out_dir = self.file_backend.join_path(
+ self.out_dir, basename) # type: ignore # noqa: E501
+
+ runner.logger.info(f'Checkpoints will be saved to {self.out_dir}.')
+
+ if self.save_best is not None:
+ if len(self.key_indicators) == 1:
+ if 'best_ckpt' not in runner.message_hub.runtime_info:
+ self.best_ckpt_path = None
+ else:
+ self.best_ckpt_path = runner.message_hub.get_info(
+ 'best_ckpt')
+ else:
+ for key_indicator in self.key_indicators:
+ best_ckpt_name = f'best_ckpt_{key_indicator}'
+ if best_ckpt_name not in runner.message_hub.runtime_info:
+ self.best_ckpt_path_dict[key_indicator] = None
+ else:
+ self.best_ckpt_path_dict[
+ key_indicator] = runner.message_hub.get_info(
+ best_ckpt_name)
+
+ def after_train_epoch(self, runner) -> None:
+ """Save the checkpoint and synchronize buffers after each epoch.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ if not self.by_epoch:
+ return
+
+ # save checkpoint for following cases:
+ # 1. every ``self.interval`` epochs
+ # 2. reach the last epoch of training
+ if self.every_n_epochs(runner, self.interval) or (
+ self.save_last and self.is_last_train_epoch(runner)):
+ runner.logger.info(
+ f'Saving checkpoint at {runner.epoch + 1} epochs')
+ self._save_checkpoint(runner)
+
+ def after_val_epoch(self, runner, metrics):
+ """Save the checkpoint and synchronize buffers after each evaluation
+ epoch.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ metrics (dict): Evaluation results of all metrics
+ """
+ self._save_best_checkpoint(runner, metrics)
+
+ def _get_metric_score(self, metrics, key_indicator):
+ eval_res = OrderedDict()
+ if metrics is not None:
+ eval_res.update(metrics)
+
+ if len(eval_res) == 0:
+ warnings.warn(
+ 'Since `eval_res` is an empty dict, the behavior to save '
+ 'the best checkpoint will be skipped in this evaluation.')
+ return None
+
+ return eval_res[key_indicator]
+
+ def _save_checkpoint(self, runner) -> None:
+ """Save the current checkpoint and delete outdated checkpoint.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ if self.by_epoch:
+ ckpt_filename = self.filename_tmpl.format(runner.epoch + 1)
+ else:
+ ckpt_filename = self.filename_tmpl.format(runner.iter + 1)
+
+ runner.save_checkpoint(
+ self.out_dir,
+ ckpt_filename,
+ self.file_client_args,
+ save_optimizer=self.save_optimizer,
+ save_param_scheduler=self.save_param_scheduler,
+ by_epoch=self.by_epoch,
+ backend_args=self.backend_args,
+ **self.args)
+
+ # Model parallel-like training should involve pulling sharded states
+ # from all ranks, but skip the following procedure.
+ if not is_main_process():
+ return
+
+ runner.message_hub.update_info(
+ 'last_ckpt',
+ self.file_backend.join_path(self.out_dir, ckpt_filename))
+
+ # remove other checkpoints
+ if self.max_keep_ckpts > 0:
+ if self.by_epoch:
+ current_ckpt = runner.epoch + 1
+ else:
+ current_ckpt = runner.iter + 1
+ redundant_ckpts = range(
+ current_ckpt - self.max_keep_ckpts * self.interval, 0,
+ -self.interval)
+ for _step in redundant_ckpts:
+ ckpt_path = self.file_backend.join_path(
+ self.out_dir, self.filename_tmpl.format(_step))
+ if self.file_backend.isfile(ckpt_path):
+ self.file_backend.remove(ckpt_path)
+ else:
+ break
+
+ save_file = osp.join(runner.work_dir, 'last_checkpoint')
+ filepath = self.file_backend.join_path(self.out_dir, ckpt_filename)
+ with open(save_file, 'w') as f:
+ f.write(filepath)
+
+ def _save_best_checkpoint(self, runner, metrics) -> None:
+ """Save the current checkpoint and delete outdated checkpoint.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ metrics (dict): Evaluation results of all metrics.
+ """
+ if not self.save_best:
+ return
+
+ if self.by_epoch:
+ ckpt_filename = self.filename_tmpl.format(runner.epoch)
+ cur_type, cur_time = 'epoch', runner.epoch
+ else:
+ ckpt_filename = self.filename_tmpl.format(runner.iter)
+ cur_type, cur_time = 'iter', runner.iter
+
+ # handle auto in self.key_indicators and self.rules before the loop
+ if 'auto' in self.key_indicators:
+ self._init_rule(self.rules, [list(metrics.keys())[0]])
+
+ # save best logic
+ # get score from messagehub
+ for key_indicator, rule in zip(self.key_indicators, self.rules):
+ key_score = self._get_metric_score(metrics, key_indicator)
+
+ if len(self.key_indicators) == 1:
+ best_score_key = 'best_score'
+ runtime_best_ckpt_key = 'best_ckpt'
+ best_ckpt_path = self.best_ckpt_path
+ else:
+ best_score_key = f'best_score_{key_indicator}'
+ runtime_best_ckpt_key = f'best_ckpt_{key_indicator}'
+ best_ckpt_path = self.best_ckpt_path_dict[key_indicator]
+
+ if best_score_key not in runner.message_hub.runtime_info:
+ best_score = self.init_value_map[rule]
+ else:
+ best_score = runner.message_hub.get_info(best_score_key)
+
+ if key_score is None or not self.is_better_than[key_indicator](
+ key_score, best_score):
+ continue
+
+ best_score = key_score
+ runner.message_hub.update_info(best_score_key, best_score)
+
+ if best_ckpt_path and \
+ self.file_client.isfile(best_ckpt_path) and \
+ is_main_process():
+ self.file_client.remove(best_ckpt_path)
+ runner.logger.info(
+ f'The previous best checkpoint {best_ckpt_path} '
+ 'is removed')
+
+ best_ckpt_name = f'best_{key_indicator}_{ckpt_filename}'
+ if len(self.key_indicators) == 1:
+ self.best_ckpt_path = self.file_client.join_path( # type: ignore # noqa: E501
+ self.out_dir, best_ckpt_name)
+ runner.message_hub.update_info(runtime_best_ckpt_key,
+ self.best_ckpt_path)
+ else:
+ self.best_ckpt_path_dict[
+ key_indicator] = self.file_client.join_path( # type: ignore # noqa: E501
+ self.out_dir, best_ckpt_name)
+ runner.message_hub.update_info(
+ runtime_best_ckpt_key,
+ self.best_ckpt_path_dict[key_indicator])
+ runner.save_checkpoint(
+ self.out_dir,
+ filename=best_ckpt_name,
+ file_client_args=self.file_client_args,
+ save_optimizer=False,
+ save_param_scheduler=False,
+ by_epoch=False,
+ backend_args=self.backend_args)
+ runner.logger.info(
+ f'The best checkpoint with {best_score:0.4f} {key_indicator} '
+ f'at {cur_time} {cur_type} is saved to {best_ckpt_name}.')
+
+ def _init_rule(self, rules, key_indicators) -> None:
+ """Initialize rule, key_indicator, comparison_func, and best score. If
+ key_indicator is a list of string and rule is a string, all metric in
+ the key_indicator will share the same rule.
+
+ Here is the rule to determine which rule is used for key indicator when
+ the rule is not specific (note that the key indicator matching is case-
+ insensitive):
+
+ 1. If the key indicator is in ``self.greater_keys``, the rule
+ will be specified as 'greater'.
+ 2. Or if the key indicator is in ``self.less_keys``, the rule
+ will be specified as 'less'.
+ 3. Or if any one item in ``self.greater_keys`` is a substring of
+ key_indicator, the rule will be specified as 'greater'.
+ 4. Or if any one item in ``self.less_keys`` is a substring of
+ key_indicator, the rule will be specified as 'less'.
+
+ Args:
+ rule (List[Optional[str]]): Comparison rule for best score.
+ key_indicator (List[str]): Key indicator to determine
+ the comparison rule.
+ """
+ if len(rules) == 1:
+ rules = rules * len(key_indicators)
+
+ self.rules = []
+ for rule, key_indicator in zip(rules, key_indicators):
+
+ if rule not in self.rule_map and rule is not None:
+ raise KeyError('rule must be greater, less or None, '
+ f'but got {rule}.')
+
+ if rule is None and key_indicator != 'auto':
+ # `_lc` here means we use the lower case of keys for
+ # case-insensitive matching
+ key_indicator_lc = key_indicator.lower()
+ greater_keys = {key.lower() for key in self.greater_keys}
+ less_keys = {key.lower() for key in self.less_keys}
+
+ if key_indicator_lc in greater_keys:
+ rule = 'greater'
+ elif key_indicator_lc in less_keys:
+ rule = 'less'
+ elif any(key in key_indicator_lc for key in greater_keys):
+ rule = 'greater'
+ elif any(key in key_indicator_lc for key in less_keys):
+ rule = 'less'
+ else:
+ raise ValueError('Cannot infer the rule for key '
+ f'{key_indicator}, thus a specific rule '
+ 'must be specified.')
+ if rule is not None:
+ self.is_better_than[key_indicator] = self.rule_map[rule]
+ self.rules.append(rule)
+
+ self.key_indicators = key_indicators
+
+ def after_train_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None,
+ outputs=Optional[dict]) -> None:
+ """Save the checkpoint and synchronize buffers after each iteration.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ batch_idx (int): The index of the current batch in the train loop.
+ data_batch (dict or tuple or list, optional): Data from dataloader.
+ outputs (dict, optional): Outputs from model.
+ """
+ if self.by_epoch:
+ return
+
+ # save checkpoint for following cases:
+ # 1. every ``self.interval`` iterations
+ # 2. reach the last iteration of training
+ if self.every_n_train_iters(runner, self.interval) or \
+ (self.save_last and
+ self.is_last_train_iter(runner)):
+ runner.logger.info(
+ f'Saving checkpoint at {runner.iter + 1} iterations')
+ self._save_checkpoint(runner)
diff --git a/testbed/open-mmlab__mmengine/mmengine/hooks/ema_hook.py b/testbed/open-mmlab__mmengine/mmengine/hooks/ema_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..bad7d8f86a86101aadf36e0a2d75d97c87a807b2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hooks/ema_hook.py
@@ -0,0 +1,237 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import itertools
+import logging
+from typing import Dict, Optional
+
+from mmengine.logging import print_log
+from mmengine.model import is_model_wrapper
+from mmengine.registry import HOOKS, MODELS
+from .hook import DATA_BATCH, Hook
+
+
+@HOOKS.register_module()
+class EMAHook(Hook):
+ """A Hook to apply Exponential Moving Average (EMA) on the model during
+ training.
+
+ Note:
+ - EMAHook takes priority over CheckpointHook.
+ - The original model parameters are actually saved in ema field after
+ train.
+ - ``begin_iter`` and ``begin_epoch`` cannot be set at the same time.
+
+ Args:
+ ema_type (str): The type of EMA strategy to use. You can find the
+ supported strategies in :mod:`mmengine.model.averaged_model`.
+ Defaults to 'ExponentialMovingAverage'.
+ strict_load (bool): Whether to strictly enforce that the keys of
+ ``state_dict`` in checkpoint match the keys returned by
+ ``self.module.state_dict``. Defaults to False.
+ Changed in v0.3.0.
+ begin_iter (int): The number of iteration to enable ``EMAHook``.
+ Defaults to 0.
+ begin_epoch (int): The number of epoch to enable ``EMAHook``.
+ Defaults to 0.
+ **kwargs: Keyword arguments passed to subclasses of
+ :obj:`BaseAveragedModel`
+ """
+
+ priority = 'NORMAL'
+
+ def __init__(self,
+ ema_type: str = 'ExponentialMovingAverage',
+ strict_load: bool = False,
+ begin_iter: int = 0,
+ begin_epoch: int = 0,
+ **kwargs):
+ self.strict_load = strict_load
+ self.ema_cfg = dict(type=ema_type, **kwargs)
+ assert not (begin_iter != 0 and begin_epoch != 0), (
+ '`begin_iter` and `begin_epoch` should not be both set.')
+ assert begin_iter >= 0, (
+ f'begin_iter must larger than 0, but got begin: {begin_iter}')
+ assert begin_epoch >= 0, (
+ f'begin_epoch must larger than 0, but got begin: {begin_epoch}')
+ self.begin_iter = begin_iter
+ self.begin_epoch = begin_epoch
+ # If `begin_epoch` and `begin_iter` are not set, `EMAHook` will be
+ # enabled at 0 iteration.
+ self.enabled_by_epoch = self.begin_epoch > 0
+
+ def before_run(self, runner) -> None:
+ """Create an ema copy of the model.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ model = runner.model
+ if is_model_wrapper(model):
+ model = model.module
+ self.src_model = model
+ self.ema_model = MODELS.build(
+ self.ema_cfg, default_args=dict(model=self.src_model))
+
+ def before_train(self, runner) -> None:
+ """Check the begin_epoch/iter is smaller than max_epochs/iters.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ if self.enabled_by_epoch:
+ assert self.begin_epoch <= runner.max_epochs, (
+ 'self.begin_epoch should be smaller than runner.max_epochs: '
+ f'{runner.max_epochs}, but got begin: {self.begin_epoch}')
+ else:
+ assert self.begin_iter <= runner.max_iters, (
+ 'self.begin_iter should be smaller than runner.max_iters: '
+ f'{runner.max_iters}, but got begin: {self.begin_iter}')
+
+ def after_train_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None,
+ outputs: Optional[dict] = None) -> None:
+ """Update ema parameter.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ batch_idx (int): The index of the current batch in the train loop.
+ data_batch (Sequence[dict], optional): Data from dataloader.
+ Defaults to None.
+ outputs (dict, optional): Outputs from model. Defaults to None.
+ """
+ if self._ema_started(runner):
+ self.ema_model.update_parameters(self.src_model)
+ else:
+ ema_params = self.ema_model.module.state_dict()
+ src_params = self.src_model.state_dict()
+ for k, p in ema_params.items():
+ p.data.copy_(src_params[k].data)
+
+ def before_val_epoch(self, runner) -> None:
+ """We load parameter values from ema model to source model before
+ validation.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ self._swap_ema_parameters()
+
+ def after_val_epoch(self,
+ runner,
+ metrics: Optional[Dict[str, float]] = None) -> None:
+ """We recover source model's parameter from ema model after validation.
+
+ Args:
+ runner (Runner): The runner of the validation process.
+ metrics (Dict[str, float], optional): Evaluation results of all
+ metrics on validation dataset. The keys are the names of the
+ metrics, and the values are corresponding results.
+ """
+ self._swap_ema_parameters()
+
+ def before_test_epoch(self, runner) -> None:
+ """We load parameter values from ema model to source model before test.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ self._swap_ema_parameters()
+
+ def after_test_epoch(self,
+ runner,
+ metrics: Optional[Dict[str, float]] = None) -> None:
+ """We recover source model's parameter from ema model after test.
+
+ Args:
+ runner (Runner): The runner of the testing process.
+ metrics (Dict[str, float], optional): Evaluation results of all
+ metrics on test dataset. The keys are the names of the
+ metrics, and the values are corresponding results.
+ """
+ self._swap_ema_parameters()
+
+ def before_save_checkpoint(self, runner, checkpoint: dict) -> None:
+ """Save ema parameters to checkpoint.
+
+ Args:
+ runner (Runner): The runner of the testing process.
+ """
+ checkpoint['ema_state_dict'] = self.ema_model.state_dict()
+ # Save ema parameters to the source model's state dict so that we
+ # can directly load the averaged model weights for deployment.
+ # Swapping the state_dict key-values instead of swapping model
+ # parameters because the state_dict is a shallow copy of model
+ # parameters.
+ self._swap_ema_state_dict(checkpoint)
+
+ def after_load_checkpoint(self, runner, checkpoint: dict) -> None:
+ """Resume ema parameters from checkpoint.
+
+ Args:
+ runner (Runner): The runner of the testing process.
+ """
+ from mmengine.runner.checkpoint import load_state_dict
+ if 'ema_state_dict' in checkpoint and runner._resume:
+ # The original model parameters are actually saved in ema
+ # field swap the weights back to resume ema state.
+ self._swap_ema_state_dict(checkpoint)
+ self.ema_model.load_state_dict(
+ checkpoint['ema_state_dict'], strict=self.strict_load)
+
+ # Support load checkpoint without ema state dict.
+ else:
+ if runner._resume:
+ print_log(
+ 'There is no `ema_state_dict` in checkpoint. '
+ '`EMAHook` will make a copy of `state_dict` as the '
+ 'initial `ema_state_dict`', 'current', logging.WARNING)
+ load_state_dict(
+ self.ema_model.module,
+ copy.deepcopy(checkpoint['state_dict']),
+ strict=self.strict_load)
+
+ def _swap_ema_parameters(self) -> None:
+ """Swap the parameter of model with ema_model."""
+ avg_param = (
+ itertools.chain(self.ema_model.module.parameters(),
+ self.ema_model.module.buffers())
+ if self.ema_model.update_buffers else
+ self.ema_model.module.parameters())
+ src_param = (
+ itertools.chain(self.src_model.parameters(),
+ self.src_model.buffers())
+ if self.ema_model.update_buffers else self.src_model.parameters())
+ for p_avg, p_src in zip(avg_param, src_param):
+ tmp = p_avg.data.clone()
+ p_avg.data.copy_(p_src.data)
+ p_src.data.copy_(tmp)
+
+ def _swap_ema_state_dict(self, checkpoint):
+ """Swap the state dict values of model with ema_model."""
+ model_state = checkpoint['state_dict']
+ ema_state = checkpoint['ema_state_dict']
+ for k in ema_state:
+ if k[:7] == 'module.':
+ tmp = ema_state[k]
+ ema_state[k] = model_state[k[7:]]
+ model_state[k[7:]] = tmp
+
+ def _ema_started(self, runner) -> bool:
+ """Whether ``EMAHook`` has been initialized at current iteration or
+ epoch.
+
+ :attr:`ema_model` will be initialized when ``runner.iter`` or
+ ``runner.epoch`` is greater than ``self.begin`` for the first time.
+
+ Args:
+ runner (Runner): Runner of the training, validation process.
+
+ Returns:
+ bool: Whether ``EMAHook`` has been initialized.
+ """
+ if self.enabled_by_epoch:
+ return runner.epoch + 1 >= self.begin_epoch
+ else:
+ return runner.iter + 1 >= self.begin_iter
diff --git a/testbed/open-mmlab__mmengine/mmengine/hooks/empty_cache_hook.py b/testbed/open-mmlab__mmengine/mmengine/hooks/empty_cache_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9b5eba0ed42753ac0163c8d91cd93bbe3b10a23
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hooks/empty_cache_hook.py
@@ -0,0 +1,72 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from typing import Optional, Sequence, Union
+
+import torch
+
+from mmengine.registry import HOOKS
+from .hook import Hook
+
+DATA_BATCH = Optional[Union[dict, tuple, list]]
+
+
+@HOOKS.register_module()
+class EmptyCacheHook(Hook):
+ """Releases all unoccupied cached GPU memory during the process of
+ training.
+
+ Args:
+ before_epoch (bool): Whether to release cache before an epoch. Defaults
+ to False.
+ after_epoch (bool): Whether to release cache after an epoch. Defaults
+ to True.
+ after_iter (bool): Whether to release cache after an iteration.
+ Defaults to False.
+ """
+
+ priority = 'NORMAL'
+
+ def __init__(self,
+ before_epoch: bool = False,
+ after_epoch: bool = True,
+ after_iter: bool = False) -> None:
+ self._do_before_epoch = before_epoch
+ self._do_after_epoch = after_epoch
+ self._do_after_iter = after_iter
+
+ def _after_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None,
+ outputs: Optional[Union[dict, Sequence]] = None,
+ mode: str = 'train') -> None:
+ """Empty cache after an iteration.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ batch_idx (int): The index of the current batch in the loop.
+ data_batch (dict or tuple or list, optional): Data from dataloader.
+ outputs (dict or sequence, optional): Outputs from model.
+ mode (str): Current mode of runner. Defaults to 'train'.
+ """
+ if self._do_after_iter:
+ torch.cuda.empty_cache()
+
+ def _before_epoch(self, runner, mode: str = 'train') -> None:
+ """Empty cache before an epoch.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ mode (str): Current mode of runner. Defaults to 'train'.
+ """
+ if self._do_before_epoch:
+ torch.cuda.empty_cache()
+
+ def _after_epoch(self, runner, mode: str = 'train') -> None:
+ """Empty cache after an epoch.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ mode (str): Current mode of runner. Defaults to 'train'.
+ """
+ if self._do_after_epoch:
+ torch.cuda.empty_cache()
diff --git a/testbed/open-mmlab__mmengine/mmengine/hooks/hook.py b/testbed/open-mmlab__mmengine/mmengine/hooks/hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..26dce2452a613ad8eac6f32554a4e614d2d4a979
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hooks/hook.py
@@ -0,0 +1,452 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from typing import Dict, Optional, Sequence, Union
+
+from mmengine import is_method_overridden
+
+DATA_BATCH = Optional[Union[dict, tuple, list]]
+
+
+class Hook:
+ """Base hook class.
+
+ All hooks should inherit from this class.
+ """
+
+ priority = 'NORMAL'
+ stages = ('before_run', 'after_load_checkpoint', 'before_train',
+ 'before_train_epoch', 'before_train_iter', 'after_train_iter',
+ 'after_train_epoch', 'before_val', 'before_val_epoch',
+ 'before_val_iter', 'after_val_iter', 'after_val_epoch',
+ 'after_val', 'before_save_checkpoint', 'after_train',
+ 'before_test', 'before_test_epoch', 'before_test_iter',
+ 'after_test_iter', 'after_test_epoch', 'after_test', 'after_run')
+
+ def before_run(self, runner) -> None:
+ """All subclasses should override this method, if they need any
+ operations before the training validation or testing process.
+
+ Args:
+ runner (Runner): The runner of the training, validation or testing
+ process.
+ """
+ pass
+
+ def after_run(self, runner) -> None:
+ """All subclasses should override this method, if they need any
+ operations before the training validation or testing process.
+
+ Args:
+ runner (Runner): The runner of the training, validation or testing
+ process.
+ """
+ pass
+
+ def before_train(self, runner) -> None:
+ """All subclasses should override this method, if they need any
+ operations before train.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ pass
+
+ def after_train(self, runner) -> None:
+ """All subclasses should override this method, if they need any
+ operations after train.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ pass
+
+ def before_val(self, runner) -> None:
+ """All subclasses should override this method, if they need any
+ operations before validation.
+
+ Args:
+ runner (Runner): The runner of the validation process.
+ """
+ pass
+
+ def after_val(self, runner) -> None:
+ """All subclasses should override this method, if they need any
+ operations after validation.
+
+ Args:
+ runner (Runner): The runner of the validation process.
+ """
+ pass
+
+ def before_test(self, runner) -> None:
+ """All subclasses should override this method, if they need any
+ operations before testing.
+
+ Args:
+ runner (Runner): The runner of the testing process.
+ """
+ pass
+
+ def after_test(self, runner) -> None:
+ """All subclasses should override this method, if they need any
+ operations after testing.
+
+ Args:
+ runner (Runner): The runner of the testing process.
+ """
+ pass
+
+ def before_save_checkpoint(self, runner, checkpoint: dict) -> None:
+ """All subclasses should override this method, if they need any
+ operations before saving the checkpoint.
+
+ Args:
+ runner (Runner): The runner of the training, validation or testing
+ process.
+ checkpoint (dict): Model's checkpoint.
+ """
+ pass
+
+ def after_load_checkpoint(self, runner, checkpoint: dict) -> None:
+ """All subclasses should override this method, if they need any
+ operations after loading the checkpoint.
+
+ Args:
+ runner (Runner): The runner of the training, validation or testing
+ process.
+ checkpoint (dict): Model's checkpoint.
+ """
+ pass
+
+ def before_train_epoch(self, runner) -> None:
+ """All subclasses should override this method, if they need any
+ operations before each training epoch.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ self._before_epoch(runner, mode='train')
+
+ def before_val_epoch(self, runner) -> None:
+ """All subclasses should override this method, if they need any
+ operations before each validation epoch.
+
+ Args:
+ runner (Runner): The runner of the validation process.
+ """
+ self._before_epoch(runner, mode='val')
+
+ def before_test_epoch(self, runner) -> None:
+ """All subclasses should override this method, if they need any
+ operations before each test epoch.
+
+ Args:
+ runner (Runner): The runner of the testing process.
+ """
+ self._before_epoch(runner, mode='test')
+
+ def after_train_epoch(self, runner) -> None:
+ """All subclasses should override this method, if they need any
+ operations after each training epoch.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ self._after_epoch(runner, mode='train')
+
+ def after_val_epoch(self,
+ runner,
+ metrics: Optional[Dict[str, float]] = None) -> None:
+ """All subclasses should override this method, if they need any
+ operations after each validation epoch.
+
+ Args:
+ runner (Runner): The runner of the validation process.
+ metrics (Dict[str, float], optional): Evaluation results of all
+ metrics on validation dataset. The keys are the names of the
+ metrics, and the values are corresponding results.
+ """
+ self._after_epoch(runner, mode='val')
+
+ def after_test_epoch(self,
+ runner,
+ metrics: Optional[Dict[str, float]] = None) -> None:
+ """All subclasses should override this method, if they need any
+ operations after each test epoch.
+
+ Args:
+ runner (Runner): The runner of the testing process.
+ metrics (Dict[str, float], optional): Evaluation results of all
+ metrics on test dataset. The keys are the names of the
+ metrics, and the values are corresponding results.
+ """
+ self._after_epoch(runner, mode='test')
+
+ def before_train_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None) -> None:
+ """All subclasses should override this method, if they need any
+ operations before each training iteration.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ batch_idx (int): The index of the current batch in the train loop.
+ data_batch (dict or tuple or list, optional): Data from dataloader.
+ """
+ self._before_iter(
+ runner, batch_idx=batch_idx, data_batch=data_batch, mode='train')
+
+ def before_val_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None) -> None:
+ """All subclasses should override this method, if they need any
+ operations before each validation iteration.
+
+ Args:
+ runner (Runner): The runner of the validation process.
+ batch_idx (int): The index of the current batch in the val loop.
+ data_batch (dict, optional): Data from dataloader.
+ Defaults to None.
+ """
+ self._before_iter(
+ runner, batch_idx=batch_idx, data_batch=data_batch, mode='val')
+
+ def before_test_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None) -> None:
+ """All subclasses should override this method, if they need any
+ operations before each test iteration.
+
+ Args:
+ runner (Runner): The runner of the testing process.
+ batch_idx (int): The index of the current batch in the test loop.
+ data_batch (dict or tuple or list, optional): Data from dataloader.
+ Defaults to None.
+ """
+ self._before_iter(
+ runner, batch_idx=batch_idx, data_batch=data_batch, mode='test')
+
+ def after_train_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None,
+ outputs: Optional[dict] = None) -> None:
+ """All subclasses should override this method, if they need any
+ operations after each training iteration.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ batch_idx (int): The index of the current batch in the train loop.
+ data_batch (dict tuple or list, optional): Data from dataloader.
+ outputs (dict, optional): Outputs from model.
+ """
+ self._after_iter(
+ runner,
+ batch_idx=batch_idx,
+ data_batch=data_batch,
+ outputs=outputs,
+ mode='train')
+
+ def after_val_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None,
+ outputs: Optional[Sequence] = None) -> None:
+ """All subclasses should override this method, if they need any
+ operations after each validation iteration.
+
+ Args:
+ runner (Runner): The runner of the validation process.
+ batch_idx (int): The index of the current batch in the val loop.
+ data_batch (dict or tuple or list, optional): Data from dataloader.
+ outputs (Sequence, optional): Outputs from model.
+ """
+ self._after_iter(
+ runner,
+ batch_idx=batch_idx,
+ data_batch=data_batch,
+ outputs=outputs,
+ mode='val')
+
+ def after_test_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None,
+ outputs: Optional[Sequence] = None) -> None:
+ """All subclasses should override this method, if they need any
+ operations after each test iteration.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ batch_idx (int): The index of the current batch in the test loop.
+ data_batch (dict or tuple or list, optional): Data from dataloader.
+ outputs (Sequence, optional): Outputs from model.
+ """
+ self._after_iter(
+ runner,
+ batch_idx=batch_idx,
+ data_batch=data_batch,
+ outputs=outputs,
+ mode='test')
+
+ def _before_epoch(self, runner, mode: str = 'train') -> None:
+ """All subclasses should override this method, if they need any
+ operations before each epoch.
+
+ Args:
+ runner (Runner): The runner of the training, validation or testing
+ process.
+ mode (str): Current mode of runner. Defaults to 'train'.
+ """
+ pass
+
+ def _after_epoch(self, runner, mode: str = 'train') -> None:
+ """All subclasses should override this method, if they need any
+ operations after each epoch.
+
+ Args:
+ runner (Runner): The runner of the training, validation or testing
+ process.
+ mode (str): Current mode of runner. Defaults to 'train'.
+ """
+ pass
+
+ def _before_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None,
+ mode: str = 'train') -> None:
+ """All subclasses should override this method, if they need any
+ operations before each iter.
+
+ Args:
+ runner (Runner): The runner of the training, validation or testing
+ process.
+ batch_idx (int): The index of the current batch in the loop.
+ data_batch (dict or tuple or list, optional): Data from dataloader.
+ mode (str): Current mode of runner. Defaults to 'train'.
+ """
+ pass
+
+ def _after_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None,
+ outputs: Optional[Union[Sequence, dict]] = None,
+ mode: str = 'train') -> None:
+ """All subclasses should override this method, if they need any
+ operations after each epoch.
+
+ Args:
+ runner (Runner): The runner of the training, validation or testing
+ process.
+ batch_idx (int): The index of the current batch in the loop.
+ data_batch (dict or tuple or list, optional): Data from dataloader.
+ outputs (dict or Sequence, optional): Outputs from model.
+ mode (str): Current mode of runner. Defaults to 'train'.
+ """
+ pass
+
+ def every_n_epochs(self, runner, n: int) -> bool:
+ """Test whether current epoch can be evenly divided by n.
+
+ Args:
+ runner (Runner): The runner of the training, validation or testing
+ process.
+ n (int): Whether current epoch can be evenly divided by n.
+
+ Returns:
+ bool: Whether current epoch can be evenly divided by n.
+ """
+ return (runner.epoch + 1) % n == 0 if n > 0 else False
+
+ def every_n_inner_iters(self, batch_idx: int, n: int) -> bool:
+ """Test whether current inner iteration can be evenly divided by n.
+
+ Args:
+ batch_idx (int): Current batch index of the training, validation
+ or testing loop.
+ n (int): Whether current inner iteration can be evenly
+ divided by n.
+
+ Returns:
+ bool: Whether current inner iteration can be evenly
+ divided by n.
+ """
+ return (batch_idx + 1) % n == 0 if n > 0 else False
+
+ def every_n_train_iters(self, runner, n: int) -> bool:
+ """Test whether current training iteration can be evenly divided by n.
+
+ Args:
+ runner (Runner): The runner of the training, validation or testing
+ process.
+ n (int): Whether current iteration can be evenly divided by n.
+
+ Returns:
+ bool: Return True if the current iteration can be evenly divided
+ by n, otherwise False.
+ """
+ return (runner.iter + 1) % n == 0 if n > 0 else False
+
+ def end_of_epoch(self, dataloader, batch_idx: int) -> bool:
+ """Check whether the current iteration reaches the last iteration of
+ the dataloader.
+
+ Args:
+ dataloader (Dataloader): The dataloader of the training,
+ validation or testing process.
+ batch_idx (int): The index of the current batch in the loop.
+ Returns:
+ bool: Whether reaches the end of current epoch or not.
+ """
+ return batch_idx + 1 == len(dataloader)
+
+ def is_last_train_epoch(self, runner) -> bool:
+ """Test whether current epoch is the last train epoch.
+
+ Args:
+ runner (Runner): The runner of the training process.
+
+ Returns:
+ bool: Whether reaches the end of training epoch.
+ """
+ return runner.epoch + 1 == runner.max_epochs
+
+ def is_last_train_iter(self, runner) -> bool:
+ """Test whether current iteration is the last train iteration.
+
+ Args:
+ runner (Runner): The runner of the training process.
+
+ Returns:
+ bool: Whether current iteration is the last train iteration.
+ """
+ return runner.iter + 1 == runner.max_iters
+
+ def get_triggered_stages(self) -> list:
+ trigger_stages = set()
+ for stage in Hook.stages:
+ if is_method_overridden(stage, Hook, self):
+ trigger_stages.add(stage)
+
+ # some methods will be triggered in multi stages
+ # use this dict to map method to stages.
+ method_stages_map = {
+ '_before_epoch':
+ ['before_train_epoch', 'before_val_epoch', 'before_test_epoch'],
+ '_after_epoch':
+ ['after_train_epoch', 'after_val_epoch', 'after_test_epoch'],
+ '_before_iter':
+ ['before_train_iter', 'before_val_iter', 'before_test_iter'],
+ '_after_iter':
+ ['after_train_iter', 'after_val_iter', 'after_test_iter'],
+ }
+
+ for method, map_stages in method_stages_map.items():
+ if is_method_overridden(method, Hook, self):
+ trigger_stages.update(map_stages)
+
+ return list(trigger_stages)
diff --git a/testbed/open-mmlab__mmengine/mmengine/hooks/iter_timer_hook.py b/testbed/open-mmlab__mmengine/mmengine/hooks/iter_timer_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..5632c2b25e03b5773ec694452535be1ecb661d19
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hooks/iter_timer_hook.py
@@ -0,0 +1,107 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import time
+from typing import Optional, Sequence, Union
+
+from mmengine.registry import HOOKS
+from .hook import Hook
+
+DATA_BATCH = Optional[Union[dict, tuple, list]]
+
+
+@HOOKS.register_module()
+class IterTimerHook(Hook):
+ """A hook that logs the time spent during iteration.
+
+ E.g. ``data_time`` for loading data and ``time`` for a model train step.
+ """
+
+ priority = 'NORMAL'
+
+ def __init__(self):
+ self.time_sec_tot = 0
+ self.time_sec_test_val = 0
+ self.start_iter = 0
+
+ def before_train(self, runner) -> None:
+ """Synchronize the number of iterations with the runner after resuming
+ from checkpoints.
+
+ Args:
+ runner: The runner of the training, validation or testing
+ process.
+ """
+ self.start_iter = runner.iter
+
+ def _before_epoch(self, runner, mode: str = 'train') -> None:
+ """Record timestamp before start an epoch.
+
+ Args:
+ runner (Runner): The runner of the training validation and
+ testing process.
+ mode (str): Current mode of runner. Defaults to 'train'.
+ """
+ self.t = time.time()
+
+ def _after_epoch(self, runner, mode: str = 'train') -> None:
+ self.time_sec_test_val = 0
+
+ def _before_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None,
+ mode: str = 'train') -> None:
+ """Calculating time for loading data and updating "data_time"
+ ``HistoryBuffer`` of ``runner.message_hub``.
+
+ Args:
+ runner (Runner): The runner of the training, validation and
+ testing process.
+ batch_idx (int): The index of the current batch in the loop.
+ data_batch (dict or tuple or list, optional): Data from
+ dataloader.
+ mode (str): Current mode of runner. Defaults to 'train'.
+ """
+ # Update data loading time in `runner.message_hub`.
+ runner.message_hub.update_scalar(f'{mode}/data_time',
+ time.time() - self.t)
+
+ def _after_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None,
+ outputs: Optional[Union[dict, Sequence]] = None,
+ mode: str = 'train') -> None:
+ """Calculating time for an iteration and updating "time"
+ ``HistoryBuffer`` of ``runner.message_hub``.
+
+ Args:
+ runner (Runner): The runner of the training validation and
+ testing process.
+ batch_idx (int): The index of the current batch in the loop.
+ data_batch (dict or tuple or list, optional): Data from dataloader.
+ outputs (dict or sequence, optional): Outputs from model.
+ mode (str): Current mode of runner. Defaults to 'train'.
+ """
+ # Update iteration time in `runner.message_hub`.
+ message_hub = runner.message_hub
+ message_hub.update_scalar(f'{mode}/time', time.time() - self.t)
+ self.t = time.time()
+ iter_time = message_hub.get_scalar(f'{mode}/time')
+ if mode == 'train':
+ self.time_sec_tot += iter_time.current()
+ # Calculate average iterative time.
+ time_sec_avg = self.time_sec_tot / (
+ runner.iter - self.start_iter + 1)
+ # Calculate eta.
+ eta_sec = time_sec_avg * (runner.max_iters - runner.iter - 1)
+ runner.message_hub.update_info('eta', eta_sec)
+ else:
+ if mode == 'val':
+ cur_dataloader = runner.val_dataloader
+ else:
+ cur_dataloader = runner.test_dataloader
+
+ self.time_sec_test_val += iter_time.current()
+ time_sec_avg = self.time_sec_test_val / (batch_idx + 1)
+ eta_sec = time_sec_avg * (len(cur_dataloader) - batch_idx - 1)
+ runner.message_hub.update_info('eta', eta_sec)
diff --git a/testbed/open-mmlab__mmengine/mmengine/hooks/logger_hook.py b/testbed/open-mmlab__mmengine/mmengine/hooks/logger_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..71752be1428c48e1a358abd540eb2ad6aafd6869
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hooks/logger_hook.py
@@ -0,0 +1,282 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import os.path as osp
+import warnings
+from pathlib import Path
+from typing import Dict, Optional, Sequence, Union
+
+from mmengine.fileio import FileClient, dump
+from mmengine.fileio.io import get_file_backend
+from mmengine.hooks import Hook
+from mmengine.registry import HOOKS
+from mmengine.utils import is_tuple_of, scandir
+
+DATA_BATCH = Optional[Union[dict, tuple, list]]
+SUFFIX_TYPE = Union[Sequence[str], str]
+
+
+@HOOKS.register_module()
+class LoggerHook(Hook):
+ """Collect logs from different components of ``Runner`` and write them to
+ terminal, JSON file, tensorboard and wandb .etc.
+
+ ``LoggerHook`` is used to record logs formatted by ``LogProcessor`` during
+ training/validation/testing phase. It is used to control following
+ behaviors:
+
+ - The frequency of logs update in terminal, local, tensorboad wandb.etc.
+ - The frequency of show experiment information in terminal.
+ - The work directory to save logs.
+
+ Args:
+ interval (int): Logging interval (every k iterations).
+ Defaults to 10.
+ ignore_last (bool): Ignore the log of last iterations in each epoch if
+ the number of remaining iterations is less than :attr:`interval`.
+ Defaults to True.
+ interval_exp_name (int): Logging interval for experiment name. This
+ feature is to help users conveniently get the experiment
+ information from screen or log file. Defaults to 1000.
+ out_dir (str or Path, optional): The root directory to save
+ checkpoints. If not specified, ``runner.work_dir`` will be used
+ by default. If specified, the ``out_dir`` will be the concatenation
+ of ``out_dir`` and the last level directory of ``runner.work_dir``.
+ For example, if the input ``our_dir`` is ``./tmp`` and
+ ``runner.work_dir`` is ``./work_dir/cur_exp``, then the log will be
+ saved in ``./tmp/cur_exp``. Defaults to None.
+ out_suffix (Tuple[str] or str): Those files in ``runner._log_dir``
+ ending with ``out_suffix`` will be copied to ``out_dir``. Defaults
+ to ('json', '.log', '.py').
+ keep_local (bool): Whether to keep local logs in the local machine
+ when :attr:`out_dir` is specified. If False, the local log will be
+ removed. Defaults to True.
+ file_client_args (dict, optional): Arguments to instantiate a
+ FileClient. See :class:`mmengine.fileio.FileClient` for details.
+ Defaults to None. It will be deprecated in future. Please use
+ `backend_args` instead.
+ log_metric_by_epoch (bool): Whether to output metric in validation step
+ by epoch. It can be true when running in epoch based runner.
+ If set to True, `after_val_epoch` will set `step` to self.epoch in
+ `runner.visualizer.add_scalars`. Otherwise `step` will be
+ self.iter. Default to True.
+ backend_args (dict, optional): Arguments to instantiate the
+ preifx of uri corresponding backend. Defaults to None.
+ New in v0.2.0.
+
+ Examples:
+ >>> # The simplest LoggerHook config.
+ >>> logger_hook_cfg = dict(interval=20)
+ """
+ priority = 'BELOW_NORMAL'
+
+ def __init__(self,
+ interval: int = 10,
+ ignore_last: bool = True,
+ interval_exp_name: int = 1000,
+ out_dir: Optional[Union[str, Path]] = None,
+ out_suffix: SUFFIX_TYPE = ('.json', '.log', '.py', 'yaml'),
+ keep_local: bool = True,
+ file_client_args: Optional[dict] = None,
+ log_metric_by_epoch: bool = True,
+ backend_args: Optional[dict] = None):
+ self.interval = interval
+ self.ignore_last = ignore_last
+ self.interval_exp_name = interval_exp_name
+
+ if out_dir is None and file_client_args is not None:
+ raise ValueError(
+ 'file_client_args should be "None" when `out_dir` is not'
+ 'specified.')
+ self.out_dir = out_dir
+
+ if file_client_args is not None:
+ warnings.warn(
+ '"file_client_args" will be deprecated in future. '
+ 'Please use "backend_args" instead', DeprecationWarning)
+ if backend_args is not None:
+ raise ValueError(
+ '"file_client_args" and "backend_args" cannot be set '
+ 'at the same time.')
+
+ if not (out_dir is None or isinstance(out_dir, str)
+ or is_tuple_of(out_dir, str)):
+ raise TypeError('out_dir should be None or string or tuple of '
+ f'string, but got {type(out_dir)}')
+ self.out_suffix = out_suffix
+
+ self.keep_local = keep_local
+ self.file_client_args = file_client_args
+ self.json_log_path: Optional[str] = None
+
+ if self.out_dir is not None:
+ self.file_client = FileClient.infer_client(file_client_args,
+ self.out_dir)
+ if file_client_args is None:
+ self.file_backend = get_file_backend(
+ self.out_dir, backend_args=backend_args)
+ else:
+ self.file_backend = self.file_client
+
+ self.log_metric_by_epoch = log_metric_by_epoch
+
+ def before_run(self, runner) -> None:
+ """Infer ``self.file_client`` from ``self.out_dir``. Initialize the
+ ``self.start_iter`` and record the meta information.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ if self.out_dir is not None:
+ # The final `self.out_dir` is the concatenation of `self.out_dir`
+ # and the last level directory of `runner.work_dir`
+ basename = osp.basename(runner.work_dir.rstrip(osp.sep))
+ self.out_dir = self.file_backend.join_path(self.out_dir, basename)
+ runner.logger.info(
+ f'Text logs will be saved to {self.out_dir} after the '
+ 'training process.')
+
+ self.json_log_path = f'{runner.timestamp}.json'
+
+ def after_train_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None,
+ outputs: Optional[dict] = None) -> None:
+ """Record logs after training iteration.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ batch_idx (int): The index of the current batch in the train loop.
+ data_batch (dict tuple or list, optional): Data from dataloader.
+ outputs (dict, optional): Outputs from model.
+ """
+ # Print experiment name every n iterations.
+ if self.every_n_train_iters(
+ runner, self.interval_exp_name) or (self.end_of_epoch(
+ runner.train_dataloader, batch_idx)):
+ exp_info = f'Exp name: {runner.experiment_name}'
+ runner.logger.info(exp_info)
+ if self.every_n_inner_iters(batch_idx, self.interval):
+ tag, log_str = runner.log_processor.get_log_after_iter(
+ runner, batch_idx, 'train')
+ elif (self.end_of_epoch(runner.train_dataloader, batch_idx)
+ and not self.ignore_last):
+ # `runner.max_iters` may not be divisible by `self.interval`. if
+ # `self.ignore_last==True`, the log of remaining iterations will
+ # be recorded (Epoch [4][1000/1007], the logs of 998-1007
+ # iterations will be recorded).
+ tag, log_str = runner.log_processor.get_log_after_iter(
+ runner, batch_idx, 'train')
+ else:
+ return
+ runner.logger.info(log_str)
+ runner.visualizer.add_scalars(
+ tag, step=runner.iter + 1, file_path=self.json_log_path)
+
+ def after_val_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None,
+ outputs: Optional[Sequence] = None) -> None:
+ """Record logs after validation iteration.
+
+ Args:
+ runner (Runner): The runner of the validation process.
+ batch_idx (int): The index of the current batch in the validation
+ loop.
+ data_batch (dict or tuple or list, optional): Data from dataloader.
+ Defaults to None.
+ outputs (sequence, optional): Outputs from model.
+ """
+ if self.every_n_inner_iters(batch_idx, self.interval):
+ _, log_str = runner.log_processor.get_log_after_iter(
+ runner, batch_idx, 'val')
+ runner.logger.info(log_str)
+
+ def after_test_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None,
+ outputs: Optional[Sequence] = None) -> None:
+ """Record logs after testing iteration.
+
+ Args:
+ runner (Runner): The runner of the testing process.
+ batch_idx (int): The index of the current batch in the test loop.
+ data_batch (dict or tuple or list, optional): Data from dataloader.
+ outputs (sequence, optional): Outputs from model.
+ """
+ if self.every_n_inner_iters(batch_idx, self.interval):
+ _, log_str = runner.log_processor.get_log_after_iter(
+ runner, batch_idx, 'test')
+ runner.logger.info(log_str)
+
+ def after_val_epoch(self,
+ runner,
+ metrics: Optional[Dict[str, float]] = None) -> None:
+ """All subclasses should override this method, if they need any
+ operations after each validation epoch.
+
+ Args:
+ runner (Runner): The runner of the validation process.
+ metrics (Dict[str, float], optional): Evaluation results of all
+ metrics on validation dataset. The keys are the names of the
+ metrics, and the values are corresponding results.
+ """
+ tag, log_str = runner.log_processor.get_log_after_epoch(
+ runner, len(runner.val_dataloader), 'val')
+ runner.logger.info(log_str)
+ if self.log_metric_by_epoch:
+ # when `log_metric_by_epoch` is set to True, it's expected
+ # that validation metric can be logged by epoch rather than
+ # by iter. At the same time, scalars related to time should
+ # still be logged by iter to avoid messy visualized result.
+ # see details in PR #278.
+ metric_tags = {k: v for k, v in tag.items() if 'time' not in k}
+ runner.visualizer.add_scalars(
+ metric_tags, step=runner.epoch, file_path=self.json_log_path)
+ else:
+ runner.visualizer.add_scalars(
+ tag, step=runner.iter, file_path=self.json_log_path)
+
+ def after_test_epoch(self,
+ runner,
+ metrics: Optional[Dict[str, float]] = None) -> None:
+ """All subclasses should override this method, if they need any
+ operations after each test epoch.
+
+ Args:
+ runner (Runner): The runner of the testing process.
+ metrics (Dict[str, float], optional): Evaluation results of all
+ metrics on test dataset. The keys are the names of the
+ metrics, and the values are corresponding results.
+ """
+ tag, log_str = runner.log_processor.get_log_after_epoch(
+ runner, len(runner.test_dataloader), 'test')
+ runner.logger.info(log_str)
+ dump(tag, osp.join(runner.log_dir, self.json_log_path)) # type: ignore
+
+ def after_run(self, runner) -> None:
+ """Copy logs to ``self.out_dir`` if ``self.out_dir is not None``
+
+ Args:
+ runner (Runner): The runner of the training/testing/validation
+ process.
+ """
+ # copy or upload logs to self.out_dir
+ if self.out_dir is None:
+ return
+ for filename in scandir(runner._log_dir, self.out_suffix, True):
+ local_filepath = osp.join(runner._log_dir, filename)
+ out_filepath = self.file_backend.join_path(self.out_dir, filename)
+ with open(local_filepath) as f:
+ self.file_backend.put_text(f.read(), out_filepath)
+
+ runner.logger.info(
+ f'The file {local_filepath} has been uploaded to '
+ f'{out_filepath}.')
+
+ if not self.keep_local:
+ os.remove(local_filepath)
+ runner.logger.info(f'{local_filepath} was removed due to the '
+ '`self.keep_local=False`')
diff --git a/testbed/open-mmlab__mmengine/mmengine/hooks/naive_visualization_hook.py b/testbed/open-mmlab__mmengine/mmengine/hooks/naive_visualization_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..079a81ce05bbffeb658f8d670fe7f17b1c17617e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hooks/naive_visualization_hook.py
@@ -0,0 +1,90 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os.path as osp
+from typing import Optional, Sequence, Tuple, Union
+
+import cv2
+import numpy as np
+
+from mmengine.hooks import Hook
+from mmengine.registry import HOOKS
+from mmengine.utils.dl_utils import tensor2imgs
+
+DATA_BATCH = Optional[Union[dict, tuple, list]]
+
+
+# TODO: Due to interface changes, the current class
+# functions incorrectly
+@HOOKS.register_module()
+class NaiveVisualizationHook(Hook):
+ """Show or Write the predicted results during the process of testing.
+
+ Args:
+ interval (int): Visualization interval. Defaults to 1.
+ draw_gt (bool): Whether to draw the ground truth. Default to True.
+ draw_pred (bool): Whether to draw the predicted result.
+ Default to True.
+ """
+ priority = 'NORMAL'
+
+ def __init__(self,
+ interval: int = 1,
+ draw_gt: bool = True,
+ draw_pred: bool = True):
+ self.draw_gt = draw_gt
+ self.draw_pred = draw_pred
+ self._interval = interval
+
+ def _unpad(self, input: np.ndarray, unpad_shape: Tuple[int,
+ int]) -> np.ndarray:
+ """Unpad the input image.
+
+ Args:
+ input (np.ndarray): The image to unpad.
+ unpad_shape (tuple): The shape of image before padding.
+
+ Returns:
+ np.ndarray: The image before padding.
+ """
+ unpad_width, unpad_height = unpad_shape
+ unpad_image = input[:unpad_height, :unpad_width]
+ return unpad_image
+
+ def before_train(self, runner) -> None:
+ """Call add_graph method of visualizer.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ runner.visualizer.add_graph(runner.model, None)
+
+ def after_test_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None,
+ outputs: Optional[Sequence] = None) -> None:
+ """Show or Write the predicted results.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ batch_idx (int): The index of the current batch in the test loop.
+ data_batch (dict or tuple or list, optional): Data from dataloader.
+ outputs (Sequence, optional): Outputs from model.
+ """
+ if self.every_n_inner_iters(batch_idx, self._interval):
+ for data, output in zip(data_batch, outputs): # type: ignore
+ input = data['inputs']
+ data_sample = data['data_sample']
+ input = tensor2imgs(input,
+ **data_sample.get('img_norm_cfg',
+ dict()))[0]
+ # TODO We will implement a function to revert the augmentation
+ # in the future.
+ ori_shape = (data_sample.ori_width, data_sample.ori_height)
+ if 'pad_shape' in data_sample:
+ input = self._unpad(input,
+ data_sample.get('scale', ori_shape))
+ origin_image = cv2.resize(input, ori_shape)
+ name = osp.basename(data_sample.img_path)
+ runner.visualizer.add_datasample(name, origin_image,
+ data_sample, output,
+ self.draw_gt, self.draw_pred)
diff --git a/testbed/open-mmlab__mmengine/mmengine/hooks/param_scheduler_hook.py b/testbed/open-mmlab__mmengine/mmengine/hooks/param_scheduler_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb033ce4a56f524d2eab41fbaeff077968fd7891
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hooks/param_scheduler_hook.py
@@ -0,0 +1,80 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from typing import Optional, Union
+
+from mmengine.registry import HOOKS
+from .hook import Hook
+
+DATA_BATCH = Optional[Union[dict, tuple, list]]
+
+
+@HOOKS.register_module()
+class ParamSchedulerHook(Hook):
+ """A hook to update some hyper-parameters in optimizer, e.g., learning rate
+ and momentum."""
+
+ priority = 'LOW'
+
+ def after_train_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None,
+ outputs: Optional[dict] = None) -> None:
+ """Call step function for each scheduler after each iteration.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ batch_idx (int): The index of the current batch in the train loop.
+ data_batch (dict or tuple or list, optional): Data from dataloader.
+ In order to keep this interface consistent with other hooks,
+ we keep ``data_batch`` here.
+ outputs (dict, optional): Outputs from model.
+ In order to keep this interface consistent with other hooks, we
+ keep ``data_batch`` here.
+ """
+
+ def step(param_schedulers):
+ assert isinstance(param_schedulers, list)
+ for scheduler in param_schedulers:
+ if not scheduler.by_epoch:
+ scheduler.step()
+
+ if runner.param_schedulers is None:
+ return
+
+ if isinstance(runner.param_schedulers, list):
+ step(runner.param_schedulers)
+ elif isinstance(runner.param_schedulers, dict):
+ for param_schedulers in runner.param_schedulers.values():
+ step(param_schedulers)
+ else:
+ raise TypeError(
+ 'runner.param_schedulers should be list of ParamScheduler or '
+ 'a dict containing list of ParamScheduler, '
+ f'but got {runner.param_schedulers}')
+
+ def after_train_epoch(self, runner) -> None:
+ """Call step function for each scheduler after each epoch.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+
+ def step(param_schedulers):
+ assert isinstance(param_schedulers, list)
+ for scheduler in param_schedulers:
+ if scheduler.by_epoch:
+ scheduler.step()
+
+ if runner.param_schedulers is None:
+ return
+
+ if isinstance(runner.param_schedulers, list):
+ step(runner.param_schedulers)
+ elif isinstance(runner.param_schedulers, dict):
+ for param_schedulers in runner.param_schedulers.values():
+ step(param_schedulers)
+ else:
+ raise TypeError(
+ 'runner.param_schedulers should be list of ParamScheduler or '
+ 'a dict containing list of ParamScheduler, '
+ f'but got {runner.param_schedulers}')
diff --git a/testbed/open-mmlab__mmengine/mmengine/hooks/runtime_info_hook.py b/testbed/open-mmlab__mmengine/mmengine/hooks/runtime_info_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..64ecafa9fcd34d32d5ef7e7ede0b5da7b1f189aa
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hooks/runtime_info_hook.py
@@ -0,0 +1,131 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from typing import Dict, Optional, Union
+
+from mmengine.registry import HOOKS
+from mmengine.utils import get_git_hash
+from mmengine.version import __version__
+from .hook import Hook
+
+DATA_BATCH = Optional[Union[dict, tuple, list]]
+
+
+@HOOKS.register_module()
+class RuntimeInfoHook(Hook):
+ """A hook that updates runtime information into message hub.
+
+ E.g. ``epoch``, ``iter``, ``max_epochs``, and ``max_iters`` for the
+ training state. Components that cannot access the runner can get runtime
+ information through the message hub.
+ """
+
+ priority = 'VERY_HIGH'
+
+ def before_run(self, runner) -> None:
+ """Update metainfo.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ metainfo = dict(
+ cfg=runner.cfg.pretty_text,
+ seed=runner.seed,
+ experiment_name=runner.experiment_name,
+ mmengine_version=__version__ + get_git_hash())
+ runner.message_hub.update_info_dict(metainfo)
+
+ def before_train(self, runner) -> None:
+ """Update resumed training state.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ runner.message_hub.update_info('epoch', runner.epoch)
+ runner.message_hub.update_info('iter', runner.iter)
+ runner.message_hub.update_info('max_epochs', runner.max_epochs)
+ runner.message_hub.update_info('max_iters', runner.max_iters)
+ if hasattr(runner.train_dataloader.dataset, 'metainfo'):
+ runner.message_hub.update_info(
+ 'dataset_meta', runner.train_dataloader.dataset.metainfo)
+
+ def before_train_epoch(self, runner) -> None:
+ """Update current epoch information before every epoch.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ runner.message_hub.update_info('epoch', runner.epoch)
+
+ def before_train_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None) -> None:
+ """Update current iter and learning rate information before every
+ iteration.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ batch_idx (int): The index of the current batch in the train loop.
+ data_batch (Sequence[dict], optional): Data from dataloader.
+ Defaults to None.
+ """
+ runner.message_hub.update_info('iter', runner.iter)
+ lr_dict = runner.optim_wrapper.get_lr()
+ assert isinstance(lr_dict, dict), (
+ '`runner.optim_wrapper.get_lr()` should return a dict '
+ 'of learning rate when training with OptimWrapper(single '
+ 'optimizer) or OptimWrapperDict(multiple optimizer), '
+ f'but got {type(lr_dict)} please check your optimizer '
+ 'constructor return an `OptimWrapper` or `OptimWrapperDict` '
+ 'instance')
+ for name, lr in lr_dict.items():
+ runner.message_hub.update_scalar(f'train/{name}', lr[0])
+
+ def after_train_iter(self,
+ runner,
+ batch_idx: int,
+ data_batch: DATA_BATCH = None,
+ outputs: Optional[dict] = None) -> None:
+ """Update ``log_vars`` in model outputs every iteration.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ batch_idx (int): The index of the current batch in the train loop.
+ data_batch (Sequence[dict], optional): Data from dataloader.
+ Defaults to None.
+ outputs (dict, optional): Outputs from model. Defaults to None.
+ """
+ if outputs is not None:
+ for key, value in outputs.items():
+ runner.message_hub.update_scalar(f'train/{key}', value)
+
+ def after_val_epoch(self,
+ runner,
+ metrics: Optional[Dict[str, float]] = None) -> None:
+ """All subclasses should override this method, if they need any
+ operations after each validation epoch.
+
+ Args:
+ runner (Runner): The runner of the validation process.
+ metrics (Dict[str, float], optional): Evaluation results of all
+ metrics on validation dataset. The keys are the names of the
+ metrics, and the values are corresponding results.
+ """
+ if metrics is not None:
+ for key, value in metrics.items():
+ runner.message_hub.update_scalar(f'val/{key}', value)
+
+ def after_test_epoch(self,
+ runner,
+ metrics: Optional[Dict[str, float]] = None) -> None:
+ """All subclasses should override this method, if they need any
+ operations after each test epoch.
+
+ Args:
+ runner (Runner): The runner of the testing process.
+ metrics (Dict[str, float], optional): Evaluation results of all
+ metrics on test dataset. The keys are the names of the
+ metrics, and the values are corresponding results.
+ """
+ if metrics is not None:
+ for key, value in metrics.items():
+ runner.message_hub.update_scalar(f'test/{key}', value)
diff --git a/testbed/open-mmlab__mmengine/mmengine/hooks/sampler_seed_hook.py b/testbed/open-mmlab__mmengine/mmengine/hooks/sampler_seed_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..9aed9dbcf594fd23ca78dacaa4443d18d0ad41ce
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hooks/sampler_seed_hook.py
@@ -0,0 +1,36 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from mmengine.registry import HOOKS
+from .hook import Hook
+
+
+@HOOKS.register_module()
+class DistSamplerSeedHook(Hook):
+ """Data-loading sampler for distributed training.
+
+ When distributed training, it is only useful in conjunction with
+ :obj:`EpochBasedRunner`, while :obj:`IterBasedRunner` achieves the same
+ purpose with :obj:`IterLoader`.
+ """
+
+ priority = 'NORMAL'
+
+ def before_train_epoch(self, runner) -> None:
+ """Set the seed for sampler and batch_sampler.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ if hasattr(runner.train_loop.dataloader, 'sampler') and hasattr(
+ runner.train_loop.dataloader.sampler, 'set_epoch'):
+ # In case the` _SingleProcessDataLoaderIter` has no sampler,
+ # or data loader uses `SequentialSampler` in Pytorch.
+ runner.train_loop.dataloader.sampler.set_epoch(runner.epoch)
+
+ elif hasattr(runner.train_loop.dataloader,
+ 'batch_sampler') and hasattr(
+ runner.train_loop.dataloader.batch_sampler.sampler,
+ 'set_epoch'):
+ # In case the` _SingleProcessDataLoaderIter` has no batch sampler.
+ # batch sampler in pytorch warps the sampler as its attributes.
+ runner.train_loop.dataloader.batch_sampler.sampler.set_epoch(
+ runner.epoch)
diff --git a/testbed/open-mmlab__mmengine/mmengine/hooks/sync_buffer_hook.py b/testbed/open-mmlab__mmengine/mmengine/hooks/sync_buffer_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a88d960964f6aa79e4285dfb3d755c23e9baa0b
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hooks/sync_buffer_hook.py
@@ -0,0 +1,24 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from mmengine.dist import all_reduce_params, is_distributed
+from mmengine.registry import HOOKS
+from .hook import Hook
+
+
+@HOOKS.register_module()
+class SyncBuffersHook(Hook):
+ """Synchronize model buffers such as running_mean and running_var in BN at
+ the end of each epoch."""
+
+ priority = 'NORMAL'
+
+ def __init__(self) -> None:
+ self.distributed = is_distributed()
+
+ def after_train_epoch(self, runner) -> None:
+ """All-reduce model buffers at the end of each epoch.
+
+ Args:
+ runner (Runner): The runner of the training process.
+ """
+ if self.distributed:
+ all_reduce_params(runner.model.buffers(), op='mean')
diff --git a/testbed/open-mmlab__mmengine/mmengine/hub/__init__.py b/testbed/open-mmlab__mmengine/mmengine/hub/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6f2add99c96c9401df11cafda2283f80353e5f1
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hub/__init__.py
@@ -0,0 +1,4 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .hub import get_config, get_model
+
+__all__ = ['get_config', 'get_model']
diff --git a/testbed/open-mmlab__mmengine/mmengine/hub/deprecated.json b/testbed/open-mmlab__mmengine/mmengine/hub/deprecated.json
new file mode 100644
index 0000000000000000000000000000000000000000..473a57c0eeedd666c2adad3cf3775851db033c83
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hub/deprecated.json
@@ -0,0 +1,6 @@
+{
+ "resnet50_caffe": "detectron/resnet50_caffe",
+ "resnet50_caffe_bgr": "detectron2/resnet50_caffe_bgr",
+ "resnet101_caffe": "detectron/resnet101_caffe",
+ "resnet101_caffe_bgr": "detectron2/resnet101_caffe_bgr"
+ }
diff --git a/testbed/open-mmlab__mmengine/mmengine/hub/hub.py b/testbed/open-mmlab__mmengine/mmengine/hub/hub.py
new file mode 100644
index 0000000000000000000000000000000000000000..b24ac2c125143789c8553086eec7767b9c761c41
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hub/hub.py
@@ -0,0 +1,89 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import importlib
+import os.path as osp
+
+from mmengine.config import Config
+from mmengine.config.utils import (_get_cfg_metainfo,
+ _get_external_cfg_base_path,
+ _get_package_and_cfg_path)
+from mmengine.registry import MODELS, DefaultScope
+from mmengine.runner import load_checkpoint
+from mmengine.utils import get_installed_path, install_package
+
+
+def get_config(cfg_path: str, pretrained: bool = False) -> Config:
+ """Get config from external package.
+
+ Args:
+ cfg_path (str): External relative config path.
+ pretrained (bool): Whether to save pretrained model path. If
+ ``pretrained==True``, the url of pretrained model can be accessed
+ by ``cfg.model_path``. Defaults to False.
+
+ Examples:
+ >>> cfg = get_config('mmdet::faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py', pretrained=True)
+ >>> # Equivalent to
+ >>> # cfg = Config.fromfile('/path/to/faster-rcnn_r50_fpn_1x_coco.py')
+ >>> cfg.model_path
+ https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth
+
+ Returns:
+ Config: A `Config` parsed from external package.
+ """ # noqa E301
+ # Get package name and relative config path.
+ package, cfg_path = _get_package_and_cfg_path(cfg_path)
+ # Install package if it's not installed.
+ install_package(package)
+ package_path = get_installed_path(package)
+ try:
+ # Use `cfg_path` to search target config file.
+ cfg_meta = _get_cfg_metainfo(package_path, cfg_path)
+ cfg_path = osp.join(package_path, '.mim', cfg_meta['Config'])
+ cfg = Config.fromfile(cfg_path)
+ if pretrained:
+ assert 'Weights' in cfg_meta, ('Cannot find `Weights` in cfg_file'
+ '.metafile.yml, please check the'
+ 'metafile')
+ cfg.model_path = cfg_meta['Weights']
+ except ValueError:
+ # Since the base config does not contain a metafile, the absolute
+ # config is `osp.join(package_path, cfg_path_prefix, cfg_name)`
+ cfg_path = _get_external_cfg_base_path(package_path, cfg_path)
+ cfg = Config.fromfile(cfg_path)
+ except Exception as e:
+ raise e
+ return cfg
+
+
+def get_model(cfg_path: str, pretrained: bool = False, **kwargs):
+ """Get built model from external package.
+
+ Args:
+ cfg_path (str): External relative config path with prefix
+ 'package::' and without suffix.
+ pretrained (bool): Whether to load pretrained model. Defaults to False.
+ kwargs (dict): Default arguments to build model.
+
+ Examples:
+ >>> model = get_model('mmdet::faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py', pretrained=True)
+ >>> type(model)
+
+
+ Returns:
+ nn.Module: Built model.
+ """ # noqa E301
+ package = cfg_path.split('::')[0]
+ with DefaultScope.overwrite_default_scope(package): # type: ignore
+ cfg = get_config(cfg_path, pretrained)
+ if 'data_preprocessor' in cfg:
+ cfg.model.data_preprocessor = cfg.data_preprocessor
+ models_module = importlib.import_module(f'{package}.utils')
+ models_module.register_all_modules() # type: ignore
+ model = MODELS.build(cfg.model, default_args=kwargs)
+ if pretrained:
+ load_checkpoint(model, cfg.model_path)
+ # Hack to use pretrained weights.
+ # If we do not set _is_init here, Runner will call
+ # `model.init_weights()` to overwrite the pretrained model.
+ model._is_init = True
+ return model
diff --git a/testbed/open-mmlab__mmengine/mmengine/hub/mmcls.json b/testbed/open-mmlab__mmengine/mmengine/hub/mmcls.json
new file mode 100644
index 0000000000000000000000000000000000000000..071db8709c42fb386f961c3b14e9583eb51ad2c9
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hub/mmcls.json
@@ -0,0 +1,59 @@
+{
+ "vgg11": "https://download.openmmlab.com/mmclassification/v0/vgg/vgg11_batch256_imagenet_20210208-4271cd6c.pth",
+ "vgg13": "https://download.openmmlab.com/mmclassification/v0/vgg/vgg13_batch256_imagenet_20210208-4d1d6080.pth",
+ "vgg16": "https://download.openmmlab.com/mmclassification/v0/vgg/vgg16_batch256_imagenet_20210208-db26f1a5.pth",
+ "vgg19": "https://download.openmmlab.com/mmclassification/v0/vgg/vgg19_batch256_imagenet_20210208-e6920e4a.pth",
+ "vgg11_bn": "https://download.openmmlab.com/mmclassification/v0/vgg/vgg11_bn_batch256_imagenet_20210207-f244902c.pth",
+ "vgg13_bn": "https://download.openmmlab.com/mmclassification/v0/vgg/vgg13_bn_batch256_imagenet_20210207-1a8b7864.pth",
+ "vgg16_bn": "https://download.openmmlab.com/mmclassification/v0/vgg/vgg16_bn_batch256_imagenet_20210208-7e55cd29.pth",
+ "vgg19_bn": "https://download.openmmlab.com/mmclassification/v0/vgg/vgg19_bn_batch256_imagenet_20210208-da620c4f.pth",
+ "resnet18": "https://download.openmmlab.com/mmclassification/v0/resnet/resnet18_8xb32_in1k_20210831-fbbb1da6.pth",
+ "resnet34": "https://download.openmmlab.com/mmclassification/v0/resnet/resnet34_8xb32_in1k_20210831-f257d4e6.pth",
+ "resnet50": "https://download.openmmlab.com/mmclassification/v0/resnet/resnet50_8xb32_in1k_20210831-ea4938fc.pth",
+ "resnet101": "https://download.openmmlab.com/mmclassification/v0/resnet/resnet101_8xb32_in1k_20210831-539c63f8.pth",
+ "resnet152": "https://download.openmmlab.com/mmclassification/v0/resnet/resnet152_8xb32_in1k_20210901-4d7582fa.pth",
+ "resnet50_v1d": "https://download.openmmlab.com/mmclassification/v0/resnet/resnetv1d50_b32x8_imagenet_20210531-db14775a.pth",
+ "resnet101_v1d": "https://download.openmmlab.com/mmclassification/v0/resnet/resnetv1d101_b32x8_imagenet_20210531-6e13bcd3.pth",
+ "resnet152_v1d": "https://download.openmmlab.com/mmclassification/v0/resnet/resnetv1d152_b32x8_imagenet_20210531-278cf22a.pth",
+ "resnext50_32x4d": "https://download.openmmlab.com/mmclassification/v0/resnext/resnext50_32x4d_b32x8_imagenet_20210429-56066e27.pth",
+ "resnext101_32x4d": "https://download.openmmlab.com/mmclassification/v0/resnext/resnext101_32x4d_b32x8_imagenet_20210506-e0fa3dd5.pth",
+ "resnext101_32x8d": "https://download.openmmlab.com/mmclassification/v0/resnext/resnext101_32x8d_b32x8_imagenet_20210506-23a247d5.pth",
+ "resnext152_32x4d": "https://download.openmmlab.com/mmclassification/v0/resnext/resnext152_32x4d_b32x8_imagenet_20210524-927787be.pth",
+ "se-resnet50": "https://download.openmmlab.com/mmclassification/v0/se-resnet/se-resnet50_batch256_imagenet_20200804-ae206104.pth",
+ "se-resnet101": "https://download.openmmlab.com/mmclassification/v0/se-resnet/se-resnet101_batch256_imagenet_20200804-ba5b51d4.pth",
+ "resnest50": "https://download.openmmlab.com/mmclassification/v0/resnest/resnest50_imagenet_converted-1ebf0afe.pth",
+ "resnest101": "https://download.openmmlab.com/mmclassification/v0/resnest/resnest101_imagenet_converted-032caa52.pth",
+ "resnest200": "https://download.openmmlab.com/mmclassification/v0/resnest/resnest200_imagenet_converted-581a60f2.pth",
+ "resnest269": "https://download.openmmlab.com/mmclassification/v0/resnest/resnest269_imagenet_converted-59930960.pth",
+ "shufflenet_v1": "https://download.openmmlab.com/mmclassification/v0/shufflenet_v1/shufflenet_v1_batch1024_imagenet_20200804-5d6cec73.pth",
+ "shufflenet_v2": "https://download.openmmlab.com/mmclassification/v0/shufflenet_v2/shufflenet_v2_batch1024_imagenet_20200812-5bf4721e.pth",
+ "mobilenet_v2": "https://download.openmmlab.com/mmclassification/v0/mobilenet_v2/mobilenet_v2_batch256_imagenet_20200708-3b2dc3af.pth",
+ "mobilenet_v3_small": "https://download.openmmlab.com/mmclassification/v0/mobilenet_v3/convert/mobilenet_v3_small-8427ecf0.pth",
+ "mobilenet_v3_large": "https://download.openmmlab.com/mmclassification/v0/mobilenet_v3/convert/mobilenet_v3_large-3ea3c186.pth",
+ "repvgg_A0": "https://download.openmmlab.com/mmclassification/v0/repvgg/repvgg-A0_3rdparty_4xb64-coslr-120e_in1k_20210909-883ab98c.pth",
+ "repvgg_A1": "https://download.openmmlab.com/mmclassification/v0/repvgg/repvgg-A1_3rdparty_4xb64-coslr-120e_in1k_20210909-24003a24.pth",
+ "repvgg_A2": "https://download.openmmlab.com/mmclassification/v0/repvgg/repvgg-A2_3rdparty_4xb64-coslr-120e_in1k_20210909-97d7695a.pth",
+ "repvgg_B0": "https://download.openmmlab.com/mmclassification/v0/repvgg/repvgg-B0_3rdparty_4xb64-coslr-120e_in1k_20210909-446375f4.pth",
+ "repvgg_B1": "https://download.openmmlab.com/mmclassification/v0/repvgg/repvgg-B1_3rdparty_4xb64-coslr-120e_in1k_20210909-750cdf67.pth",
+ "repvgg_B1g2": "https://download.openmmlab.com/mmclassification/v0/repvgg/repvgg-B1g2_3rdparty_4xb64-coslr-120e_in1k_20210909-344f6422.pth",
+ "repvgg_B1g4": "https://download.openmmlab.com/mmclassification/v0/repvgg/repvgg-B1g4_3rdparty_4xb64-coslr-120e_in1k_20210909-d4c1a642.pth",
+ "repvgg_B2": "https://download.openmmlab.com/mmclassification/v0/repvgg/repvgg-B2_3rdparty_4xb64-coslr-120e_in1k_20210909-bd6b937c.pth",
+ "repvgg_B2g4": "https://download.openmmlab.com/mmclassification/v0/repvgg/repvgg-B2g4_3rdparty_4xb64-autoaug-lbs-mixup-coslr-200e_in1k_20210909-7b7955f0.pth",
+ "repvgg_B3": "https://download.openmmlab.com/mmclassification/v0/repvgg/repvgg-B3_3rdparty_4xb64-autoaug-lbs-mixup-coslr-200e_in1k_20210909-dda968bf.pth",
+ "repvgg_B3g4": "https://download.openmmlab.com/mmclassification/v0/repvgg/repvgg-B3g4_3rdparty_4xb64-autoaug-lbs-mixup-coslr-200e_in1k_20210909-4e54846a.pth",
+ "repvgg_D2se": "https://download.openmmlab.com/mmclassification/v0/repvgg/repvgg-D2se_3rdparty_4xb64-autoaug-lbs-mixup-coslr-200e_in1k_20210909-cf3139b7.pth",
+ "res2net101_w26": "https://download.openmmlab.com/mmclassification/v0/res2net/res2net101-w26-s4_3rdparty_8xb32_in1k_20210927-870b6c36.pth",
+ "res2net50_w14": "https://download.openmmlab.com/mmclassification/v0/res2net/res2net50-w14-s8_3rdparty_8xb32_in1k_20210927-bc967bf1.pth",
+ "res2net50_w26": "https://download.openmmlab.com/mmclassification/v0/res2net/res2net50-w26-s8_3rdparty_8xb32_in1k_20210927-f547a94b.pth",
+ "swin_tiny": "https://download.openmmlab.com/mmclassification/v0/swin-transformer/swin_tiny_224_b16x64_300e_imagenet_20210616_090925-66df6be6.pth",
+ "swin_small": "https://download.openmmlab.com/mmclassification/v0/swin-transformer/swin_small_224_b16x64_300e_imagenet_20210615_110219-7f9d988b.pth",
+ "swin_base": "https://download.openmmlab.com/mmclassification/v0/swin-transformer/convert/swin_base_patch4_window7_224_22kto1k-f967f799.pth",
+ "swin_large": "https://download.openmmlab.com/mmclassification/v0/swin-transformer/convert/swin_large_patch4_window7_224_22kto1k-5f0996db.pth",
+ "t2t_vit_t_14": "https://download.openmmlab.com/mmclassification/v0/t2t-vit/t2t-vit-t-14_3rdparty_8xb64_in1k_20210928-b7c09b62.pth",
+ "t2t_vit_t_19": "https://download.openmmlab.com/mmclassification/v0/t2t-vit/t2t-vit-t-19_3rdparty_8xb64_in1k_20210928-7f1478d5.pth",
+ "t2t_vit_t_24": "https://download.openmmlab.com/mmclassification/v0/t2t-vit/t2t-vit-t-24_3rdparty_8xb64_in1k_20210928-fe95a61b.pth",
+ "tnt_small": "https://download.openmmlab.com/mmclassification/v0/tnt/tnt-small-p16_3rdparty_in1k_20210903-c56ee7df.pth",
+ "vit_base_p16": "https://download.openmmlab.com/mmclassification/v0/vit/finetune/vit-base-p16_in21k-pre-3rdparty_ft-64xb64_in1k-384_20210928-98e8652b.pth",
+ "vit_base_p32": "https://download.openmmlab.com/mmclassification/v0/vit/finetune/vit-base-p32_in21k-pre-3rdparty_ft-64xb64_in1k-384_20210928-9cea8599.pth",
+ "vit_large_p16": "https://download.openmmlab.com/mmclassification/v0/vit/finetune/vit-large-p16_in21k-pre-3rdparty_ft-64xb64_in1k-384_20210928-b20ba619.pth"
+ }
diff --git a/testbed/open-mmlab__mmengine/mmengine/hub/openmmlab.json b/testbed/open-mmlab__mmengine/mmengine/hub/openmmlab.json
new file mode 100644
index 0000000000000000000000000000000000000000..0966212ef32a656aafe76c2956def67899937455
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hub/openmmlab.json
@@ -0,0 +1,50 @@
+{
+ "vgg16_caffe": "https://download.openmmlab.com/pretrain/third_party/vgg16_caffe-292e1171.pth",
+ "detectron/resnet50_caffe": "https://download.openmmlab.com/pretrain/third_party/resnet50_caffe-788b5fa3.pth",
+ "detectron2/resnet50_caffe": "https://download.openmmlab.com/pretrain/third_party/resnet50_msra-5891d200.pth",
+ "detectron/resnet101_caffe": "https://download.openmmlab.com/pretrain/third_party/resnet101_caffe-3ad79236.pth",
+ "detectron2/resnet101_caffe": "https://download.openmmlab.com/pretrain/third_party/resnet101_msra-6cc46731.pth",
+ "detectron2/resnext101_32x8d": "https://download.openmmlab.com/pretrain/third_party/resnext101_32x8d-1516f1aa.pth",
+ "resnext50_32x4d": "https://download.openmmlab.com/pretrain/third_party/resnext50-32x4d-0ab1a123.pth",
+ "resnext101_32x4d": "https://download.openmmlab.com/pretrain/third_party/resnext101_32x4d-a5af3160.pth",
+ "resnext101_64x4d": "https://download.openmmlab.com/pretrain/third_party/resnext101_64x4d-ee2c6f71.pth",
+ "contrib/resnet50_gn": "https://download.openmmlab.com/pretrain/third_party/resnet50_gn_thangvubk-ad1730dd.pth",
+ "detectron/resnet50_gn": "https://download.openmmlab.com/pretrain/third_party/resnet50_gn-9186a21c.pth",
+ "detectron/resnet101_gn": "https://download.openmmlab.com/pretrain/third_party/resnet101_gn-cac0ab98.pth",
+ "jhu/resnet50_gn_ws": "https://download.openmmlab.com/pretrain/third_party/resnet50_gn_ws-15beedd8.pth",
+ "jhu/resnet101_gn_ws": "https://download.openmmlab.com/pretrain/third_party/resnet101_gn_ws-3e3c308c.pth",
+ "jhu/resnext50_32x4d_gn_ws": "https://download.openmmlab.com/pretrain/third_party/resnext50_32x4d_gn_ws-0d87ac85.pth",
+ "jhu/resnext101_32x4d_gn_ws": "https://download.openmmlab.com/pretrain/third_party/resnext101_32x4d_gn_ws-34ac1a9e.pth",
+ "jhu/resnext50_32x4d_gn": "https://download.openmmlab.com/pretrain/third_party/resnext50_32x4d_gn-c7e8b754.pth",
+ "jhu/resnext101_32x4d_gn": "https://download.openmmlab.com/pretrain/third_party/resnext101_32x4d_gn-ac3bb84e.pth",
+ "msra/hrnetv2_w18_small": "https://download.openmmlab.com/pretrain/third_party/hrnetv2_w18_small-b5a04e21.pth",
+ "msra/hrnetv2_w18": "https://download.openmmlab.com/pretrain/third_party/hrnetv2_w18-00eb2006.pth",
+ "msra/hrnetv2_w32": "https://download.openmmlab.com/pretrain/third_party/hrnetv2_w32-dc9eeb4f.pth",
+ "msra/hrnetv2_w40": "https://download.openmmlab.com/pretrain/third_party/hrnetv2_w40-ed0b031c.pth",
+ "msra/hrnetv2_w48": "https://download.openmmlab.com/pretrain/third_party/hrnetv2_w48-d2186c55.pth",
+ "bninception_caffe": "https://download.openmmlab.com/pretrain/third_party/bn_inception_caffe-ed2e8665.pth",
+ "kin400/i3d_r50_f32s2_k400": "https://download.openmmlab.com/pretrain/third_party/i3d_r50_f32s2_k400-2c57e077.pth",
+ "kin400/nl3d_r50_f32s2_k400": "https://download.openmmlab.com/pretrain/third_party/nl3d_r50_f32s2_k400-fa7e7caa.pth",
+ "res2net101_v1d_26w_4s": "https://download.openmmlab.com/pretrain/third_party/res2net101_v1d_26w_4s_mmdetv2-f0a600f9.pth",
+ "regnetx_400mf": "https://download.openmmlab.com/pretrain/third_party/regnetx_400mf-a5b10d96.pth",
+ "regnetx_800mf": "https://download.openmmlab.com/pretrain/third_party/regnetx_800mf-1f4be4c7.pth",
+ "regnetx_1.6gf": "https://download.openmmlab.com/pretrain/third_party/regnetx_1.6gf-5791c176.pth",
+ "regnetx_3.2gf": "https://download.openmmlab.com/pretrain/third_party/regnetx_3.2gf-c2599b0f.pth",
+ "regnetx_4.0gf": "https://download.openmmlab.com/pretrain/third_party/regnetx_4.0gf-a88f671e.pth",
+ "regnetx_6.4gf": "https://download.openmmlab.com/pretrain/third_party/regnetx_6.4gf-006af45d.pth",
+ "regnetx_8.0gf": "https://download.openmmlab.com/pretrain/third_party/regnetx_8.0gf-3c68abe7.pth",
+ "regnetx_12gf": "https://download.openmmlab.com/pretrain/third_party/regnetx_12gf-4c2a3350.pth",
+ "resnet18_v1c": "https://download.openmmlab.com/pretrain/third_party/resnet18_v1c-b5776b93.pth",
+ "resnet50_v1c": "https://download.openmmlab.com/pretrain/third_party/resnet50_v1c-2cccc1ad.pth",
+ "resnet101_v1c": "https://download.openmmlab.com/pretrain/third_party/resnet101_v1c-e67eebb6.pth",
+ "mmedit/vgg16": "https://download.openmmlab.com/mmediting/third_party/vgg_state_dict.pth",
+ "mmedit/res34_en_nomixup": "https://download.openmmlab.com/mmediting/third_party/model_best_resnet34_En_nomixup.pth",
+ "mmedit/mobilenet_v2": "https://download.openmmlab.com/mmediting/third_party/mobilenet_v2.pth",
+ "contrib/mobilenet_v3_large": "https://download.openmmlab.com/pretrain/third_party/mobilenet_v3_large-bc2c3fd3.pth",
+ "contrib/mobilenet_v3_small": "https://download.openmmlab.com/pretrain/third_party/mobilenet_v3_small-47085aa1.pth",
+ "resnest50": "https://download.openmmlab.com/pretrain/third_party/resnest50_d2-7497a55b.pth",
+ "resnest101": "https://download.openmmlab.com/pretrain/third_party/resnest101_d2-f3b931b2.pth",
+ "resnest200": "https://download.openmmlab.com/pretrain/third_party/resnest200_d2-ca88e41f.pth",
+ "darknet53": "https://download.openmmlab.com/pretrain/third_party/darknet53-a628ea1b.pth",
+ "mmdet/mobilenet_v2": "https://download.openmmlab.com/mmdetection/v2.0/third_party/mobilenet_v2_batch256_imagenet-ff34753d.pth"
+ }
diff --git a/testbed/open-mmlab__mmengine/mmengine/hub/torchvision_0.12.json b/testbed/open-mmlab__mmengine/mmengine/hub/torchvision_0.12.json
new file mode 100644
index 0000000000000000000000000000000000000000..06defe67484dff91cf6f69109324cb1dd9d64bc3
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/hub/torchvision_0.12.json
@@ -0,0 +1,57 @@
+{
+ "alexnet": "https://download.pytorch.org/models/alexnet-owt-7be5be79.pth",
+ "densenet121": "https://download.pytorch.org/models/densenet121-a639ec97.pth",
+ "densenet169": "https://download.pytorch.org/models/densenet169-b2777c0a.pth",
+ "densenet201": "https://download.pytorch.org/models/densenet201-c1103571.pth",
+ "densenet161": "https://download.pytorch.org/models/densenet161-8d451a50.pth",
+ "efficientnet_b0": "https://download.pytorch.org/models/efficientnet_b0_rwightman-3dd342df.pth",
+ "efficientnet_b1": "https://download.pytorch.org/models/efficientnet_b1_rwightman-533bc792.pth",
+ "efficientnet_b2": "https://download.pytorch.org/models/efficientnet_b2_rwightman-bcdf34b7.pth",
+ "efficientnet_b3": "https://download.pytorch.org/models/efficientnet_b3_rwightman-cf984f9c.pth",
+ "efficientnet_b4": "https://download.pytorch.org/models/efficientnet_b4_rwightman-7eb33cd5.pth",
+ "efficientnet_b5": "https://download.pytorch.org/models/efficientnet_b5_lukemelas-b6417697.pth",
+ "efficientnet_b6": "https://download.pytorch.org/models/efficientnet_b6_lukemelas-c76e70fd.pth",
+ "efficientnet_b7": "https://download.pytorch.org/models/efficientnet_b7_lukemelas-dcc49843.pth",
+ "googlenet": "https://download.pytorch.org/models/googlenet-1378be20.pth",
+ "inception_v3_google": "https://download.pytorch.org/models/inception_v3_google-0cc3c7bd.pth",
+ "mobilenet_v2": "https://download.pytorch.org/models/mobilenet_v2-b0353104.pth",
+ "mobilenet_v3_large": "https://download.pytorch.org/models/mobilenet_v3_large-8738ca79.pth",
+ "mobilenet_v3_small": "https://download.pytorch.org/models/mobilenet_v3_small-047dcff4.pth",
+ "regnet_y_400mf": "https://download.pytorch.org/models/regnet_y_400mf-c65dace8.pth",
+ "regnet_y_800mf": "https://download.pytorch.org/models/regnet_y_800mf-1b27b58c.pth",
+ "regnet_y_1_6gf": "https://download.pytorch.org/models/regnet_y_1_6gf-b11a554e.pth",
+ "regnet_y_3_2gf": "https://download.pytorch.org/models/regnet_y_3_2gf-b5a9779c.pth",
+ "regnet_y_8gf": "https://download.pytorch.org/models/regnet_y_8gf-d0d0e4a8.pth",
+ "regnet_y_16gf": "https://download.pytorch.org/models/regnet_y_16gf-9e6ed7dd.pth",
+ "regnet_y_32gf": "https://download.pytorch.org/models/regnet_y_32gf-4dee3f7a.pth",
+ "regnet_x_400mf": "https://download.pytorch.org/models/regnet_x_400mf-adf1edd5.pth",
+ "regnet_x_800mf": "https://download.pytorch.org/models/regnet_x_800mf-ad17e45c.pth",
+ "regnet_x_1_6gf": "https://download.pytorch.org/models/regnet_x_1_6gf-e3633e7f.pth",
+ "regnet_x_3_2gf": "https://download.pytorch.org/models/regnet_x_3_2gf-f342aeae.pth",
+ "regnet_x_8gf": "https://download.pytorch.org/models/regnet_x_8gf-03ceed89.pth",
+ "regnet_x_16gf": "https://download.pytorch.org/models/regnet_x_16gf-2007eb11.pth",
+ "regnet_x_32gf": "https://download.pytorch.org/models/regnet_x_32gf-9d47f8d0.pth",
+ "resnet18": "https://download.pytorch.org/models/resnet18-f37072fd.pth",
+ "resnet34": "https://download.pytorch.org/models/resnet34-b627a593.pth",
+ "resnet50": "https://download.pytorch.org/models/resnet50-0676ba61.pth",
+ "resnet101": "https://download.pytorch.org/models/resnet101-63fe2227.pth",
+ "resnet152": "https://download.pytorch.org/models/resnet152-394f9c45.pth",
+ "resnext50_32x4d": "https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth",
+ "resnext101_32x8d": "https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth",
+ "wide_resnet50_2": "https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth",
+ "wide_resnet101_2": "https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth",
+ "shufflenetv2_x0.5": "https://download.pytorch.org/models/shufflenetv2_x0.5-f707e7126e.pth",
+ "shufflenetv2_x1.0": "https://download.pytorch.org/models/shufflenetv2_x1-5666bf0f80.pth",
+ "shufflenetv2_x1.5": null,
+ "shufflenetv2_x2.0": null,
+ "squeezenet1_0": "https://download.pytorch.org/models/squeezenet1_0-b66bff10.pth",
+ "squeezenet1_1": "https://download.pytorch.org/models/squeezenet1_1-b8a52dc0.pth",
+ "vgg11": "https://download.pytorch.org/models/vgg11-8a719046.pth",
+ "vgg13": "https://download.pytorch.org/models/vgg13-19584684.pth",
+ "vgg16": "https://download.pytorch.org/models/vgg16-397923af.pth",
+ "vgg19": "https://download.pytorch.org/models/vgg19-dcbb9e9d.pth",
+ "vgg11_bn": "https://download.pytorch.org/models/vgg11_bn-6002323d.pth",
+ "vgg13_bn": "https://download.pytorch.org/models/vgg13_bn-abd245e5.pth",
+ "vgg16_bn": "https://download.pytorch.org/models/vgg16_bn-6c64b313.pth",
+ "vgg19_bn": "https://download.pytorch.org/models/vgg19_bn-c79401a0.pth"
+}
diff --git a/testbed/open-mmlab__mmengine/mmengine/logging/__init__.py b/testbed/open-mmlab__mmengine/mmengine/logging/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba5533c2363f49c749d0dba87f49496e3861ed80
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/logging/__init__.py
@@ -0,0 +1,6 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .history_buffer import HistoryBuffer
+from .logger import MMLogger, print_log
+from .message_hub import MessageHub
+
+__all__ = ['HistoryBuffer', 'MessageHub', 'MMLogger', 'print_log']
diff --git a/testbed/open-mmlab__mmengine/mmengine/logging/history_buffer.py b/testbed/open-mmlab__mmengine/mmengine/logging/history_buffer.py
new file mode 100644
index 0000000000000000000000000000000000000000..34a78ac616f281887fab10e5d7d30afb91d80fa7
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/logging/history_buffer.py
@@ -0,0 +1,209 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import warnings
+from typing import Any, Callable, Optional, Sequence, Tuple, Union
+
+import numpy as np
+
+
+class HistoryBuffer:
+ """Unified storage format for different log types.
+
+ ``HistoryBuffer`` records the history of log for further statistics.
+
+ Examples:
+ >>> history_buffer = HistoryBuffer()
+ >>> # Update history_buffer.
+ >>> history_buffer.update(1)
+ >>> history_buffer.update(2)
+ >>> history_buffer.min() # minimum of (1, 2)
+ 1
+ >>> history_buffer.max() # maximum of (1, 2)
+ 2
+ >>> history_buffer.mean() # mean of (1, 2)
+ 1.5
+ >>> history_buffer.statistics('mean') # access method by string.
+ 1.5
+
+ Args:
+ log_history (Sequence): History logs. Defaults to [].
+ count_history (Sequence): Counts of history logs. Defaults to [].
+ max_length (int): The max length of history logs. Defaults to 1000000.
+ """
+ _statistics_methods: dict = dict()
+
+ def __init__(self,
+ log_history: Sequence = [],
+ count_history: Sequence = [],
+ max_length: int = 1000000):
+
+ self.max_length = max_length
+ self._set_default_statistics()
+ assert len(log_history) == len(count_history), \
+ 'The lengths of log_history and count_histroy should be equal'
+ if len(log_history) > max_length:
+ warnings.warn(f'The length of history buffer({len(log_history)}) '
+ f'exceeds the max_length({max_length}), the first '
+ 'few elements will be ignored.')
+ self._log_history = np.array(log_history[-max_length:])
+ self._count_history = np.array(count_history[-max_length:])
+ else:
+ self._log_history = np.array(log_history)
+ self._count_history = np.array(count_history)
+
+ def _set_default_statistics(self) -> None:
+ """Register default statistic methods: min, max, current and mean."""
+ self._statistics_methods.setdefault('min', HistoryBuffer.min)
+ self._statistics_methods.setdefault('max', HistoryBuffer.max)
+ self._statistics_methods.setdefault('current', HistoryBuffer.current)
+ self._statistics_methods.setdefault('mean', HistoryBuffer.mean)
+
+ def update(self, log_val: Union[int, float], count: int = 1) -> None:
+ """update the log history.
+
+ If the length of the buffer exceeds ``self._max_length``, the oldest
+ element will be removed from the buffer.
+
+ Args:
+ log_val (int or float): The value of log.
+ count (int): The accumulation times of log, defaults to 1.
+ ``count`` will be used in smooth statistics.
+ """
+ if (not isinstance(log_val, (int, float))
+ or not isinstance(count, (int, float))):
+ raise TypeError(f'log_val must be int or float but got '
+ f'{type(log_val)}, count must be int but got '
+ f'{type(count)}')
+ self._log_history = np.append(self._log_history, log_val)
+ self._count_history = np.append(self._count_history, count)
+ if len(self._log_history) > self.max_length:
+ self._log_history = self._log_history[-self.max_length:]
+ self._count_history = self._count_history[-self.max_length:]
+
+ @property
+ def data(self) -> Tuple[np.ndarray, np.ndarray]:
+ """Get the ``_log_history`` and ``_count_history``.
+
+ Returns:
+ Tuple[np.ndarray, np.ndarray]: History logs and the counts of
+ the history logs.
+ """
+ return self._log_history, self._count_history
+
+ @classmethod
+ def register_statistics(cls, method: Callable) -> Callable:
+ """Register custom statistics method to ``_statistics_methods``.
+
+ The registered method can be called by ``history_buffer.statistics``
+ with corresponding method name and arguments.
+
+ Examples:
+ >>> @HistoryBuffer.register_statistics
+ >>> def weighted_mean(self, window_size, weight):
+ >>> assert len(weight) == window_size
+ >>> return (self._log_history[-window_size:] *
+ >>> np.array(weight)).sum() / \
+ >>> self._count_history[-window_size:]
+
+ >>> log_buffer = HistoryBuffer([1, 2], [1, 1])
+ >>> log_buffer.statistics('weighted_mean', 2, [2, 1])
+ 2
+
+ Args:
+ method (Callable): Custom statistics method.
+ Returns:
+ Callable: Original custom statistics method.
+ """
+ method_name = method.__name__
+ assert method_name not in cls._statistics_methods, \
+ 'method_name cannot be registered twice!'
+ cls._statistics_methods[method_name] = method
+ return method
+
+ def statistics(self, method_name: str, *arg, **kwargs) -> Any:
+ """Access statistics method by name.
+
+ Args:
+ method_name (str): Name of method.
+
+ Returns:
+ Any: Depends on corresponding method.
+ """
+ if method_name not in self._statistics_methods:
+ raise KeyError(f'{method_name} has not been registered in '
+ 'HistoryBuffer._statistics_methods')
+ method = self._statistics_methods[method_name]
+ # Provide self arguments for registered functions.
+ return method(self, *arg, **kwargs)
+
+ def mean(self, window_size: Optional[int] = None) -> np.ndarray:
+ """Return the mean of the latest ``window_size`` values in log
+ histories.
+
+ If ``window_size is None`` or ``window_size > len(self._log_history)``,
+ return the global mean value of history logs.
+
+ Args:
+ window_size (int, optional): Size of statistics window.
+ Returns:
+ np.ndarray: Mean value within the window.
+ """
+ if window_size is not None:
+ assert isinstance(window_size, int), \
+ 'The type of window size should be int, but got ' \
+ f'{type(window_size)}'
+ else:
+ window_size = len(self._log_history)
+ logs_sum = self._log_history[-window_size:].sum()
+ counts_sum = self._count_history[-window_size:].sum()
+ return logs_sum / counts_sum
+
+ def max(self, window_size: Optional[int] = None) -> np.ndarray:
+ """Return the maximum value of the latest ``window_size`` values in log
+ histories.
+
+ If ``window_size is None`` or ``window_size > len(self._log_history)``,
+ return the global maximum value of history logs.
+
+ Args:
+ window_size (int, optional): Size of statistics window.
+ Returns:
+ np.ndarray: The maximum value within the window.
+ """
+ if window_size is not None:
+ assert isinstance(window_size, int), \
+ 'The type of window size should be int, but got ' \
+ f'{type(window_size)}'
+ else:
+ window_size = len(self._log_history)
+ return self._log_history[-window_size:].max()
+
+ def min(self, window_size: Optional[int] = None) -> np.ndarray:
+ """Return the minimum value of the latest ``window_size`` values in log
+ histories.
+
+ If ``window_size is None`` or ``window_size > len(self._log_history)``,
+ return the global minimum value of history logs.
+
+ Args:
+ window_size (int, optional): Size of statistics window.
+ Returns:
+ np.ndarray: The minimum value within the window.
+ """
+ if window_size is not None:
+ assert isinstance(window_size, int), \
+ 'The type of window size should be int, but got ' \
+ f'{type(window_size)}'
+ else:
+ window_size = len(self._log_history)
+ return self._log_history[-window_size:].min()
+
+ def current(self) -> np.ndarray:
+ """Return the recently updated values in log histories.
+
+ Returns:
+ np.ndarray: Recently updated values in log histories.
+ """
+ if len(self._log_history) == 0:
+ raise ValueError('HistoryBuffer._log_history is an empty array! '
+ 'please call update first')
+ return self._log_history[-1]
diff --git a/testbed/open-mmlab__mmengine/mmengine/logging/logger.py b/testbed/open-mmlab__mmengine/mmengine/logging/logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..2be03ab2c55b9021751a98f419def76f0be0e3d5
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/logging/logger.py
@@ -0,0 +1,302 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import logging
+import os
+import sys
+from logging import Logger, LogRecord
+from typing import Optional, Union
+
+from termcolor import colored
+
+from mmengine.utils import ManagerMixin
+from mmengine.utils.manager import _accquire_lock, _release_lock
+
+
+class MMFormatter(logging.Formatter):
+ """Colorful format for MMLogger. If the log level is error, the logger will
+ additionally output the location of the code.
+
+ Args:
+ color (bool): Whether to use colorful format. filehandler is not
+ allowed to use color format, otherwise it will be garbled.
+ blink (bool): Whether to blink the ``INFO`` and ``DEBUG`` logging
+ level.
+ **kwargs: Keyword arguments passed to
+ :meth:`logging.Formatter.__init__`.
+ """
+ _color_mapping: dict = dict(
+ ERROR='red', WARNING='yellow', INFO='white', DEBUG='green')
+
+ def __init__(self, color: bool = True, blink: bool = False, **kwargs):
+ super().__init__(**kwargs)
+ assert not (not color and blink), (
+ 'blink should only be available when color is True')
+ # Get prefix format according to color.
+ error_prefix = self._get_prefix('ERROR', color, blink=True)
+ warn_prefix = self._get_prefix('WARNING', color, blink=True)
+ info_prefix = self._get_prefix('INFO', color, blink)
+ debug_prefix = self._get_prefix('DEBUG', color, blink)
+
+ # Config output format.
+ self.err_format = (f'%(asctime)s - %(name)s - {error_prefix} - '
+ '%(pathname)s - %(funcName)s - %(lineno)d - '
+ '%(message)s')
+ self.warn_format = (f'%(asctime)s - %(name)s - {warn_prefix} - %('
+ 'message)s')
+ self.info_format = (f'%(asctime)s - %(name)s - {info_prefix} - %('
+ 'message)s')
+ self.debug_format = (f'%(asctime)s - %(name)s - {debug_prefix} - %('
+ 'message)s')
+
+ def _get_prefix(self, level: str, color: bool, blink=False) -> str:
+ """Get the prefix of the target log level.
+
+ Args:
+ level (str): log level.
+ color (bool): Whether to get colorful prefix.
+ blink (bool): Whether the prefix will blink.
+
+ Returns:
+ str: The plain or colorful prefix.
+ """
+ if color:
+ attrs = ['underline']
+ if blink:
+ attrs.append('blink')
+ prefix = colored(level, self._color_mapping[level], attrs=attrs)
+ else:
+ prefix = level
+ return prefix
+
+ def format(self, record: LogRecord) -> str:
+ """Override the `logging.Formatter.format`` method `. Output the
+ message according to the specified log level.
+
+ Args:
+ record (LogRecord): A LogRecord instance represents an event being
+ logged.
+
+ Returns:
+ str: Formatted result.
+ """
+ if record.levelno == logging.ERROR:
+ self._style._fmt = self.err_format
+ elif record.levelno == logging.WARNING:
+ self._style._fmt = self.warn_format
+ elif record.levelno == logging.INFO:
+ self._style._fmt = self.info_format
+ elif record.levelno == logging.DEBUG:
+ self._style._fmt = self.debug_format
+
+ result = logging.Formatter.format(self, record)
+ return result
+
+
+class MMLogger(Logger, ManagerMixin):
+ """Formatted logger used to record messages.
+
+ ``MMLogger`` can create formatted logger to log message with different
+ log levels and get instance in the same way as ``ManagerMixin``.
+ ``MMLogger`` has the following features:
+
+ - Distributed log storage, ``MMLogger`` can choose whether to save log of
+ different ranks according to `log_file`.
+ - Message with different log levels will have different colors and format
+ when displayed on terminal.
+
+ Note:
+ - The `name` of logger and the ``instance_name`` of ``MMLogger`` could
+ be different. We can only get ``MMLogger`` instance by
+ ``MMLogger.get_instance`` but not ``logging.getLogger``. This feature
+ ensures ``MMLogger`` will not be incluenced by third-party logging
+ config.
+ - Different from ``logging.Logger``, ``MMLogger`` will not log warning
+ or error message without ``Handler``.
+
+ Examples:
+ >>> logger = MMLogger.get_instance(name='MMLogger',
+ >>> logger_name='Logger')
+ >>> # Although logger has name attribute just like `logging.Logger`
+ >>> # We cannot get logger instance by `logging.getLogger`.
+ >>> assert logger.name == 'Logger'
+ >>> assert logger.instance_name = 'MMLogger'
+ >>> assert id(logger) != id(logging.getLogger('Logger'))
+ >>> # Get logger that do not store logs.
+ >>> logger1 = MMLogger.get_instance('logger1')
+ >>> # Get logger only save rank0 logs.
+ >>> logger2 = MMLogger.get_instance('logger2', log_file='out.log')
+ >>> # Get logger only save multiple ranks logs.
+ >>> logger3 = MMLogger.get_instance('logger3', log_file='out.log',
+ >>> distributed=True)
+
+ Args:
+ name (str): Global instance name.
+ logger_name (str): ``name`` attribute of ``Logging.Logger`` instance.
+ If `logger_name` is not defined, defaults to 'mmengine'.
+ log_file (str, optional): The log filename. If specified, a
+ ``FileHandler`` will be added to the logger. Defaults to None.
+ log_level (str): The log level of the handler and logger. Defaults to
+ "NOTSET".
+ file_mode (str): The file mode used to open log file. Defaults to 'w'.
+ distributed (bool): Whether to save distributed logs, Defaults to
+ false.
+ """
+
+ def __init__(self,
+ name: str,
+ logger_name='mmengine',
+ log_file: Optional[str] = None,
+ log_level: str = 'INFO',
+ file_mode: str = 'w',
+ distributed=False):
+ Logger.__init__(self, logger_name)
+ ManagerMixin.__init__(self, name)
+ # Get rank in DDP mode.
+
+ rank = _get_rank()
+
+ # Config stream_handler. If `rank != 0`. stream_handler can only
+ # export ERROR logs.
+ stream_handler = logging.StreamHandler(stream=sys.stdout)
+ # `StreamHandler` record month, day, hour, minute, and second
+ # timestamp.
+ stream_handler.setFormatter(
+ MMFormatter(color=True, datefmt='%m/%d %H:%M:%S'))
+ # Only rank0 `StreamHandler` will log messages below error level.
+ stream_handler.setLevel(log_level) if rank == 0 else \
+ stream_handler.setLevel(logging.ERROR)
+ self.handlers.append(stream_handler)
+
+ if log_file is not None:
+ if rank != 0:
+ # rename `log_file` with rank suffix.
+ path_split = log_file.split(os.sep)
+ if '.' in path_split[-1]:
+ filename_list = path_split[-1].split('.')
+ filename_list[-2] = f'{filename_list[-2]}_rank{rank}'
+ path_split[-1] = '.'.join(filename_list)
+ else:
+ path_split[-1] = f'{path_split[-1]}_rank{rank}'
+ log_file = os.sep.join(path_split)
+ # Save multi-ranks logs if distributed is True. The logs of rank0
+ # will always be saved.
+ if rank == 0 or distributed:
+ # Here, the default behaviour of the official logger is 'a'.
+ # Thus, we provide an interface to change the file mode to
+ # the default behaviour. `FileHandler` is not supported to
+ # have colors, otherwise it will appear garbled.
+ file_handler = logging.FileHandler(log_file, file_mode)
+ # `StreamHandler` record year, month, day hour, minute,
+ # and second timestamp. file_handler will only record logs
+ # without color to avoid garbled code saved in files.
+ file_handler.setFormatter(
+ MMFormatter(color=False, datefmt='%Y/%m/%d %H:%M:%S'))
+ file_handler.setLevel(log_level)
+ self.handlers.append(file_handler)
+
+ @classmethod
+ def get_current_instance(cls) -> 'MMLogger':
+ """Get latest created ``MMLogger`` instance.
+
+ :obj:`MMLogger` can call :meth:`get_current_instance` before any
+ instance has been created, and return a logger with the instance name
+ "mmengine".
+
+ Returns:
+ MMLogger: Configured logger instance.
+ """
+ if not cls._instance_dict:
+ cls.get_instance('mmengine')
+ return super().get_current_instance()
+
+ def callHandlers(self, record: LogRecord) -> None:
+ """Pass a record to all relevant handlers.
+
+ Override ``callHandlers`` method in ``logging.Logger`` to avoid
+ multiple warning messages in DDP mode. Loop through all handlers of
+ the logger instance and its parents in the logger hierarchy. If no
+ handler was found, the record will not be output.
+
+ Args:
+ record (LogRecord): A ``LogRecord`` instance contains logged
+ message.
+ """
+ for handler in self.handlers:
+ if record.levelno >= handler.level:
+ handler.handle(record)
+
+ def setLevel(self, level):
+ """Set the logging level of this logger.
+
+ If ``logging.Logger.selLevel`` is called, all ``logging.Logger``
+ instances managed by ``logging.Manager`` will clear the cache. Since
+ ``MMLogger`` is not managed by ``logging.Manager`` anymore,
+ ``MMLogger`` should override this method to clear caches of all
+ ``MMLogger`` instance which is managed by :obj:`ManagerMixin`.
+
+ level must be an int or a str.
+ """
+ # Compatible with python3.6. `logging.Logger` does not have
+ # `_cache` attribute in python3.6.
+ self.level = logging._checkLevel(level)
+ if hasattr(self, '_cache'):
+ _accquire_lock()
+ # The same logic as `logging.Manager._clear_cache`.
+ for logger in MMLogger._instance_dict.values():
+ logger._cache.clear()
+ _release_lock()
+
+
+def print_log(msg,
+ logger: Optional[Union[Logger, str]] = None,
+ level=logging.INFO) -> None:
+ """Print a log message.
+
+ Args:
+ msg (str): The message to be logged.
+ logger (Logger or str, optional): If the type of logger is
+ ``logging.Logger``, we directly use logger to log messages.
+ Some special loggers are:
+
+ - "silent": No message will be printed.
+ - "current": Use latest created logger to log message.
+ - other str: Instance name of logger. The corresponding logger
+ will log message if it has been created, otherwise ``print_log``
+ will raise a `ValueError`.
+ - None: The `print()` method will be used to print log messages.
+ level (int): Logging level. Only available when `logger` is a Logger
+ object, "current", or a created logger instance name.
+ """
+ if logger is None:
+ print(msg)
+ elif isinstance(logger, logging.Logger):
+ logger.log(level, msg)
+ elif logger == 'silent':
+ pass
+ elif logger == 'current':
+ logger_instance = MMLogger.get_current_instance()
+ logger_instance.log(level, msg)
+ elif isinstance(logger, str):
+ # If the type of `logger` is `str`, but not with value of `current` or
+ # `silent`, we assume it indicates the name of the logger. If the
+ # corresponding logger has not been created, `print_log` will raise
+ # a `ValueError`.
+ if MMLogger.check_instance_created(logger):
+ logger_instance = MMLogger.get_instance(logger)
+ logger_instance.log(level, msg)
+ else:
+ raise ValueError(f'MMLogger: {logger} has not been created!')
+ else:
+ raise TypeError(
+ '`logger` should be either a logging.Logger object, str, '
+ f'"silent", "current" or None, but got {type(logger)}')
+
+
+def _get_rank():
+ """Support using logging module without torch."""
+ try:
+ # requires torch
+ from mmengine.dist import get_rank
+ except ImportError:
+ return 0
+ else:
+ return get_rank()
diff --git a/testbed/open-mmlab__mmengine/mmengine/logging/message_hub.py b/testbed/open-mmlab__mmengine/mmengine/logging/message_hub.py
new file mode 100644
index 0000000000000000000000000000000000000000..79fc131ae4b1d68774ef2933384e355b8eeb832a
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/logging/message_hub.py
@@ -0,0 +1,442 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import logging
+from collections import OrderedDict
+from typing import TYPE_CHECKING, Any, Optional, Union
+
+import numpy as np
+
+from mmengine.utils import ManagerMixin
+from .history_buffer import HistoryBuffer
+from .logger import print_log
+
+if TYPE_CHECKING:
+ import torch
+
+
+class MessageHub(ManagerMixin):
+ """Message hub for component interaction. MessageHub is created and
+ accessed in the same way as ManagerMixin.
+
+ ``MessageHub`` will record log information and runtime information. The
+ log information refers to the learning rate, loss, etc. of the model
+ during training phase, which will be stored as ``HistoryBuffer``. The
+ runtime information refers to the iter times, meta information of
+ runner etc., which will be overwritten by next update.
+
+ Args:
+ name (str): Name of message hub used to get corresponding instance
+ globally.
+ log_scalars (OrderedDict, optional): Each key-value pair in the
+ dictionary is the name of the log information such as "loss", "lr",
+ "metric" and their corresponding values. The type of value must be
+ HistoryBuffer. Defaults to None.
+ runtime_info (OrderedDict, optional): Each key-value pair in the
+ dictionary is the name of the runtime information and their
+ corresponding values. Defaults to None.
+ resumed_keys (OrderedDict, optional): Each key-value pair in the
+ dictionary decides whether the key in :attr:`_log_scalars` and
+ :attr:`_runtime_info` will be serialized.
+
+ Note:
+ Key in :attr:`_resumed_keys` belongs to :attr:`_log_scalars` or
+ :attr:`_runtime_info`. The corresponding value cannot be set
+ repeatedly.
+
+ Examples:
+ >>> # create empty `MessageHub`.
+ >>> message_hub1 = MessageHub()
+ >>> log_scalars = OrderedDict(loss=HistoryBuffer())
+ >>> runtime_info = OrderedDict(task='task')
+ >>> resumed_keys = dict(loss=True)
+ >>> # create `MessageHub` from data.
+ >>> message_hub2 = MessageHub(
+ >>> name='name',
+ >>> log_scalars=log_scalars,
+ >>> runtime_info=runtime_info,
+ >>> resumed_keys=resumed_keys)
+ """
+
+ def __init__(self,
+ name: str,
+ log_scalars: Optional[OrderedDict] = None,
+ runtime_info: Optional[OrderedDict] = None,
+ resumed_keys: Optional[OrderedDict] = None):
+ super().__init__(name)
+ self._log_scalars = log_scalars if log_scalars is not None else \
+ OrderedDict()
+ self._runtime_info = runtime_info if runtime_info is not None else \
+ OrderedDict()
+ self._resumed_keys = resumed_keys if resumed_keys is not None else \
+ OrderedDict()
+
+ assert isinstance(self._log_scalars, OrderedDict)
+ assert isinstance(self._runtime_info, OrderedDict)
+ assert isinstance(self._resumed_keys, OrderedDict)
+
+ for value in self._log_scalars.values():
+ assert isinstance(value, HistoryBuffer), \
+ ("The type of log_scalars'value must be HistoryBuffer, but "
+ f'got {type(value)}')
+
+ for key in self._resumed_keys.keys():
+ assert key in self._log_scalars or key in self._runtime_info, \
+ ('Key in `resumed_keys` must contained in `log_scalars` or '
+ f'`runtime_info`, but got {key}')
+
+ @classmethod
+ def get_current_instance(cls) -> 'MessageHub':
+ """Get latest created ``MessageHub`` instance.
+
+ :obj:`MessageHub` can call :meth:`get_current_instance` before any
+ instance has been created, and return a message hub with the instance
+ name "mmengine".
+
+ Returns:
+ MessageHub: Empty ``MessageHub`` instance.
+ """
+ if not cls._instance_dict:
+ cls.get_instance('mmengine')
+ return super().get_current_instance()
+
+ def update_scalar(self,
+ key: str,
+ value: Union[int, float, np.ndarray, 'torch.Tensor'],
+ count: int = 1,
+ resumed: bool = True) -> None:
+ """Update :attr:_log_scalars.
+
+ Update ``HistoryBuffer`` in :attr:`_log_scalars`. If corresponding key
+ ``HistoryBuffer`` has been created, ``value`` and ``count`` is the
+ argument of ``HistoryBuffer.update``, Otherwise, ``update_scalar``
+ will create an ``HistoryBuffer`` with value and count via the
+ constructor of ``HistoryBuffer``.
+
+ Examples:
+ >>> message_hub = MessageHub
+ >>> # create loss `HistoryBuffer` with value=1, count=1
+ >>> message_hub.update_scalar('loss', 1)
+ >>> # update loss `HistoryBuffer` with value
+ >>> message_hub.update_scalar('loss', 3)
+ >>> message_hub.update_scalar('loss', 3, resumed=False)
+ AssertionError: loss used to be true, but got false now. resumed
+ keys cannot be modified repeatedly'
+
+ Note:
+ The ``resumed`` argument needs to be consistent for the same
+ ``key``.
+
+ Args:
+ key (str): Key of ``HistoryBuffer``.
+ value (torch.Tensor or np.ndarray or int or float): Value of log.
+ count (torch.Tensor or np.ndarray or int or float): Accumulation
+ times of log, defaults to 1. `count` will be used in smooth
+ statistics.
+ resumed (str): Whether the corresponding ``HistoryBuffer``
+ could be resumed. Defaults to True.
+ """
+ self._set_resumed_keys(key, resumed)
+ checked_value = self._get_valid_value(value)
+ assert isinstance(count, int), (
+ f'The type of count must be int. but got {type(count): {count}}')
+ if key in self._log_scalars:
+ self._log_scalars[key].update(checked_value, count)
+ else:
+ self._log_scalars[key] = HistoryBuffer([checked_value], [count])
+
+ def update_scalars(self, log_dict: dict, resumed: bool = True) -> None:
+ """Update :attr:`_log_scalars` with a dict.
+
+ ``update_scalars`` iterates through each pair of log_dict key-value,
+ and calls ``update_scalar``. If type of value is dict, the value should
+ be ``dict(value=xxx) or dict(value=xxx, count=xxx)``. Item in
+ ``log_dict`` has the same resume option.
+
+ Note:
+ The ``resumed`` argument needs to be consistent for the same
+ ``log_dict``.
+
+ Args:
+ log_dict (str): Used for batch updating :attr:`_log_scalars`.
+ resumed (bool): Whether all ``HistoryBuffer`` referred in
+ log_dict should be resumed. Defaults to True.
+
+ Examples:
+ >>> message_hub = MessageHub.get_instance('mmengine')
+ >>> log_dict = dict(a=1, b=2, c=3)
+ >>> message_hub.update_scalars(log_dict)
+ >>> # The default count of `a`, `b` and `c` is 1.
+ >>> log_dict = dict(a=1, b=2, c=dict(value=1, count=2))
+ >>> message_hub.update_scalars(log_dict)
+ >>> # The count of `c` is 2.
+ """
+ assert isinstance(log_dict, dict), ('`log_dict` must be a dict!, '
+ f'but got {type(log_dict)}')
+ for log_name, log_val in log_dict.items():
+ if isinstance(log_val, dict):
+ assert 'value' in log_val, \
+ f'value must be defined in {log_val}'
+ count = self._get_valid_value(log_val.get('count', 1))
+ value = log_val['value']
+ else:
+ count = 1
+ value = log_val
+ assert isinstance(count,
+ int), ('The type of count must be int. but got '
+ f'{type(count): {count}}')
+ self.update_scalar(log_name, value, count, resumed)
+
+ def update_info(self, key: str, value: Any, resumed: bool = True) -> None:
+ """Update runtime information.
+
+ The key corresponding runtime information will be overwritten each
+ time calling ``update_info``.
+
+ Note:
+ The ``resumed`` argument needs to be consistent for the same
+ ``key``.
+
+ Examples:
+ >>> message_hub = MessageHub()
+ >>> message_hub.update_info('iter', 100)
+
+ Args:
+ key (str): Key of runtime information.
+ value (Any): Value of runtime information.
+ resumed (bool): Whether the corresponding ``HistoryBuffer``
+ could be resumed.
+ """
+ self._set_resumed_keys(key, resumed)
+ self._runtime_info[key] = value
+
+ def update_info_dict(self, info_dict: dict, resumed: bool = True) -> None:
+ """Update runtime information with dictionary.
+
+ The key corresponding runtime information will be overwritten each
+ time calling ``update_info``.
+
+ Note:
+ The ``resumed`` argument needs to be consistent for the same
+ ``info_dict``.
+
+ Examples:
+ >>> message_hub = MessageHub()
+ >>> message_hub.update_info({'iter': 100})
+
+ Args:
+ info_dict (str): Runtime information dictionary.
+ resumed (bool): Whether the corresponding ``HistoryBuffer``
+ could be resumed.
+ """
+ assert isinstance(info_dict, dict), ('`log_dict` must be a dict!, '
+ f'but got {type(info_dict)}')
+ for key, value in info_dict.items():
+ self.update_info(key, value, resumed=resumed)
+
+ def _set_resumed_keys(self, key: str, resumed: bool) -> None:
+ """Set corresponding resumed keys.
+
+ This method is called by ``update_scalar``, ``update_scalars`` and
+ ``update_info`` to set the corresponding key is true or false in
+ :attr:`_resumed_keys`.
+
+ Args:
+ key (str): Key of :attr:`_log_scalrs` or :attr:`_runtime_info`.
+ resumed (bool): Whether the corresponding ``HistoryBuffer``
+ could be resumed.
+ """
+ if key not in self._resumed_keys:
+ self._resumed_keys[key] = resumed
+ else:
+ assert self._resumed_keys[key] == resumed, \
+ f'{key} used to be {self._resumed_keys[key]}, but got ' \
+ '{resumed} now. resumed keys cannot be modified repeatedly.'
+
+ @property
+ def log_scalars(self) -> OrderedDict:
+ """Get all ``HistoryBuffer`` instances.
+
+ Note:
+ Considering the large memory footprint of history buffers in the
+ post-training, :meth:`get_scalar` will return a reference of
+ history buffer rather than a copy.
+
+ Returns:
+ OrderedDict: All ``HistoryBuffer`` instances.
+ """
+ return self._log_scalars
+
+ @property
+ def runtime_info(self) -> OrderedDict:
+ """Get all runtime information.
+
+ Returns:
+ OrderedDict: A copy of all runtime information.
+ """
+ # return copy.deepcopy(self._runtime_info)
+ return self._runtime_info
+
+ def get_scalar(self, key: str) -> HistoryBuffer:
+ """Get ``HistoryBuffer`` instance by key.
+
+ Note:
+ Considering the large memory footprint of history buffers in the
+ post-training, :meth:`get_scalar` will not return a reference of
+ history buffer rather than a copy.
+
+ Args:
+ key (str): Key of ``HistoryBuffer``.
+
+ Returns:
+ HistoryBuffer: Corresponding ``HistoryBuffer`` instance if the
+ key exists.
+ """
+ if key not in self.log_scalars:
+ raise KeyError(f'{key} is not found in Messagehub.log_buffers: '
+ f'instance name is: {MessageHub.instance_name}')
+ return self.log_scalars[key]
+
+ def get_info(self, key: str) -> Any:
+ """Get runtime information by key.
+
+ Args:
+ key (str): Key of runtime information.
+
+ Returns:
+ Any: A copy of corresponding runtime information if the key exists.
+ """
+ if key not in self.runtime_info:
+ raise KeyError(f'{key} is not found in Messagehub.log_buffers: '
+ f'instance name is: {MessageHub.instance_name}')
+
+ # TODO: There are restrictions on objects that can be saved
+ # return copy.deepcopy(self._runtime_info[key])
+ return self._runtime_info[key]
+
+ def _get_valid_value(
+ self, value: Union['torch.Tensor', np.ndarray, int, float]) \
+ -> Union[int, float]:
+ """Convert value to python built-in type.
+
+ Args:
+ value (torch.Tensor or np.ndarray or int or float): value of log.
+
+ Returns:
+ float or int: python built-in type value.
+ """
+ if isinstance(value, np.ndarray):
+ assert value.size == 1
+ value = value.item()
+ elif isinstance(value, (int, float)):
+ value = value
+ else:
+ # check whether value is torch.Tensor but don't want
+ # to import torch in this file
+ assert hasattr(value, 'numel') and value.numel() == 1
+ value = value.item()
+ return value # type: ignore
+
+ def state_dict(self) -> dict:
+ """Returns a dictionary containing log scalars, runtime information and
+ resumed keys, which should be resumed.
+
+ The returned ``state_dict`` can be loaded by :meth:`load_state_dict`.
+
+ Returns:
+ dict: A dictionary contains ``log_scalars``, ``runtime_info`` and
+ ``resumed_keys``.
+ """
+ saved_scalars = OrderedDict()
+ saved_info = OrderedDict()
+
+ for key, value in self._log_scalars.items():
+ if self._resumed_keys.get(key, False):
+ saved_scalars[key] = copy.deepcopy(value)
+
+ for key, value in self._runtime_info.items():
+ if self._resumed_keys.get(key, False):
+ try:
+ saved_info[key] = copy.deepcopy(value)
+ except: # noqa: E722
+ print_log(
+ f'{key} in message_hub cannot be copied, '
+ f'just return its reference. ',
+ logger='current',
+ level=logging.WARNING)
+ saved_info[key] = value
+ return dict(
+ log_scalars=saved_scalars,
+ runtime_info=saved_info,
+ resumed_keys=self._resumed_keys)
+
+ def load_state_dict(self, state_dict: Union['MessageHub', dict]) -> None:
+ """Loads log scalars, runtime information and resumed keys from
+ ``state_dict`` or ``message_hub``.
+
+ If ``state_dict`` is a dictionary returned by :meth:`state_dict`, it
+ will only make copies of data which should be resumed from the source
+ ``message_hub``.
+
+ If ``state_dict`` is a ``message_hub`` instance, it will make copies of
+ all data from the source message_hub. We suggest to load data from
+ ``dict`` rather than a ``MessageHub`` instance.
+
+ Args:
+ state_dict (dict or MessageHub): A dictionary contains key
+ ``log_scalars`` ``runtime_info`` and ``resumed_keys``, or a
+ MessageHub instance.
+ """
+ if isinstance(state_dict, dict):
+ for key in ('log_scalars', 'runtime_info', 'resumed_keys'):
+ assert key in state_dict, (
+ 'The loaded `state_dict` of `MessageHub` must contain '
+ f'key: `{key}`')
+ # The old `MessageHub` could save non-HistoryBuffer `log_scalars`,
+ # therefore the loaded `log_scalars` needs to be filtered.
+ for key, value in state_dict['log_scalars'].items():
+ if not isinstance(value, HistoryBuffer):
+ print_log(
+ f'{key} in message_hub is not HistoryBuffer, '
+ f'just skip resuming it.',
+ logger='current',
+ level=logging.WARNING)
+ continue
+ self.log_scalars[key] = value
+
+ for key, value in state_dict['runtime_info'].items():
+ try:
+ self._runtime_info[key] = copy.deepcopy(value)
+ except: # noqa: E722
+ print_log(
+ f'{key} in message_hub cannot be copied, '
+ f'just return its reference.',
+ logger='current',
+ level=logging.WARNING)
+ self._runtime_info[key] = value
+
+ for key, value in state_dict['resumed_keys'].items():
+ if key not in set(self.log_scalars.keys()) | \
+ set(self._runtime_info.keys()):
+ print_log(
+ f'resumed key: {key} is not defined in message_hub, '
+ f'just skip resuming this key.',
+ logger='current',
+ level=logging.WARNING)
+ continue
+ elif not value:
+ print_log(
+ f'Although resumed key: {key} is False, {key} '
+ 'will still be loaded this time. This key will '
+ 'not be saved by the next calling of '
+ '`MessageHub.state_dict()`',
+ logger='current',
+ level=logging.WARNING)
+ self._resumed_keys[key] = value
+
+ # Since some checkpoints saved serialized `message_hub` instance,
+ # `load_state_dict` support loading `message_hub` instance for
+ # compatibility
+ else:
+ self._log_scalars = copy.deepcopy(state_dict._log_scalars)
+ self._runtime_info = copy.deepcopy(state_dict._runtime_info)
+ self._resumed_keys = copy.deepcopy(state_dict._resumed_keys)
diff --git a/testbed/open-mmlab__mmengine/mmengine/model/__init__.py b/testbed/open-mmlab__mmengine/mmengine/model/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7f6973b22ec266f31ece5a0482dd5371c36c086
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/model/__init__.py
@@ -0,0 +1,37 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from mmengine.utils.dl_utils import TORCH_VERSION
+from mmengine.utils.version_utils import digit_version
+from .averaged_model import (BaseAveragedModel, ExponentialMovingAverage,
+ MomentumAnnealingEMA, StochasticWeightAverage)
+from .base_model import BaseDataPreprocessor, BaseModel, ImgDataPreprocessor
+from .base_module import BaseModule, ModuleDict, ModuleList, Sequential
+from .utils import (convert_sync_batchnorm, detect_anomalous_params,
+ merge_dict, revert_sync_batchnorm, stack_batch)
+from .weight_init import (BaseInit, Caffe2XavierInit, ConstantInit,
+ KaimingInit, NormalInit, PretrainedInit,
+ TruncNormalInit, UniformInit, XavierInit,
+ bias_init_with_prob, caffe2_xavier_init,
+ constant_init, initialize, kaiming_init, normal_init,
+ trunc_normal_init, uniform_init, update_init_info,
+ xavier_init)
+from .wrappers import (BaseTTAModel, MMDistributedDataParallel,
+ MMSeparateDistributedDataParallel, is_model_wrapper)
+
+__all__ = [
+ 'MMDistributedDataParallel', 'is_model_wrapper', 'BaseAveragedModel',
+ 'StochasticWeightAverage', 'ExponentialMovingAverage',
+ 'MomentumAnnealingEMA', 'BaseModel', 'BaseDataPreprocessor',
+ 'ImgDataPreprocessor', 'MMSeparateDistributedDataParallel', 'BaseModule',
+ 'stack_batch', 'merge_dict', 'detect_anomalous_params', 'ModuleList',
+ 'ModuleDict', 'Sequential', 'revert_sync_batchnorm', 'update_init_info',
+ 'constant_init', 'xavier_init', 'normal_init', 'trunc_normal_init',
+ 'uniform_init', 'kaiming_init', 'caffe2_xavier_init',
+ 'bias_init_with_prob', 'BaseInit', 'ConstantInit', 'XavierInit',
+ 'NormalInit', 'TruncNormalInit', 'UniformInit', 'KaimingInit',
+ 'Caffe2XavierInit', 'PretrainedInit', 'initialize',
+ 'convert_sync_batchnorm', 'BaseTTAModel'
+]
+
+if digit_version(TORCH_VERSION) >= digit_version('1.11.0'):
+ from .wrappers import MMFullyShardedDataParallel # noqa:F401
+ __all__.append('MMFullyShardedDataParallel')
diff --git a/testbed/open-mmlab__mmengine/mmengine/model/averaged_model.py b/testbed/open-mmlab__mmengine/mmengine/model/averaged_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..84a85c1cebb6ac98d3feae4dbc0bcdf43d50613a
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/model/averaged_model.py
@@ -0,0 +1,259 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import warnings
+from abc import abstractmethod
+from copy import deepcopy
+from typing import Optional
+
+import torch
+import torch.nn as nn
+from torch import Tensor
+
+from mmengine.registry import MODELS
+
+
+class BaseAveragedModel(nn.Module):
+ """A base class for averaging model weights.
+
+ Weight averaging, such as SWA and EMA, is a widely used technique for
+ training neural networks. This class implements the averaging process
+ for a model. All subclasses must implement the `avg_func` method.
+ This class creates a copy of the provided module :attr:`model`
+ on the :attr:`device` and allows computing running averages of the
+ parameters of the :attr:`model`.
+
+ The code is referenced from: https://github.com/pytorch/pytorch/blob/master/torch/optim/swa_utils.py.
+
+ Different from the `AveragedModel` in PyTorch, we use in-place operation
+ to improve the parameter updating speed, which is about 5 times faster
+ than the non-in-place version.
+
+ In mmengine, we provide two ways to use the model averaging:
+
+ 1. Use the model averaging module in hook:
+ We provide an :class:`mmengine.hooks.EMAHook` to apply the model
+ averaging during training. Add ``custom_hooks=[dict(type='EMAHook')]``
+ to the config or the runner.
+
+ 2. Use the model averaging module directly in the algorithm. Take the ema
+ teacher in semi-supervise as an example:
+
+ >>> from mmengine.model import ExponentialMovingAverage
+ >>> student = ResNet(depth=50)
+ >>> # use ema model as teacher
+ >>> ema_teacher = ExponentialMovingAverage(student)
+
+ Args:
+ model (nn.Module): The model to be averaged.
+ interval (int): Interval between two updates. Defaults to 1.
+ device (torch.device, optional): If provided, the averaged model will
+ be stored on the :attr:`device`. Defaults to None.
+ update_buffers (bool): if True, it will compute running averages for
+ both the parameters and the buffers of the model. Defaults to
+ False.
+ """ # noqa: E501
+
+ def __init__(self,
+ model: nn.Module,
+ interval: int = 1,
+ device: Optional[torch.device] = None,
+ update_buffers: bool = False) -> None:
+ super().__init__()
+ self.module = deepcopy(model).requires_grad_(False)
+ self.interval = interval
+ if device is not None:
+ self.module = self.module.to(device)
+ self.register_buffer('steps',
+ torch.tensor(0, dtype=torch.long, device=device))
+ self.update_buffers = update_buffers
+ if update_buffers:
+ self.avg_parameters = self.module.state_dict()
+ else:
+ self.avg_parameters = dict(self.module.named_parameters())
+
+ @abstractmethod
+ def avg_func(self, averaged_param: Tensor, source_param: Tensor,
+ steps: int) -> None:
+ """Use in-place operation to compute the average of the parameters. All
+ subclasses must implement this method.
+
+ Args:
+ averaged_param (Tensor): The averaged parameters.
+ source_param (Tensor): The source parameters.
+ steps (int): The number of times the parameters have been
+ updated.
+ """
+
+ def forward(self, *args, **kwargs):
+ """Forward method of the averaged model."""
+ return self.module(*args, **kwargs)
+
+ def update_parameters(self, model: nn.Module) -> None:
+ """Update the parameters of the model. This method will execute the
+ ``avg_func`` to compute the new parameters and update the model's
+ parameters.
+
+ Args:
+ model (nn.Module): The model whose parameters will be averaged.
+ """
+ src_parameters = (
+ model.state_dict()
+ if self.update_buffers else dict(model.named_parameters()))
+ if self.steps == 0:
+ for k, p_avg in self.avg_parameters.items():
+ p_avg.data.copy_(src_parameters[k].data)
+ elif self.steps % self.interval == 0:
+ for k, p_avg in self.avg_parameters.items():
+ if p_avg.dtype.is_floating_point:
+ device = p_avg.device
+ self.avg_func(p_avg.data,
+ src_parameters[k].data.to(device),
+ self.steps)
+ if not self.update_buffers:
+ # If not update the buffers,
+ # keep the buffers in sync with the source model.
+ for b_avg, b_src in zip(self.module.buffers(), model.buffers()):
+ b_avg.data.copy_(b_src.data.to(b_avg.device))
+ self.steps += 1
+
+
+@MODELS.register_module()
+class StochasticWeightAverage(BaseAveragedModel):
+ """Implements the stochastic weight averaging (SWA) of the model.
+
+ Stochastic Weight Averaging was proposed in `Averaging Weights Leads to
+ Wider Optima and Better Generalization, UAI 2018.
+ `_ by Pavel Izmailov, Dmitrii
+ Podoprikhin, Timur Garipov, Dmitry Vetrov and Andrew Gordon Wilson.
+ """
+
+ def avg_func(self, averaged_param: Tensor, source_param: Tensor,
+ steps: int) -> None:
+ """Compute the average of the parameters using stochastic weight
+ average.
+
+ Args:
+ averaged_param (Tensor): The averaged parameters.
+ source_param (Tensor): The source parameters.
+ steps (int): The number of times the parameters have been
+ updated.
+ """
+ averaged_param.add_(
+ source_param - averaged_param,
+ alpha=1 / float(steps // self.interval + 1))
+
+
+@MODELS.register_module()
+class ExponentialMovingAverage(BaseAveragedModel):
+ r"""Implements the exponential moving average (EMA) of the model.
+
+ All parameters are updated by the formula as below:
+
+ .. math::
+
+ Xema_{t+1} = (1 - momentum) * Xema_{t} + momentum * X_t
+
+ .. note::
+ This :attr:`momentum` argument is different from one used in optimizer
+ classes and the conventional notion of momentum. Mathematically,
+ :math:`Xema_{t+1}` is the moving average and :math:`X_t` is the
+ new observed value. The value of momentum is usually a small number,
+ allowing observed values to slowly update the ema parameters.
+
+ Args:
+ model (nn.Module): The model to be averaged.
+ momentum (float): The momentum used for updating ema parameter.
+ Defaults to 0.0002.
+ Ema's parameter are updated with the formula
+ :math:`averaged\_param = (1-momentum) * averaged\_param +
+ momentum * source\_param`.
+ interval (int): Interval between two updates. Defaults to 1.
+ device (torch.device, optional): If provided, the averaged model will
+ be stored on the :attr:`device`. Defaults to None.
+ update_buffers (bool): if True, it will compute running averages for
+ both the parameters and the buffers of the model. Defaults to
+ False.
+ """ # noqa: W605
+
+ def __init__(self,
+ model: nn.Module,
+ momentum: float = 0.0002,
+ interval: int = 1,
+ device: Optional[torch.device] = None,
+ update_buffers: bool = False) -> None:
+ super().__init__(model, interval, device, update_buffers)
+ assert 0.0 < momentum < 1.0, 'momentum must be in range (0.0, 1.0)'\
+ f'but got {momentum}'
+ if momentum > 0.5:
+ warnings.warn(
+ 'The value of momentum in EMA is usually a small number,'
+ 'which is different from the conventional notion of '
+ f'momentum but got {momentum}. Please make sure the '
+ f'value is correct.')
+ self.momentum = momentum
+
+ def avg_func(self, averaged_param: Tensor, source_param: Tensor,
+ steps: int) -> None:
+ """Compute the moving average of the parameters using exponential
+ moving average.
+
+ Args:
+ averaged_param (Tensor): The averaged parameters.
+ source_param (Tensor): The source parameters.
+ steps (int): The number of times the parameters have been
+ updated.
+ """
+ averaged_param.lerp_(source_param, self.momentum)
+
+
+@MODELS.register_module()
+class MomentumAnnealingEMA(ExponentialMovingAverage):
+ r"""Exponential moving average (EMA) with momentum annealing strategy.
+
+ Args:
+ model (nn.Module): The model to be averaged.
+ momentum (float): The momentum used for updating ema parameter.
+ Defaults to 0.0002.
+ Ema's parameter are updated with the formula
+ :math:`averaged\_param = (1-momentum) * averaged\_param +
+ momentum * source\_param`.
+ gamma (int): Use a larger momentum early in training and gradually
+ annealing to a smaller value to update the ema model smoothly. The
+ momentum is calculated as max(momentum, gamma / (gamma + steps))
+ Defaults to 100.
+ interval (int): Interval between two updates. Defaults to 1.
+ device (torch.device, optional): If provided, the averaged model will
+ be stored on the :attr:`device`. Defaults to None.
+ update_buffers (bool): if True, it will compute running averages for
+ both the parameters and the buffers of the model. Defaults to
+ False.
+ """
+
+ def __init__(self,
+ model: nn.Module,
+ momentum: float = 0.0002,
+ gamma: int = 100,
+ interval: int = 1,
+ device: Optional[torch.device] = None,
+ update_buffers: bool = False) -> None:
+ super().__init__(
+ model=model,
+ momentum=momentum,
+ interval=interval,
+ device=device,
+ update_buffers=update_buffers)
+ assert gamma > 0, f'gamma must be greater than 0, but got {gamma}'
+ self.gamma = gamma
+
+ def avg_func(self, averaged_param: Tensor, source_param: Tensor,
+ steps: int) -> None:
+ """Compute the moving average of the parameters using the linear
+ momentum strategy.
+
+ Args:
+ averaged_param (Tensor): The averaged parameters.
+ source_param (Tensor): The source parameters.
+ steps (int): The number of times the parameters have been
+ updated.
+ """
+ momentum = max(self.momentum, self.gamma / (self.gamma + self.steps))
+ averaged_param.lerp_(source_param, momentum)
diff --git a/testbed/open-mmlab__mmengine/mmengine/model/base_model/__init__.py b/testbed/open-mmlab__mmengine/mmengine/model/base_model/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..66a3cb89a9326799c2822bfb0b06cb2a0602c4e6
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/model/base_model/__init__.py
@@ -0,0 +1,5 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .base_model import BaseModel
+from .data_preprocessor import BaseDataPreprocessor, ImgDataPreprocessor
+
+__all__ = ['BaseModel', 'ImgDataPreprocessor', 'BaseDataPreprocessor']
diff --git a/testbed/open-mmlab__mmengine/mmengine/model/base_model/base_model.py b/testbed/open-mmlab__mmengine/mmengine/model/base_model/base_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9316506d8613d1f500f9325a6a0aebea3e9e360
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/model/base_model/base_model.py
@@ -0,0 +1,320 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from abc import abstractmethod
+from collections import OrderedDict
+from typing import Dict, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+
+from mmengine.optim import OptimWrapper
+from mmengine.registry import MODELS
+from mmengine.utils import is_list_of
+from ..base_module import BaseModule
+from .data_preprocessor import BaseDataPreprocessor
+
+
+class BaseModel(BaseModule):
+ """Base class for all algorithmic models.
+
+ BaseModel implements the basic functions of the algorithmic model, such as
+ weights initialize, batch inputs preprocess(see more information in
+ :class:`BaseDataPreprocessor`), parse losses, and update model parameters.
+
+ Subclasses inherit from BaseModel only need to implement the forward
+ method, which implements the logic to calculate loss and predictions,
+ then can be trained in the runner.
+
+ Examples:
+ >>> @MODELS.register_module()
+ >>> class ToyModel(BaseModel):
+ >>>
+ >>> def __init__(self):
+ >>> super().__init__()
+ >>> self.backbone = nn.Sequential()
+ >>> self.backbone.add_module('conv1', nn.Conv2d(3, 6, 5))
+ >>> self.backbone.add_module('pool', nn.MaxPool2d(2, 2))
+ >>> self.backbone.add_module('conv2', nn.Conv2d(6, 16, 5))
+ >>> self.backbone.add_module('fc1', nn.Linear(16 * 5 * 5, 120))
+ >>> self.backbone.add_module('fc2', nn.Linear(120, 84))
+ >>> self.backbone.add_module('fc3', nn.Linear(84, 10))
+ >>>
+ >>> self.criterion = nn.CrossEntropyLoss()
+ >>>
+ >>> def forward(self, batch_inputs, data_samples, mode='tensor'):
+ >>> data_samples = torch.stack(data_samples)
+ >>> if mode == 'tensor':
+ >>> return self.backbone(batch_inputs)
+ >>> elif mode == 'predict':
+ >>> feats = self.backbone(batch_inputs)
+ >>> predictions = torch.argmax(feats, 1)
+ >>> return predictions
+ >>> elif mode == 'loss':
+ >>> feats = self.backbone(batch_inputs)
+ >>> loss = self.criterion(feats, data_samples)
+ >>> return dict(loss=loss)
+
+ Args:
+ data_preprocessor (dict, optional): The pre-process config of
+ :class:`BaseDataPreprocessor`.
+ init_cfg (dict, optional): The weight initialized config for
+ :class:`BaseModule`.
+
+ Attributes:
+ data_preprocessor (:obj:`BaseDataPreprocessor`): Used for
+ pre-processing data sampled by dataloader to the format accepted by
+ :meth:`forward`.
+ init_cfg (dict, optional): Initialization config dict.
+ """
+
+ def __init__(self,
+ data_preprocessor: Optional[Union[dict, nn.Module]] = None,
+ init_cfg: Optional[dict] = None):
+ super().__init__(init_cfg)
+ if data_preprocessor is None:
+ data_preprocessor = dict(type='BaseDataPreprocessor')
+ if isinstance(data_preprocessor, nn.Module):
+ self.data_preprocessor = data_preprocessor
+ elif isinstance(data_preprocessor, dict):
+ self.data_preprocessor = MODELS.build(data_preprocessor)
+ else:
+ raise TypeError('data_preprocessor should be a `dict` or '
+ f'`nn.Module` instance, but got '
+ f'{type(data_preprocessor)}')
+
+ def train_step(self, data: Union[dict, tuple, list],
+ optim_wrapper: OptimWrapper) -> Dict[str, torch.Tensor]:
+ """Implements the default model training process including
+ preprocessing, model forward propagation, loss calculation,
+ optimization, and back-propagation.
+
+ During non-distributed training. If subclasses do not override the
+ :meth:`train_step`, :class:`EpochBasedTrainLoop` or
+ :class:`IterBasedTrainLoop` will call this method to update model
+ parameters. The default parameter update process is as follows:
+
+ 1. Calls ``self.data_processor(data, training=False)`` to collect
+ batch_inputs and corresponding data_samples(labels).
+ 2. Calls ``self(batch_inputs, data_samples, mode='loss')`` to get raw
+ loss
+ 3. Calls ``self.parse_losses`` to get ``parsed_losses`` tensor used to
+ backward and dict of loss tensor used to log messages.
+ 4. Calls ``optim_wrapper.update_params(loss)`` to update model.
+
+ Args:
+ data (dict or tuple or list): Data sampled from dataset.
+ optim_wrapper (OptimWrapper): OptimWrapper instance
+ used to update model parameters.
+
+ Returns:
+ Dict[str, torch.Tensor]: A ``dict`` of tensor for logging.
+ """
+ # Enable automatic mixed precision training context.
+ with optim_wrapper.optim_context(self):
+ data = self.data_preprocessor(data, True)
+ losses = self._run_forward(data, mode='loss') # type: ignore
+ parsed_losses, log_vars = self.parse_losses(losses) # type: ignore
+ optim_wrapper.update_params(parsed_losses)
+ return log_vars
+
+ def val_step(self, data: Union[tuple, dict, list]) -> list:
+ """Gets the predictions of given data.
+
+ Calls ``self.data_preprocessor(data, False)`` and
+ ``self(inputs, data_sample, mode='predict')`` in order. Return the
+ predictions which will be passed to evaluator.
+
+ Args:
+ data (dict or tuple or list): Data sampled from dataset.
+
+ Returns:
+ list: The predictions of given data.
+ """
+ data = self.data_preprocessor(data, False)
+ return self._run_forward(data, mode='predict') # type: ignore
+
+ def test_step(self, data: Union[dict, tuple, list]) -> list:
+ """``BaseModel`` implements ``test_step`` the same as ``val_step``.
+
+ Args:
+ data (dict or tuple or list): Data sampled from dataset.
+
+ Returns:
+ list: The predictions of given data.
+ """
+ data = self.data_preprocessor(data, False)
+ return self._run_forward(data, mode='predict') # type: ignore
+
+ def parse_losses(
+ self, losses: Dict[str, torch.Tensor]
+ ) -> Tuple[torch.Tensor, Dict[str, torch.Tensor]]:
+ """Parses the raw outputs (losses) of the network.
+
+ Args:
+ losses (dict): Raw output of the network, which usually contain
+ losses and other necessary information.
+
+ Returns:
+ tuple[Tensor, dict]: There are two elements. The first is the
+ loss tensor passed to optim_wrapper which may be a weighted sum
+ of all losses, and the second is log_vars which will be sent to
+ the logger.
+ """
+ log_vars = []
+ for loss_name, loss_value in losses.items():
+ if isinstance(loss_value, torch.Tensor):
+ log_vars.append([loss_name, loss_value.mean()])
+ elif is_list_of(loss_value, torch.Tensor):
+ log_vars.append(
+ [loss_name,
+ sum(_loss.mean() for _loss in loss_value)])
+ else:
+ raise TypeError(
+ f'{loss_name} is not a tensor or list of tensors')
+
+ loss = sum(value for key, value in log_vars if 'loss' in key)
+ log_vars.insert(0, ['loss', loss])
+ log_vars = OrderedDict(log_vars) # type: ignore
+
+ return loss, log_vars # type: ignore
+
+ def to(self, *args, **kwargs) -> nn.Module:
+ """Overrides this method to call :meth:`BaseDataPreprocessor.to`
+ additionally.
+
+ Returns:
+ nn.Module: The model itself.
+ """
+ device = torch._C._nn._parse_to(*args, **kwargs)[0]
+ if device is not None:
+ self._set_device(torch.device(device))
+ return super().to(*args, **kwargs)
+
+ def cuda(
+ self,
+ device: Optional[Union[int, str, torch.device]] = None,
+ ) -> nn.Module:
+ """Overrides this method to call :meth:`BaseDataPreprocessor.cuda`
+ additionally.
+
+ Returns:
+ nn.Module: The model itself.
+ """
+ if device is None or isinstance(device, int):
+ device = torch.device('cuda', index=device)
+ self._set_device(torch.device(device))
+ return super().cuda(device)
+
+ def npu(
+ self,
+ device: Union[int, str, torch.device, None] = None,
+ ) -> nn.Module:
+ """Overrides this method to call :meth:`BaseDataPreprocessor.npu`
+ additionally.
+
+ Returns:
+ nn.Module: The model itself.
+
+ Note:
+ This generation of NPU(Ascend910) does not support
+ the use of multiple cards in a single process,
+ so the index here needs to be consistent with the default device
+ """
+ device = torch.npu.current_device()
+ self._set_device(device)
+ return super().npu()
+
+ def cpu(self, *args, **kwargs) -> nn.Module:
+ """Overrides this method to call :meth:`BaseDataPreprocessor.cpu`
+ additionally.
+
+ Returns:
+ nn.Module: The model itself.
+ """
+ self._set_device(torch.device('cpu'))
+ return super().cpu()
+
+ def _set_device(self, device: torch.device) -> None:
+ """Recursively set device for `BaseDataPreprocessor` instance.
+
+ Args:
+ device (torch.device): the desired device of the parameters and
+ buffers in this module.
+ """
+
+ def apply_fn(module):
+ if not isinstance(module, BaseDataPreprocessor):
+ return
+ if device is not None:
+ module._device = device
+
+ self.apply(apply_fn)
+
+ @abstractmethod
+ def forward(self,
+ inputs: torch.Tensor,
+ data_samples: Optional[list] = None,
+ mode: str = 'tensor') -> Union[Dict[str, torch.Tensor], list]:
+ """Returns losses or predictions of training, validation, testing, and
+ simple inference process.
+
+ ``forward`` method of BaseModel is an abstract method, its subclasses
+ must implement this method.
+
+ Accepts ``batch_inputs`` and ``data_sample`` processed by
+ :attr:`data_preprocessor`, and returns results according to mode
+ arguments.
+
+ During non-distributed training, validation, and testing process,
+ ``forward`` will be called by ``BaseModel.train_step``,
+ ``BaseModel.val_step`` and ``BaseModel.val_step`` directly.
+
+ During distributed data parallel training process,
+ ``MMSeparateDistributedDataParallel.train_step`` will first call
+ ``DistributedDataParallel.forward`` to enable automatic
+ gradient synchronization, and then call ``forward`` to get training
+ loss.
+
+ Args:
+ inputs (torch.Tensor): batch input tensor collated by
+ :attr:`data_preprocessor`.
+ data_samples (list, optional):
+ data samples collated by :attr:`data_preprocessor`.
+ mode (str): mode should be one of ``loss``, ``predict`` and
+ ``tensor``
+
+ - ``loss``: Called by ``train_step`` and return loss ``dict``
+ used for logging
+ - ``predict``: Called by ``val_step`` and ``test_step``
+ and return list of `results used for computing metric.
+ - ``tensor``: Called by custom use to get ``Tensor`` type
+ results.
+
+ Returns:
+ dict or list:
+ - If ``mode == loss``, return a ``dict`` of loss tensor used
+ for backward and logging.
+ - If ``mode == predict``, return a ``list`` of inference
+ results.
+ - If ``mode == tensor``, return a tensor or ``tuple`` of tensor
+ or ``dict of tensor for custom use.
+ """
+
+ def _run_forward(self, data: Union[dict, tuple, list],
+ mode: str) -> Union[Dict[str, torch.Tensor], list]:
+ """Unpacks data for :meth:`forward`
+
+ Args:
+ data (dict or tuple or list): Data sampled from dataset.
+ mode (str): Mode of forward.
+
+ Returns:
+ dict or list: Results of training or testing mode.
+ """
+ if isinstance(data, dict):
+ results = self(**data, mode=mode)
+ elif isinstance(data, (list, tuple)):
+ results = self(*data, mode=mode)
+ else:
+ raise TypeError('Output of `data_preprocessor` should be '
+ f'list, tuple or dict, but got {type(data)}')
+ return results
diff --git a/testbed/open-mmlab__mmengine/mmengine/model/base_model/data_preprocessor.py b/testbed/open-mmlab__mmengine/mmengine/model/base_model/data_preprocessor.py
new file mode 100644
index 0000000000000000000000000000000000000000..17d70e067ee82546a6bc8313ab9fa0b45871e6e9
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/model/base_model/data_preprocessor.py
@@ -0,0 +1,272 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import math
+from typing import Mapping, Optional, Sequence, Union
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from mmengine.registry import MODELS
+from mmengine.structures import BaseDataElement
+from mmengine.utils import is_list_of
+from ..utils import stack_batch
+
+CastData = Union[tuple, dict, BaseDataElement, torch.Tensor, list, bytes, str,
+ None]
+
+
+@MODELS.register_module()
+class BaseDataPreprocessor(nn.Module):
+ """Base data pre-processor used for copying data to the target device.
+
+ Subclasses inherit from ``BaseDataPreprocessor`` could override the
+ forward method to implement custom data pre-processing, such as
+ batch-resize, MixUp, or CutMix.
+
+ Args:
+ non_blocking (bool): Whether block current process
+ when transferring data to device.
+ New in version 0.3.0.
+
+ Note:
+ Data dictionary returned by dataloader must be a dict and at least
+ contain the ``inputs`` key.
+ """
+
+ def __init__(self, non_blocking: Optional[bool] = False):
+ super().__init__()
+ self._non_blocking = non_blocking
+ self._device = torch.device('cpu')
+
+ def cast_data(self, data: CastData) -> CastData:
+ """Copying data to the target device.
+
+ Args:
+ data (dict): Data returned by ``DataLoader``.
+
+ Returns:
+ CollatedResult: Inputs and data sample at target device.
+ """
+ if isinstance(data, Mapping):
+ return {key: self.cast_data(data[key]) for key in data}
+ elif isinstance(data, (str, bytes)) or data is None:
+ return data
+ elif isinstance(data, tuple) and hasattr(data, '_fields'):
+ # namedtuple
+ return type(data)(*(self.cast_data(sample) for sample in data)) # type: ignore # noqa: E501 # yapf:disable
+ elif isinstance(data, Sequence):
+ return type(data)(self.cast_data(sample) for sample in data) # type: ignore # noqa: E501 # yapf:disable
+ elif isinstance(data, (torch.Tensor, BaseDataElement)):
+ return data.to(self.device, non_blocking=self._non_blocking)
+ else:
+ raise TypeError(
+ '`BaseDataPreprocessor.cast_data`: batch data must contain '
+ 'tensors, numpy arrays, numbers, dicts or lists, but '
+ f'found {type(data)}')
+
+ def forward(self, data: dict, training: bool = False) -> Union[dict, list]:
+ """Preprocesses the data into the model input format.
+
+ After the data pre-processing of :meth:`cast_data`, ``forward``
+ will stack the input tensor list to a batch tensor at the first
+ dimension.
+
+ Args:
+ data (dict): Data returned by dataloader
+ training (bool): Whether to enable training time augmentation.
+
+ Returns:
+ dict or list: Data in the same format as the model input.
+ """
+ return self.cast_data(data) # type: ignore
+
+ @property
+ def device(self):
+ return self._device
+
+ def to(self, *args, **kwargs) -> nn.Module:
+ """Overrides this method to set the :attr:`device`
+
+ Returns:
+ nn.Module: The model itself.
+ """
+ device = torch._C._nn._parse_to(*args, **kwargs)[0]
+ if device is not None:
+ self._device = torch.device(device)
+ return super().to(*args, **kwargs)
+
+ def cuda(self, *args, **kwargs) -> nn.Module:
+ """Overrides this method to set the :attr:`device`
+
+ Returns:
+ nn.Module: The model itself.
+ """
+ self._device = torch.device(torch.cuda.current_device())
+ return super().cuda()
+
+ def cpu(self, *args, **kwargs) -> nn.Module:
+ """Overrides this method to set the :attr:`device`
+
+ Returns:
+ nn.Module: The model itself.
+ """
+ self._device = torch.device('cpu')
+ return super().cpu()
+
+
+@MODELS.register_module()
+class ImgDataPreprocessor(BaseDataPreprocessor):
+ """Image pre-processor for normalization and bgr to rgb conversion.
+
+ Accepts the data sampled by the dataloader, and preprocesses it into the
+ format of the model input. ``ImgDataPreprocessor`` provides the
+ basic data pre-processing as follows
+
+ - Collates and moves data to the target device.
+ - Converts inputs from bgr to rgb if the shape of input is (3, H, W).
+ - Normalizes image with defined std and mean.
+ - Pads inputs to the maximum size of current batch with defined
+ ``pad_value``. The padding size can be divisible by a defined
+ ``pad_size_divisor``
+ - Stack inputs to batch_inputs.
+
+ For ``ImgDataPreprocessor``, the dimension of the single inputs must be
+ (3, H, W).
+
+ Note:
+ ``ImgDataPreprocessor`` and its subclass is built in the
+ constructor of :class:`BaseDataset`.
+
+ Args:
+ mean (Sequence[float or int], optional): The pixel mean of image
+ channels. If ``bgr_to_rgb=True`` it means the mean value of R,
+ G, B channels. If the length of `mean` is 1, it means all
+ channels have the same mean value, or the input is a gray image.
+ If it is not specified, images will not be normalized. Defaults
+ None.
+ std (Sequence[float or int], optional): The pixel standard deviation of
+ image channels. If ``bgr_to_rgb=True`` it means the standard
+ deviation of R, G, B channels. If the length of `std` is 1,
+ it means all channels have the same standard deviation, or the
+ input is a gray image. If it is not specified, images will
+ not be normalized. Defaults None.
+ pad_size_divisor (int): The size of padded image should be
+ divisible by ``pad_size_divisor``. Defaults to 1.
+ pad_value (float or int): The padded pixel value. Defaults to 0.
+ bgr_to_rgb (bool): whether to convert image from BGR to RGB.
+ Defaults to False.
+ rgb_to_bgr (bool): whether to convert image from RGB to RGB.
+ Defaults to False.
+ non_blocking (bool): Whether block current process
+ when transferring data to device.
+ New in version v0.3.0.
+
+ Note:
+ if images do not need to be normalized, `std` and `mean` should be
+ both set to None, otherwise both of them should be set to a tuple of
+ corresponding values.
+ """
+
+ def __init__(self,
+ mean: Optional[Sequence[Union[float, int]]] = None,
+ std: Optional[Sequence[Union[float, int]]] = None,
+ pad_size_divisor: int = 1,
+ pad_value: Union[float, int] = 0,
+ bgr_to_rgb: bool = False,
+ rgb_to_bgr: bool = False,
+ non_blocking: Optional[bool] = False):
+ super().__init__(non_blocking)
+ assert not (bgr_to_rgb and rgb_to_bgr), (
+ '`bgr2rgb` and `rgb2bgr` cannot be set to True at the same time')
+ assert (mean is None) == (std is None), (
+ 'mean and std should be both None or tuple')
+ if mean is not None:
+ assert len(mean) == 3 or len(mean) == 1, (
+ '`mean` should have 1 or 3 values, to be compatible with '
+ f'RGB or gray image, but got {len(mean)} values')
+ assert len(std) == 3 or len(std) == 1, ( # type: ignore
+ '`std` should have 1 or 3 values, to be compatible with RGB ' # type: ignore # noqa: E501
+ f'or gray image, but got {len(std)} values') # type: ignore
+ self._enable_normalize = True
+ self.register_buffer('mean',
+ torch.tensor(mean).view(-1, 1, 1), False)
+ self.register_buffer('std',
+ torch.tensor(std).view(-1, 1, 1), False)
+ else:
+ self._enable_normalize = False
+ self._channel_conversion = rgb_to_bgr or bgr_to_rgb
+ self.pad_size_divisor = pad_size_divisor
+ self.pad_value = pad_value
+
+ def forward(self, data: dict, training: bool = False) -> Union[dict, list]:
+ """Performs normalization、padding and bgr2rgb conversion based on
+ ``BaseDataPreprocessor``.
+
+ Args:
+ data (dict): Data sampled from dataset. If the collate
+ function of DataLoader is :obj:`pseudo_collate`, data will be a
+ list of dict. If collate function is :obj:`default_collate`,
+ data will be a tuple with batch input tensor and list of data
+ samples.
+ training (bool): Whether to enable training time augmentation. If
+ subclasses override this method, they can perform different
+ preprocessing strategies for training and testing based on the
+ value of ``training``.
+
+ Returns:
+ dict or list: Data in the same format as the model input.
+ """
+ data = self.cast_data(data) # type: ignore
+ _batch_inputs = data['inputs']
+ # Process data with `pseudo_collate`.
+ if is_list_of(_batch_inputs, torch.Tensor):
+ batch_inputs = []
+ for _batch_input in _batch_inputs:
+ # channel transform
+ if self._channel_conversion:
+ _batch_input = _batch_input[[2, 1, 0], ...]
+ # Convert to float after channel conversion to ensure
+ # efficiency
+ _batch_input = _batch_input.float()
+ # Normalization.
+ if self._enable_normalize:
+ if self.mean.shape[0] == 3:
+ assert _batch_input.dim(
+ ) == 3 and _batch_input.shape[0] == 3, (
+ 'If the mean has 3 values, the input tensor '
+ 'should in shape of (3, H, W), but got the tensor '
+ f'with shape {_batch_input.shape}')
+ _batch_input = (_batch_input - self.mean) / self.std
+ batch_inputs.append(_batch_input)
+ # Pad and stack Tensor.
+ batch_inputs = stack_batch(batch_inputs, self.pad_size_divisor,
+ self.pad_value)
+ # Process data with `default_collate`.
+ elif isinstance(_batch_inputs, torch.Tensor):
+ assert _batch_inputs.dim() == 4, (
+ 'The input of `ImgDataPreprocessor` should be a NCHW tensor '
+ 'or a list of tensor, but got a tensor with shape: '
+ f'{_batch_inputs.shape}')
+ if self._channel_conversion:
+ _batch_inputs = _batch_inputs[:, [2, 1, 0], ...]
+ # Convert to float after channel conversion to ensure
+ # efficiency
+ _batch_inputs = _batch_inputs.float()
+ if self._enable_normalize:
+ _batch_inputs = (_batch_inputs - self.mean) / self.std
+ h, w = _batch_inputs.shape[2:]
+ target_h = math.ceil(
+ h / self.pad_size_divisor) * self.pad_size_divisor
+ target_w = math.ceil(
+ w / self.pad_size_divisor) * self.pad_size_divisor
+ pad_h = target_h - h
+ pad_w = target_w - w
+ batch_inputs = F.pad(_batch_inputs, (0, pad_w, 0, pad_h),
+ 'constant', self.pad_value)
+ else:
+ raise TypeError('Output of `cast_data` should be a list of dict '
+ 'or a tuple with inputs and data_samples, but got'
+ f'{type(data)}: {data}')
+ data['inputs'] = batch_inputs
+ data.setdefault('data_samples', None)
+ return data
diff --git a/testbed/open-mmlab__mmengine/mmengine/model/base_module.py b/testbed/open-mmlab__mmengine/mmengine/model/base_module.py
new file mode 100644
index 0000000000000000000000000000000000000000..9adceaf3153abf0530659c759149d219c60b3669
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/model/base_module.py
@@ -0,0 +1,220 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import logging
+import warnings
+from abc import ABCMeta
+from collections import defaultdict
+from logging import FileHandler
+from typing import Iterable, Optional
+
+import torch.nn as nn
+
+from mmengine.dist import master_only
+from mmengine.logging import MMLogger, print_log
+from .weight_init import initialize, update_init_info
+
+
+class BaseModule(nn.Module, metaclass=ABCMeta):
+ """Base module for all modules in openmmlab. ``BaseModule`` is a wrapper of
+ ``torch.nn.Module`` with additional functionality of parameter
+ initialization. Compared with ``torch.nn.Module``, ``BaseModule`` mainly
+ adds three attributes.
+
+ - ``init_cfg``: the config to control the initialization.
+ - ``init_weights``: The function of parameter initialization and recording
+ initialization information.
+ - ``_params_init_info``: Used to track the parameter initialization
+ information. This attribute only exists during executing the
+ ``init_weights``.
+ Args:
+ init_cfg (dict, optional): Initialization config dict.
+ """
+
+ def __init__(self, init_cfg=None):
+ """Initialize BaseModule, inherited from `torch.nn.Module`"""
+
+ # NOTE init_cfg can be defined in different levels, but init_cfg
+ # in low levels has a higher priority.
+
+ super().__init__()
+ # define default value of init_cfg instead of hard code
+ # in init_weights() function
+ self._is_init = False
+
+ self.init_cfg = copy.deepcopy(init_cfg)
+
+ # Backward compatibility in derived classes
+ # if pretrained is not None:
+ # warnings.warn('DeprecationWarning: pretrained is a deprecated \
+ # key, please consider using init_cfg')
+ # self.init_cfg = dict(type='Pretrained', checkpoint=pretrained)
+
+ @property
+ def is_init(self):
+ return self._is_init
+
+ def init_weights(self):
+ """Initialize the weights."""
+
+ is_top_level_module = False
+ # check if it is top-level module
+ if not hasattr(self, '_params_init_info'):
+ # The `_params_init_info` is used to record the initialization
+ # information of the parameters
+ # the key should be the obj:`nn.Parameter` of model and the value
+ # should be a dict containing
+ # - init_info (str): The string that describes the initialization.
+ # - tmp_mean_value (FloatTensor): The mean of the parameter,
+ # which indicates whether the parameter has been modified.
+ # this attribute would be deleted after all parameters
+ # is initialized.
+ self._params_init_info = defaultdict(dict)
+ is_top_level_module = True
+
+ # Initialize the `_params_init_info`,
+ # When detecting the `tmp_mean_value` of
+ # the corresponding parameter is changed, update related
+ # initialization information
+ for name, param in self.named_parameters():
+ self._params_init_info[param][
+ 'init_info'] = f'The value is the same before and ' \
+ f'after calling `init_weights` ' \
+ f'of {self.__class__.__name__} '
+ self._params_init_info[param][
+ 'tmp_mean_value'] = param.data.mean().cpu()
+
+ # pass `params_init_info` to all submodules
+ # All submodules share the same `params_init_info`,
+ # so it will be updated when parameters are
+ # modified at any level of the model.
+ for sub_module in self.modules():
+ sub_module._params_init_info = self._params_init_info
+
+ logger = MMLogger.get_current_instance()
+ logger_name = logger.instance_name
+
+ module_name = self.__class__.__name__
+ if not self._is_init:
+ if self.init_cfg:
+ print_log(
+ f'initialize {module_name} with init_cfg {self.init_cfg}',
+ logger=logger_name,
+ level=logging.DEBUG)
+ initialize(self, self.init_cfg)
+ if isinstance(self.init_cfg, dict):
+ # prevent the parameters of
+ # the pre-trained model
+ # from being overwritten by
+ # the `init_weights`
+ if self.init_cfg['type'] == 'Pretrained':
+ return
+
+ for m in self.children():
+ if hasattr(m, 'init_weights'):
+ m.init_weights()
+ # users may overload the `init_weights`
+ update_init_info(
+ m,
+ init_info=f'Initialized by '
+ f'user-defined `init_weights`'
+ f' in {m.__class__.__name__} ')
+
+ self._is_init = True
+ else:
+ warnings.warn(f'init_weights of {self.__class__.__name__} has '
+ f'been called more than once.')
+
+ if is_top_level_module:
+ # self._dump_init_info(logger_name)
+ self._dump_init_info()
+
+ for sub_module in self.modules():
+ del sub_module._params_init_info
+
+ @master_only
+ def _dump_init_info(self):
+ """Dump the initialization information to a file named
+ `initialization.log.json` in workdir.
+
+ Args:
+ logger_name (str): The name of logger.
+ """
+
+ logger = MMLogger.get_current_instance()
+ logger_name = logger.instance_name
+ with_file_handler = False
+ # dump the information to the logger file if there is a `FileHandler`
+ for handler in logger.handlers:
+ if isinstance(handler, FileHandler):
+ handler.stream.write(
+ 'Name of parameter - Initialization information\n')
+ for name, param in self.named_parameters():
+ handler.stream.write(
+ f'\n{name} - {param.shape}: '
+ f"\n{self._params_init_info[param]['init_info']} \n")
+ handler.stream.flush()
+ with_file_handler = True
+ if not with_file_handler:
+ for name, param in self.named_parameters():
+ print_log(
+ f'\n{name} - {param.shape}: '
+ f"\n{self._params_init_info[param]['init_info']} \n ",
+ logger=logger_name)
+
+ def __repr__(self):
+ s = super().__repr__()
+ if self.init_cfg:
+ s += f'\ninit_cfg={self.init_cfg}'
+ return s
+
+
+class Sequential(BaseModule, nn.Sequential):
+ """Sequential module in openmmlab.
+
+ Ensures that all modules in ``Sequential`` have a different initialization
+ strategy than the outer model
+
+ Args:
+ init_cfg (dict, optional): Initialization config dict.
+ """
+
+ def __init__(self, *args, init_cfg: Optional[dict] = None):
+ BaseModule.__init__(self, init_cfg)
+ nn.Sequential.__init__(self, *args)
+
+
+class ModuleList(BaseModule, nn.ModuleList):
+ """ModuleList in openmmlab.
+
+ Ensures that all modules in ``ModuleList`` have a different initialization
+ strategy than the outer model
+
+ Args:
+ modules (iterable, optional): An iterable of modules to add.
+ init_cfg (dict, optional): Initialization config dict.
+ """
+
+ def __init__(self,
+ modules: Optional[Iterable] = None,
+ init_cfg: Optional[dict] = None):
+ BaseModule.__init__(self, init_cfg)
+ nn.ModuleList.__init__(self, modules)
+
+
+class ModuleDict(BaseModule, nn.ModuleDict):
+ """ModuleDict in openmmlab.
+
+ Ensures that all modules in ``ModuleDict`` have a different initialization
+ strategy than the outer model
+
+ Args:
+ modules (dict, optional): A mapping (dictionary) of (string: module)
+ or an iterable of key-value pairs of type (string, module).
+ init_cfg (dict, optional): Initialization config dict.
+ """
+
+ def __init__(self,
+ modules: Optional[dict] = None,
+ init_cfg: Optional[dict] = None):
+ BaseModule.__init__(self, init_cfg)
+ nn.ModuleDict.__init__(self, modules)
diff --git a/testbed/open-mmlab__mmengine/mmengine/model/utils.py b/testbed/open-mmlab__mmengine/mmengine/model/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce17b58c8d66d128fd9f20b3e18af3cce0bf41e6
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/model/utils.py
@@ -0,0 +1,256 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import logging
+import warnings
+from typing import List, Union
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from mmengine.logging import print_log
+from mmengine.utils.dl_utils import mmcv_full_available
+
+
+def stack_batch(tensor_list: List[torch.Tensor],
+ pad_size_divisor: int = 1,
+ pad_value: Union[int, float] = 0) -> torch.Tensor:
+ """Stack multiple tensors to form a batch and pad the tensor to the max
+ shape use the right bottom padding mode in these images. If
+ ``pad_size_divisor > 0``, add padding to ensure the shape of each dim is
+ divisible by ``pad_size_divisor``.
+
+ Args:
+ tensor_list (List[Tensor]): A list of tensors with the same dim.
+ pad_size_divisor (int): If ``pad_size_divisor > 0``, add padding
+ to ensure the shape of each dim is divisible by
+ ``pad_size_divisor``. This depends on the model, and many
+ models need to be divisible by 32. Defaults to 1
+ pad_value (int, float): The padding value. Defaults to 0.
+
+ Returns:
+ Tensor: The n dim tensor.
+ """
+ assert isinstance(
+ tensor_list,
+ list), (f'Expected input type to be list, but got {type(tensor_list)}')
+ assert tensor_list, '`tensor_list` could not be an empty list'
+ assert len({
+ tensor.ndim
+ for tensor in tensor_list
+ }) == 1, (f'Expected the dimensions of all tensors must be the same, '
+ f'but got {[tensor.ndim for tensor in tensor_list]}')
+
+ dim = tensor_list[0].dim()
+ num_img = len(tensor_list)
+ all_sizes: torch.Tensor = torch.Tensor(
+ [tensor.shape for tensor in tensor_list])
+ max_sizes = torch.ceil(
+ torch.max(all_sizes, dim=0)[0] / pad_size_divisor) * pad_size_divisor
+ padded_sizes = max_sizes - all_sizes
+ # The first dim normally means channel, which should not be padded.
+ padded_sizes[:, 0] = 0
+ if padded_sizes.sum() == 0:
+ return torch.stack(tensor_list)
+ # `pad` is the second arguments of `F.pad`. If pad is (1, 2, 3, 4),
+ # it means that padding the last dim with 1(left) 2(right), padding the
+ # penultimate dim to 3(top) 4(bottom). The order of `pad` is opposite of
+ # the `padded_sizes`. Therefore, the `padded_sizes` needs to be reversed,
+ # and only odd index of pad should be assigned to keep padding "right" and
+ # "bottom".
+ pad = torch.zeros(num_img, 2 * dim, dtype=torch.int)
+ pad[:, 1::2] = padded_sizes[:, range(dim - 1, -1, -1)]
+ batch_tensor = []
+ for idx, tensor in enumerate(tensor_list):
+ batch_tensor.append(
+ F.pad(tensor, tuple(pad[idx].tolist()), value=pad_value))
+ return torch.stack(batch_tensor)
+
+
+def detect_anomalous_params(loss: torch.Tensor, model) -> None:
+ parameters_in_graph = set()
+ visited = set()
+
+ def traverse(grad_fn):
+ if grad_fn is None:
+ return
+ if grad_fn not in visited:
+ visited.add(grad_fn)
+ if hasattr(grad_fn, 'variable'):
+ parameters_in_graph.add(grad_fn.variable)
+ parents = grad_fn.next_functions
+ if parents is not None:
+ for parent in parents:
+ grad_fn = parent[0]
+ traverse(grad_fn)
+
+ traverse(loss.grad_fn)
+ from mmengine.logging import MMLogger
+ logger = MMLogger.get_current_instance()
+ for n, p in model.named_parameters():
+ if p not in parameters_in_graph and p.requires_grad:
+ logger.log(
+ level=logging.ERROR,
+ msg=f'{n} with shape {p.size()} is not '
+ f'in the computational graph \n')
+
+
+def merge_dict(*args):
+ """Merge all dictionaries into one dictionary.
+
+ If pytorch version >= 1.8, ``merge_dict`` will be wrapped
+ by ``torch.fx.wrap``, which will make ``torch.fx.symbolic_trace`` skip
+ trace ``merge_dict``.
+
+ Note:
+ If a function needs to be traced by ``torch.fx.symbolic_trace``,
+ but inevitably needs to use ``update`` method of ``dict``(``update``
+ is not traceable). It should use ``merge_dict`` to replace
+ ``xxx.update``.
+
+ Args:
+ *args: dictionary needs to be merged.
+
+ Returns:
+ dict: Merged dict from args
+ """
+ output = dict()
+ for item in args:
+ assert isinstance(
+ item,
+ dict), (f'all arguments of merge_dict should be a dict, but got '
+ f'{type(item)}')
+ output.update(item)
+ return output
+
+
+# torch.fx is only available when pytorch version >= 1.8.
+# If the subclass of `BaseModel` has multiple submodules, and each module
+# will return a loss dict during training process, i.e., `TwoStageDetector`
+# in mmdet. It should use `merge_dict` to get the total loss, rather than
+# `loss.update` to keep model traceable.
+try:
+ import torch.fx
+
+ # make torch.fx skip trace `merge_dict`.
+ merge_dict = torch.fx.wrap(merge_dict)
+
+except ImportError:
+ warnings.warn('Cannot import torch.fx, `merge_dict` is a simple function '
+ 'to merge multiple dicts')
+
+
+class _BatchNormXd(nn.modules.batchnorm._BatchNorm):
+ """A general BatchNorm layer without input dimension check.
+
+ Reproduced from @kapily's work:
+ (https://github.com/pytorch/pytorch/issues/41081#issuecomment-783961547)
+ The only difference between BatchNorm1d, BatchNorm2d, BatchNorm3d, etc
+ is `_check_input_dim` that is designed for tensor sanity checks.
+ The check has been bypassed in this class for the convenience of converting
+ SyncBatchNorm.
+ """
+
+ def _check_input_dim(self, input: torch.Tensor):
+ return
+
+
+def revert_sync_batchnorm(module: nn.Module) -> nn.Module:
+ """Helper function to convert all `SyncBatchNorm` (SyncBN) and
+ `mmcv.ops.sync_bn.SyncBatchNorm`(MMSyncBN) layers in the model to
+ `BatchNormXd` layers.
+
+ Adapted from @kapily's work:
+ (https://github.com/pytorch/pytorch/issues/41081#issuecomment-783961547)
+
+ Args:
+ module (nn.Module): The module containing `SyncBatchNorm` layers.
+
+ Returns:
+ module_output: The converted module with `BatchNormXd` layers.
+ """
+ module_output = module
+ module_checklist = [torch.nn.modules.batchnorm.SyncBatchNorm]
+
+ if mmcv_full_available():
+ from mmcv.ops import SyncBatchNorm
+ module_checklist.append(SyncBatchNorm)
+
+ if isinstance(module, tuple(module_checklist)):
+ module_output = _BatchNormXd(module.num_features, module.eps,
+ module.momentum, module.affine,
+ module.track_running_stats)
+ if module.affine:
+ # no_grad() may not be needed here but
+ # just to be consistent with `convert_sync_batchnorm()`
+ with torch.no_grad():
+ module_output.weight = module.weight
+ module_output.bias = module.bias
+ module_output.running_mean = module.running_mean
+ module_output.running_var = module.running_var
+ module_output.num_batches_tracked = module.num_batches_tracked
+ module_output.training = module.training
+ # qconfig exists in quantized models
+ if hasattr(module, 'qconfig'):
+ module_output.qconfig = module.qconfig
+ for name, child in module.named_children():
+ # Some custom modules or 3rd party implemented modules may raise an
+ # error when calling `add_module`. Therefore, try to catch the error
+ # and do not raise it. See https://github.com/open-mmlab/mmengine/issues/638 # noqa: E501
+ # for more details.
+ try:
+ module_output.add_module(name, revert_sync_batchnorm(child))
+ except Exception:
+ print_log(
+ F'Failed to convert {child} from SyncBN to BN!',
+ logger='current',
+ level=logging.WARNING)
+ del module
+ return module_output
+
+
+def convert_sync_batchnorm(module: nn.Module,
+ implementation='torch') -> nn.Module:
+ """Helper function to convert all `BatchNorm` layers in the model to
+ `SyncBatchNorm` (SyncBN) or `mmcv.ops.sync_bn.SyncBatchNorm`(MMSyncBN)
+ layers. Adapted from _.
+
+ Args:
+ module (nn.Module): The module containing `SyncBatchNorm` layers.
+ implementation (str): The type of `SyncBatchNorm` to convert to.
+
+ - 'torch': convert to `torch.nn.modules.batchnorm.SyncBatchNorm`.
+ - 'mmcv': convert to `mmcv.ops.sync_bn.SyncBatchNorm`.
+
+ Returns:
+ nn.Module: The converted module with `SyncBatchNorm` layers.
+ """ # noqa: E501
+ module_output = module
+
+ if isinstance(module, torch.nn.modules.batchnorm._BatchNorm):
+ if implementation == 'torch':
+ SyncBatchNorm = torch.nn.modules.batchnorm.SyncBatchNorm
+ elif implementation == 'mmcv':
+ from mmcv.ops import SyncBatchNorm # type: ignore
+ else:
+ raise ValueError('sync_bn should be "torch" or "mmcv", but got '
+ f'{implementation}')
+
+ module_output = SyncBatchNorm(module.num_features, module.eps,
+ module.momentum, module.affine,
+ module.track_running_stats)
+
+ if module.affine:
+ with torch.no_grad():
+ module_output.weight = module.weight
+ module_output.bias = module.bias
+ module_output.running_mean = module.running_mean
+ module_output.running_var = module.running_var
+ module_output.num_batches_tracked = module.num_batches_tracked
+ if hasattr(module, 'qconfig'):
+ module_output.qconfig = module.qconfig
+ for name, child in module.named_children():
+ module_output.add_module(name,
+ convert_sync_batchnorm(child, implementation))
+ del module
+ return module_output
diff --git a/testbed/open-mmlab__mmengine/mmengine/model/weight_init.py b/testbed/open-mmlab__mmengine/mmengine/model/weight_init.py
new file mode 100644
index 0000000000000000000000000000000000000000..44c871616d6cad20ec1c8a1fd4378df281c2299c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/model/weight_init.py
@@ -0,0 +1,678 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import math
+import warnings
+
+import numpy as np
+import torch
+import torch.nn as nn
+from torch import Tensor
+
+from mmengine.logging import print_log
+from mmengine.registry import WEIGHT_INITIALIZERS, build_from_cfg
+
+
+def update_init_info(module, init_info):
+ """Update the `_params_init_info` in the module if the value of parameters
+ are changed.
+
+ Args:
+ module (obj:`nn.Module`): The module of PyTorch with a user-defined
+ attribute `_params_init_info` which records the initialization
+ information.
+ init_info (str): The string that describes the initialization.
+ """
+ assert hasattr(
+ module,
+ '_params_init_info'), f'Can not find `_params_init_info` in {module}'
+ for name, param in module.named_parameters():
+
+ assert param in module._params_init_info, (
+ f'Find a new :obj:`Parameter` '
+ f'named `{name}` during executing the '
+ f'`init_weights` of '
+ f'`{module.__class__.__name__}`. '
+ f'Please do not add or '
+ f'replace parameters during executing '
+ f'the `init_weights`. ')
+
+ # The parameter has been changed during executing the
+ # `init_weights` of module
+ mean_value = param.data.mean().cpu()
+ if module._params_init_info[param]['tmp_mean_value'] != mean_value:
+ module._params_init_info[param]['init_info'] = init_info
+ module._params_init_info[param]['tmp_mean_value'] = mean_value
+
+
+def constant_init(module, val, bias=0):
+ if hasattr(module, 'weight') and module.weight is not None:
+ nn.init.constant_(module.weight, val)
+ if hasattr(module, 'bias') and module.bias is not None:
+ nn.init.constant_(module.bias, bias)
+
+
+def xavier_init(module, gain=1, bias=0, distribution='normal'):
+ assert distribution in ['uniform', 'normal']
+ if hasattr(module, 'weight') and module.weight is not None:
+ if distribution == 'uniform':
+ nn.init.xavier_uniform_(module.weight, gain=gain)
+ else:
+ nn.init.xavier_normal_(module.weight, gain=gain)
+ if hasattr(module, 'bias') and module.bias is not None:
+ nn.init.constant_(module.bias, bias)
+
+
+def normal_init(module, mean=0, std=1, bias=0):
+ if hasattr(module, 'weight') and module.weight is not None:
+ nn.init.normal_(module.weight, mean, std)
+ if hasattr(module, 'bias') and module.bias is not None:
+ nn.init.constant_(module.bias, bias)
+
+
+def trunc_normal_init(module: nn.Module,
+ mean: float = 0,
+ std: float = 1,
+ a: float = -2,
+ b: float = 2,
+ bias: float = 0) -> None:
+ if hasattr(module, 'weight') and module.weight is not None:
+ trunc_normal_(module.weight, mean, std, a, b) # type: ignore
+ if hasattr(module, 'bias') and module.bias is not None:
+ nn.init.constant_(module.bias, bias) # type: ignore
+
+
+def uniform_init(module, a=0, b=1, bias=0):
+ if hasattr(module, 'weight') and module.weight is not None:
+ nn.init.uniform_(module.weight, a, b)
+ if hasattr(module, 'bias') and module.bias is not None:
+ nn.init.constant_(module.bias, bias)
+
+
+def kaiming_init(module,
+ a=0,
+ mode='fan_out',
+ nonlinearity='relu',
+ bias=0,
+ distribution='normal'):
+ assert distribution in ['uniform', 'normal']
+ if hasattr(module, 'weight') and module.weight is not None:
+ if distribution == 'uniform':
+ nn.init.kaiming_uniform_(
+ module.weight, a=a, mode=mode, nonlinearity=nonlinearity)
+ else:
+ nn.init.kaiming_normal_(
+ module.weight, a=a, mode=mode, nonlinearity=nonlinearity)
+ if hasattr(module, 'bias') and module.bias is not None:
+ nn.init.constant_(module.bias, bias)
+
+
+def caffe2_xavier_init(module, bias=0):
+ # `XavierFill` in Caffe2 corresponds to `kaiming_uniform_` in PyTorch
+ # Acknowledgment to FAIR's internal code
+ kaiming_init(
+ module,
+ a=1,
+ mode='fan_in',
+ nonlinearity='leaky_relu',
+ bias=bias,
+ distribution='uniform')
+
+
+def bias_init_with_prob(prior_prob):
+ """initialize conv/fc bias value according to a given probability value."""
+ bias_init = float(-np.log((1 - prior_prob) / prior_prob))
+ return bias_init
+
+
+def _get_bases_name(m):
+ return [b.__name__ for b in m.__class__.__bases__]
+
+
+class BaseInit:
+
+ def __init__(self, *, bias=0, bias_prob=None, layer=None):
+ self.wholemodule = False
+ if not isinstance(bias, (int, float)):
+ raise TypeError(f'bias must be a number, but got a {type(bias)}')
+
+ if bias_prob is not None:
+ if not isinstance(bias_prob, float):
+ raise TypeError(f'bias_prob type must be float, \
+ but got {type(bias_prob)}')
+
+ if layer is not None:
+ if not isinstance(layer, (str, list)):
+ raise TypeError(f'layer must be a str or a list of str, \
+ but got a {type(layer)}')
+ else:
+ layer = []
+
+ if bias_prob is not None:
+ self.bias = bias_init_with_prob(bias_prob)
+ else:
+ self.bias = bias
+ self.layer = [layer] if isinstance(layer, str) else layer
+
+ def _get_init_info(self):
+ info = f'{self.__class__.__name__}, bias={self.bias}'
+ return info
+
+
+@WEIGHT_INITIALIZERS.register_module(name='Constant')
+class ConstantInit(BaseInit):
+ """Initialize module parameters with constant values.
+
+ Args:
+ val (int | float): the value to fill the weights in the module with
+ bias (int | float): the value to fill the bias. Defaults to 0.
+ bias_prob (float, optional): the probability for bias initialization.
+ Defaults to None.
+ layer (str | list[str], optional): the layer will be initialized.
+ Defaults to None.
+ """
+
+ def __init__(self, val, **kwargs):
+ super().__init__(**kwargs)
+ self.val = val
+
+ def __call__(self, module):
+
+ def init(m):
+ if self.wholemodule:
+ constant_init(m, self.val, self.bias)
+ else:
+ layername = m.__class__.__name__
+ basesname = _get_bases_name(m)
+ if len(set(self.layer) & set([layername] + basesname)):
+ constant_init(m, self.val, self.bias)
+
+ module.apply(init)
+ if hasattr(module, '_params_init_info'):
+ update_init_info(module, init_info=self._get_init_info())
+
+ def _get_init_info(self):
+ info = f'{self.__class__.__name__}: val={self.val}, bias={self.bias}'
+ return info
+
+
+@WEIGHT_INITIALIZERS.register_module(name='Xavier')
+class XavierInit(BaseInit):
+ r"""Initialize module parameters with values according to the method
+ described in `Understanding the difficulty of training deep feedforward
+ neural networks - Glorot, X. & Bengio, Y. (2010).
+ `_
+
+ Args:
+ gain (int | float): an optional scaling factor. Defaults to 1.
+ bias (int | float): the value to fill the bias. Defaults to 0.
+ bias_prob (float, optional): the probability for bias initialization.
+ Defaults to None.
+ distribution (str): distribution either be ``'normal'``
+ or ``'uniform'``. Defaults to ``'normal'``.
+ layer (str | list[str], optional): the layer will be initialized.
+ Defaults to None.
+ """
+
+ def __init__(self, gain=1, distribution='normal', **kwargs):
+ super().__init__(**kwargs)
+ self.gain = gain
+ self.distribution = distribution
+
+ def __call__(self, module):
+
+ def init(m):
+ if self.wholemodule:
+ xavier_init(m, self.gain, self.bias, self.distribution)
+ else:
+ layername = m.__class__.__name__
+ basesname = _get_bases_name(m)
+ if len(set(self.layer) & set([layername] + basesname)):
+ xavier_init(m, self.gain, self.bias, self.distribution)
+
+ module.apply(init)
+ if hasattr(module, '_params_init_info'):
+ update_init_info(module, init_info=self._get_init_info())
+
+ def _get_init_info(self):
+ info = f'{self.__class__.__name__}: gain={self.gain}, ' \
+ f'distribution={self.distribution}, bias={self.bias}'
+ return info
+
+
+@WEIGHT_INITIALIZERS.register_module(name='Normal')
+class NormalInit(BaseInit):
+ r"""Initialize module parameters with the values drawn from the normal
+ distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`.
+
+ Args:
+ mean (int | float):the mean of the normal distribution. Defaults to 0.
+ std (int | float): the standard deviation of the normal distribution.
+ Defaults to 1.
+ bias (int | float): the value to fill the bias. Defaults to 0.
+ bias_prob (float, optional): the probability for bias initialization.
+ Defaults to None.
+ layer (str | list[str], optional): the layer will be initialized.
+ Defaults to None.
+ """
+
+ def __init__(self, mean=0, std=1, **kwargs):
+ super().__init__(**kwargs)
+ self.mean = mean
+ self.std = std
+
+ def __call__(self, module):
+
+ def init(m):
+ if self.wholemodule:
+ normal_init(m, self.mean, self.std, self.bias)
+ else:
+ layername = m.__class__.__name__
+ basesname = _get_bases_name(m)
+ if len(set(self.layer) & set([layername] + basesname)):
+ normal_init(m, self.mean, self.std, self.bias)
+
+ module.apply(init)
+ if hasattr(module, '_params_init_info'):
+ update_init_info(module, init_info=self._get_init_info())
+
+ def _get_init_info(self):
+ info = f'{self.__class__.__name__}: mean={self.mean},' \
+ f' std={self.std}, bias={self.bias}'
+ return info
+
+
+@WEIGHT_INITIALIZERS.register_module(name='TruncNormal')
+class TruncNormalInit(BaseInit):
+ r"""Initialize module parameters with the values drawn from the normal
+ distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)` with values
+ outside :math:`[a, b]`.
+
+ Args:
+ mean (float): the mean of the normal distribution. Defaults to 0.
+ std (float): the standard deviation of the normal distribution.
+ Defaults to 1.
+ a (float): The minimum cutoff value.
+ b ( float): The maximum cutoff value.
+ bias (float): the value to fill the bias. Defaults to 0.
+ bias_prob (float, optional): the probability for bias initialization.
+ Defaults to None.
+ layer (str | list[str], optional): the layer will be initialized.
+ Defaults to None.
+ """
+
+ def __init__(self,
+ mean: float = 0,
+ std: float = 1,
+ a: float = -2,
+ b: float = 2,
+ **kwargs) -> None:
+ super().__init__(**kwargs)
+ self.mean = mean
+ self.std = std
+ self.a = a
+ self.b = b
+
+ def __call__(self, module: nn.Module) -> None:
+
+ def init(m):
+ if self.wholemodule:
+ trunc_normal_init(m, self.mean, self.std, self.a, self.b,
+ self.bias)
+ else:
+ layername = m.__class__.__name__
+ basesname = _get_bases_name(m)
+ if len(set(self.layer) & set([layername] + basesname)):
+ trunc_normal_init(m, self.mean, self.std, self.a, self.b,
+ self.bias)
+
+ module.apply(init)
+ if hasattr(module, '_params_init_info'):
+ update_init_info(module, init_info=self._get_init_info())
+
+ def _get_init_info(self):
+ info = f'{self.__class__.__name__}: a={self.a}, b={self.b},' \
+ f' mean={self.mean}, std={self.std}, bias={self.bias}'
+ return info
+
+
+@WEIGHT_INITIALIZERS.register_module(name='Uniform')
+class UniformInit(BaseInit):
+ r"""Initialize module parameters with values drawn from the uniform
+ distribution :math:`\mathcal{U}(a, b)`.
+
+ Args:
+ a (int | float): the lower bound of the uniform distribution.
+ Defaults to 0.
+ b (int | float): the upper bound of the uniform distribution.
+ Defaults to 1.
+ bias (int | float): the value to fill the bias. Defaults to 0.
+ bias_prob (float, optional): the probability for bias initialization.
+ Defaults to None.
+ layer (str | list[str], optional): the layer will be initialized.
+ Defaults to None.
+ """
+
+ def __init__(self, a=0, b=1, **kwargs):
+ super().__init__(**kwargs)
+ self.a = a
+ self.b = b
+
+ def __call__(self, module):
+
+ def init(m):
+ if self.wholemodule:
+ uniform_init(m, self.a, self.b, self.bias)
+ else:
+ layername = m.__class__.__name__
+ basesname = _get_bases_name(m)
+ if len(set(self.layer) & set([layername] + basesname)):
+ uniform_init(m, self.a, self.b, self.bias)
+
+ module.apply(init)
+ if hasattr(module, '_params_init_info'):
+ update_init_info(module, init_info=self._get_init_info())
+
+ def _get_init_info(self):
+ info = f'{self.__class__.__name__}: a={self.a},' \
+ f' b={self.b}, bias={self.bias}'
+ return info
+
+
+@WEIGHT_INITIALIZERS.register_module(name='Kaiming')
+class KaimingInit(BaseInit):
+ r"""Initialize module parameters with the values according to the method
+ described in `Delving deep into rectifiers: Surpassing human-level
+ performance on ImageNet classification - He, K. et al. (2015).
+ `_
+
+ Args:
+ a (int | float): the negative slope of the rectifier used after this
+ layer (only used with ``'leaky_relu'``). Defaults to 0.
+ mode (str): either ``'fan_in'`` or ``'fan_out'``. Choosing
+ ``'fan_in'`` preserves the magnitude of the variance of the weights
+ in the forward pass. Choosing ``'fan_out'`` preserves the
+ magnitudes in the backwards pass. Defaults to ``'fan_out'``.
+ nonlinearity (str): the non-linear function (`nn.functional` name),
+ recommended to use only with ``'relu'`` or ``'leaky_relu'`` .
+ Defaults to 'relu'.
+ bias (int | float): the value to fill the bias. Defaults to 0.
+ bias_prob (float, optional): the probability for bias initialization.
+ Defaults to None.
+ distribution (str): distribution either be ``'normal'`` or
+ ``'uniform'``. Defaults to ``'normal'``.
+ layer (str | list[str], optional): the layer will be initialized.
+ Defaults to None.
+ """
+
+ def __init__(self,
+ a=0,
+ mode='fan_out',
+ nonlinearity='relu',
+ distribution='normal',
+ **kwargs):
+ super().__init__(**kwargs)
+ self.a = a
+ self.mode = mode
+ self.nonlinearity = nonlinearity
+ self.distribution = distribution
+
+ def __call__(self, module):
+
+ def init(m):
+ if self.wholemodule:
+ kaiming_init(m, self.a, self.mode, self.nonlinearity,
+ self.bias, self.distribution)
+ else:
+ layername = m.__class__.__name__
+ basesname = _get_bases_name(m)
+ if len(set(self.layer) & set([layername] + basesname)):
+ kaiming_init(m, self.a, self.mode, self.nonlinearity,
+ self.bias, self.distribution)
+
+ module.apply(init)
+ if hasattr(module, '_params_init_info'):
+ update_init_info(module, init_info=self._get_init_info())
+
+ def _get_init_info(self):
+ info = f'{self.__class__.__name__}: a={self.a}, mode={self.mode}, ' \
+ f'nonlinearity={self.nonlinearity}, ' \
+ f'distribution ={self.distribution}, bias={self.bias}'
+ return info
+
+
+@WEIGHT_INITIALIZERS.register_module(name='Caffe2Xavier')
+class Caffe2XavierInit(KaimingInit):
+ # `XavierFill` in Caffe2 corresponds to `kaiming_uniform_` in PyTorch
+ # Acknowledgment to FAIR's internal code
+ def __init__(self, **kwargs):
+ super().__init__(
+ a=1,
+ mode='fan_in',
+ nonlinearity='leaky_relu',
+ distribution='uniform',
+ **kwargs)
+
+ def __call__(self, module):
+ super().__call__(module)
+
+
+@WEIGHT_INITIALIZERS.register_module(name='Pretrained')
+class PretrainedInit:
+ """Initialize module by loading a pretrained model.
+
+ Args:
+ checkpoint (str): the checkpoint file of the pretrained model should
+ be load.
+ prefix (str, optional): the prefix of a sub-module in the pretrained
+ model. it is for loading a part of the pretrained model to
+ initialize. For example, if we would like to only load the
+ backbone of a detector model, we can set ``prefix='backbone.'``.
+ Defaults to None.
+ map_location (str): map tensors into proper locations. Defaults to cpu.
+ """
+
+ def __init__(self, checkpoint, prefix=None, map_location='cpu'):
+ self.checkpoint = checkpoint
+ self.prefix = prefix
+ self.map_location = map_location
+
+ def __call__(self, module):
+ from mmengine.runner.checkpoint import (_load_checkpoint_with_prefix,
+ load_checkpoint,
+ load_state_dict)
+ if self.prefix is None:
+ print_log(f'load model from: {self.checkpoint}', logger='current')
+ load_checkpoint(
+ module,
+ self.checkpoint,
+ map_location=self.map_location,
+ strict=False,
+ logger='current')
+ else:
+ print_log(
+ f'load {self.prefix} in model from: {self.checkpoint}',
+ logger='current')
+ state_dict = _load_checkpoint_with_prefix(
+ self.prefix, self.checkpoint, map_location=self.map_location)
+ load_state_dict(module, state_dict, strict=False, logger='current')
+
+ if hasattr(module, '_params_init_info'):
+ update_init_info(module, init_info=self._get_init_info())
+
+ def _get_init_info(self):
+ info = f'{self.__class__.__name__}: load from {self.checkpoint}'
+ return info
+
+
+def _initialize(module, cfg, wholemodule=False):
+ func = build_from_cfg(cfg, WEIGHT_INITIALIZERS)
+ # wholemodule flag is for override mode, there is no layer key in override
+ # and initializer will give init values for the whole module with the name
+ # in override.
+ func.wholemodule = wholemodule
+ func(module)
+
+
+def _initialize_override(module, override, cfg):
+ if not isinstance(override, (dict, list)):
+ raise TypeError(f'override must be a dict or a list of dict, \
+ but got {type(override)}')
+
+ override = [override] if isinstance(override, dict) else override
+
+ for override_ in override:
+
+ cp_override = copy.deepcopy(override_)
+ name = cp_override.pop('name', None)
+ if name is None:
+ raise ValueError('`override` must contain the key "name",'
+ f'but got {cp_override}')
+ # if override only has name key, it means use args in init_cfg
+ if not cp_override:
+ cp_override.update(cfg)
+ # if override has name key and other args except type key, it will
+ # raise error
+ elif 'type' not in cp_override.keys():
+ raise ValueError(
+ f'`override` need "type" key, but got {cp_override}')
+
+ if hasattr(module, name):
+ _initialize(getattr(module, name), cp_override, wholemodule=True)
+ else:
+ raise RuntimeError(f'module did not have attribute {name}, '
+ f'but init_cfg is {cp_override}.')
+
+
+def initialize(module, init_cfg):
+ r"""Initialize a module.
+
+ Args:
+ module (``torch.nn.Module``): the module will be initialized.
+ init_cfg (dict | list[dict]): initialization configuration dict to
+ define initializer. OpenMMLab has implemented 6 initializers
+ including ``Constant``, ``Xavier``, ``Normal``, ``Uniform``,
+ ``Kaiming``, and ``Pretrained``.
+
+ Example:
+ >>> module = nn.Linear(2, 3, bias=True)
+ >>> init_cfg = dict(type='Constant', layer='Linear', val =1 , bias =2)
+ >>> initialize(module, init_cfg)
+ >>> module = nn.Sequential(nn.Conv1d(3, 1, 3), nn.Linear(1,2))
+ >>> # define key ``'layer'`` for initializing layer with different
+ >>> # configuration
+ >>> init_cfg = [dict(type='Constant', layer='Conv1d', val=1),
+ dict(type='Constant', layer='Linear', val=2)]
+ >>> initialize(module, init_cfg)
+ >>> # define key``'override'`` to initialize some specific part in
+ >>> # module
+ >>> class FooNet(nn.Module):
+ >>> def __init__(self):
+ >>> super().__init__()
+ >>> self.feat = nn.Conv2d(3, 16, 3)
+ >>> self.reg = nn.Conv2d(16, 10, 3)
+ >>> self.cls = nn.Conv2d(16, 5, 3)
+ >>> model = FooNet()
+ >>> init_cfg = dict(type='Constant', val=1, bias=2, layer='Conv2d',
+ >>> override=dict(type='Constant', name='reg', val=3, bias=4))
+ >>> initialize(model, init_cfg)
+ >>> model = ResNet(depth=50)
+ >>> # Initialize weights with the pretrained model.
+ >>> init_cfg = dict(type='Pretrained',
+ checkpoint='torchvision://resnet50')
+ >>> initialize(model, init_cfg)
+ >>> # Initialize weights of a sub-module with the specific part of
+ >>> # a pretrained model by using "prefix".
+ >>> url = 'http://download.openmmlab.com/mmdetection/v2.0/retinanet/'\
+ >>> 'retinanet_r50_fpn_1x_coco/'\
+ >>> 'retinanet_r50_fpn_1x_coco_20200130-c2398f9e.pth'
+ >>> init_cfg = dict(type='Pretrained',
+ checkpoint=url, prefix='backbone.')
+ """
+ if not isinstance(init_cfg, (dict, list)):
+ raise TypeError(f'init_cfg must be a dict or a list of dict, \
+ but got {type(init_cfg)}')
+
+ if isinstance(init_cfg, dict):
+ init_cfg = [init_cfg]
+
+ for cfg in init_cfg:
+ # should deeply copy the original config because cfg may be used by
+ # other modules, e.g., one init_cfg shared by multiple bottleneck
+ # blocks, the expected cfg will be changed after pop and will change
+ # the initialization behavior of other modules
+ cp_cfg = copy.deepcopy(cfg)
+ override = cp_cfg.pop('override', None)
+ _initialize(module, cp_cfg)
+
+ if override is not None:
+ cp_cfg.pop('layer', None)
+ _initialize_override(module, override, cp_cfg)
+ else:
+ # All attributes in module have same initialization.
+ pass
+
+
+def _no_grad_trunc_normal_(tensor: Tensor, mean: float, std: float, a: float,
+ b: float) -> Tensor:
+ # Method based on
+ # https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf
+ # Modified from
+ # https://github.com/pytorch/pytorch/blob/master/torch/nn/init.py
+ def norm_cdf(x):
+ # Computes standard normal cumulative distribution function
+ return (1. + math.erf(x / math.sqrt(2.))) / 2.
+
+ if (mean < a - 2 * std) or (mean > b + 2 * std):
+ warnings.warn(
+ 'mean is more than 2 std from [a, b] in nn.init.trunc_normal_. '
+ 'The distribution of values may be incorrect.',
+ stacklevel=2)
+
+ with torch.no_grad():
+ # Values are generated by using a truncated uniform distribution and
+ # then using the inverse CDF for the normal distribution.
+ # Get upper and lower cdf values
+ lower = norm_cdf((a - mean) / std)
+ upper = norm_cdf((b - mean) / std)
+
+ # Uniformly fill tensor with values from [lower, upper], then translate
+ # to [2lower-1, 2upper-1].
+ tensor.uniform_(2 * lower - 1, 2 * upper - 1)
+
+ # Use inverse cdf transform for normal distribution to get truncated
+ # standard normal
+ tensor.erfinv_()
+
+ # Transform to proper mean, std
+ tensor.mul_(std * math.sqrt(2.))
+ tensor.add_(mean)
+
+ # Clamp to ensure it's in the proper range
+ tensor.clamp_(min=a, max=b)
+ return tensor
+
+
+def trunc_normal_(tensor: Tensor,
+ mean: float = 0.,
+ std: float = 1.,
+ a: float = -2.,
+ b: float = 2.) -> Tensor:
+ r"""Fills the input Tensor with values drawn from a truncated
+ normal distribution. The values are effectively drawn from the
+ normal distribution :math:`\mathcal{N}(\text{mean}, \text{std}^2)`
+ with values outside :math:`[a, b]` redrawn until they are within
+ the bounds. The method used for generating the random values works
+ best when :math:`a \leq \text{mean} \leq b`.
+
+ Modified from
+ https://github.com/pytorch/pytorch/blob/master/torch/nn/init.py
+
+ Args:
+ tensor (``torch.Tensor``): an n-dimensional `torch.Tensor`.
+ mean (float): the mean of the normal distribution.
+ std (float): the standard deviation of the normal distribution.
+ a (float): the minimum cutoff value.
+ b (float): the maximum cutoff value.
+ """
+ return _no_grad_trunc_normal_(tensor, mean, std, a, b)
diff --git a/testbed/open-mmlab__mmengine/mmengine/model/wrappers/__init__.py b/testbed/open-mmlab__mmengine/mmengine/model/wrappers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b0a0b63244e35e397378f01fcf2db0f7f4aaa3f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/model/wrappers/__init__.py
@@ -0,0 +1,17 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from mmengine.utils.dl_utils import TORCH_VERSION
+from mmengine.utils.version_utils import digit_version
+from .distributed import MMDistributedDataParallel
+from .seperate_distributed import MMSeparateDistributedDataParallel
+from .test_time_aug import BaseTTAModel
+from .utils import is_model_wrapper
+
+__all__ = [
+ 'MMDistributedDataParallel', 'is_model_wrapper',
+ 'MMSeparateDistributedDataParallel', 'BaseTTAModel'
+]
+
+if digit_version(TORCH_VERSION) >= digit_version('1.11.0'):
+ from .fully_sharded_distributed import \
+ MMFullyShardedDataParallel # noqa:F401
+ __all__.append('MMFullyShardedDataParallel')
diff --git a/testbed/open-mmlab__mmengine/mmengine/model/wrappers/distributed.py b/testbed/open-mmlab__mmengine/mmengine/model/wrappers/distributed.py
new file mode 100644
index 0000000000000000000000000000000000000000..4113aebf9ee49015f84d25f2f242c43ee9d92a23
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/model/wrappers/distributed.py
@@ -0,0 +1,167 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from typing import Any, Dict, Union
+
+import torch
+from torch.nn.parallel import DataParallel, DistributedDataParallel
+
+from mmengine.optim import OptimWrapper
+from mmengine.registry import MODEL_WRAPPERS
+from ..utils import detect_anomalous_params
+
+MODEL_WRAPPERS.register_module(module=DistributedDataParallel)
+MODEL_WRAPPERS.register_module(module=DataParallel)
+
+
+@MODEL_WRAPPERS.register_module()
+class MMDistributedDataParallel(DistributedDataParallel):
+ """A distributed model wrapper used for training,testing and validation in
+ loop.
+
+ Different from DistributedDataParallel, MMDistributedDataParallel
+ implements three methods :meth:`train_step`, :meth:`val_step` and
+ :meth:`test_step`, which will be called by ``train_loop``, ``val_loop``
+ and ``test_loop``.
+
+ - ``train_step``: Called by ``runner.train_loop``, and implement
+ default model forward, gradient back propagation, parameter updating
+ logic. To take advantage of DistributedDataParallel's automatic gradient
+ synchronization, ``train_step`` calls ``DistributedDataParallel.forward``
+ to calculate the losses, and call other methods of :class:`BaseModel` to
+ pre-process data and parse losses. Finally, update model parameters by
+ :class:`OptimWrapper` and return the loss dictionary used
+ for logging.
+
+ - ``val_step``: Called by ``runner.val_loop`` and get the inference
+ results. Since there is no gradient synchronization requirement,
+ this procedure is equivalent to ``BaseModel.val_step``
+
+ - ``test_step``: Called by ``runner.test_loop``, equivalent ``val_step``.
+
+ Args:
+ detect_anomalous_params (bool): This option is only used for
+ debugging which will slow down the training speed.
+ Detect anomalous parameters that are not included in
+ the computational graph with `loss` as the root.
+ There are two cases
+
+ - Parameters were not used during forward pass.
+ - Parameters were not used to produce loss.
+
+ Defaults to False.
+
+ **kwargs: keyword arguments passed to ``DistributedDataParallel``.
+
+ - device_ids (List[int] or torch.device, optional): CUDA devices
+ for module.
+ - output_device (int or torch.device, optional): Device location of
+ output for single-device CUDA modules.
+ - dim (int): Defaults to 0.
+ - broadcast_buffers (bool): Flag that enables syncing (
+ broadcasting) buffers of the module at beginning of the
+ ``forward`` function. Defaults to True
+ - find_unused_parameters (bool): Whether to find parameters of
+ module, which are not in the forward graph. Defaults to False.
+ - process_group (ProcessGroup, optional): The process group to be
+ used for distributed data all-reduction.
+ - bucket_cap_mb (int): bucket size in MegaBytes (MB). Defaults
+ to 25.
+ - check_reduction (bool): This argument is deprecated. Defaults
+ to False.
+ - gradient_as_bucket_view (bool): Defaults to False.
+ - static_graph (bool): Defaults to False.
+
+ See more information about arguments in
+ :class:`torch.nn.parallel.DistributedDataParallel`.
+
+ Note:
+ If model has multiple submodules and each module has
+ separate optimization strategies,
+ :class:`MMSeparateDistributedDataParallel` should be used to wrap
+ the model.
+
+ Note:
+ If model itself has custom optimization strategy, rather than
+ simply forward model and update model. A custom model wrapper
+ inherit from ``MMDistributedDataParallel`` should be defined and
+ override the ``train_step`` method.
+ """
+
+ def __init__(self,
+ module,
+ detect_anomalous_params: bool = False,
+ **kwargs):
+ super().__init__(module=module, **kwargs)
+ self.detect_anomalous_params = detect_anomalous_params
+
+ def train_step(self, data: Union[dict, tuple, list],
+ optim_wrapper: OptimWrapper) -> Dict[str, torch.Tensor]:
+ """Interface for model forward, backward and parameters updating during
+ training process.
+
+ :meth:`train_step` will perform the following steps in order:
+
+ - If :attr:`module` defines the preprocess method,
+ call ``module.preprocess`` to pre-processing data.
+ - Call ``module.forward(**data)`` and get losses.
+ - Parse losses.
+ - Call ``optim_wrapper.optimizer_step`` to update parameters.
+ - Return log messages of losses.
+
+ Args:
+ data (dict or tuple or list): Data sampled from dataset.
+ optim_wrapper (OptimWrapper): A wrapper of optimizer to
+ update parameters.
+
+ Returns:
+ Dict[str, torch.Tensor]: A ``dict`` of tensor for logging.
+ """
+ # Enable automatic mixed precision training context.
+ with optim_wrapper.optim_context(self):
+ data = self.module.data_preprocessor(data, training=True)
+ losses = self._run_forward(data, mode='loss')
+ parsed_loss, log_vars = self.module.parse_losses(losses)
+ optim_wrapper.update_params(parsed_loss)
+ if self.detect_anomalous_params:
+ detect_anomalous_params(parsed_loss, model=self)
+ return log_vars
+
+ def val_step(self, data: Union[dict, tuple, list]) -> list:
+ """Gets the prediction of module during validation process.
+
+ Args:
+ data (dict or tuple or list): Data sampled from dataset.
+
+ Returns:
+ list: The predictions of given data.
+ """
+ return self.module.val_step(data)
+
+ def test_step(self, data: Union[dict, tuple, list]) -> list:
+ """Gets the predictions of module during testing process.
+
+ Args:
+ data (dict or tuple or list): Data sampled from dataset.
+
+ Returns:
+ list: The predictions of given data.
+ """
+ return self.module.test_step(data)
+
+ def _run_forward(self, data: Union[dict, tuple, list], mode: str) -> Any:
+ """Unpacks data for :meth:`forward`
+
+ Args:
+ data (dict or tuple or list): Data sampled from dataset.
+ mode (str): Mode of forward.
+
+ Returns:
+ dict or list: Results of training or testing mode.
+ """
+ if isinstance(data, dict):
+ results = self(**data, mode=mode)
+ elif isinstance(data, (list, tuple)):
+ results = self(*data, mode=mode)
+ else:
+ raise TypeError('Output of `data_preprocessor` should be '
+ f'list, tuple or dict, but got {type(data)}')
+ return results
diff --git a/testbed/open-mmlab__mmengine/mmengine/model/wrappers/fully_sharded_distributed.py b/testbed/open-mmlab__mmengine/mmengine/model/wrappers/fully_sharded_distributed.py
new file mode 100644
index 0000000000000000000000000000000000000000..87780b3bfe3bd42dee7e766262f4a5b7ebe22f9a
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/model/wrappers/fully_sharded_distributed.py
@@ -0,0 +1,223 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from typing import Callable, Dict, List, Optional, Union
+
+import torch
+import torch.nn as nn
+from torch.distributed import ProcessGroup
+from torch.distributed.fsdp.fully_sharded_data_parallel import (
+ BackwardPrefetch, CPUOffload, FullyShardedDataParallel)
+
+from mmengine.optim import OptimWrapper
+from mmengine.registry import MODEL_WRAPPERS, Registry
+from mmengine.structures import BaseDataElement
+
+# support customize fsdp policy
+FSDP_WRAP_POLICIES = Registry('fsdp wrap policy')
+
+
+@MODEL_WRAPPERS.register_module()
+class MMFullyShardedDataParallel(FullyShardedDataParallel):
+ """A wrapper for sharding Module parameters across data parallel workers.
+
+ Different from FullyShardedDataParallel, MMFullyShardedDataParallel
+ implements three methods :meth:`train_step`, :meth:`val_step` and
+ :meth:`test_step`, which will be called by ``train_loop``, ``val_loop``
+ and ``test_loop``.
+
+ - ``train_step``: Called by ``runner.train_loop``, and implement
+ default model forward, gradient back propagation, parameter updating
+ logic.
+
+ - ``val_step``: Called by ``runner.val_loop`` and get the inference
+ results. Specially, since MMFullyShardedDataParallel will wrap model
+ recursively, it may cause some problem if one just use
+ ``BaseModel.val_step`` to implement ``val_step`` here. To avoid that,
+ ``val_step`` will call methods of :obj:`BaseModel` to pre-process
+ data first, and use ``FullyShardedDataParallel.forward`` to get result.
+
+ - ``test_step``: Called by ``runner.test_loop`` and get the inference
+ results. Its logic is equivalent to ``val_loop``.
+
+ Args:
+ module (nn.Module): module to be wrapped with FSDP.
+ process_group (Optional[ProcessGroup]): process group for sharding.
+ cpu_offload (Optional[Union[bool,CPUOffload]]):
+ CPU offloading config.
+ Different from FullyShardedDataParallel,Since it can be set by
+ users' pre-defined config in MMEngine,its type is expected to be
+ `None`, `bool` or `CPUOffload`.
+
+ Currently, only parameter and gradient CPU offload is supported.
+ It can be enabled via passing in
+ ``cpu_offload=CPUOffload(offload_params=True)``. Note that this
+ currently implicitly enables gradient offloading to CPU in order
+ for params and grads to be on same device to work with optimizer.
+ This API is subject to change. Default is ``None`` in which case
+ there will be no offloading.
+ fsdp_auto_wrap_policy: (Optional[Union[str,Callable]]):
+ Specifying a policy to recursively wrap layers with FSDP.
+ Different from FullyShardedDataParallel, Since it can be set by
+ users' pre-defined config in MMEngine, its type is expected to be
+ `None`, `str` or `Callable`. If it's `str`, then
+ MMFullyShardedDataParallel will try to get specified method in
+ ``FSDP_WRAP_POLICIES`` registry,and this method will be passed to
+ FullyShardedDataParallel to finally initialize model.
+
+ Note that this policy currently will only apply to child modules of
+ the passed in module. The remainder modules are always wrapped in
+ the returned FSDP root instance.
+ ``default_auto_wrap_policy`` written in
+ ``torch.distributed.fsdp.wrap`` is an example of
+ ``fsdp_auto_wrap_policy`` callable, this policy wraps layers with
+ parameter sizes larger than 100M. Users can supply the customized
+ ``fsdp_auto_wrap_policy`` callable that should accept following
+ arguments: ``module: nn.Module``, ``recurse: bool``,
+ ``unwrapped_params: int``, extra customized arguments could be
+ added to the customized ``fsdp_auto_wrap_policy`` callable as well.
+
+ Example::
+
+ >>> def custom_auto_wrap_policy(
+ >>> module: nn.Module,
+ >>> recurse: bool,
+ >>> unwrapped_params: int,
+ >>> # These are customizable for this policy function.
+ >>> min_num_params: int = int(1e8),
+ >>> ) -> bool:
+ >>> return unwrapped_params >= min_num_params
+
+ backward_prefetch: (Optional[Union[str,BackwardPrefetch]]):
+ Different from FullyShardedDataParallel, Since it will be set by
+ users' pre-defined config in MMEngine,its type is expected to be
+ `None`, `str` or `BackwardPrefetch`.
+
+ This is an experimental feature that is subject to change in the
+ the near future. It allows users to enable two different
+ backward_prefetch algorithms to help backward communication and
+ computation overlapping.
+ Pros and cons of each algorithm is explained in class
+ ``BackwardPrefetch``.
+
+ **kwargs: Keyword arguments passed to
+ :class:`FullyShardedDataParallel`.
+ """
+
+ def __init__(
+ self,
+ module: nn.Module,
+ process_group: Optional[ProcessGroup] = None,
+ cpu_offload: Optional[Union[bool, CPUOffload]] = None,
+ fsdp_auto_wrap_policy: Optional[Union[str, Callable]] = None,
+ backward_prefetch: Optional[Union[str, BackwardPrefetch]] = None,
+ **kwargs,
+ ):
+
+ if cpu_offload is not None:
+ if isinstance(cpu_offload, bool):
+ cpu_offload = CPUOffload(offload_params=cpu_offload)
+ elif not isinstance(cpu_offload, CPUOffload):
+ raise TypeError(
+ '`cpu_offload` should be `None`, `bool`'
+ f'or `CPUOffload`, but has type {type(cpu_offload)}')
+
+ if fsdp_auto_wrap_policy is not None:
+ if isinstance(fsdp_auto_wrap_policy, str):
+ assert fsdp_auto_wrap_policy in FSDP_WRAP_POLICIES, \
+ '`FSDP_WRAP_POLICIES` has no ' \
+ f'function {fsdp_auto_wrap_policy}'
+ fsdp_auto_wrap_policy = FSDP_WRAP_POLICIES.get( # type: ignore
+ fsdp_auto_wrap_policy)
+ if not isinstance(fsdp_auto_wrap_policy,
+ Callable): # type: ignore
+ raise TypeError(
+ 'Registered `fsdp_auto_wrap_policy` needs to be '
+ '`Callable`, but has type '
+ f'{type(fsdp_auto_wrap_policy)}')
+ elif not isinstance(fsdp_auto_wrap_policy,
+ Callable): # type: ignore
+ raise TypeError(
+ '`fsdp_auto_wrap_policy` should be `None`, `str` '
+ 'or `Callable`, but has type '
+ f'{type(fsdp_auto_wrap_policy)}')
+
+ if backward_prefetch is not None:
+ if isinstance(backward_prefetch, str):
+ assert backward_prefetch in ['pre', 'post'], \
+ '`backward_prefetch` should be either `pre` or `post`,' \
+ f' but get {backward_prefetch}'
+ if backward_prefetch == 'pre':
+ backward_prefetch = BackwardPrefetch.BACKWARD_PRE
+ else:
+ backward_prefetch = BackwardPrefetch.BACKWARD_POST
+ elif not isinstance(backward_prefetch, BackwardPrefetch):
+ raise TypeError('`backward_prefetch` should be `None`, `str` '
+ 'or `BackwardPrefetch`, but has type '
+ f'{type(backward_prefetch)}')
+
+ super().__init__(
+ module=module,
+ process_group=process_group,
+ auto_wrap_policy=fsdp_auto_wrap_policy,
+ cpu_offload=cpu_offload,
+ backward_prefetch=backward_prefetch,
+ **kwargs)
+
+ def train_step(self, data: dict,
+ optim_wrapper: OptimWrapper) -> Dict[str, torch.Tensor]:
+ """Interface for model forward, backward and parameters updating during
+ training process.
+
+ :meth:`train_step` will perform the following steps in order:
+
+ - If :attr:`module` defines the preprocess method,
+ call ``module.preprocess`` to pre-processing data.
+ - Call ``module.forward(**data)`` and get losses.
+ - Parse losses.
+ - Call ``optim_wrapper.optimizer_step`` to update parameters.
+ - Return log messages of losses.
+
+ Args:
+ data (dict): Data sampled by dataloader.
+ optim_wrapper (OptimWrapper): A wrapper of optimizer to
+ update parameters.
+
+ Returns:
+ Dict[str, torch.Tensor]: A ``dict`` of tensor for logging.
+ """
+ # enable automatic mixed precision training context.
+ with optim_wrapper.optim_context(self):
+ data = self.module.data_preprocessor(data, training=True)
+ if isinstance(data, dict):
+ losses = self(**data, mode='loss')
+ elif isinstance(data, (list, tuple)):
+ losses = self(*data, mode='loss')
+ else:
+ raise TypeError('Output of `data_preprocessor` should be '
+ f'list tuple or dict, but got {type(data)}')
+ parsed_loss, log_vars = self.module.parse_losses(losses)
+ optim_wrapper.update_params(parsed_loss)
+ return log_vars
+
+ def val_step(self, data: dict) -> List[BaseDataElement]:
+ """Gets the prediction of module during validation process.
+
+ Args:
+ data (dict): Data sampled by dataloader.
+
+ Returns:
+ List[BaseDataElement] or dict: The predictions of given data.
+ """
+ inputs, data_sample = self.module.data_preprocessor(data, False)
+ return self(inputs, data_sample, mode='predict')
+
+ def test_step(self, data: dict) -> List[BaseDataElement]:
+ """Gets the predictions of module during testing process.
+
+ Args:
+ data (dict): Data sampled by dataloader.
+
+ Returns:
+ List[BaseDataElement]: The predictions of given data.
+ """
+ inputs, data_sample = self.module.data_preprocessor(data, False)
+ return self(inputs, data_sample, mode='predict')
diff --git a/testbed/open-mmlab__mmengine/mmengine/model/wrappers/seperate_distributed.py b/testbed/open-mmlab__mmengine/mmengine/model/wrappers/seperate_distributed.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac9c2383c325282a19d655b156820b711de04d53
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/model/wrappers/seperate_distributed.py
@@ -0,0 +1,155 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from contextlib import ExitStack, contextmanager
+from typing import Dict, Union
+
+import torch
+import torch.nn as nn
+from torch.nn.parallel.distributed import DistributedDataParallel
+
+from mmengine.device import get_device
+from mmengine.optim import OptimWrapperDict
+from mmengine.registry import MODEL_WRAPPERS
+from .distributed import MMDistributedDataParallel
+
+
+@MODEL_WRAPPERS.register_module()
+class MMSeparateDistributedDataParallel(DistributedDataParallel):
+ """A DistributedDataParallel wrapper for models in MMGeneration.
+
+ In MMedting and MMGeneration there is a need to wrap different modules in
+ the models with separate DistributedDataParallel. Otherwise, it will cause
+ errors for GAN training. For example, the GAN model, usually has two
+ submodules: generator and discriminator. If we wrap both of them in one
+ standard DistributedDataParallel, it will cause errors during training,
+ because when we update the parameters of the generator (or discriminator),
+ the parameters of the discriminator (or generator) is not updated, which is
+ not allowed for DistributedDataParallel. So we design this wrapper to
+ separately wrap DistributedDataParallel for generator and discriminator.
+ In this wrapper, we perform two operations:
+
+ 1. Wraps each module in the models with separate MMDistributedDataParallel.
+ Note that only modules with parameters will be wrapped.
+ 2. Calls ``train_step``, ``val_step`` and ``test_step`` of submodules to
+ get losses and predictions.
+
+ Args:
+ module (nn.Module): model contain multiple submodules which have
+ separately updating strategy.
+ broadcast_buffers (bool): Same as that in
+ ``torch.nn.parallel.distributed.DistributedDataParallel``.
+ Defaults to False.
+ find_unused_parameters (bool): Same as that in
+ ``torch.nn.parallel.distributed.DistributedDataParallel``.
+ Traverse the autograd graph of all tensors contained in returned
+ value of the wrapped module's forward function. Defaults to False.
+ **kwargs: Keyword arguments passed to ``MMDistributedDataParallel``.
+
+ - device_ids (List[int] or torch.device, optional): CUDA devices
+ for module.
+ - output_device (int or torch.device, optional): Device location of
+ output for single-device CUDA modules.
+ - dim (int): Defaults to 0.
+ - process_group (ProcessGroup, optional): The process group to be
+ used for distributed data all-reduction.
+ - bucket_cap_mb (int): bucket size in MegaBytes (MB). Defaults
+ to 25.
+ - check_reduction (bool): This argument is deprecated. Defaults
+ to False.
+ - gradient_as_bucket_view (bool): Defaults to False.
+ - static_graph (bool): Defaults to False.
+
+ See more information about arguments in
+ :class:`torch.nn.parallel.DistributedDataParallel`.
+ """
+
+ def __init__(self,
+ module: nn.Module,
+ broadcast_buffers: bool = False,
+ find_unused_parameters: bool = False,
+ **kwargs):
+ super(DistributedDataParallel, self).__init__()
+ self.module = module
+ device = get_device()
+ # Wrap the submodule with parameters of `self.module` to
+ # `MMDistributedDataParallel`
+ for name, sub_module in module._modules.items():
+ # module without parameters.
+ if next(sub_module.parameters(), None) is None:
+ sub_module = sub_module.to(device)
+ elif all(not p.requires_grad for p in sub_module.parameters()):
+ sub_module = sub_module.to(device)
+ else:
+ sub_module = MMDistributedDataParallel(
+ module=sub_module.to(device),
+ broadcast_buffers=broadcast_buffers,
+ find_unused_parameters=find_unused_parameters,
+ **kwargs)
+ module._modules[name] = sub_module
+
+ def train_step(self, data: Union[dict, tuple, list],
+ optim_wrapper: OptimWrapperDict) -> Dict[str, torch.Tensor]:
+ """Interface for model forward, backward and parameters updating during
+ training process.
+
+ Args:
+ data (dict or tuple or list): Data sampled from dataset.
+ optim_wrapper (OptimWrapperDict): A wrapper of optimizer to
+ update parameters.
+
+ Returns:
+ Dict[str, torch.Tensor]: A dict of tensor for logging.
+ """
+ return self.module.train_step(data, optim_wrapper)
+
+ def val_step(self, data: Union[dict, tuple, list]) -> list:
+ """Gets the prediction of module during validation process.
+
+ Args:
+ data (dict or tuple or list): Data sampled from dataset.
+
+ Returns:
+ list: The predictions of given data.
+ """
+ return self.module.val_step(data)
+
+ def test_step(self, data: Union[dict, tuple, list]) -> list:
+ """Gets the predictions of module during testing process.
+
+ Args:
+ data (dict or tuple or list): Data sampled from dataset.
+
+ Returns:
+ list: The predictions of given data.
+ """
+ return self.module.test_step(data)
+
+ @contextmanager
+ def no_sync(self):
+ """Enables ``no_sync`` context of all sub ``MMDistributedDataParallel``
+ modules."""
+ with ExitStack() as stack:
+ for sub_ddp_model in self.module._modules.values():
+ stack.enter_context(sub_ddp_model.no_sync())
+ yield
+
+ def train(self, mode: bool = True) -> 'MMSeparateDistributedDataParallel':
+ """Sets the module in training mode.
+
+ In order to make the ddp wrapper inheritance hierarchy more uniform,
+ ``MMSeparateDistributedDataParallel`` inherits from
+ ``DistributedDataParallel``, but will not call its constructor.
+ Since the attributes of ``DistributedDataParallel`` have not been
+ initialized, call the ``train`` method of ``DistributedDataParallel``
+ will raise an error if pytorch version <= 1.9. Therefore, override
+ this method to call the ``train`` method of submodules.
+
+ Args:
+ mode (bool): whether to set training mode (``True``) or evaluation
+ mode (``False``). Defaults to ``True``.
+
+ Returns:
+ Module: self.
+ """
+ self.training = mode
+ self.module.train(mode)
+ return self
diff --git a/testbed/open-mmlab__mmengine/mmengine/model/wrappers/test_time_aug.py b/testbed/open-mmlab__mmengine/mmengine/model/wrappers/test_time_aug.py
new file mode 100644
index 0000000000000000000000000000000000000000..d99919df9e236915bc7bc02fc19819901e870a12
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/model/wrappers/test_time_aug.py
@@ -0,0 +1,127 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from abc import abstractmethod
+from typing import Dict, List, Union
+
+import torch
+import torch.nn as nn
+
+from mmengine import MODELS
+from mmengine.structures import BaseDataElement
+
+# multi-batch inputs processed by different augmentations from the same batch.
+EnhancedBatchInputs = List[Union[torch.Tensor, List[torch.Tensor]]]
+# multi-batch data samples processed by different augmentations from the same
+# batch. The inner list stands for different augmentations and the outer list
+# stands for batch.
+EnhancedBatchDataSamples = List[List[BaseDataElement]]
+DATA_BATCH = Union[Dict[str, Union[EnhancedBatchInputs,
+ EnhancedBatchDataSamples]], tuple, dict]
+MergedDataSamples = List[BaseDataElement]
+
+
+@MODELS.register_module()
+class BaseTTAModel(nn.Module):
+ """Base model for inference with test-time augmentation.
+
+ ``BaseTTAModel`` is a wrapper for inference given multi-batch data.
+ It implements the :meth:`test_step` for multi-batch data inference.
+ ``multi-batch`` data means data processed by different augmentation
+ from the same batch.
+
+ During test time augmentation, the data processed by
+ :obj:`mmcv.transforms.TestTimeAug`, and then collated by
+ ``pseudo_collate`` will have the following format:
+
+ .. code-block::
+
+ result = dict(
+ inputs=[
+ [image1_aug1, image2_aug1],
+ [image1_aug2, image2_aug2]
+ ],
+ data_samples=[
+ [data_sample1_aug1, data_sample2_aug1],
+ [data_sample1_aug2, data_sample2_aug2],
+ ]
+ )
+
+ ``image{i}_aug{j}`` means the i-th image of the batch, which is
+ augmented by the j-th augmentation.
+
+ ``BaseTTAModel`` will collate the data to:
+
+ .. code-block::
+
+ data1 = dict(
+ inputs=[image1_aug1, image2_aug1],
+ data_samples=[data_sample1_aug1, data_sample2_aug1]
+ )
+
+ data2 = dict(
+ inputs=[image1_aug2, image2_aug2],
+ data_samples=[data_sample1_aug2, data_sample2_aug2]
+ )
+
+ ``data1`` and ``data2`` will be passed to model, and the results will be
+ merged by :meth:`merge_preds`.
+
+ Note:
+ :meth:`merge_preds` is an abstract method, all subclasses should
+ implement it.
+
+ Args:
+ module (dict or nn.Module): Tested model.
+ """
+
+ def __init__(self, module: Union[dict, nn.Module]):
+ super().__init__()
+ if isinstance(module, nn.Module):
+ self.module = module
+ elif isinstance(module, dict):
+ self.module = MODELS.build(module)
+ else:
+ raise TypeError('The type of module should be a `nn.Module` '
+ f'instance or a dict, but got {module}')
+ assert hasattr(self.module, 'test_step'), (
+ 'Model wrapped by BaseTTAModel must implement `test_step`!')
+
+ @abstractmethod
+ def merge_preds(self, data_samples_list: EnhancedBatchDataSamples) \
+ -> MergedDataSamples:
+ """Merge predictions of enhanced data to one prediction.
+
+ Args:
+ data_samples_list (EnhancedBatchDataSamples): List of predictions
+ of all enhanced data.
+
+ Returns:
+ List[BaseDataElement]: Merged prediction.
+ """
+
+ def test_step(self, data: DATA_BATCH) -> MergedDataSamples:
+ """Get predictions of each enhanced data, a multiple predictions.
+
+ Args:
+ data (DataBatch): Enhanced data batch sampled from dataloader.
+
+ Returns:
+ MergedDataSamples: Merged prediction.
+ """
+ data_list: Union[List[dict], List[list]]
+ if isinstance(data, dict):
+ num_augs = len(data[next(iter(data))])
+ data_list = [{key: value[idx]
+ for key, value in data.items()}
+ for idx in range(num_augs)]
+ elif isinstance(data, (tuple, list)):
+ num_augs = len(data[0])
+ data_list = [[_data[idx] for _data in data]
+ for idx in range(num_augs)]
+ else:
+ raise TypeError('data given by dataLoader should be a dict, '
+ f'tuple or a list, but got {type(data)}')
+
+ predictions = []
+ for data in data_list: # type: ignore
+ predictions.append(self.module.test_step(data))
+ return self.merge_preds(list(zip(*predictions))) # type: ignore
diff --git a/testbed/open-mmlab__mmengine/mmengine/model/wrappers/utils.py b/testbed/open-mmlab__mmengine/mmengine/model/wrappers/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..86e1e123b98b8ad2172214cb3ddc8e688eacecff
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/model/wrappers/utils.py
@@ -0,0 +1,30 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch.nn as nn
+
+from mmengine.registry import MODEL_WRAPPERS, Registry
+
+
+def is_model_wrapper(model: nn.Module, registry: Registry = MODEL_WRAPPERS):
+ """Check if a module is a model wrapper.
+
+ The following 4 model in MMEngine (and their subclasses) are regarded as
+ model wrappers: DataParallel, DistributedDataParallel,
+ MMDataParallel, MMDistributedDataParallel. You may add you own
+ model wrapper by registering it to ``mmengine.registry.MODEL_WRAPPERS``.
+
+ Args:
+ model (nn.Module): The model to be checked.
+ registry (Registry): The parent registry to search for model wrappers.
+
+ Returns:
+ bool: True if the input model is a model wrapper.
+ """
+ module_wrappers = tuple(registry.module_dict.values())
+ if isinstance(model, module_wrappers):
+ return True
+
+ if not registry.children:
+ return False
+
+ return any(
+ is_model_wrapper(model, child) for child in registry.children.values())
diff --git a/testbed/open-mmlab__mmengine/mmengine/optim/__init__.py b/testbed/open-mmlab__mmengine/mmengine/optim/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b34441ef45b4de0a618634cc2d5cc73f1b038f2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/optim/__init__.py
@@ -0,0 +1,29 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .optimizer import (OPTIM_WRAPPER_CONSTRUCTORS, OPTIMIZERS,
+ AmpOptimWrapper, DefaultOptimWrapperConstructor,
+ OptimWrapper, OptimWrapperDict, build_optim_wrapper)
+# yapf: disable
+from .scheduler import (ConstantLR, ConstantMomentum, ConstantParamScheduler,
+ CosineAnnealingLR, CosineAnnealingMomentum,
+ CosineAnnealingParamScheduler, ExponentialLR,
+ ExponentialMomentum, ExponentialParamScheduler,
+ LinearLR, LinearMomentum, LinearParamScheduler,
+ MultiStepLR, MultiStepMomentum,
+ MultiStepParamScheduler, OneCycleLR,
+ OneCycleParamScheduler, PolyLR, PolyMomentum,
+ PolyParamScheduler, StepLR, StepMomentum,
+ StepParamScheduler, _ParamScheduler)
+
+# yapf: enable
+__all__ = [
+ 'OPTIM_WRAPPER_CONSTRUCTORS', 'OPTIMIZERS', 'build_optim_wrapper',
+ 'DefaultOptimWrapperConstructor', 'ConstantLR', 'CosineAnnealingLR',
+ 'ExponentialLR', 'LinearLR', 'MultiStepLR', 'StepLR', 'ConstantMomentum',
+ 'CosineAnnealingMomentum', 'ExponentialMomentum', 'LinearMomentum',
+ 'MultiStepMomentum', 'StepMomentum', 'ConstantParamScheduler',
+ 'CosineAnnealingParamScheduler', 'ExponentialParamScheduler',
+ 'LinearParamScheduler', 'MultiStepParamScheduler', 'StepParamScheduler',
+ '_ParamScheduler', 'OptimWrapper', 'AmpOptimWrapper', 'OptimWrapperDict',
+ 'OneCycleParamScheduler', 'OneCycleLR', 'PolyLR', 'PolyMomentum',
+ 'PolyParamScheduler'
+]
diff --git a/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/__init__.py b/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fdc77679ba142e80eb385c33aa6e308e91a64627
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/__init__.py
@@ -0,0 +1,14 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .amp_optimizer_wrapper import AmpOptimWrapper
+from .builder import (OPTIM_WRAPPER_CONSTRUCTORS, OPTIMIZERS,
+ build_optim_wrapper)
+from .default_constructor import DefaultOptimWrapperConstructor
+from .optimizer_wrapper import OptimWrapper
+from .optimizer_wrapper_dict import OptimWrapperDict
+from .zero_optimizer import ZeroRedundancyOptimizer
+
+__all__ = [
+ 'OPTIM_WRAPPER_CONSTRUCTORS', 'OPTIMIZERS',
+ 'DefaultOptimWrapperConstructor', 'build_optim_wrapper', 'OptimWrapper',
+ 'AmpOptimWrapper', 'OptimWrapperDict', 'ZeroRedundancyOptimizer'
+]
diff --git a/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/amp_optimizer_wrapper.py b/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/amp_optimizer_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..66f1255643be8ff77a7b03d6dec50d54e1ce6bd0
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/amp_optimizer_wrapper.py
@@ -0,0 +1,137 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from contextlib import contextmanager
+
+import torch
+import torch.nn as nn
+
+from mmengine.device import is_cuda_available, is_npu_available
+from mmengine.registry import OPTIM_WRAPPERS
+from mmengine.utils import digit_version
+from mmengine.utils.dl_utils import TORCH_VERSION
+from .optimizer_wrapper import OptimWrapper
+
+if is_npu_available():
+ from torch.npu.amp import GradScaler
+else:
+ from torch.cuda.amp import GradScaler
+
+
+@OPTIM_WRAPPERS.register_module()
+class AmpOptimWrapper(OptimWrapper):
+ """A subclass of :class:`OptimWrapper` that supports automatic mixed
+ precision training based on torch.cuda.amp.
+
+ ``AmpOptimWrapper`` provides a unified interface with
+ ``OptimWrapper``, so ``AmpOptimWrapper`` can be used in the same way
+ as ``OptimWrapper``.
+
+ Warnings:
+ ``AmpOptimWrapper`` requires PyTorch >= 1.6.
+
+ Args:
+ loss_scale (float or str or dict): The initial configuration of
+ `torch.cuda.amp.GradScaler`. See more specific arguments
+ introduction at `PyTorch AMP `_ # noqa: E501
+ Defaults to ``dynamic``.
+
+ - "dynamic": Initialize GradScale without any arguments.
+ - float: Initialize GradScaler with ``init_scale``.
+ - dict: Initialize GradScaler with more detail configuration.
+
+ **kwargs: Keyword arguments passed to OptimWrapper.
+
+ Note:
+ If you use ``IterBasedRunner`` and enable gradient accumulation,
+ the original `max_iters` should be multiplied by
+ ``accumulative_counts``.
+ """
+
+ def __init__(self, loss_scale='dynamic', **kwargs):
+ assert digit_version(TORCH_VERSION) >= digit_version('1.6.0'), (
+ '`torch.cuda.amp` is only available when pytorch version >= 1.6')
+ assert is_cuda_available() or is_npu_available(), (
+ '``AmpOptimizerWrapper`` is only available training on gpu or npu')
+ super().__init__(**kwargs)
+ self._scale_update_param = None
+ if loss_scale == 'dynamic':
+ # If loss_scale is a string, it must be 'dynamic', then dynamic
+ # loss scaling will be used.
+ self.loss_scaler = GradScaler()
+ elif isinstance(loss_scale, float):
+ # Static loss scaling
+ self._scale_update_param = loss_scale
+ self.loss_scaler = GradScaler(init_scale=loss_scale)
+ elif isinstance(loss_scale, dict):
+ # More specific configuration.
+ self.loss_scaler = GradScaler(**loss_scale)
+ else:
+ raise TypeError('loss_scale must be of type float, dict, or '
+ f'"dynamic", but got {loss_scale}')
+
+ def backward(self, loss: torch.Tensor, **kwargs):
+ """Perform gradient back propagation with :attr:`loss_scaler`.
+
+ Args:
+ loss (torch.Tensor): The loss of current iteration.
+ kwargs: Keyword arguments passed to :meth:`torch.Tensor.backward`
+ """
+ self.loss_scaler.scale(loss).backward(**kwargs)
+ self._inner_count += 1
+
+ def step(self, **kwargs):
+ """Update parameters with :attr:`loss_scaler`.
+
+ Args:
+ kwargs: Keyword arguments passed to
+ :meth:`torch.optim.Optimizer.step`.
+ """
+ if self.clip_grad_kwargs:
+ self.loss_scaler.unscale_(self.optimizer)
+ self._clip_grad()
+ self.loss_scaler.step(self.optimizer, **kwargs)
+ self.loss_scaler.update(self._scale_update_param)
+
+ def state_dict(self) -> dict:
+ """Get the state dictionary of :attr:`optimizer` and
+ :attr:`loss_scaler`.
+
+ Based on the state dictionary of the optimizer, the returned state
+ dictionary will add a key named "loss_scaler".
+
+ Returns:
+ dict: The merged state dict of :attr:`loss_scaler` and
+ :attr:`optimizer`.
+ """
+ # save state_dict of loss_scaler
+ state_dict = self.optimizer.state_dict()
+ state_dict['loss_scaler'] = self.loss_scaler.state_dict()
+ return state_dict
+
+ def load_state_dict(self, state_dict: dict):
+ """Load and parse the state dictionary of :attr:`optimizer` and
+ :attr:`loss_scaler`.
+
+ If state_dict contains "loss_scaler.", the :attr:`loss_scaler` will
+ load the corresponding keys. Otherwise, only the :attr:`optimizer`
+ will load the state dictionary.
+
+ Args:
+ state_dict (dict): The state dict of :attr:`optimizer` and
+ :attr:`loss_scaler`
+ """
+ if 'loss_scaler' in state_dict:
+ self.loss_scaler.load_state_dict(state_dict.pop('loss_scaler'))
+ self.optimizer.load_state_dict(state_dict)
+
+ @contextmanager
+ def optim_context(self, model: nn.Module):
+ """Enables the context for mixed precision training, and enables the
+ context for disabling gradient synchronization during gradient
+ accumulation context.
+
+ Args:
+ model (nn.Module): The training model.
+ """
+ from mmengine.runner.amp import autocast
+ with super().optim_context(model), autocast():
+ yield
diff --git a/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/builder.py b/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..8eae0e5429ad466c25063feafac67786319e9979
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/builder.py
@@ -0,0 +1,70 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import inspect
+from typing import List, Union
+
+import torch
+import torch.nn as nn
+
+from mmengine.config import Config, ConfigDict
+from mmengine.device import is_npu_available
+from mmengine.registry import OPTIM_WRAPPER_CONSTRUCTORS, OPTIMIZERS
+from .optimizer_wrapper import OptimWrapper
+
+
+def register_torch_optimizers() -> List[str]:
+ """Register optimizers in ``torch.optim`` to the ``OPTIMIZERS`` registry.
+
+ Returns:
+ List[str]: A list of registered optimizers' name.
+ """
+ torch_optimizers = []
+ for module_name in dir(torch.optim):
+ if module_name.startswith('__'):
+ continue
+ _optim = getattr(torch.optim, module_name)
+ if inspect.isclass(_optim) and issubclass(_optim,
+ torch.optim.Optimizer):
+ OPTIMIZERS.register_module(module=_optim)
+ torch_optimizers.append(module_name)
+ return torch_optimizers
+
+
+TORCH_OPTIMIZERS = register_torch_optimizers()
+
+
+def build_optim_wrapper(model: nn.Module,
+ cfg: Union[dict, Config, ConfigDict]) -> OptimWrapper:
+ """Build function of OptimWrapper.
+
+ If ``constructor`` is set in the ``cfg``, this method will build an
+ optimizer wrapper constructor, and use optimizer wrapper constructor to
+ build the optimizer wrapper. If ``constructor`` is not set, the
+ ``DefaultOptimWrapperConstructor`` will be used by default.
+
+ Args:
+ model (nn.Module): Model to be optimized.
+ cfg (dict): Config of optimizer wrapper, optimizer constructor and
+ optimizer.
+
+ Returns:
+ OptimWrapper: The built optimizer wrapper.
+ """
+ optim_wrapper_cfg = copy.deepcopy(cfg)
+ constructor_type = optim_wrapper_cfg.pop('constructor',
+ 'DefaultOptimWrapperConstructor')
+ paramwise_cfg = optim_wrapper_cfg.pop('paramwise_cfg', None)
+
+ # Since the current generation of NPU(Ascend 910) only supports
+ # mixed precision training, here we turn on mixed precision by default
+ # on the NPU to make the training normal
+ if is_npu_available():
+ optim_wrapper_cfg['type'] = 'AmpOptimWrapper'
+
+ optim_wrapper_constructor = OPTIM_WRAPPER_CONSTRUCTORS.build(
+ dict(
+ type=constructor_type,
+ optim_wrapper_cfg=optim_wrapper_cfg,
+ paramwise_cfg=paramwise_cfg))
+ optim_wrapper = optim_wrapper_constructor(model)
+ return optim_wrapper
diff --git a/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/default_constructor.py b/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/default_constructor.py
new file mode 100644
index 0000000000000000000000000000000000000000..e89cf53fb186beb83c582b34738f494e783067dd
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/default_constructor.py
@@ -0,0 +1,304 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import warnings
+from typing import List, Optional, Union
+
+import torch
+import torch.nn as nn
+from torch.nn import GroupNorm, LayerNorm
+
+from mmengine.logging import print_log
+from mmengine.registry import (OPTIM_WRAPPER_CONSTRUCTORS, OPTIM_WRAPPERS,
+ OPTIMIZERS)
+from mmengine.utils import is_list_of
+from mmengine.utils.dl_utils import mmcv_full_available
+from mmengine.utils.dl_utils.parrots_wrapper import _BatchNorm, _InstanceNorm
+from .optimizer_wrapper import OptimWrapper
+
+
+@OPTIM_WRAPPER_CONSTRUCTORS.register_module()
+class DefaultOptimWrapperConstructor:
+ """Default constructor for optimizers.
+
+ By default, each parameter share the same optimizer settings, and we
+ provide an argument ``paramwise_cfg`` to specify parameter-wise settings.
+ It is a dict and may contain the following fields:
+
+ - ``custom_keys`` (dict): Specified parameters-wise settings by keys. If
+ one of the keys in ``custom_keys`` is a substring of the name of one
+ parameter, then the setting of the parameter will be specified by
+ ``custom_keys[key]`` and other setting like ``bias_lr_mult`` etc. will
+ be ignored. It should be noted that the aforementioned ``key`` is the
+ longest key that is a substring of the name of the parameter. If there
+ are multiple matched keys with the same length, then the key with lower
+ alphabet order will be chosen.
+ ``custom_keys[key]`` should be a dict and may contain fields ``lr_mult``
+ and ``decay_mult``. See Example 2 below.
+ - ``bias_lr_mult`` (float): It will be multiplied to the learning
+ rate for all bias parameters (except for those in normalization
+ layers and offset layers of DCN).
+ - ``bias_decay_mult`` (float): It will be multiplied to the weight
+ decay for all bias parameters (except for those in
+ normalization layers, depthwise conv layers, offset layers of DCN).
+ - ``norm_decay_mult`` (float): It will be multiplied to the weight
+ decay for all weight and bias parameters of normalization
+ layers.
+ - ``flat_decay_mult`` (float): It will be multiplied to the weight
+ decay for all one-dimensional parameters
+ - ``dwconv_decay_mult`` (float): It will be multiplied to the weight
+ decay for all weight and bias parameters of depthwise conv
+ layers.
+ - ``dcn_offset_lr_mult`` (float): It will be multiplied to the learning
+ rate for parameters of offset layer in the deformable convs
+ of a model.
+ - ``bypass_duplicate`` (bool): If true, the duplicate parameters
+ would not be added into optimizer. Default: False.
+
+ Note:
+
+ 1. If the option ``dcn_offset_lr_mult`` is used, the constructor will
+ override the effect of ``bias_lr_mult`` in the bias of offset layer.
+ So be careful when using both ``bias_lr_mult`` and
+ ``dcn_offset_lr_mult``. If you wish to apply both of them to the offset
+ layer in deformable convs, set ``dcn_offset_lr_mult`` to the original
+ ``dcn_offset_lr_mult`` * ``bias_lr_mult``.
+
+ 2. If the option ``dcn_offset_lr_mult`` is used, the constructor will
+ apply it to all the DCN layers in the model. So be careful when the
+ model contains multiple DCN layers in places other than backbone.
+
+ Args:
+ optim_wrapper_cfg (dict): The config dict of the optimizer wrapper.
+
+ Required fields of ``optim_wrapper_cfg`` are
+
+ - ``type``: class name of the OptimizerWrapper
+ - ``optimizer``: The configuration of optimizer.
+
+ Optional fields of ``optim_wrapper_cfg`` are
+
+ - any arguments of the corresponding optimizer wrapper type,
+ e.g., accumulative_counts, clip_grad, etc.
+
+ Required fields of ``optimizer`` are
+
+ - `type`: class name of the optimizer.
+
+ Optional fields of ``optimizer`` are
+
+ - any arguments of the corresponding optimizer type, e.g.,
+ lr, weight_decay, momentum, etc.
+
+ paramwise_cfg (dict, optional): Parameter-wise options.
+
+ Example 1:
+ >>> model = torch.nn.modules.Conv1d(1, 1, 1)
+ >>> optim_wrapper_cfg = dict(
+ >>> dict(type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01,
+ >>> momentum=0.9, weight_decay=0.0001))
+ >>> paramwise_cfg = dict(norm_decay_mult=0.)
+ >>> optim_wrapper_builder = DefaultOptimWrapperConstructor(
+ >>> optim_wrapper_cfg, paramwise_cfg)
+ >>> optim_wrapper = optim_wrapper_builder(model)
+
+ Example 2:
+ >>> # assume model have attribute model.backbone and model.cls_head
+ >>> optim_wrapper_cfg = dict(type='OptimWrapper', optimizer=dict(
+ >>> type='SGD', lr=0.01, weight_decay=0.95))
+ >>> paramwise_cfg = dict(custom_keys={
+ >>> 'backbone': dict(lr_mult=0.1, decay_mult=0.9)})
+ >>> optim_wrapper_builder = DefaultOptimWrapperConstructor(
+ >>> optim_wrapper_cfg, paramwise_cfg)
+ >>> optim_wrapper = optim_wrapper_builder(model)
+ >>> # Then the `lr` and `weight_decay` for model.backbone is
+ >>> # (0.01 * 0.1, 0.95 * 0.9). `lr` and `weight_decay` for
+ >>> # model.cls_head is (0.01, 0.95).
+ """
+
+ def __init__(self,
+ optim_wrapper_cfg: dict,
+ paramwise_cfg: Optional[dict] = None):
+ if not isinstance(optim_wrapper_cfg, dict):
+ raise TypeError('optimizer_cfg should be a dict',
+ f'but got {type(optim_wrapper_cfg)}')
+ assert 'optimizer' in optim_wrapper_cfg, (
+ '`optim_wrapper_cfg` must contain "optimizer" config')
+ self.optim_wrapper_cfg = optim_wrapper_cfg.copy()
+ self.optimizer_cfg = self.optim_wrapper_cfg.pop('optimizer')
+ self.paramwise_cfg = {} if paramwise_cfg is None else paramwise_cfg
+ self.base_lr = self.optimizer_cfg.get('lr', None)
+ self.base_wd = self.optimizer_cfg.get('weight_decay', None)
+ self._validate_cfg()
+
+ def _validate_cfg(self) -> None:
+ """verify the correctness of the config."""
+ if not isinstance(self.paramwise_cfg, dict):
+ raise TypeError('paramwise_cfg should be None or a dict, '
+ f'but got {type(self.paramwise_cfg)}')
+
+ if 'custom_keys' in self.paramwise_cfg:
+ if not isinstance(self.paramwise_cfg['custom_keys'], dict):
+ raise TypeError(
+ 'If specified, custom_keys must be a dict, '
+ f'but got {type(self.paramwise_cfg["custom_keys"])}')
+ if self.base_wd is None:
+ for key in self.paramwise_cfg['custom_keys']:
+ if 'decay_mult' in self.paramwise_cfg['custom_keys'][key]:
+ raise ValueError('base_wd should not be None')
+
+ # get base lr and weight decay
+ # weight_decay must be explicitly specified if mult is specified
+ if ('bias_decay_mult' in self.paramwise_cfg
+ or 'norm_decay_mult' in self.paramwise_cfg
+ or 'dwconv_decay_mult' in self.paramwise_cfg):
+ if self.base_wd is None:
+ raise ValueError('base_wd should not be None')
+
+ def _is_in(self, param_group: dict, param_group_list: list) -> bool:
+ """check whether the `param_group` is in the`param_group_list`"""
+ assert is_list_of(param_group_list, dict)
+ param = set(param_group['params'])
+ param_set = set()
+ for group in param_group_list:
+ param_set.update(set(group['params']))
+
+ return not param.isdisjoint(param_set)
+
+ def add_params(self,
+ params: List[dict],
+ module: nn.Module,
+ prefix: str = '',
+ is_dcn_module: Optional[Union[int, float]] = None) -> None:
+ """Add all parameters of module to the params list.
+
+ The parameters of the given module will be added to the list of param
+ groups, with specific rules defined by paramwise_cfg.
+
+ Args:
+ params (list[dict]): A list of param groups, it will be modified
+ in place.
+ module (nn.Module): The module to be added.
+ prefix (str): The prefix of the module
+ is_dcn_module (int|float|None): If the current module is a
+ submodule of DCN, `is_dcn_module` will be passed to
+ control conv_offset layer's learning rate. Defaults to None.
+ """
+ # get param-wise options
+ custom_keys = self.paramwise_cfg.get('custom_keys', {})
+ # first sort with alphabet order and then sort with reversed len of str
+ sorted_keys = sorted(sorted(custom_keys.keys()), key=len, reverse=True)
+
+ bias_lr_mult = self.paramwise_cfg.get('bias_lr_mult', None)
+ bias_decay_mult = self.paramwise_cfg.get('bias_decay_mult', None)
+ norm_decay_mult = self.paramwise_cfg.get('norm_decay_mult', None)
+ dwconv_decay_mult = self.paramwise_cfg.get('dwconv_decay_mult', None)
+ flat_decay_mult = self.paramwise_cfg.get('flat_decay_mult', None)
+ bypass_duplicate = self.paramwise_cfg.get('bypass_duplicate', False)
+ dcn_offset_lr_mult = self.paramwise_cfg.get('dcn_offset_lr_mult', None)
+
+ # special rules for norm layers and depth-wise conv layers
+ is_norm = isinstance(module,
+ (_BatchNorm, _InstanceNorm, GroupNorm, LayerNorm))
+ is_dwconv = (
+ isinstance(module, torch.nn.Conv2d)
+ and module.in_channels == module.groups)
+
+ for name, param in module.named_parameters(recurse=False):
+ param_group = {'params': [param]}
+ if not param.requires_grad:
+ params.append(param_group)
+ continue
+ if bypass_duplicate and self._is_in(param_group, params):
+ warnings.warn(f'{prefix} is duplicate. It is skipped since '
+ f'bypass_duplicate={bypass_duplicate}')
+ continue
+ # if the parameter match one of the custom keys, ignore other rules
+ is_custom = False
+ for key in sorted_keys:
+ if key in f'{prefix}.{name}':
+ is_custom = True
+ lr_mult = custom_keys[key].get('lr_mult', 1.)
+ param_group['lr'] = self.base_lr * lr_mult
+ if self.base_wd is not None:
+ decay_mult = custom_keys[key].get('decay_mult', 1.)
+ param_group['weight_decay'] = self.base_wd * decay_mult
+ # add custom settings to param_group
+ for k, v in custom_keys[key].items():
+ param_group[k] = v
+ break
+
+ if not is_custom:
+ # bias_lr_mult affects all bias parameters
+ # except for norm.bias dcn.conv_offset.bias
+ if name == 'bias' and not (
+ is_norm or is_dcn_module) and bias_lr_mult is not None:
+ param_group['lr'] = self.base_lr * bias_lr_mult
+
+ if (prefix.find('conv_offset') != -1 and is_dcn_module
+ and dcn_offset_lr_mult is not None
+ and isinstance(module, torch.nn.Conv2d)):
+ # deal with both dcn_offset's bias & weight
+ param_group['lr'] = self.base_lr * dcn_offset_lr_mult
+
+ # apply weight decay policies
+ if self.base_wd is not None:
+ # norm decay
+ if is_norm and norm_decay_mult is not None:
+ param_group[
+ 'weight_decay'] = self.base_wd * norm_decay_mult
+ # bias lr and decay
+ elif (name == 'bias' and not is_dcn_module
+ and bias_decay_mult is not None):
+ param_group[
+ 'weight_decay'] = self.base_wd * bias_decay_mult
+ # depth-wise conv
+ elif is_dwconv and dwconv_decay_mult is not None:
+ param_group[
+ 'weight_decay'] = self.base_wd * dwconv_decay_mult
+ # flatten parameters except dcn offset
+ elif (param.ndim == 1 and not is_dcn_module
+ and flat_decay_mult is not None):
+ param_group[
+ 'weight_decay'] = self.base_wd * flat_decay_mult
+ params.append(param_group)
+ for key, value in param_group.items():
+ if key == 'params':
+ continue
+ full_name = f'{prefix}.{name}' if prefix else name
+ print_log(
+ f'paramwise_options -- {full_name}:{key}={value}',
+ logger='current')
+
+ if mmcv_full_available():
+ from mmcv.ops import DeformConv2d, ModulatedDeformConv2d
+ is_dcn_module = isinstance(module,
+ (DeformConv2d, ModulatedDeformConv2d))
+ else:
+ is_dcn_module = False
+ for child_name, child_mod in module.named_children():
+ child_prefix = f'{prefix}.{child_name}' if prefix else child_name
+ self.add_params(
+ params,
+ child_mod,
+ prefix=child_prefix,
+ is_dcn_module=is_dcn_module)
+
+ def __call__(self, model: nn.Module) -> OptimWrapper:
+ if hasattr(model, 'module'):
+ model = model.module
+
+ optim_wrapper_cfg = self.optim_wrapper_cfg.copy()
+ optim_wrapper_cfg.setdefault('type', 'OptimWrapper')
+ optimizer_cfg = self.optimizer_cfg.copy()
+ # if no paramwise option is specified, just use the global setting
+ if not self.paramwise_cfg:
+ optimizer_cfg['params'] = model.parameters()
+ optimizer = OPTIMIZERS.build(optimizer_cfg)
+ else:
+ # set param-wise lr and weight decay recursively
+ params: List = []
+ self.add_params(params, model)
+ optimizer_cfg['params'] = params
+ optimizer = OPTIMIZERS.build(optimizer_cfg)
+ optim_wrapper = OPTIM_WRAPPERS.build(
+ optim_wrapper_cfg, default_args=dict(optimizer=optimizer))
+ return optim_wrapper
diff --git a/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/optimizer_wrapper.py b/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/optimizer_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..644d5739fcafff8e8fa364c395b243b5966b29e7
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/optimizer_wrapper.py
@@ -0,0 +1,479 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import logging
+from contextlib import contextmanager
+from typing import Dict, List, Optional
+
+import torch
+import torch.nn as nn
+from torch.optim import Optimizer
+
+from mmengine.logging import MessageHub, print_log
+from mmengine.registry import OPTIM_WRAPPERS
+from mmengine.utils.dl_utils import has_batch_norm
+
+
+@OPTIM_WRAPPERS.register_module()
+class OptimWrapper:
+ """Optimizer wrapper provides a common interface for updating parameters.
+
+ Optimizer wrapper provides a unified interface for single precision
+ training and automatic mixed precision training with different hardware.
+ OptimWrapper encapsulates optimizer to provide simplified interfaces
+ for commonly used training techniques such as gradient accumulative and
+ grad clips. ``OptimWrapper`` implements the basic logic of gradient
+ accumulation and gradient clipping based on ``torch.optim.Optimizer``.
+ The subclasses only need to override some methods to implement the mixed
+ precision training. See more information in :class:`AmpOptimWrapper`.
+
+ Args:
+ optimizer (Optimizer): Optimizer used to update model parameters.
+ accumulative_counts (int): The number of iterations to accumulate
+ gradients. The parameters will be updated per
+ ``accumulative_counts``.
+ clip_grad (dict, optional): If ``clip_grad`` is not None, it will be
+ the arguments of :func:`torch.nn.utils.clip_grad_norm_` or
+ :func:`torch.nn.utils.clip_grad_value_`. ``clip_grad`` should be a
+ dict, and the keys could be set as follows:
+
+ If the key ``type`` is not set, or ``type`` is "norm",
+ the accepted keys are as follows:
+
+ - max_norm (float or int): Max norm of the gradients.
+ - norm_type (float or int): Type of the used p-norm. Can be
+ ``'inf'`` for infinity norm.
+ - error_if_nonfinite (bool): If True, an error is thrown if
+ the total norm of the gradients from :attr:`parameters` is
+ ``nan``, ``inf``, or ``-inf``. Default: False (will switch
+ to True in the future)
+
+ If the key ``type`` is set to "value", the accepted keys are as
+ follows:
+
+ - clip_value (float or int): maximum allowed value of the
+ gradients. The gradients are clipped in the range
+ ``(-clip_value, +clip_value)``.
+
+ Note:
+ If ``accumulative_counts`` is larger than 1, perform
+ :meth:`update_params` under the context of ``optim_context``
+ could avoid unnecessary gradient synchronization.
+
+ Note:
+ If you use ``IterBasedRunner`` and enable gradient accumulation,
+ the original `max_iters` should be multiplied by
+ ``accumulative_counts``.
+
+ Note:
+ The subclass should ensure that once :meth:`update_params` is called,
+ ``_inner_count += 1`` is automatically performed.
+
+ Examples:
+ >>> # Config sample of OptimWrapper and enable clipping gradient by
+ >>> # norm.
+ >>> optim_wrapper_cfg = dict(
+ >>> type='OptimWrapper',
+ >>> _accumulative_counts=1,
+ >>> clip_grad=dict(max_norm=0.2))
+ >>> # Config sample of OptimWrapper and enable clipping gradient by
+ >>> # value.
+ >>> optim_wrapper_cfg = dict(
+ >>> type='OptimWrapper',
+ >>> _accumulative_counts=1,
+ >>> clip_grad=dict(type='value', clip_value=0.2))
+ >>> # Use OptimWrapper to update model.
+ >>> import torch.nn as nn
+ >>> import torch
+ >>> from torch.optim import SGD
+ >>> from torch.utils.data import DataLoader
+ >>> from mmengine.optim import OptimWrapper
+ >>>
+ >>> model = nn.Linear(1, 1)
+ >>> dataset = torch.randn(10, 1, 1)
+ >>> dataloader = DataLoader(dataset)
+ >>> optimizer = SGD(model.parameters(), lr=0.1)
+ >>> optim_wrapper = OptimWrapper(optimizer)
+ >>>
+ >>> for data in dataloader:
+ >>> loss = model(data)
+ >>> optim_wrapper.update_params(loss)
+ >>> # Enable gradient accumulation
+ >>> optim_wrapper_cfg = dict(
+ >>> type='OptimWrapper',
+ >>> _accumulative_counts=3,
+ >>> clip_grad=dict(max_norm=0.2))
+ >>> ddp_model = DistributedDataParallel(model)
+ >>> optimizer = SGD(ddp_model.parameters(), lr=0.1)
+ >>> optim_wrapper = OptimWrapper(optimizer)
+ >>> optim_wrapper.initialize_count_status(0, len(dataloader))
+ >>> # If model is a subclass instance of DistributedDataParallel,
+ >>> # `optim_context` context manager can avoid unnecessary gradient
+ >>> # synchronize.
+ >>> for iter, data in enumerate(dataloader):
+ >>> with optim_wrapper.optim_context(ddp_model):
+ >>> loss = model(data)
+ >>> optim_wrapper.update_params(loss)
+ """
+
+ def __init__(self,
+ optimizer: Optimizer,
+ accumulative_counts: int = 1,
+ clip_grad: Optional[dict] = None):
+ assert accumulative_counts > 0, (
+ '_accumulative_counts at least greater than or equal to 1')
+ self._accumulative_counts = accumulative_counts
+
+ assert isinstance(optimizer, Optimizer), (
+ 'optimizer must be a `torch.optim.Optimizer` instance, but got '
+ f'{type(optimizer)}')
+ self.optimizer = optimizer
+
+ if clip_grad is not None:
+ # clip_grad_kwargs should not be non-empty dict.
+ assert isinstance(clip_grad, dict) and clip_grad, (
+ 'If `clip_grad` is not None, it should be a `dict` '
+ 'which is the arguments of `torch.nn.utils.clip_grad_norm_` '
+ 'or clip_grad_value_`.')
+ clip_type = clip_grad.pop('type', 'norm')
+ if clip_type == 'norm':
+ self.clip_func = torch.nn.utils.clip_grad_norm_
+ self.grad_name = 'grad_norm'
+ elif clip_type == 'value':
+ self.clip_func = torch.nn.utils.clip_grad_value_
+ self.grad_name = 'grad_value'
+ else:
+ raise ValueError('type of clip_grad should be "norm" or '
+ f'"value" but got {clip_type}')
+ assert clip_grad, ('`clip_grad` should contain other arguments '
+ 'besides `type`. The arguments should match '
+ 'with the `torch.nn.utils.clip_grad_norm_` or '
+ 'clip_grad_value_`')
+ self.clip_grad_kwargs = clip_grad
+ # Used to update `grad_norm` log message.
+ self.message_hub = MessageHub.get_current_instance()
+ self._inner_count = 0
+ # `_max_counts` means the total number of parameter updates. It
+ # ensures that the gradient of the last few iterations will not be
+ # lost when the `_max_counts` is not divisible by
+ # `accumulative_counts`.
+ self._max_counts = -1
+ # The `_remainder_iter` is used for calculating loss factor at the
+ # last few iterations. If `_max_counts` has not been initialized,
+ # the loss factor will always be the same as `_accumulative_counts`.
+ self._remainder_counts = -1
+
+ def update_params(self,
+ loss: torch.Tensor,
+ step_kwargs: Optional[Dict] = None,
+ zero_kwargs: Optional[Dict] = None) -> None:
+ """Update parameters in :attr:`optimizer`.
+
+ Args:
+ loss (torch.Tensor): A tensor for back propagation.
+ step_kwargs (dict): Arguments for optimizer.step.
+ Defaults to None.
+ New in version v0.4.0.
+ zero_kwargs (dict): Arguments for optimizer.zero_grad.
+ Defaults to None.
+ New in version v0.4.0.
+ """
+ if step_kwargs is None:
+ step_kwargs = {}
+ if zero_kwargs is None:
+ zero_kwargs = {}
+ loss = self.scale_loss(loss)
+ self.backward(loss)
+ # Update parameters only if `self._inner_count` is divisible by
+ # `self._accumulative_counts` or `self._inner_count` equals to
+ # `self._max_counts`
+ if self.should_update():
+ self.step(**step_kwargs)
+ self.zero_grad(**zero_kwargs)
+
+ def backward(self, loss: torch.Tensor, **kwargs) -> None:
+ """Perform gradient back propagation.
+
+ Provide unified ``backward`` interface compatible with automatic mixed
+ precision training. Subclass can overload this method to implement the
+ required logic. For example, ``torch.cuda.amp`` require some extra
+ operation on GradScaler during backward process.
+
+ Note:
+ If subclasses inherit from ``OptimWrapper`` override
+ ``backward``, ``_inner_count +=1`` must be implemented.
+
+ Args:
+ loss (torch.Tensor): The loss of current iteration.
+ kwargs: Keyword arguments passed to :meth:`torch.Tensor.backward`.
+ """
+ loss.backward(**kwargs)
+ self._inner_count += 1
+
+ def zero_grad(self, **kwargs) -> None:
+ """A wrapper of ``Optimizer.zero_grad``.
+
+ Provide unified ``zero_grad`` interface compatible with automatic mixed
+ precision training. Subclass can overload this method to implement the
+ required logic.
+
+ Args:
+ kwargs: Keyword arguments passed to
+ :meth:`torch.optim.Optimizer.zero_grad`.
+ """
+ self.optimizer.zero_grad(**kwargs)
+
+ def step(self, **kwargs) -> None:
+ """A wrapper of ``Optimizer.step``.
+
+ Provide unified ``step`` interface compatible with automatic mixed
+ precision training. Subclass can overload this method to implement the
+ required logic. For example, ``torch.cuda.amp`` require some extra
+ operation on ``GradScaler`` during step process.
+
+ Clip grad if :attr:`clip_grad_kwargs` is not None, and then update
+ parameters.
+
+ Args:
+ kwargs: Keyword arguments passed to
+ :meth:`torch.optim.Optimizer.step`.
+ """
+ if self.clip_grad_kwargs:
+ self._clip_grad()
+ self.optimizer.step(**kwargs)
+
+ def state_dict(self) -> dict:
+ """A wrapper of ``Optimizer.state_dict``.
+
+ Provide unified ``state_dict`` interface compatible with automatic
+ mixed precision training. Subclass can overload this method to
+ implement the required logic. For example, the state dictionary of
+ GradScaler should be saved when training with ``torch.cuda.amp``.
+
+ Returns:
+ dict: The state dictionary of :attr:`optimizer`.
+ """
+ return self.optimizer.state_dict()
+
+ def load_state_dict(self, state_dict: dict) -> None:
+ """A wrapper of ``Optimizer.load_state_dict``. load the state dict of
+ :attr:`optimizer`.
+
+ Provide unified ``load_state_dict`` interface compatible with automatic
+ mixed precision training. Subclass can overload this method to
+ implement the required logic. For example, the state dictionary of
+ GradScaler should be loaded when training with ``torch.cuda.amp``.
+
+ Args:
+ state_dict (dict): The state dictionary of :attr:`optimizer`.
+ """
+ self.optimizer.load_state_dict(state_dict)
+
+ @property
+ def param_groups(self) -> List[dict]:
+ """A wrapper of ``Optimizer.param_groups``.
+
+ Make OptimizeWrapper compatible with :class:`_ParamScheduler`.
+
+ Returns:
+ dict: the ``param_groups`` of :attr:`optimizer`.
+ """
+ return self.optimizer.param_groups
+
+ @property
+ def defaults(self) -> dict:
+ """A wrapper of ``Optimizer.defaults``.
+
+ Make OptimizeWrapper compatible with :class:`_ParamScheduler`.
+
+ Returns:
+ dict: the ``param_groups`` of :attr:`optimizer`.
+ """
+ return self.optimizer.defaults
+
+ def get_lr(self) -> Dict[str, List[float]]:
+ """Get the learning rate of the optimizer.
+
+ Provide unified interface to get learning rate of optimizer.
+
+ Returns:
+ Dict[str, List[float]]: Learning rate of the optimizer.
+ """
+ lr = [group['lr'] for group in self.param_groups]
+ return dict(lr=lr)
+
+ def get_momentum(self) -> Dict[str, List[float]]:
+ """Get the momentum of the optimizer.
+
+ Provide unified interface to get momentum of optimizer.
+
+ Returns:
+ Dict[str, List[float]]: Momentum of the optimizer.
+ """
+ momentum = []
+ for group in self.param_groups:
+ # Get momentum of SGD.
+ if 'momentum' in group.keys():
+ momentum.append(group['momentum'])
+ # Get momentum of Adam.
+ elif 'betas' in group.keys():
+ momentum.append(group['betas'][0])
+ else:
+ momentum.append(0)
+ return dict(momentum=momentum)
+
+ @contextmanager
+ def optim_context(self, model: nn.Module):
+ """A Context for gradient accumulation and automatic mix precision
+ training.
+
+ If subclasses need to enable the context for mix precision training,
+ e.g., ``:class:`AmpOptimWrapper``, the corresponding context should be
+ enabled in `optim_context`. Since ``OptimWrapper`` uses default fp32
+ training, ``optim_context`` will only enable the context for
+ blocking the unnecessary gradient synchronization during gradient
+ accumulation
+
+ If model is an instance with ``no_sync`` method (which means
+ blocking the gradient synchronization) and
+ ``self._accumulative_counts != 1``. The model will not automatically
+ synchronize gradients if ``cur_iter`` is divisible by
+ ``self._accumulative_counts``. Otherwise, this method will enable an
+ empty context.
+
+ Args:
+ model (nn.Module): The training model.
+ """
+ # During gradient accumulation process, the gradient synchronize
+ # should only happen before updating parameters.
+ if not self.should_sync() and hasattr(model, 'no_sync'):
+ with model.no_sync():
+ yield
+ else:
+ yield
+
+ def _clip_grad(self) -> None:
+ """Clip the gradients of parameters."""
+ params: List[torch.Tensor] = []
+ for param_group in self.optimizer.param_groups:
+ params.extend(param_group['params'])
+
+ params = list(
+ filter(lambda p: p.requires_grad and p.grad is not None, params))
+ if len(params) > 0:
+ grad = self.clip_func(params, **self.clip_grad_kwargs)
+ # `torch.nn.utils.clip_grad_value_` will return None.
+ if grad is not None:
+ self.message_hub.update_scalar(f'train/{self.grad_name}',
+ float(grad))
+
+ def initialize_count_status(self, model: nn.Module, init_counts: int,
+ max_counts: int) -> None:
+ """Initialize gradient accumulation related attributes.
+
+ ``OptimWrapper`` can be used without calling
+ ``initialize_iter_status``. However, Consider the case of ``len(
+ dataloader) == 10``, and the ``accumulative_iter == 3``. Since 10 is
+ not divisible by 3, the last iteration will not trigger
+ ``optimizer.step()``, resulting in one less parameter updating.
+
+ Args:
+ model (nn.Module): Training model
+ init_counts (int): The initial value of the inner count.
+ max_counts (int): The maximum value of the inner count.
+ """
+ self._inner_count = init_counts
+ self._max_counts = max_counts
+ if self._inner_count % self._accumulative_counts != 0:
+ print_log(
+ 'Resumed iteration number is not divisible by '
+ '`_accumulative_counts` in `GradientCumulativeOptimizerHook`, '
+ 'which means the gradient of some iterations is lost and the '
+ 'result may be influenced slightly.',
+ logger='current',
+ level=logging.WARNING)
+
+ if has_batch_norm(model) and self._accumulative_counts > 1:
+ print_log(
+ 'Gradient accumulative may slightly decrease '
+ 'performance because the model has BatchNorm layers.',
+ logger='current',
+ level=logging.WARNING)
+ # Remainder of `_max_counts` divided by `_accumulative_counts`
+ self._remainder_counts = self._max_counts % self._accumulative_counts
+
+ def should_update(self) -> bool:
+ """Decide whether the parameters should be updated at the current
+ iteration.
+
+ Called by :meth:`update_params` and check whether the optimizer
+ wrapper should update parameters at current iteration.
+
+ Returns:
+ bool: Whether to update parameters.
+ """
+ return (self._inner_count % self._accumulative_counts == 0
+ or self._inner_count == self._max_counts)
+
+ def should_sync(self) -> bool:
+ """Decide whether the automatic gradient synchronization should be
+ allowed at the current iteration.
+
+ It takes effect when gradient accumulation is used to skip
+ synchronization at the iterations where the parameter is not updated.
+
+ Since ``should_sync`` is called by :meth:`optim_context`, and it is
+ called before :meth:`backward` which means ``self._inner_count += 1``
+ has not happened yet. Therefore, ``self._inner_count += 1`` should be
+ performed manually here.
+
+ Returns:
+ bool: Whether to block the automatic gradient synchronization.
+ """
+ return ((self._inner_count + 1) % self._accumulative_counts == 0
+ or (self._inner_count + 1) == self._max_counts)
+
+ def scale_loss(self, loss: torch.Tensor) -> torch.Tensor:
+ """Get scaled loss according to ``_accumulative_counts``,
+ ``_inner_count`` and max_counts.
+
+ Args:
+ loss (torch.Tensor): Original loss calculated by model.
+
+ Returns:
+ loss (torch.Tensor): Scaled loss.
+ """
+ if self._accumulative_counts == 1:
+ # update parameters without gradient accumulation. The gradient
+ # should not be rescaled and `loss_factor=1`.
+ loss_factor = 1
+ elif self._max_counts == -1:
+ loss_factor = self._accumulative_counts
+ else:
+ # if `self._accumulative_counts > 1`, the gradient needs to be
+ # rescaled and accumulated. In most cases, `loss_factor` equals to
+ # `self._accumulative_counts`. However, `self._max_counts` may not
+ # be divisible by `self._accumulative_counts`, so the
+ # `loss_scale` for the last few iterations needs to be
+ # recalculated.
+ if self._inner_count < self._max_counts - self._remainder_counts:
+ loss_factor = self._accumulative_counts
+ else:
+ loss_factor = self._remainder_counts
+ assert loss_factor > 0, (
+ 'loss_factor should be larger than zero! This error could '
+ 'happened when initialize_iter_status called with an '
+ 'error `init_counts` or `max_counts`')
+
+ loss = loss / loss_factor
+ return loss
+
+ @property
+ def inner_count(self):
+ """Get the number of updating parameters of optimizer wrapper."""
+ return self._inner_count
+
+ def __repr__(self):
+ wrapper_info = (f'Type: {type(self).__name__}\n'
+ f'_accumulative_counts: {self._accumulative_counts}\n'
+ 'optimizer: \n')
+ optimizer_str = repr(self.optimizer) + '\n'
+ return wrapper_info + optimizer_str
diff --git a/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/optimizer_wrapper_dict.py b/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/optimizer_wrapper_dict.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a4b25800360fcab30941886ed80ac3948fde57f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/optimizer_wrapper_dict.py
@@ -0,0 +1,189 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from contextlib import contextmanager
+from typing import Dict, Iterator, List, Optional, Tuple
+
+import torch
+import torch.nn as nn
+
+from .optimizer_wrapper import OptimWrapper
+
+
+class OptimWrapperDict(OptimWrapper):
+ """A dictionary container of :obj:`OptimWrapper`.
+
+ If runner is training with multiple optimizers, all optimizer wrappers
+ should be managed by :obj:`OptimWrapperDict` which is built by
+ ``CustomOptimWrapperConstructor``. ``OptimWrapperDict`` will load and save
+ the state dictionary of all optimizer wrappers.
+
+ Consider the semantic ambiguity of calling :meth:``update_params``,
+ :meth:`backward` of all optimizer wrappers, ``OptimWrapperDict`` will not
+ implement these methods.
+
+ Examples:
+ >>> import torch.nn as nn
+ >>> from torch.optim import SGD
+ >>> from mmengine.optim import OptimWrapperDict, OptimWrapper
+ >>> model1 = nn.Linear(1, 1)
+ >>> model2 = nn.Linear(1, 1)
+ >>> optim_wrapper1 = OptimWrapper(SGD(model1.parameters(), lr=0.1))
+ >>> optim_wrapper2 = OptimWrapper(SGD(model2.parameters(), lr=0.1))
+ >>> optim_wrapper_dict = OptimWrapperDict(model1=optim_wrapper1,
+ >>> model2=optim_wrapper2)
+
+ Note:
+ The optimizer wrapper contained in ``OptimWrapperDict`` can be accessed
+ in the same way as `dict`.
+
+ Args:
+ **optim_wrappers: A dictionary of ``OptimWrapper`` instance.
+ """
+
+ def __init__(self, **optim_wrapper_dict: OptimWrapper):
+ for key, value in optim_wrapper_dict.items():
+ assert isinstance(value, OptimWrapper), (
+ '`OptimWrapperDict` only accept OptimWrapper instance, '
+ f'but got {key}: {type(value)}')
+ self.optim_wrappers = optim_wrapper_dict
+
+ def update_params(self,
+ loss: torch.Tensor,
+ step_kwargs: Optional[Dict] = None,
+ zero_kwargs: Optional[Dict] = None) -> None:
+ """Update all optimizer wrappers would lead to a duplicate backward
+ errors, and OptimWrapperDict does not know which optimizer wrapper
+ should be updated.
+
+ Therefore, this method is not implemented. The optimizer wrapper of
+ OptimWrapperDict should be accessed and call its `update_params.
+ """
+ raise NotImplementedError('`update_params` should be called by each '
+ 'optimizer separately`')
+
+ def backward(self, loss: torch.Tensor, **kwargs) -> None:
+ """Since OptimWrapperDict doesn't know which optimizer wrapper's
+ backward method should be called (``loss_scaler`` maybe different in
+ different :obj:AmpOptimWrapper), this method is not implemented.
+
+ The optimizer wrapper of OptimWrapperDict should be accessed and call
+ its `backward.
+ """
+ raise NotImplementedError('`backward` should be called by each '
+ 'optimizer separately`')
+
+ def step(self, **kwargs) -> None:
+ """Since the backward method is not implemented, the step should not be
+ implemented either."""
+ raise NotImplementedError('`step` should be called by each '
+ 'optimizer separately`')
+
+ def zero_grad(self, **kwargs) -> None:
+ """Set the gradients of all optimizer wrappers to zero."""
+ for optim_wrapper in self.optim_wrappers.values():
+ optim_wrapper.zero_grad()
+
+ @contextmanager
+ def optim_context(self, model: nn.Module):
+ """``optim_context`` should be called by each optimizer separately."""
+ raise NotImplementedError(
+ '`optim_context` should be called by each optimizer separately')
+
+ def initialize_count_status(self, model: nn.Module, cur_iter,
+ max_iters) -> None:
+ """Do nothing but provide unified interface for :obj:`OptimWrapper`
+
+ Since ``OptimWrapperDict`` does not know the correspondence between
+ model and optimizer wrapper. ``initialize_iter_status`` will do nothing
+ and each optimizer wrapper should call ``initialize_iter_status``
+ separately.
+ """
+ return
+
+ @property
+ def param_groups(self):
+ """Returns the parameter groups of each OptimWrapper."""
+ param_groups = dict()
+ for key, value in self.optim_wrappers.items():
+ param_groups[key] = value.param_groups
+ return param_groups
+
+ def get_lr(self) -> Dict[str, List[float]]:
+ """Get the learning rate of all optimizers.
+
+ Returns:
+ Dict[str, List[float]]: Learning rate of all optimizers.
+ """
+ lr_dict = dict()
+ for name, optim_wrapper in self.optim_wrappers.items():
+ lr_dict[f'{name}.lr'] = optim_wrapper.get_lr()['lr']
+ return lr_dict
+
+ def get_momentum(self) -> Dict[str, List[float]]:
+ """Get the momentum of all optimizers.
+
+ Returns:
+ Dict[str, List[float]]: momentum of all optimizers.
+ """
+ momentum_dict = dict()
+ for name, optim_wrapper in self.optim_wrappers.items():
+ momentum_dict[f'{name}.momentum'] = optim_wrapper.get_momentum(
+ )['momentum']
+ return momentum_dict
+
+ def state_dict(self) -> dict:
+ """Get the state dictionary of all optimizer wrappers.
+
+ Returns:
+ dict: Each key-value pair in the dictionary represents the name
+ and state dictionary of corresponding :obj:`OptimWrapper`.
+ """
+ state_dict = dict()
+ for name, optim_wrapper in self.optim_wrappers.items():
+ state_dict[name] = optim_wrapper.state_dict()
+ return state_dict
+
+ def load_state_dict(self, state_dict: dict) -> None:
+ """Load the state dictionary from the ``state_dict``.
+
+ Args:
+ state_dict (dict): Each key-value pair in `state_dict` represents
+ the name and the state dictionary of corresponding
+ :obj:`OptimWrapper`.
+ """
+ for name, _state_dict in state_dict.items():
+ assert name in self.optim_wrappers, (
+ f'Mismatched `state_dict`! cannot found {name} in '
+ 'OptimWrapperDict')
+ self.optim_wrappers[name].load_state_dict(_state_dict)
+
+ def items(self) -> Iterator[Tuple[str, OptimWrapper]]:
+ """A generator to get the name and corresponding
+ :obj:`OptimWrapper`"""
+ yield from self.optim_wrappers.items()
+
+ def values(self) -> Iterator[OptimWrapper]:
+ """A generator to get :obj:`OptimWrapper`"""
+ yield from self.optim_wrappers.values()
+
+ def keys(self) -> Iterator[str]:
+ """A generator to get the name of :obj:`OptimWrapper`"""
+ yield from self.optim_wrappers.keys()
+
+ def __getitem__(self, key: str) -> OptimWrapper:
+ assert key in self.optim_wrappers, (
+ f'Cannot find {key} in OptimWrapperDict, please check '
+ 'your optimizer constructor.')
+ return self.optim_wrappers[key]
+
+ def __contains__(self, key: str) -> bool:
+ return key in self.optim_wrappers
+
+ def __len__(self) -> int:
+ return len(self.optim_wrappers)
+
+ def __repr__(self) -> str:
+ desc = ''
+ for name, optim_wrapper in self.optim_wrappers.items():
+ desc += f'name: {name}\n'
+ desc += repr(optim_wrapper)
+ return desc
diff --git a/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/zero_optimizer.py b/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/zero_optimizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c5630a765c0352031cbdcd1f85ebbe210129a0f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/optim/optimizer/zero_optimizer.py
@@ -0,0 +1,79 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+
+import torch
+from torch.distributed.rpc import is_available
+
+from mmengine.dist import is_main_process
+from mmengine.utils import digit_version
+from mmengine.utils.dl_utils import TORCH_VERSION
+
+try:
+ from torch.distributed.optim import \
+ ZeroRedundancyOptimizer as _ZeroRedundancyOptimizer
+except ImportError:
+ _ZeroRedundancyOptimizer = object
+
+from .builder import OPTIMIZERS
+
+
+@OPTIMIZERS.register_module()
+class ZeroRedundancyOptimizer(_ZeroRedundancyOptimizer):
+ """A wrapper class of :class:`ZeroRedundancyOptimizer` that gets a
+ optimizer type as string.
+
+ This class wraps an arbitrary :class:`torch.optim.Optimizer` and shards its
+ states across ranks in the group as described by ZeRO_. The local optimizer
+ instance in each rank is only responsible for updating approximately
+ ``1 / world_size`` parameters and hence only needs to keep
+ ``1 / world_size`` optimizer states. After parameters are updated locally,
+ each rank will broadcast its parameters to all other peers to keep all
+ model replicas in the same state. ``ZeroRedundancyOptimizer`` can be used
+ in conjunction with :class:`torch.nn.parallel.DistributedDataParallel` to
+ reduce per-rank peak memory consumption.
+
+ ``ZeroRedundancyOptimizer`` uses a sorted-greedy algorithm to pack a number
+ of parameters at each rank. Each parameter belongs to a single rank and is
+ not divided among ranks. The partition is arbitrary and might not match the
+ the parameter registration or usage order.
+
+ Warnings:
+ ``ZeroRedundancyOptimizer`` requires PyTorch >= 1.8.
+
+ Warnings:
+ ``ZeroRedundancyOptimizer`` requires PyTorch >= 1.12 to enable param
+ groups.
+
+ Args:
+ params (``Iterable``): an ``Iterable`` of :class:`torch.Tensor` s
+ or :class:`dict` s giving all parameters, which will be sharded
+ across ranks.
+ optimizer_type (str): the string of the local optimizer class.
+
+ .. _ZeRO: https://arxiv.org/abs/1910.02054
+ """
+
+ def __init__(self, params, optimizer_type: str, **kwargs):
+ assert digit_version(TORCH_VERSION) >= digit_version('1.8.0'), (
+ '`torch.distributed.optim.ZeroReundancyOptimizer` is only '
+ 'available when pytorch version >= 1.8.')
+ assert is_available(), 'torch.distributed.rpc is not available.'
+ # Avoid the generator becoming empty after the following check
+ params = list(params)
+ assert (
+ all(isinstance(p, torch.Tensor) for p in params)
+ or digit_version(TORCH_VERSION) >= digit_version('1.12.0')), (
+ 'PyTorch ZeroRedundancyOptimizer started to support param '
+ 'groups since 1.12.0. Please update your pytorch version to '
+ 'enable this feature, or disable param groups by deleting '
+ '`paramwise_cfg` filed in config file.')
+ optimizer_class = getattr(torch.optim, optimizer_type)
+ # TODO: Register a DDP communication hook for `overlap_with_ddp=True`.
+ # Currently only `overlap_with_ddp=False` is supported. For more
+ # details, please refer to the pytorch's official documentation.
+ super().__init__(params, optimizer_class, **kwargs)
+
+ def state_dict(self):
+ """Consolidate `state_dict`s from ranks to save the `state_dict`."""
+ self.consolidate_state_dict()
+ state_dict = super().state_dict() if is_main_process() else dict()
+ return state_dict
diff --git a/testbed/open-mmlab__mmengine/mmengine/optim/scheduler/__init__.py b/testbed/open-mmlab__mmengine/mmengine/optim/scheduler/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c12d1c2970d39561e3ddec2e92e49f67bbfdc4ba
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/optim/scheduler/__init__.py
@@ -0,0 +1,30 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+# yapf: disable
+from .lr_scheduler import (ConstantLR, CosineAnnealingLR, CosineRestartLR,
+ ExponentialLR, LinearLR, MultiStepLR, OneCycleLR,
+ PolyLR, StepLR)
+from .momentum_scheduler import (ConstantMomentum, CosineAnnealingMomentum,
+ CosineRestartMomentum, ExponentialMomentum,
+ LinearMomentum, MultiStepMomentum,
+ PolyMomentum, StepMomentum)
+from .param_scheduler import (ConstantParamScheduler,
+ CosineAnnealingParamScheduler,
+ CosineRestartParamScheduler,
+ ExponentialParamScheduler, LinearParamScheduler,
+ MultiStepParamScheduler, OneCycleParamScheduler,
+ PolyParamScheduler, StepParamScheduler,
+ _ParamScheduler)
+
+# yapf: enable
+
+__all__ = [
+ 'ConstantLR', 'CosineAnnealingLR', 'ExponentialLR', 'LinearLR',
+ 'MultiStepLR', 'StepLR', 'ConstantMomentum', 'CosineAnnealingMomentum',
+ 'ExponentialMomentum', 'LinearMomentum', 'MultiStepMomentum',
+ 'StepMomentum', 'ConstantParamScheduler', 'CosineAnnealingParamScheduler',
+ 'ExponentialParamScheduler', 'LinearParamScheduler',
+ 'MultiStepParamScheduler', 'StepParamScheduler', '_ParamScheduler',
+ 'PolyParamScheduler', 'PolyLR', 'PolyMomentum', 'OneCycleParamScheduler',
+ 'OneCycleLR', 'CosineRestartParamScheduler', 'CosineRestartLR',
+ 'CosineRestartMomentum'
+]
diff --git a/testbed/open-mmlab__mmengine/mmengine/optim/scheduler/lr_scheduler.py b/testbed/open-mmlab__mmengine/mmengine/optim/scheduler/lr_scheduler.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1eeabec5f794e8130158ac710907f33827c8f77
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/optim/scheduler/lr_scheduler.py
@@ -0,0 +1,316 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from mmengine.registry import PARAM_SCHEDULERS
+from .param_scheduler import (ConstantParamScheduler,
+ CosineAnnealingParamScheduler,
+ CosineRestartParamScheduler,
+ ExponentialParamScheduler, LinearParamScheduler,
+ MultiStepParamScheduler, OneCycleParamScheduler,
+ PolyParamScheduler, StepParamScheduler)
+
+
+class LRSchedulerMixin:
+ """A mixin class for learning rate schedulers."""
+
+ def __init__(self, optimizer, *args, **kwargs):
+ super().__init__(optimizer, 'lr', *args, **kwargs)
+
+
+@PARAM_SCHEDULERS.register_module()
+class ConstantLR(LRSchedulerMixin, ConstantParamScheduler):
+ """Decays the learning rate value of each parameter group by a small
+ constant factor until the number of epoch reaches a pre-defined milestone:
+ ``end``. Notice that such decay can happen simultaneously with other
+ changes to the learning rate value from outside this scheduler.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): Wrapped optimizer.
+ factor (float): The number we multiply learning rate until the
+ milestone. Defaults to 1./3.
+ begin (int): Step at which to start updating the learning rate.
+ Defaults to 0.
+ end (int): Step at which to stop updating the learning rate.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without state
+ dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled learning rate is updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the learning rate for each update.
+ Defaults to False.
+ """
+
+
+@PARAM_SCHEDULERS.register_module()
+class CosineAnnealingLR(LRSchedulerMixin, CosineAnnealingParamScheduler):
+ r"""Set the learning rate of each parameter group using a cosine annealing
+ schedule, where :math:`\eta_{max}` is set to the initial value and
+ :math:`T_{cur}` is the number of epochs since the last restart in SGDR:
+
+ .. math::
+ \begin{aligned}
+ \eta_t & = \eta_{min} + \frac{1}{2}(\eta_{max} - \eta_{min})\left(1
+ + \cos\left(\frac{T_{cur}}{T_{max}}\pi\right)\right),
+ & T_{cur} \neq (2k+1)T_{max}; \\
+ \eta_{t+1} & = \eta_{t} + \frac{1}{2}(\eta_{max} - \eta_{min})
+ \left(1 - \cos\left(\frac{1}{T_{max}}\pi\right)\right),
+ & T_{cur} = (2k+1)T_{max}.
+ \end{aligned}
+
+ Notice that because the schedule
+ is defined recursively, the learning rate can be simultaneously modified
+ outside this scheduler by other operators. If the learning rate is set
+ solely by this scheduler, the learning rate at each step becomes:
+
+ .. math::
+ \eta_t = \eta_{min} + \frac{1}{2}(\eta_{max} - \eta_{min})\left(1 +
+ \cos\left(\frac{T_{cur}}{T_{max}}\pi\right)\right)
+
+ It has been proposed in
+ `SGDR: Stochastic Gradient Descent with Warm Restarts`_. Note that this
+ only implements the cosine annealing part of SGDR, and not the restarts.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): Wrapped optimizer.
+ T_max (int): Maximum number of iterations.
+ eta_min (float): Minimum learning rate. Defaults to None.
+ begin (int): Step at which to start updating the learning rate.
+ Defaults to 0.
+ end (int): Step at which to stop updating the learning rate.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled learning rate is updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the learning rate for each update.
+ Defaults to False.
+ eta_min_ratio (float, optional): The ratio of the minimum parameter
+ value to the base parameter value. Either `eta_min` or
+ `eta_min_ratio` should be specified. Defaults to None.
+ New in version 0.3.2.
+
+ .. _SGDR\: Stochastic Gradient Descent with Warm Restarts:
+ https://arxiv.org/abs/1608.03983
+ """
+
+
+@PARAM_SCHEDULERS.register_module()
+class ExponentialLR(LRSchedulerMixin, ExponentialParamScheduler):
+ """Decays the learning rate of each parameter group by gamma every epoch.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): Wrapped optimizer.
+ gamma (float): Multiplicative factor of learning rate decay.
+ begin (int): Step at which to start updating the learning rate.
+ Defaults to 0.
+ end (int): Step at which to stop updating the learning rate.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled learning rate is updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the learning rate for each update.
+ Defaults to False.
+ """
+
+
+@PARAM_SCHEDULERS.register_module()
+class LinearLR(LRSchedulerMixin, LinearParamScheduler):
+ """Decays the learning rate of each parameter group by linearly changing
+ small multiplicative factor until the number of epoch reaches a pre-defined
+ milestone: ``end``.
+
+ Notice that such decay can happen simultaneously with other changes to the
+ learning rate from outside this scheduler.
+ Args:
+ optimizer (Optimizer or OptimWrapper): Wrapped optimizer.
+ start_factor (float): The number we multiply learning rate in the
+ first epoch. The multiplication factor changes towards end_factor
+ in the following epochs. Defaults to 1./3.
+ end_factor (float): The number we multiply learning rate at the end
+ of linear changing process. Defaults to 1.0.
+ begin (int): Step at which to start updating the learning rate.
+ Defaults to 0.
+ end (int): Step at which to stop updating the learning rate.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled learning rate is updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the learning rate for each update.
+ Defaults to False.
+ """
+
+
+@PARAM_SCHEDULERS.register_module()
+class MultiStepLR(LRSchedulerMixin, MultiStepParamScheduler):
+ """Decays the specified learning rate in each parameter group by gamma once
+ the number of epoch reaches one of the milestones. Notice that such decay
+ can happen simultaneously with other changes to the learning rate from
+ outside this scheduler.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): Wrapped optimizer.
+ milestones (list): List of epoch indices. Must be increasing.
+ gamma (float): Multiplicative factor of learning rate decay.
+ Defaults to 0.1.
+ begin (int): Step at which to start updating the learning rate.
+ Defaults to 0.
+ end (int): Step at which to stop updating the learning rate.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled learning rate is updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the learning rate for each update.
+ Defaults to False.
+ """
+
+
+@PARAM_SCHEDULERS.register_module()
+class StepLR(LRSchedulerMixin, StepParamScheduler):
+ """Decays the learning rate of each parameter group by gamma every
+ step_size epochs. Notice that such decay can happen simultaneously with
+ other changes to the learning rate from outside this scheduler.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): Wrapped optimizer.
+ step_size (int): Period of learning rate decay.
+ gamma (float): Multiplicative factor of learning rate decay.
+ Defaults to 0.1.
+ begin (int): Step at which to start updating the learning rate.
+ Defaults to 0.
+ end (int): Step at which to stop updating the learning rate.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled learning rate is updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the learning rate for each update.
+ Defaults to False.
+ """
+
+
+@PARAM_SCHEDULERS.register_module()
+class PolyLR(LRSchedulerMixin, PolyParamScheduler):
+ """Decays the learning rate of each parameter group in a polynomial decay
+ scheme.
+
+ Notice that such decay can happen simultaneously with other changes to the
+ parameter value from outside this scheduler.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): Wrapped optimizer.
+ eta_min (float): Minimum learning rate at the end of scheduling.
+ Defaults to 0.
+ power (float): The power of the polynomial. Defaults to 1.0.
+ begin (int): Step at which to start updating the parameters.
+ Defaults to 0.
+ end (int): Step at which to stop updating the parameters.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled parameters are updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the value for each update.
+ Defaults to False.
+ """
+
+
+@PARAM_SCHEDULERS.register_module()
+class OneCycleLR(LRSchedulerMixin, OneCycleParamScheduler):
+ r"""Sets the learning rate of each parameter group according to the
+ 1cycle learning rate policy. The 1cycle policy anneals the learning
+ rate from an initial learning rate to some maximum learning rate and then
+ from that maximum learning rate to some minimum learning rate much lower
+ than the initial learning rate.
+ This policy was initially described in the paper `Super-Convergence:
+ Very Fast Training of Neural Networks Using Large Learning Rates`_.
+
+ The 1cycle learning rate policy changes the learning rate after every
+ batch. `step` should be called after a batch has been used for training.
+
+ This scheduler is not chainable.
+
+ Note also that the total number of steps in the cycle can be determined in
+ one of two ways (listed in order of precedence):
+
+ #. A value for total_steps is explicitly provided.
+ #. A number of epochs (epochs) and a number of steps per epoch
+ (steps_per_epoch) are provided.
+ In this case, the number of total steps is inferred by
+ total_steps = epochs * steps_per_epoch
+
+ You must either provide a value for total_steps or provide a value for both
+ epochs and steps_per_epoch.
+
+ The default behaviour of this scheduler follows the fastai implementation
+ of 1cycle, which claims that "unpublished work has shown even better
+ results by using only two phases". To mimic the behaviour of the original
+ paper instead, set ``three_phase=True``.
+
+ Args:
+ optimizer (Optimizer): Wrapped optimizer.
+ eta_max (float or list): Upper parameter value boundaries in the cycle
+ for each parameter group.
+ total_steps (int): The total number of steps in the cycle. Note that
+ if a value is not provided here, then it must be inferred by
+ providing a value for epochs and steps_per_epoch.
+ Default to None.
+ pct_start (float): The percentage of the cycle (in number of steps)
+ spent increasing the learning rate.
+ Default to 0.3
+ anneal_strategy (str): {'cos', 'linear'}
+ Specifies the annealing strategy: "cos" for cosine annealing,
+ "linear" for linear annealing.
+ Default to 'cos'
+ div_factor (float): Determines the initial learning rate via
+ initial_param = eta_max/div_factor
+ Default to 25
+ final_div_factor (float): Determines the minimum learning rate via
+ eta_min = initial_param/final_div_factor
+ Default to 1e4
+ three_phase (bool): If ``True``, use a third phase of the schedule to
+ annihilate the learning rate according to 'final_div_factor'
+ instead of modifying the second phase (the first two phases will be
+ symmetrical about the step indicated by 'pct_start').
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled parameters are updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the value for each update.
+ Defaults to False.
+
+ .. _Super-Convergence\: Very Fast Training of Neural Networks Using Large Learning Rates:
+ https://arxiv.org/abs/1708.07120
+ """# noqa E501
+
+
+@PARAM_SCHEDULERS.register_module()
+class CosineRestartLR(LRSchedulerMixin, CosineRestartParamScheduler):
+ """Sets the learning rate of each parameter group according to the cosine
+ annealing with restarts scheme. The cosine restart policy anneals the
+ learning rate from the initial value to `eta_min` with a cosine annealing
+ schedule and then restarts another period from the maximum value multiplied
+ with `restart_weight`.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): optimizer or Wrapped
+ optimizer.
+ periods (list[int]): Periods for each cosine anneling cycle.
+ restart_weights (list[float]): Restart weights at each
+ restart iteration. Defaults to [1].
+ eta_min (float): Minimum parameter value at the end of scheduling.
+ Defaults to None.
+ eta_min_ratio (float, optional): The ratio of minimum parameter value
+ to the base parameter value. Either `min_lr` or `min_lr_ratio`
+ should be specified. Default: None.
+ begin (int): Step at which to start updating the parameters.
+ Defaults to 0.
+ end (int): Step at which to stop updating the parameters.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled parameters are updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the value for each update.
+ Defaults to False.
+ """
diff --git a/testbed/open-mmlab__mmengine/mmengine/optim/scheduler/momentum_scheduler.py b/testbed/open-mmlab__mmengine/mmengine/optim/scheduler/momentum_scheduler.py
new file mode 100644
index 0000000000000000000000000000000000000000..102b173146f525a84ad5892d5e544b6ea44c2248
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/optim/scheduler/momentum_scheduler.py
@@ -0,0 +1,283 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from mmengine.registry import PARAM_SCHEDULERS
+from .param_scheduler import (ConstantParamScheduler,
+ CosineAnnealingParamScheduler,
+ CosineRestartParamScheduler,
+ ExponentialParamScheduler, LinearParamScheduler,
+ MultiStepParamScheduler, PolyParamScheduler,
+ StepParamScheduler)
+
+
+class MomentumSchedulerMixin:
+ """A mixin class for momentum schedulers.
+
+ It can schedule the momentum in SGD and the beta_0 in Adam series.
+ """
+
+ def __init__(self, optimizer, *args, **kwargs):
+ self.use_betas = False
+ if 'momentum' in optimizer.defaults:
+ param_name = 'momentum'
+ elif 'betas' in optimizer.defaults:
+ # for Adam series optimizer, the momentum is beta_0
+ self.use_betas = True
+ param_name = 'momentum'
+ for group in optimizer.param_groups:
+ # set a reference momentum in the param groups for scheduling
+ group[param_name] = group['betas'][0]
+ else:
+ raise ValueError(
+ 'optimizer must support momentum when using momentum scheduler'
+ )
+ super().__init__(optimizer, param_name, *args, **kwargs)
+
+ def step(self):
+ """Adjusts the parameter value of each parameter group based on the
+ specified schedule."""
+ super().step()
+ if self.use_betas:
+ for group in self.optimizer.param_groups:
+ _, beta_1 = group['betas']
+ # update the betas with the calculated value
+ group['betas'] = (group['momentum'], beta_1)
+
+
+@PARAM_SCHEDULERS.register_module()
+class ConstantMomentum(MomentumSchedulerMixin, ConstantParamScheduler):
+ """Decays the momentum value of each parameter group by a small constant
+ factor until the number of epoch reaches a pre-defined milestone: ``end``.
+ Notice that such decay can happen simultaneously with other changes to the
+ momentum value from outside this scheduler.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): optimizer or Wrapped
+ optimizer.
+ factor (float): The number we multiply momentum until the milestone.
+ Defaults to 1./3.
+ begin (int): Step at which to start updating the momentum.
+ Defaults to 0.
+ end (int): Step at which to stop updating the momentum.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without state
+ dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled momentum is updated by epochs.
+ Defaults to True.
+ verbose (bool): Whether to print the momentum for each update.
+ Defaults to False.
+ """
+
+
+@PARAM_SCHEDULERS.register_module()
+class CosineAnnealingMomentum(MomentumSchedulerMixin,
+ CosineAnnealingParamScheduler):
+ r"""Set the momentum of each parameter group using a cosine annealing
+ schedule, where :math:`\eta_{max}` is set to the initial value and
+ :math:`T_{cur}` is the number of epochs since the last restart in SGDR:
+
+ .. math::
+ \begin{aligned}
+ \eta_t & = \eta_{min} + \frac{1}{2}(\eta_{max} - \eta_{min})\left(1
+ + \cos\left(\frac{T_{cur}}{T_{max}}\pi\right)\right),
+ & T_{cur} \neq (2k+1)T_{max}; \\
+ \eta_{t+1} & = \eta_{t} + \frac{1}{2}(\eta_{max} - \eta_{min})
+ \left(1 - \cos\left(\frac{1}{T_{max}}\pi\right)\right),
+ & T_{cur} = (2k+1)T_{max}.
+ \end{aligned}
+
+ Notice that because the schedule
+ is defined recursively, the momentum can be simultaneously modified
+ outside this scheduler by other operators. If the momentum is set
+ solely by this scheduler, the momentum at each step becomes:
+
+ .. math::
+ \eta_t = \eta_{min} + \frac{1}{2}(\eta_{max} - \eta_{min})\left(1 +
+ \cos\left(\frac{T_{cur}}{T_{max}}\pi\right)\right)
+
+ It has been proposed in
+ `SGDR: Stochastic Gradient Descent with Warm Restarts`_. Note that this
+ only implements the cosine annealing part of SGDR, and not the restarts.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): optimizer or Wrapped
+ optimizer.
+ T_max (int): Maximum number of iterations.
+ eta_min (float): Minimum momentum value. Defaults to None.
+ begin (int): Step at which to start updating the momentum.
+ Defaults to 0.
+ end (int): Step at which to stop updating the momentum.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled momentum is updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the momentum for each update.
+ Defaults to False.
+ eta_min_ratio (float, optional): The ratio of the minimum parameter
+ value to the base parameter value. Either `eta_min` or
+ `eta_min_ratio` should be specified. Defaults to None.
+ New in version 0.3.2.
+
+ .. _SGDR\: Stochastic Gradient Descent with Warm Restarts:
+ https://arxiv.org/abs/1608.03983
+ """
+
+
+@PARAM_SCHEDULERS.register_module()
+class ExponentialMomentum(MomentumSchedulerMixin, ExponentialParamScheduler):
+ """Decays the momentum of each parameter group by gamma every epoch.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): optimizer or Wrapped
+ optimizer.
+ gamma (float): Multiplicative factor of momentum value decay.
+ begin (int): Step at which to start updating the momentum.
+ Defaults to 0.
+ end (int): Step at which to stop updating the momentum.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled momentum is updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the momentum for each update.
+ Defaults to False.
+ """
+
+
+@PARAM_SCHEDULERS.register_module()
+class LinearMomentum(MomentumSchedulerMixin, LinearParamScheduler):
+ """Decays the momentum of each parameter group by linearly changing
+ small multiplicative factor until the number of epoch reaches a pre-defined
+ milestone: ``end``.
+
+ Notice that such decay can happen simultaneously with other changes to the
+ momentum from outside this scheduler.
+ Args:
+ optimizer (Optimizer or OptimWrapper): optimizer or Wrapped
+ optimizer.
+ start_factor (float): The number we multiply momentum in the
+ first epoch. The multiplication factor changes towards end_factor
+ in the following epochs. Defaults to 1./3.
+ end_factor (float): The number we multiply momentum at the end
+ of linear changing process. Defaults to 1.0.
+ begin (int): Step at which to start updating the momentum.
+ Defaults to 0.
+ end (int): Step at which to stop updating the momentum.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled momentum is updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the momentum for each update.
+ Defaults to False.
+ """
+
+
+@PARAM_SCHEDULERS.register_module()
+class MultiStepMomentum(MomentumSchedulerMixin, MultiStepParamScheduler):
+ """Decays the specified momentum in each parameter group by gamma once the
+ number of epoch reaches one of the milestones. Notice that such decay can
+ happen simultaneously with other changes to the momentum from outside this
+ scheduler.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): optimizer or Wrapped
+ optimizer.
+ milestones (list): List of epoch indices. Must be increasing.
+ gamma (float): Multiplicative factor of momentum value decay.
+ Defaults to 0.1.
+ begin (int): Step at which to start updating the momentum.
+ Defaults to 0.
+ end (int): Step at which to stop updating the momentum.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled momentum is updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the momentum for each update.
+ Defaults to False.
+ """
+
+
+@PARAM_SCHEDULERS.register_module()
+class StepMomentum(MomentumSchedulerMixin, StepParamScheduler):
+ """Decays the momentum of each parameter group by gamma every step_size
+ epochs. Notice that such decay can happen simultaneously with other changes
+ to the momentum from outside this scheduler.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): optimizer or Wrapped
+ optimizer.
+ step_size (int): Period of momentum value decay.
+ gamma (float): Multiplicative factor of momentum value decay.
+ Defaults to 0.1.
+ begin (int): Step at which to start updating the momentum.
+ Defaults to 0.
+ end (int): Step at which to stop updating the momentum.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled momentum is updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the momentum for each update.
+ Defaults to False.
+ """
+
+
+@PARAM_SCHEDULERS.register_module()
+class PolyMomentum(MomentumSchedulerMixin, PolyParamScheduler):
+ """Decays the momentum of each parameter group in a polynomial decay
+ scheme.
+
+ Notice that such decay can happen simultaneously with other changes to the
+ parameter value from outside this scheduler.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): optimizer or Wrapped
+ optimizer.
+ eta_min (float): Minimum momentum at the end of scheduling.
+ Defaults to 0.
+ power (float): The power of the polynomial. Defaults to 1.0.
+ begin (int): Step at which to start updating the parameters.
+ Defaults to 0.
+ end (int): Step at which to stop updating the parameters.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled parameters are updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the value for each update.
+ Defaults to False.
+ """
+
+
+@PARAM_SCHEDULERS.register_module()
+class CosineRestartMomentum(MomentumSchedulerMixin,
+ CosineRestartParamScheduler):
+ """Sets the momentum of each parameter group according to the cosine
+ annealing with restarts scheme. The cosine restart policy anneals the
+ momentum from the initial value to `eta_min` with a cosine annealing
+ schedule and then restarts another period from the maximum value multiplied
+ with `restart_weight`.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): optimizer or Wrapped
+ optimizer.
+ periods (list[int]): Periods for each cosine anneling cycle.
+ restart_weights (list[float]): Restart weights at each
+ restart iteration. Defaults to [1].
+ eta_min (float): Minimum parameter value at the end of scheduling.
+ Defaults to None.
+ eta_min_ratio (float, optional): The ratio of minimum parameter value
+ to the base parameter value. Either `min_lr` or `min_lr_ratio`
+ should be specified. Default: None.
+ begin (int): Step at which to start updating the parameters.
+ Defaults to 0.
+ end (int): Step at which to stop updating the parameters.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled parameters are updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the value for each update.
+ Defaults to False.
+ """
diff --git a/testbed/open-mmlab__mmengine/mmengine/optim/scheduler/param_scheduler.py b/testbed/open-mmlab__mmengine/mmengine/optim/scheduler/param_scheduler.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fdf5c3d8874ad107703fe2840e09f0fee08fbe7
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/optim/scheduler/param_scheduler.py
@@ -0,0 +1,1285 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+# ------------------------------------------------------------------------
+# Modified from https://github.com/pytorch/pytorch
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+# ------------------------------------------------------------------------
+
+import math
+import warnings
+import weakref
+from collections import Counter
+from functools import wraps
+from typing import Callable, List, Optional, Sequence, Union
+
+from torch.optim import Optimizer
+
+from mmengine.logging import print_log
+from mmengine.optim import OptimWrapper
+from mmengine.registry import PARAM_SCHEDULERS
+
+INF = int(1e9)
+
+OptimizerType = Union[OptimWrapper, Optimizer]
+
+
+class _ParamScheduler:
+ """Base class for parameter schedulers.
+
+ It should be inherited by all schedulers that schedule parameters in the
+ optimizer's ``param_groups``. All subclasses should overwrite the
+ ``_get_value()`` according to their own schedule strategy.
+ The implementation is motivated by
+ https://github.com/pytorch/pytorch/blob/master/torch/optim/lr_scheduler.py.
+
+ Args:
+ optimizer (OptimWrapper or Optimizer): Wrapped optimizer.
+ param_name (str): Name of the parameter to be adjusted, such as
+ ``lr``, ``momentum``.
+ begin (int): Step at which to start updating the parameters.
+ Defaults to 0.
+ end (int): Step at which to stop updating the parameters.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resuming without
+ state dict. Default value ``-1`` means the ``step`` function is
+ never be called before. Defaults to -1.
+ by_epoch (bool): Whether the scheduled parameters are updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the value for each update.
+ Defaults to False.
+ """ # noqa: E501
+
+ def __init__(self,
+ optimizer: OptimizerType,
+ param_name: str,
+ begin: int = 0,
+ end: int = INF,
+ last_step: int = -1,
+ by_epoch: bool = True,
+ verbose: bool = False):
+
+ # Attach optimizer
+ if not isinstance(optimizer, (Optimizer, OptimWrapper)):
+ raise TypeError('``optimizer`` should be an Optimizer,'
+ 'but got {}'.format(type(optimizer).__name__))
+ self.optimizer = optimizer
+ self.param_name = param_name
+
+ if end <= begin:
+ raise ValueError('end should be larger than begin, but got'
+ ' begin={}, end={}'.format(begin, end))
+ self.begin = begin
+ self.end = end
+
+ self.by_epoch = by_epoch
+
+ assert isinstance(last_step, int) and last_step >= -1
+ # Initialize valid step count and base values
+ if last_step == -1:
+ for group in optimizer.param_groups:
+ # If the param is never be scheduled, record the current value
+ # as the initial value.
+ group.setdefault(f'initial_{param_name}', group[param_name])
+ else:
+ for i, group in enumerate(optimizer.param_groups):
+ if f'initial_{param_name}' not in group:
+ raise KeyError(
+ f"param 'initial_{param_name}' is not specified "
+ 'in param_groups[{}] when resuming an optimizer'.
+ format(i))
+ self.base_values = [
+ group[f'initial_{param_name}'] for group in optimizer.param_groups
+ ]
+ self.last_step = last_step
+
+ # Following https://github.com/pytorch/pytorch/issues/20124
+ # We would like to ensure that `scheduler.step()` is called after
+ # `optimizer.step()`
+ def with_counter(method: Callable):
+ if getattr(method, '_with_counter', False):
+ # `optimizer.step()` has already been replaced, return.
+ return method
+
+ # Keep a weak reference to the optimizer instance to prevent
+ # cyclic references.
+ instance_ref = weakref.ref(method.__self__) # type: ignore
+ # Get the unbound method for the same purpose.
+ func = method.__func__ # type: ignore
+ cls = instance_ref().__class__ # type: ignore
+ del method
+
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ instance = instance_ref()
+ instance._global_step += 1
+ wrapped = func.__get__(instance, cls)
+ return wrapped(*args, **kwargs)
+
+ # Note that the returned function here is no longer a bound method,
+ # so attributes like `__func__` and `__self__` no longer exist.
+ wrapper._with_counter = True # type: ignore
+ return wrapper
+
+ # add counter to optimizer
+ self.optimizer.step = with_counter(self.optimizer.step) # type: ignore
+ self.optimizer._global_step = -1 # type: ignore
+
+ self._global_step = -1
+ self.verbose = verbose
+
+ self.step()
+
+ def state_dict(self) -> dict:
+ """Returns the state of the scheduler as a :class:`dict`.
+
+ It contains an entry for every variable in self.__dict__ which is not
+ the optimizer.
+
+ Returns:
+ dict: scheduler state.
+ """
+ return {
+ key: value
+ for key, value in self.__dict__.items() if key != 'optimizer'
+ }
+
+ def load_state_dict(self, state_dict: dict):
+ """Loads the schedulers state.
+
+ Args:
+ state_dict (dict): scheduler state. Should be an object returned
+ from a call to :meth:`state_dict`.
+ """
+ self.__dict__.update(state_dict)
+
+ def get_last_value(self):
+ """Return the last computed value by current scheduler.
+
+ Returns:
+ list: A list of the last computed value of the optimizer's
+ ``param_group``.
+ """
+ return self._last_value
+
+ def _get_value(self):
+ """Compute value using chainable form of the scheduler."""
+ raise NotImplementedError
+
+ def print_value(self, is_verbose: bool, group: int, value: float):
+ """Display the current parameter value.
+
+ Args:
+ is_verbose (bool): Whether to print the value.
+ group (int): The index of the current ``param_group``.
+ value (float): The parameter value.
+ """
+ if is_verbose:
+ print_log(
+ f'Adjusting parameter value of group {group} to {value:.4e}.',
+ logger='current')
+
+ def step(self):
+ """Adjusts the parameter value of each parameter group based on the
+ specified schedule."""
+ # Raise a warning if old pattern is detected
+ # https://github.com/pytorch/pytorch/issues/20124
+ if self._global_step == 0:
+ if not hasattr(self.optimizer.step, '_with_counter'):
+ warnings.warn(
+ 'Seems like `optimizer.step()` has been overridden after'
+ 'parameter value scheduler initialization. Please, make'
+ 'sure to call `optimizer.step()` before'
+ '`scheduler.step()`. See more details at'
+ 'https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate', # noqa: E501
+ UserWarning)
+
+ # Just check if there were two first scheduler.step() calls
+ # before optimizer.step()
+ elif self.optimizer._global_step < 0:
+ warnings.warn(
+ 'Detected call of `scheduler.step()` before'
+ '`optimizer.step()`. In PyTorch 1.1.0 and later, you'
+ 'should call them in the opposite order: '
+ '`optimizer.step()` before `scheduler.step()`. '
+ 'Failure to do this will result in PyTorch skipping '
+ 'the first value of the parameter value schedule. '
+ 'See more details at https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate', # noqa: E501
+ UserWarning)
+ self._global_step += 1
+
+ # Compute parameter value per param group in the effective range
+ if self.begin <= self._global_step < self.end:
+ self.last_step += 1
+ values = self._get_value()
+
+ for i, data in enumerate(zip(self.optimizer.param_groups, values)):
+ param_group, value = data
+ param_group[self.param_name] = value
+ self.print_value(self.verbose, i, value)
+
+ self._last_value = [
+ group[self.param_name] for group in self.optimizer.param_groups
+ ]
+
+
+@PARAM_SCHEDULERS.register_module()
+class StepParamScheduler(_ParamScheduler):
+ """Decays the parameter value of each parameter group by gamma every
+ step_size epochs. Notice that such decay can happen simultaneously with
+ other changes to the parameter value from outside this scheduler.
+
+ Args:
+ optimizer (OptimWrapper or Optimizer): Wrapped optimizer.
+ param_name (str): Name of the parameter to be adjusted, such as
+ ``lr``, ``momentum``.
+ step_size (int): Period of parameter value decay.
+ gamma (float): Multiplicative factor of parameter value decay.
+ Defaults to 0.1.
+ begin (int): Step at which to start updating the parameters.
+ Defaults to 0.
+ end (int): Step at which to stop updating the parameters.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled parameters are updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the value for each update.
+ Defaults to False.
+ """
+
+ def __init__(self,
+ optimizer: OptimizerType,
+ param_name: str,
+ step_size: int,
+ gamma: float = 0.1,
+ begin: int = 0,
+ end: int = INF,
+ last_step: int = -1,
+ by_epoch: bool = True,
+ verbose: bool = False):
+ self.step_size = step_size
+ self.gamma = gamma
+ super().__init__(
+ optimizer=optimizer,
+ param_name=param_name,
+ begin=begin,
+ end=end,
+ last_step=last_step,
+ by_epoch=by_epoch,
+ verbose=verbose)
+
+ @classmethod
+ def build_iter_from_epoch(cls,
+ *args,
+ step_size,
+ begin=0,
+ end=INF,
+ by_epoch=True,
+ epoch_length=None,
+ **kwargs):
+ """Build an iter-based instance of this scheduler from an epoch-based
+ config."""
+ assert by_epoch, 'Only epoch-based kwargs whose `by_epoch=True` can ' \
+ 'be converted to iter-based.'
+ assert epoch_length is not None and epoch_length > 0, \
+ f'`epoch_length` must be a positive integer, ' \
+ f'but got {epoch_length}.'
+ by_epoch = False
+ step_size = step_size * epoch_length
+ begin = int(begin * epoch_length)
+ if end != INF:
+ end = int(end * epoch_length)
+ return cls(
+ *args,
+ step_size=step_size,
+ begin=begin,
+ end=end,
+ by_epoch=by_epoch,
+ **kwargs)
+
+ def _get_value(self):
+ """Compute value using chainable form of the scheduler."""
+ if (self.last_step == 0) or (self.last_step % self.step_size != 0):
+ return [
+ group[self.param_name] for group in self.optimizer.param_groups
+ ]
+ return [
+ group[self.param_name] * self.gamma
+ for group in self.optimizer.param_groups
+ ]
+
+
+@PARAM_SCHEDULERS.register_module()
+class MultiStepParamScheduler(_ParamScheduler):
+ """Decays the specified parameter in each parameter group by gamma once the
+ number of epoch reaches one of the milestones. Notice that such decay can
+ happen simultaneously with other changes to the parameter from outside this
+ scheduler.
+
+ Args:
+ optimizer (OptimWrapper or Optimizer): Wrapped optimizer.
+ param_name (str): Name of the parameter to be adjusted, such as
+ ``lr``, ``momentum``.
+ milestones (list): List of epoch indices. Must be increasing.
+ gamma (float): Multiplicative factor of parameter value decay.
+ Defaults to 0.1.
+ begin (int): Step at which to start updating the parameters.
+ Defaults to 0.
+ end (int): Step at which to stop updating the parameters.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled parameters are updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the value for each update.
+ Defaults to False.
+ """
+
+ def __init__(self,
+ optimizer: OptimizerType,
+ param_name: str,
+ milestones: List[int],
+ gamma: float = 0.1,
+ last_step: int = -1,
+ begin: int = 0,
+ end: int = INF,
+ by_epoch: bool = True,
+ verbose: bool = False):
+ self.milestones = Counter(milestones)
+ self.gamma = gamma
+ super().__init__(
+ optimizer,
+ param_name=param_name,
+ begin=begin,
+ end=end,
+ last_step=last_step,
+ by_epoch=by_epoch,
+ verbose=verbose)
+
+ @classmethod
+ def build_iter_from_epoch(cls,
+ *args,
+ milestones,
+ begin=0,
+ end=INF,
+ by_epoch=True,
+ epoch_length=None,
+ **kwargs):
+ """Build an iter-based instance of this scheduler from an epoch-based
+ config."""
+ assert by_epoch, 'Only epoch-based kwargs whose `by_epoch=True` can ' \
+ 'be converted to iter-based.'
+ assert epoch_length is not None and epoch_length > 0, \
+ f'`epoch_length` must be a positive integer, ' \
+ f'but got {epoch_length}.'
+ by_epoch = False
+ milestones = [i * epoch_length for i in milestones]
+ begin = int(begin * epoch_length)
+ if end != INF:
+ end = int(end * epoch_length)
+ return cls(
+ *args,
+ milestones=milestones,
+ begin=begin,
+ end=end,
+ by_epoch=by_epoch,
+ **kwargs)
+
+ def _get_value(self):
+ """Compute value using chainable form of the scheduler."""
+ if self.last_step not in self.milestones:
+ return [
+ group[self.param_name] for group in self.optimizer.param_groups
+ ]
+ return [
+ group[self.param_name] *
+ self.gamma**self.milestones[self.last_step]
+ for group in self.optimizer.param_groups
+ ]
+
+
+@PARAM_SCHEDULERS.register_module()
+class ConstantParamScheduler(_ParamScheduler):
+ """Decays the parameter value of each parameter group by a small constant
+ factor until the number of epoch reaches a pre-defined milestone: ``end``.
+ Notice that such decay can happen simultaneously with other changes to the
+ parameter value from outside this scheduler.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): optimizer or Wrapped
+ optimizer.
+ param_name (str): Name of the parameter to be adjusted, such as
+ ``lr``, ``momentum``.
+ factor (float): The number we multiply parameter value until the
+ milestone. Defaults to 1./3.
+ begin (int): Step at which to start updating the parameters.
+ Defaults to 0.
+ end (int): Step at which to stop updating the parameters.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled parameters are updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the value for each update.
+ Defaults to False.
+ """
+
+ def __init__(self,
+ optimizer: OptimizerType,
+ param_name: str,
+ factor: float = 1.0 / 3,
+ begin: int = 0,
+ end: int = INF,
+ last_step: int = -1,
+ by_epoch: bool = True,
+ verbose: bool = False):
+ if factor > 1.0 or factor < 0:
+ raise ValueError(
+ 'Constant multiplicative factor should between 0 and 1.')
+
+ self.factor = factor
+ self.total_iters = end - begin - 1
+ super().__init__(
+ optimizer,
+ param_name=param_name,
+ begin=begin,
+ end=end,
+ last_step=last_step,
+ by_epoch=by_epoch,
+ verbose=verbose)
+
+ @classmethod
+ def build_iter_from_epoch(cls,
+ *args,
+ begin=0,
+ end=INF,
+ by_epoch=True,
+ epoch_length=None,
+ **kwargs):
+ """Build an iter-based instance of this scheduler from an epoch-based
+ config."""
+ assert by_epoch, 'Only epoch-based kwargs whose `by_epoch=True` can ' \
+ 'be converted to iter-based.'
+ assert epoch_length is not None and epoch_length > 0, \
+ f'`epoch_length` must be a positive integer, ' \
+ f'but got {epoch_length}.'
+ by_epoch = False
+ begin = int(begin * epoch_length)
+ if end != INF:
+ end = int(end * epoch_length)
+ return cls(*args, begin=begin, end=end, by_epoch=by_epoch, **kwargs)
+
+ def _get_value(self):
+ """Compute value using chainable form of the scheduler."""
+ if self.last_step == 0:
+ return [
+ group[self.param_name] * self.factor
+ for group in self.optimizer.param_groups
+ ]
+
+ if (self.last_step > self.total_iters
+ or (self.last_step != self.total_iters)):
+ return [
+ group[self.param_name] for group in self.optimizer.param_groups
+ ]
+
+ if self.last_step == self.total_iters:
+ return [
+ group[self.param_name] * (1.0 / self.factor)
+ for group in self.optimizer.param_groups
+ ]
+
+
+@PARAM_SCHEDULERS.register_module()
+class ExponentialParamScheduler(_ParamScheduler):
+ """Decays the parameter value of each parameter group by gamma every epoch.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): optimizer or Wrapped
+ optimizer.
+ param_name (str): Name of the parameter to be adjusted, such as
+ ``lr``, ``momentum``.
+ gamma (float): Multiplicative factor of parameter value decay.
+ begin (int): Step at which to start updating the parameters.
+ Defaults to 0.
+ end (int): Step at which to stop updating the parameters.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled parameters are updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the value for each update.
+ Defaults to False.
+ """
+
+ def __init__(self,
+ optimizer: OptimizerType,
+ param_name: str,
+ gamma: float,
+ begin: int = 0,
+ end: int = INF,
+ last_step: int = -1,
+ by_epoch: bool = True,
+ verbose: bool = False):
+ self.gamma = gamma
+ super().__init__(
+ optimizer,
+ param_name=param_name,
+ begin=begin,
+ end=end,
+ last_step=last_step,
+ by_epoch=by_epoch,
+ verbose=verbose)
+
+ @classmethod
+ def build_iter_from_epoch(cls,
+ *args,
+ begin=0,
+ end=INF,
+ by_epoch=True,
+ epoch_length=None,
+ **kwargs):
+ """Build an iter-based instance of this scheduler from an epoch-based
+ config."""
+ assert by_epoch, 'Only epoch-based kwargs whose `by_epoch=True` can ' \
+ 'be converted to iter-based.'
+ assert epoch_length is not None and epoch_length > 0, \
+ f'`epoch_length` must be a positive integer, ' \
+ f'but got {epoch_length}.'
+ by_epoch = False
+ begin = int(begin * epoch_length)
+ if end != INF:
+ end = int(end * epoch_length)
+ return cls(*args, begin=begin, end=end, by_epoch=by_epoch, **kwargs)
+
+ def _get_value(self):
+ """Compute value using chainable form of the scheduler."""
+ if self.last_step == 0:
+ return [
+ group[self.param_name] for group in self.optimizer.param_groups
+ ]
+ return [
+ group[self.param_name] * self.gamma
+ for group in self.optimizer.param_groups
+ ]
+
+
+@PARAM_SCHEDULERS.register_module()
+class CosineAnnealingParamScheduler(_ParamScheduler):
+ r"""Set the parameter value of each parameter group using a cosine
+ annealing schedule, where :math:`\eta_{max}` is set to the initial value
+ and :math:`T_{cur}` is the number of epochs since the last restart in SGDR:
+
+ .. math::
+ \begin{aligned}
+ \eta_t & = \eta_{min} + \frac{1}{2}(\eta_{max} - \eta_{min})\left(1
+ + \cos\left(\frac{T_{cur}}{T_{max}}\pi\right)\right),
+ & T_{cur} \neq (2k+1)T_{max}; \\
+ \eta_{t+1} & = \eta_{t} + \frac{1}{2}(\eta_{max} - \eta_{min})
+ \left(1 - \cos\left(\frac{1}{T_{max}}\pi\right)\right),
+ & T_{cur} = (2k+1)T_{max}.
+ \end{aligned}
+
+ Notice that because the schedule
+ is defined recursively, the parameter value can be simultaneously modified
+ outside this scheduler by other operators. If the parameter value is set
+ solely by this scheduler, the parameter value at each step becomes:
+
+ .. math::
+ \eta_t = \eta_{min} + \frac{1}{2}(\eta_{max} - \eta_{min})\left(1 +
+ \cos\left(\frac{T_{cur}}{T_{max}}\pi\right)\right)
+
+ It has been proposed in
+ `SGDR: Stochastic Gradient Descent with Warm Restarts`_. Note that this
+ only implements the cosine annealing part of SGDR, and not the restarts.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): optimizer or Wrapped
+ optimizer.
+ param_name (str): Name of the parameter to be adjusted, such as
+ ``lr``, ``momentum``.
+ T_max (int, optional): Maximum number of iterations. If not specified,
+ use ``end - begin``. Defaults to None.
+ eta_min (float, optional): Minimum parameter value. Defaults to None.
+ begin (int): Step at which to start updating the parameters.
+ Defaults to 0.
+ end (int): Step at which to stop updating the parameters.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled parameters are updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the value for each update.
+ Defaults to False.
+ eta_min_ratio (float, optional): The ratio of the minimum parameter
+ value to the base parameter value. Either `eta_min` or
+ `eta_min_ratio` should be specified. Defaults to None.
+ New in version 0.3.2.
+
+ .. _SGDR\: Stochastic Gradient Descent with Warm Restarts:
+ https://arxiv.org/abs/1608.03983
+ """
+
+ def __init__(self,
+ optimizer: Union[Optimizer, OptimWrapper],
+ param_name: str,
+ T_max: Optional[int] = None,
+ eta_min: Optional[float] = None,
+ begin: int = 0,
+ end: int = INF,
+ last_step: int = -1,
+ by_epoch: bool = True,
+ verbose: bool = False,
+ eta_min_ratio: Optional[float] = None):
+ # To preserve backwards compatibility
+ if eta_min is None and eta_min_ratio is None:
+ eta_min = 0.
+ assert (eta_min is None) ^ (eta_min_ratio is None), \
+ 'Either `eta_min` or `eta_min_ratio should be specified'
+ self.T_max = T_max or (end - begin)
+ self.eta_min = eta_min
+ self.eta_min_ratio = eta_min_ratio
+ super().__init__(
+ optimizer,
+ param_name=param_name,
+ begin=begin,
+ end=end,
+ last_step=last_step,
+ by_epoch=by_epoch,
+ verbose=verbose)
+
+ @classmethod
+ def build_iter_from_epoch(cls,
+ *args,
+ T_max=None,
+ begin=0,
+ end=INF,
+ by_epoch=True,
+ epoch_length=None,
+ **kwargs):
+ """Build an iter-based instance of this scheduler from an epoch-based
+ config."""
+ assert by_epoch, 'Only epoch-based kwargs whose `by_epoch=True` can ' \
+ 'be converted to iter-based.'
+ assert epoch_length is not None and epoch_length > 0, \
+ f'`epoch_length` must be a positive integer, ' \
+ f'but got {epoch_length}.'
+ by_epoch = False
+ if T_max is not None:
+ T_max = T_max * epoch_length
+ begin = int(begin * epoch_length)
+ if end != INF:
+ end = int(end * epoch_length)
+ return cls(
+ *args,
+ T_max=T_max,
+ begin=begin,
+ end=end,
+ by_epoch=by_epoch,
+ **kwargs)
+
+ def _get_value(self) -> list:
+ """Compute value using chainable form of the scheduler."""
+
+ def _get_eta_min(base_value):
+ if self.eta_min_ratio is None:
+ return self.eta_min
+ return base_value * self.eta_min_ratio
+
+ if self.last_step == 0:
+ return [
+ group[self.param_name] for group in self.optimizer.param_groups
+ ]
+ elif (self.last_step - 1 - self.T_max) % (2 * self.T_max) == 0:
+ return [
+ group[self.param_name] +
+ (base_value - _get_eta_min(base_value)) *
+ (1 - math.cos(math.pi / self.T_max)) / 2
+ for base_value, group in zip(self.base_values,
+ self.optimizer.param_groups)
+ ]
+ return [(1 + math.cos(math.pi * self.last_step / self.T_max)) /
+ (1 + math.cos(math.pi * (self.last_step - 1) / self.T_max)) *
+ (group[self.param_name] - _get_eta_min(base_value)) +
+ _get_eta_min(base_value) for base_value, group in zip(
+ self.base_values, self.optimizer.param_groups)]
+
+
+@PARAM_SCHEDULERS.register_module()
+class LinearParamScheduler(_ParamScheduler):
+ """Decays the parameter value of each parameter group by linearly changing
+ small multiplicative factor until the number of epoch reaches a pre-defined
+ milestone: ``end``.
+
+ Notice that such decay can happen simultaneously with other changes to the
+ parameter value from outside this scheduler.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): optimizer or Wrapped
+ optimizer.
+ param_name (str): Name of the parameter to be adjusted, such as
+ ``lr``, ``momentum``.
+ start_factor (float): The number we multiply parameter value in the
+ first epoch. The multiplication factor changes towards end_factor
+ in the following epochs. Defaults to 1./3.
+ end_factor (float): The number we multiply parameter value at the end
+ of linear changing process. Defaults to 1.0.
+ begin (int): Step at which to start updating the parameters.
+ Defaults to 0.
+ end (int): Step at which to stop updating the parameters.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled parameters are updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the value for each update.
+ Defaults to False.
+ """
+
+ def __init__(self,
+ optimizer: Union[Optimizer, OptimWrapper],
+ param_name: str,
+ start_factor: float = 1.0 / 3,
+ end_factor: float = 1.0,
+ begin: int = 0,
+ end: int = INF,
+ last_step: int = -1,
+ by_epoch: bool = True,
+ verbose: bool = False):
+ if start_factor > 1.0 or start_factor < 0:
+ raise ValueError(
+ 'Starting multiplicative factor should between 0 and 1.')
+
+ if end_factor > 1.0 or end_factor < 0:
+ raise ValueError(
+ 'Ending multiplicative factor should between 0 and 1.')
+
+ self.start_factor = start_factor
+ self.end_factor = end_factor
+ self.total_iters = end - begin - 1
+ super().__init__(
+ optimizer,
+ param_name=param_name,
+ begin=begin,
+ end=end,
+ last_step=last_step,
+ by_epoch=by_epoch,
+ verbose=verbose)
+
+ @classmethod
+ def build_iter_from_epoch(cls,
+ *args,
+ begin=0,
+ end=INF,
+ by_epoch=True,
+ epoch_length=None,
+ **kwargs):
+ """Build an iter-based instance of this scheduler from an epoch-based
+ config."""
+ assert by_epoch, 'Only epoch-based kwargs whose `by_epoch=True` can ' \
+ 'be converted to iter-based.'
+ assert epoch_length is not None and epoch_length > 0, \
+ f'`epoch_length` must be a positive integer, ' \
+ f'but got {epoch_length}.'
+ by_epoch = False
+ begin = int(begin * epoch_length)
+ if end != INF:
+ end = int(end * epoch_length)
+ return cls(*args, begin=begin, end=end, by_epoch=by_epoch, **kwargs)
+
+ def _get_value(self):
+ """Compute value using chainable form of the scheduler."""
+ if self.last_step == 0:
+ return [
+ group[self.param_name] * self.start_factor
+ for group in self.optimizer.param_groups
+ ]
+
+ return [
+ group[self.param_name] *
+ (1. + (self.end_factor - self.start_factor) /
+ (self.total_iters * self.start_factor + (self.last_step - 1) *
+ (self.end_factor - self.start_factor)))
+ for group in self.optimizer.param_groups
+ ]
+
+
+@PARAM_SCHEDULERS.register_module()
+class PolyParamScheduler(_ParamScheduler):
+ """Decays the parameter value of each parameter group in a polynomial decay
+ scheme.
+
+ Notice that such decay can happen simultaneously with other changes to the
+ parameter value from outside this scheduler.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): optimizer or Wrapped
+ optimizer.
+ param_name (str): Name of the parameter to be adjusted, such as
+ ``lr``, ``momentum``.
+ eta_min (float): Minimum parameter value at the end of scheduling.
+ Defaults to 0.
+ power (float): The power of the polynomial. Defaults to 1.0.
+ begin (int): Step at which to start updating the parameters.
+ Defaults to 0.
+ end (int): Step at which to stop updating the parameters.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled parameters are updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the value for each update.
+ Defaults to False.
+ """
+
+ def __init__(self,
+ optimizer: Union[Optimizer, OptimWrapper],
+ param_name: str,
+ eta_min: float = 0,
+ power: float = 1.0,
+ begin: int = 0,
+ end: int = INF,
+ last_step: int = -1,
+ by_epoch: bool = True,
+ verbose: bool = False):
+
+ self.eta_min = eta_min
+ self.power = power
+ self.total_iters = end - begin - 1
+
+ super().__init__(
+ optimizer,
+ param_name=param_name,
+ begin=begin,
+ end=end,
+ last_step=last_step,
+ by_epoch=by_epoch,
+ verbose=verbose)
+
+ @classmethod
+ def build_iter_from_epoch(cls,
+ *args,
+ begin=0,
+ end=INF,
+ by_epoch=True,
+ epoch_length=None,
+ **kwargs):
+ """Build an iter-based instance of this scheduler from an epoch-based
+ config."""
+ assert by_epoch, 'Only epoch-based kwargs whose `by_epoch=True` can ' \
+ 'be converted to iter-based.'
+ assert epoch_length is not None and epoch_length > 0, \
+ f'`epoch_length` must be a positive integer, ' \
+ f'but got {epoch_length}.'
+ by_epoch = False
+ begin = int(begin * epoch_length)
+ if end != INF:
+ end = int(end * epoch_length)
+ return cls(*args, begin=begin, end=end, by_epoch=by_epoch, **kwargs)
+
+ def _get_value(self):
+ """Compute value using chainable form of the scheduler."""
+ if self.last_step == 0:
+ return [
+ group[self.param_name] for group in self.optimizer.param_groups
+ ]
+
+ return [(group[self.param_name] - self.eta_min) *
+ (1 - 1 / (self.total_iters - self.last_step + 1))**self.power +
+ self.eta_min for group in self.optimizer.param_groups]
+
+
+@PARAM_SCHEDULERS.register_module()
+class OneCycleParamScheduler(_ParamScheduler):
+ r"""Sets the parameters of each parameter group according to the
+ 1cycle learning rate policy. The 1cycle policy anneals the learning
+ rate from an initial learning rate to some maximum learning rate and then
+ from that maximum learning rate to some minimum learning rate much lower
+ than the initial learning rate.
+ This policy was initially described in the paper `Super-Convergence:
+ Very Fast Training of Neural Networks Using Large Learning Rates`_.
+
+ The 1cycle learning rate policy changes the learning rate after every
+ batch. `step` should be called after a batch has been used for training.
+
+ This scheduler is not chainable.
+
+ Note also that the total number of steps in the cycle can be determined in
+ one of two ways (listed in order of precedence):
+
+ #. A value for total_steps is explicitly provided.
+ #. If total_steps is not defined, begin and end of the ParamSchedul will
+ works for it. In this case, the number of total steps is inferred by
+ total_steps = end - begin
+
+ The default behaviour of this scheduler follows the fastai implementation
+ of 1cycle, which claims that "unpublished work has shown even better
+ results by using only two phases". To mimic the behaviour of the original
+ paper instead, set ``three_phase=True``.
+
+ Args:
+ optimizer (Optimizer): Wrapped optimizer.
+ param_name (str): Name of the parameter to be adjusted, such as
+ ``lr``, ``momentum``.
+ eta_max (float or list): Upper parameter value boundaries in the cycle
+ for each parameter group.
+ total_steps (int): The total number of steps in the cycle. Note that
+ if a value is not provided here, then it will be equal to
+ ``end - begin``. Default to None
+ pct_start (float): The percentage of the cycle (in number of steps)
+ spent increasing the learning rate.
+ Default to 0.3
+ anneal_strategy (str): {'cos', 'linear'}
+ Specifies the annealing strategy: "cos" for cosine annealing,
+ "linear" for linear annealing.
+ Default to 'cos'
+ div_factor (float): Determines the initial learning rate via
+ initial_param = eta_max/div_factor
+ Default to 25
+ final_div_factor (float): Determines the minimum learning rate via
+ eta_min = initial_param/final_div_factor
+ Default to 1e4
+ three_phase (bool): If ``True``, use a third phase of the schedule to
+ annihilate the learning rate according to 'final_div_factor'
+ instead of modifying the second phase (the first two phases will be
+ symmetrical about the step indicated by 'pct_start').
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled parameters are updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the value for each update.
+ Defaults to False.
+
+ .. _Super-Convergence\: Very Fast Training of Neural Networks Using Large Learning Rates:
+ https://arxiv.org/abs/1708.07120
+ """# noqa E501
+
+ def __init__(self,
+ optimizer: Union[Optimizer, OptimWrapper],
+ param_name: str,
+ eta_max: float = 0,
+ total_steps: Optional[int] = None,
+ pct_start: float = 0.3,
+ anneal_strategy: str = 'cos',
+ div_factor: float = 25.,
+ final_div_factor: float = 1e4,
+ three_phase: bool = False,
+ begin: int = 0,
+ end: int = INF,
+ last_step: int = -1,
+ by_epoch: bool = True,
+ verbose: bool = False):
+
+ assert param_name == 'lr', ('OneCycle only works for learning rate '
+ 'updating, but got patam_name as '
+ f'{param_name}')
+
+ self.eta_max = eta_max
+ self.div_factor = div_factor
+ self.final_div_factor = final_div_factor
+
+ # Validate total_steps
+ if total_steps is not None:
+ if total_steps <= 0 or not isinstance(total_steps, int):
+ raise ValueError('Expected positive integer total_steps, '
+ f'but got {total_steps}')
+ self.total_steps = total_steps
+ else:
+ self.total_steps = self.end - self.begin
+
+ # Validate pct_start
+ if pct_start < 0 or pct_start > 1 or not isinstance(pct_start, float):
+ raise ValueError('Expected float between 0 and 1 pct_start, '
+ f'but got {pct_start}')
+
+ # Validate anneal_strategy
+ if anneal_strategy not in ['cos', 'linear']:
+ raise ValueError(
+ 'anneal_strategy must by one of "cos" or "linear", '
+ f'instead got {anneal_strategy}')
+ elif anneal_strategy == 'cos':
+ self.anneal_func = self._annealing_cos
+ elif anneal_strategy == 'linear':
+ self.anneal_func = self._annealing_linear
+
+ if three_phase:
+ self._schedule_phases = [
+ {
+ 'end_step': float(pct_start * self.total_steps) - 1,
+ f'start_{param_name}': f'initial_{param_name}',
+ f'end_{param_name}': f'max_{param_name}'
+ },
+ {
+ 'end_step': float(2 * pct_start * self.total_steps) - 2,
+ f'start_{param_name}': f'max_{param_name}',
+ f'end_{param_name}': f'initial_{param_name}'
+ },
+ {
+ 'end_step': self.total_steps - 1,
+ f'start_{param_name}': f'initial_{param_name}',
+ f'end_{param_name}': f'min_{param_name}'
+ },
+ ]
+ else:
+ self._schedule_phases = [
+ {
+ 'end_step': float(pct_start * self.total_steps) - 1,
+ f'start_{param_name}': f'initial_{param_name}',
+ f'end_{param_name}': f'max_{param_name}'
+ },
+ {
+ 'end_step': self.total_steps - 1,
+ f'start_{param_name}': f'max_{param_name}',
+ f'end_{param_name}': f'min_{param_name}'
+ },
+ ]
+
+ # Initialize parameters
+ max_values = self._format_param(f'max_{param_name}', optimizer,
+ eta_max)
+ if last_step == -1:
+ for idx, group in enumerate(optimizer.param_groups):
+ group[f'initial_{param_name}'] = max_values[idx] / div_factor
+ group[f'max_{param_name}'] = max_values[idx]
+ group[f'min_{param_name}'] = \
+ group[f'initial_{param_name}'] / final_div_factor
+
+ super().__init__(
+ optimizer=optimizer,
+ param_name=param_name,
+ begin=begin,
+ end=end,
+ last_step=last_step,
+ by_epoch=by_epoch,
+ verbose=verbose)
+
+ def _format_param(self, name, optimizer, param):
+ """Return correctly formatted lr/momentum for each param group."""
+ if isinstance(param, (list, tuple)):
+ if len(param) != len(optimizer.param_groups):
+ raise ValueError(
+ f'expected {len(optimizer.param_groups)} values '
+ f'for {name}, got { len(param)}')
+ return param
+ else:
+ return [param] * len(optimizer.param_groups)
+
+ @staticmethod
+ def _annealing_cos(start, end, pct):
+ """Cosine anneal from `start` to `end` as pct goes from 0.0 to 1.0."""
+
+ cos_out = math.cos(math.pi * pct) + 1
+ return end + (start - end) / 2.0 * cos_out
+
+ @staticmethod
+ def _annealing_linear(start, end, pct):
+ """Linearly anneal from `start` to `end` as pct goes from 0.0 to
+ 1.0."""
+ return (end - start) * pct + start
+
+ @classmethod
+ def build_iter_from_epoch(cls,
+ *args,
+ begin=0,
+ end=INF,
+ total_steps=None,
+ by_epoch=True,
+ epoch_length=None,
+ **kwargs):
+ """Build an iter-based instance of this scheduler from an epoch-based
+ config."""
+ assert by_epoch, 'Only epoch-based kwargs whose `by_epoch=True` can ' \
+ 'be converted to iter-based.'
+ assert epoch_length is not None and epoch_length > 0, \
+ f'`epoch_length` must be a positive integer, ' \
+ f'but got {epoch_length}.'
+ by_epoch = False
+ begin = int(begin * epoch_length)
+ if end != INF:
+ end = int(end * epoch_length)
+ if total_steps is not None:
+ total_steps = total_steps * epoch_length
+ return cls(
+ *args,
+ begin=begin,
+ end=end,
+ total_steps=total_steps,
+ by_epoch=by_epoch,
+ **kwargs)
+
+ def _get_value(self):
+ """Compute value using chainable form of the scheduler."""
+
+ params = []
+ step_num = self.last_step
+
+ if step_num > self.total_steps:
+ raise ValueError(
+ f'Tried to step {step_num + 1} times. '
+ f'The specified number of total steps is {self.total_steps}')
+
+ for group in self.optimizer.param_groups:
+ start_step = 0
+ for i, phase in enumerate(self._schedule_phases):
+ end_step = phase['end_step']
+ if step_num <= end_step or i == len(self._schedule_phases) - 1:
+ pct = (step_num - start_step) / (end_step - start_step)
+ computed_param = self.anneal_func(
+ group[phase['start_' + self.param_name]],
+ group[phase['end_' + self.param_name]], pct)
+ break
+ start_step = phase['end_step']
+
+ params.append(computed_param)
+
+ return params
+
+
+@PARAM_SCHEDULERS.register_module()
+class CosineRestartParamScheduler(_ParamScheduler):
+ """Sets the parameters of each parameter group according to the cosine
+ annealing with restarts scheme. The cosine restart policy anneals the
+ parameter from the initial value to `eta_min` with a cosine annealing
+ schedule and then restarts another period from the maximum value multiplied
+ with `restart_weight`.
+
+ Args:
+ optimizer (Optimizer or OptimWrapper): optimizer or Wrapped
+ optimizer.
+ param_name (str): Name of the parameter to be adjusted, such as
+ ``lr``, ``momentum``.
+ periods (list[int]): Periods for each cosine anneling cycle.
+ restart_weights (list[float]): Restart weights at each
+ restart iteration. Defaults to [1].
+ eta_min (float, optional): Minimum parameter value at the end of
+ scheduling. Defaults to None.
+ eta_min_ratio (float, optional): The ratio of minimum parameter value
+ to the base parameter value. Either `eta_min` or `eta_min_ratio`
+ should be specified. Defaults to None.
+ begin (int): Step at which to start updating the parameters.
+ Defaults to 0.
+ end (int): Step at which to stop updating the parameters.
+ Defaults to INF.
+ last_step (int): The index of last step. Used for resume without
+ state dict. Defaults to -1.
+ by_epoch (bool): Whether the scheduled parameters are updated by
+ epochs. Defaults to True.
+ verbose (bool): Whether to print the value for each update.
+ Defaults to False.
+ """
+
+ def __init__(self,
+ optimizer: Union[Optimizer, OptimWrapper],
+ param_name: str,
+ periods: List[int],
+ restart_weights: Sequence[float] = (1, ),
+ eta_min: Optional[float] = None,
+ eta_min_ratio: Optional[float] = None,
+ begin: int = 0,
+ end: int = INF,
+ last_step: int = -1,
+ by_epoch: bool = True,
+ verbose: bool = False):
+ assert (eta_min is None) ^ (eta_min_ratio is None)
+ self.periods = periods
+ self.eta_min = eta_min
+ self.eta_min_ratio = eta_min_ratio
+ self.restart_weights = restart_weights
+ assert (len(self.periods) == len(self.restart_weights)
+ ), 'periods and restart_weights should have the same length.'
+ self.cumulative_periods = [
+ sum(self.periods[0:i + 1]) for i in range(0, len(self.periods))
+ ]
+
+ super().__init__(
+ optimizer,
+ param_name=param_name,
+ begin=begin,
+ end=end,
+ last_step=last_step,
+ by_epoch=by_epoch,
+ verbose=verbose)
+
+ @classmethod
+ def build_iter_from_epoch(cls,
+ *args,
+ periods,
+ begin=0,
+ end=INF,
+ by_epoch=True,
+ epoch_length=None,
+ **kwargs):
+ """Build an iter-based instance of this scheduler from an epoch-based
+ config."""
+ assert by_epoch, 'Only epoch-based kwargs whose `by_epoch=True` can ' \
+ 'be converted to iter-based.'
+ assert epoch_length is not None and epoch_length > 0, \
+ f'`epoch_length` must be a positive integer, ' \
+ f'but got {epoch_length}.'
+ periods = [p * epoch_length for p in periods]
+ by_epoch = False
+ begin = int(begin * epoch_length)
+ if end != INF:
+ end = int(end * epoch_length)
+ return cls(
+ *args,
+ periods=periods,
+ begin=begin,
+ end=end,
+ by_epoch=by_epoch,
+ **kwargs)
+
+ def _get_value(self):
+ """Compute value using chainable form of the scheduler."""
+ idx = self.get_position_from_periods(self.last_step,
+ self.cumulative_periods)
+ # if current step is not in the periods, return origin parameters
+ if idx is None:
+ return [
+ group[self.param_name] for group in self.optimizer.param_groups
+ ]
+ current_weight = self.restart_weights[idx]
+ nearest_restart = 0 if idx == 0 else self.cumulative_periods[idx - 1]
+ current_periods = self.periods[idx]
+ step = self.last_step - nearest_restart
+ values = []
+ for base_value, group in zip(self.base_values,
+ self.optimizer.param_groups):
+ eta_max = base_value * current_weight
+ if self.eta_min_ratio is None:
+ eta_min = self.eta_min
+ else:
+ eta_min = base_value * self.eta_min_ratio
+ if step == 0:
+ values.append(eta_max)
+ else:
+ values.append(
+ (1 + math.cos(math.pi * step / current_periods)) /
+ (1 + math.cos(math.pi * (step - 1) / current_periods)) *
+ (group[self.param_name] - eta_min) + eta_min)
+
+ return values
+
+ @staticmethod
+ def get_position_from_periods(
+ iteration: int, cumulative_periods: List[int]) -> Optional[int]:
+ """Get the position from a period list.
+
+ It will return the index of the right-closest number in the period
+ list.
+ For example, the cumulative_periods = [100, 200, 300, 400],
+ if iteration == 50, return 0;
+ if iteration == 210, return 2;
+ if iteration == 300, return 3.
+
+ Args:
+ iteration (int): Current iteration.
+ cumulative_periods (list[int]): Cumulative period list.
+
+ Returns:
+ Optional[int]: The position of the right-closest number in the
+ period list. If not in the period, return None.
+ """
+ for i, period in enumerate(cumulative_periods):
+ if iteration < period:
+ return i
+ return None
diff --git a/testbed/open-mmlab__mmengine/mmengine/registry/__init__.py b/testbed/open-mmlab__mmengine/mmengine/registry/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e1de6bf67aaf4efd126559d09ea222ce789f9c4
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/registry/__init__.py
@@ -0,0 +1,22 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .build_functions import (build_from_cfg, build_model_from_cfg,
+ build_runner_from_cfg, build_scheduler_from_cfg)
+from .default_scope import DefaultScope
+from .registry import Registry
+from .root import (DATA_SAMPLERS, DATASETS, EVALUATOR, HOOKS, LOG_PROCESSORS,
+ LOOPS, METRICS, MODEL_WRAPPERS, MODELS,
+ OPTIM_WRAPPER_CONSTRUCTORS, OPTIM_WRAPPERS, OPTIMIZERS,
+ PARAM_SCHEDULERS, RUNNER_CONSTRUCTORS, RUNNERS, TASK_UTILS,
+ TRANSFORMS, VISBACKENDS, VISUALIZERS, WEIGHT_INITIALIZERS)
+from .utils import count_registered_modules, traverse_registry_tree
+
+__all__ = [
+ 'Registry', 'RUNNERS', 'RUNNER_CONSTRUCTORS', 'HOOKS', 'DATASETS',
+ 'DATA_SAMPLERS', 'TRANSFORMS', 'MODELS', 'WEIGHT_INITIALIZERS',
+ 'OPTIMIZERS', 'OPTIM_WRAPPER_CONSTRUCTORS', 'TASK_UTILS',
+ 'PARAM_SCHEDULERS', 'METRICS', 'MODEL_WRAPPERS', 'OPTIM_WRAPPERS', 'LOOPS',
+ 'VISBACKENDS', 'VISUALIZERS', 'LOG_PROCESSORS', 'EVALUATOR',
+ 'DefaultScope', 'traverse_registry_tree', 'count_registered_modules',
+ 'build_model_from_cfg', 'build_runner_from_cfg', 'build_from_cfg',
+ 'build_scheduler_from_cfg'
+]
diff --git a/testbed/open-mmlab__mmengine/mmengine/registry/build_functions.py b/testbed/open-mmlab__mmengine/mmengine/registry/build_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0558b693a53ce9e3bb167ae12bbf51936e07d1f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/registry/build_functions.py
@@ -0,0 +1,306 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import inspect
+import logging
+from typing import TYPE_CHECKING, Any, Optional, Union
+
+from mmengine.config import Config, ConfigDict
+from mmengine.utils import ManagerMixin
+from .registry import Registry
+
+if TYPE_CHECKING:
+ import torch.nn as nn
+
+ from mmengine.optim.scheduler import _ParamScheduler
+ from mmengine.runner import Runner
+
+
+def build_from_cfg(
+ cfg: Union[dict, ConfigDict, Config],
+ registry: Registry,
+ default_args: Optional[Union[dict, ConfigDict, Config]] = None) -> Any:
+ """Build a module from config dict when it is a class configuration, or
+ call a function from config dict when it is a function configuration.
+
+ If the global variable default scope (:obj:`DefaultScope`) exists,
+ :meth:`build` will firstly get the responding registry and then call
+ its own :meth:`build`.
+
+ At least one of the ``cfg`` and ``default_args`` contains the key "type",
+ which should be either str or class. If they all contain it, the key
+ in ``cfg`` will be used because ``cfg`` has a high priority than
+ ``default_args`` that means if a key exists in both of them, the value of
+ the key will be ``cfg[key]``. They will be merged first and the key "type"
+ will be popped up and the remaining keys will be used as initialization
+ arguments.
+
+ Examples:
+ >>> from mmengine import Registry, build_from_cfg
+ >>> MODELS = Registry('models')
+ >>> @MODELS.register_module()
+ >>> class ResNet:
+ >>> def __init__(self, depth, stages=4):
+ >>> self.depth = depth
+ >>> self.stages = stages
+ >>> cfg = dict(type='ResNet', depth=50)
+ >>> model = build_from_cfg(cfg, MODELS)
+ >>> # Returns an instantiated object
+ >>> @MODELS.register_module()
+ >>> def resnet50():
+ >>> pass
+ >>> resnet = build_from_cfg(dict(type='resnet50'), MODELS)
+ >>> # Return a result of the calling function
+
+ Args:
+ cfg (dict or ConfigDict or Config): Config dict. It should at least
+ contain the key "type".
+ registry (:obj:`Registry`): The registry to search the type from.
+ default_args (dict or ConfigDict or Config, optional): Default
+ initialization arguments. Defaults to None.
+
+ Returns:
+ object: The constructed object.
+ """
+ # Avoid circular import
+ from ..logging import print_log
+
+ if not isinstance(cfg, (dict, ConfigDict, Config)):
+ raise TypeError(
+ f'cfg should be a dict, ConfigDict or Config, but got {type(cfg)}')
+
+ if 'type' not in cfg:
+ if default_args is None or 'type' not in default_args:
+ raise KeyError(
+ '`cfg` or `default_args` must contain the key "type", '
+ f'but got {cfg}\n{default_args}')
+
+ if not isinstance(registry, Registry):
+ raise TypeError('registry must be a mmengine.Registry object, '
+ f'but got {type(registry)}')
+
+ if not (isinstance(default_args,
+ (dict, ConfigDict, Config)) or default_args is None):
+ raise TypeError(
+ 'default_args should be a dict, ConfigDict, Config or None, '
+ f'but got {type(default_args)}')
+
+ args = cfg.copy()
+ if default_args is not None:
+ for name, value in default_args.items():
+ args.setdefault(name, value)
+
+ # Instance should be built under target scope, if `_scope_` is defined
+ # in cfg, current default scope should switch to specified scope
+ # temporarily.
+ scope = args.pop('_scope_', None)
+ with registry.switch_scope_and_registry(scope) as registry:
+ obj_type = args.pop('type')
+ if isinstance(obj_type, str):
+ obj_cls = registry.get(obj_type)
+ if obj_cls is None:
+ raise KeyError(
+ f'{obj_type} is not in the {registry.name} registry. '
+ f'Please check whether the value of `{obj_type}` is '
+ 'correct or it was registered as expected. More details '
+ 'can be found at '
+ 'https://mmengine.readthedocs.io/en/latest/advanced_tutorials/config.html#import-the-custom-module' # noqa: E501
+ )
+ elif inspect.isclass(obj_type) or inspect.isfunction(obj_type):
+ obj_cls = obj_type
+ else:
+ raise TypeError(
+ f'type must be a str or valid type, but got {type(obj_type)}')
+
+ try:
+ # If `obj_cls` inherits from `ManagerMixin`, it should be
+ # instantiated by `ManagerMixin.get_instance` to ensure that it
+ # can be accessed globally.
+ if inspect.isclass(obj_cls) and \
+ issubclass(obj_cls, ManagerMixin): # type: ignore
+ obj = obj_cls.get_instance(**args) # type: ignore
+ else:
+ obj = obj_cls(**args) # type: ignore
+
+ print_log(
+ f'An `{obj_cls.__name__}` instance is built from ' # type: ignore # noqa: E501
+ 'registry, its implementation can be found in '
+ f'{obj_cls.__module__}', # type: ignore
+ logger='current',
+ level=logging.DEBUG)
+ return obj
+
+ except Exception as e:
+ # Normal TypeError does not print class name.
+ cls_location = '/'.join(
+ obj_cls.__module__.split('.')) # type: ignore
+ raise type(e)(
+ f'class `{obj_cls.__name__}` in ' # type: ignore
+ f'{cls_location}.py: {e}')
+
+
+def build_runner_from_cfg(cfg: Union[dict, ConfigDict, Config],
+ registry: Registry) -> 'Runner':
+ """Build a Runner object.
+ Examples:
+ >>> from mmengine.registry import Registry, build_runner_from_cfg
+ >>> RUNNERS = Registry('runners', build_func=build_runner_from_cfg)
+ >>> @RUNNERS.register_module()
+ >>> class CustomRunner(Runner):
+ >>> def setup_env(env_cfg):
+ >>> pass
+ >>> cfg = dict(runner_type='CustomRunner', ...)
+ >>> custom_runner = RUNNERS.build(cfg)
+
+ Args:
+ cfg (dict or ConfigDict or Config): Config dict. If "runner_type" key
+ exists, it will be used to build a custom runner. Otherwise, it
+ will be used to build a default runner.
+ registry (:obj:`Registry`): The registry to search the type from.
+
+ Returns:
+ object: The constructed runner object.
+ """
+ from ..config import Config, ConfigDict
+ from ..logging import print_log
+
+ assert isinstance(
+ cfg,
+ (dict, ConfigDict, Config
+ )), f'cfg should be a dict, ConfigDict or Config, but got {type(cfg)}'
+ assert isinstance(
+ registry, Registry), ('registry should be a mmengine.Registry object',
+ f'but got {type(registry)}')
+
+ args = cfg.copy()
+ # Runner should be built under target scope, if `_scope_` is defined
+ # in cfg, current default scope should switch to specified scope
+ # temporarily.
+ scope = args.pop('_scope_', None)
+ with registry.switch_scope_and_registry(scope) as registry:
+ obj_type = args.get('runner_type', 'mmengine.Runner')
+ if isinstance(obj_type, str):
+ runner_cls = registry.get(obj_type)
+ if runner_cls is None:
+ raise KeyError(
+ f'{obj_type} is not in the {registry.name} registry. '
+ f'Please check whether the value of `{obj_type}` is '
+ 'correct or it was registered as expected. More details '
+ 'can be found at https://mmengine.readthedocs.io/en/latest/tutorials/config.html#import-custom-python-modules' # noqa: E501
+ )
+ elif inspect.isclass(obj_type):
+ runner_cls = obj_type
+ else:
+ raise TypeError(
+ f'type must be a str or valid type, but got {type(obj_type)}')
+
+ try:
+ runner = runner_cls.from_cfg(args) # type: ignore
+ print_log(
+ f'An `{runner_cls.__name__}` instance is built from ' # type: ignore # noqa: E501
+ 'registry, its implementation can be found in'
+ f'{runner_cls.__module__}', # type: ignore
+ logger='current',
+ level=logging.DEBUG)
+ return runner
+
+ except Exception as e:
+ # Normal TypeError does not print class name.
+ cls_location = '/'.join(
+ runner_cls.__module__.split('.')) # type: ignore
+ raise type(e)(
+ f'class `{runner_cls.__name__}` in ' # type: ignore
+ f'{cls_location}.py: {e}')
+
+
+def build_model_from_cfg(
+ cfg: Union[dict, ConfigDict, Config],
+ registry: Registry,
+ default_args: Optional[Union[dict, 'ConfigDict', 'Config']] = None
+) -> 'nn.Module':
+ """Build a PyTorch model from config dict(s). Different from
+ ``build_from_cfg``, if cfg is a list, a ``nn.Sequential`` will be built.
+
+ Args:
+ cfg (dict, list[dict]): The config of modules, which is either a config
+ dict or a list of config dicts. If cfg is a list, the built
+ modules will be wrapped with ``nn.Sequential``.
+ registry (:obj:`Registry`): A registry the module belongs to.
+ default_args (dict, optional): Default arguments to build the module.
+ Defaults to None.
+
+ Returns:
+ nn.Module: A built nn.Module.
+ """
+ from ..model import Sequential
+ if isinstance(cfg, list):
+ modules = [
+ build_from_cfg(_cfg, registry, default_args) for _cfg in cfg
+ ]
+ return Sequential(*modules)
+ else:
+ return build_from_cfg(cfg, registry, default_args)
+
+
+def build_scheduler_from_cfg(
+ cfg: Union[dict, ConfigDict, Config],
+ registry: Registry,
+ default_args: Optional[Union[dict, ConfigDict, Config]] = None
+) -> '_ParamScheduler':
+ """Builds a ``ParamScheduler`` instance from config.
+
+ ``ParamScheduler`` supports building instance by its constructor or
+ method ``build_iter_from_epoch``. Therefore, its registry needs a build
+ function to handle both cases.
+
+ Args:
+ cfg (dict or ConfigDict or Config): Config dictionary. If it contains
+ the key ``convert_to_iter_based``, instance will be built by method
+ ``convert_to_iter_based``, otherwise instance will be built by its
+ constructor.
+ registry (:obj:`Registry`): The ``PARAM_SCHEDULERS`` registry.
+ default_args (dict or ConfigDict or Config, optional): Default
+ initialization arguments. It must contain key ``optimizer``. If
+ ``convert_to_iter_based`` is defined in ``cfg``, it must
+ additionally contain key ``epoch_length``. Defaults to None.
+
+ Returns:
+ object: The constructed ``ParamScheduler``.
+ """
+ assert isinstance(
+ cfg,
+ (dict, ConfigDict, Config
+ )), f'cfg should be a dict, ConfigDict or Config, but got {type(cfg)}'
+ assert isinstance(
+ registry, Registry), ('registry should be a mmengine.Registry object',
+ f'but got {type(registry)}')
+
+ args = cfg.copy()
+ if default_args is not None:
+ for name, value in default_args.items():
+ args.setdefault(name, value)
+ scope = args.pop('_scope_', None)
+ with registry.switch_scope_and_registry(scope) as registry:
+ convert_to_iter = args.pop('convert_to_iter_based', False)
+ if convert_to_iter:
+ scheduler_type = args.pop('type')
+ assert 'epoch_length' in args and args.get('by_epoch', True), (
+ 'Only epoch-based parameter scheduler can be converted to '
+ 'iter-based, and `epoch_length` should be set')
+ if isinstance(scheduler_type, str):
+ scheduler_cls = registry.get(scheduler_type)
+ if scheduler_cls is None:
+ raise KeyError(
+ f'{scheduler_type} is not in the {registry.name} '
+ 'registry. Please check whether the value of '
+ f'`{scheduler_type}` is correct or it was registered '
+ 'as expected. More details can be found at https://mmengine.readthedocs.io/en/latest/tutorials/config.html#import-custom-python-modules' # noqa: E501
+ )
+ elif inspect.isclass(scheduler_type):
+ scheduler_cls = scheduler_type
+ else:
+ raise TypeError('type must be a str or valid type, but got '
+ f'{type(scheduler_type)}')
+ return scheduler_cls.build_iter_from_epoch( # type: ignore
+ **args)
+ else:
+ args.pop('epoch_length', None)
+ return build_from_cfg(args, registry)
diff --git a/testbed/open-mmlab__mmengine/mmengine/registry/default_scope.py b/testbed/open-mmlab__mmengine/mmengine/registry/default_scope.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9f1afcaba6dadfd6542fd58fd90dc7b6948c9e7
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/registry/default_scope.py
@@ -0,0 +1,95 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import time
+from contextlib import contextmanager
+from typing import Generator, Optional
+
+from mmengine.utils.manager import ManagerMixin, _accquire_lock, _release_lock
+
+
+class DefaultScope(ManagerMixin):
+ """Scope of current task used to reset the current registry, which can be
+ accessed globally.
+
+ Consider the case of resetting the current ``Registry`` by
+ ``default_scope`` in the internal module which cannot access runner
+ directly, it is difficult to get the ``default_scope`` defined in
+ ``Runner``. However, if ``Runner`` created ``DefaultScope`` instance
+ by given ``default_scope``, the internal module can get
+ ``default_scope`` by ``DefaultScope.get_current_instance`` everywhere.
+
+ Args:
+ name (str): Name of default scope for global access.
+ scope_name (str): Scope of current task.
+
+ Examples:
+ >>> from mmengine.model import MODELS
+ >>> # Define default scope in runner.
+ >>> DefaultScope.get_instance('task', scope_name='mmdet')
+ >>> # Get default scope globally.
+ >>> scope_name = DefaultScope.get_instance('task').scope_name
+ """
+
+ def __init__(self, name: str, scope_name: str):
+ super().__init__(name)
+ assert isinstance(
+ scope_name,
+ str), (f'scope_name should be a string, but got {scope_name}')
+ self._scope_name = scope_name
+
+ @property
+ def scope_name(self) -> str:
+ """
+ Returns:
+ str: Get current scope.
+ """
+ return self._scope_name
+
+ @classmethod
+ def get_current_instance(cls) -> Optional['DefaultScope']:
+ """Get latest created default scope.
+
+ Since default_scope is an optional argument for ``Registry.build``.
+ ``get_current_instance`` should return ``None`` if there is no
+ ``DefaultScope`` created.
+
+ Examples:
+ >>> default_scope = DefaultScope.get_current_instance()
+ >>> # There is no `DefaultScope` created yet,
+ >>> # `get_current_instance` return `None`.
+ >>> default_scope = DefaultScope.get_instance(
+ >>> 'instance_name', scope_name='mmengine')
+ >>> default_scope.scope_name
+ mmengine
+ >>> default_scope = DefaultScope.get_current_instance()
+ >>> default_scope.scope_name
+ mmengine
+
+ Returns:
+ Optional[DefaultScope]: Return None If there has not been
+ ``DefaultScope`` instance created yet, otherwise return the
+ latest created DefaultScope instance.
+ """
+ _accquire_lock()
+ if cls._instance_dict:
+ instance = super().get_current_instance()
+ else:
+ instance = None
+ _release_lock()
+ return instance
+
+ @classmethod
+ @contextmanager
+ def overwrite_default_scope(cls, scope_name: Optional[str]) -> Generator:
+ """overwrite the current default scope with `scope_name`"""
+ if scope_name is None:
+ yield
+ else:
+ tmp = copy.deepcopy(cls._instance_dict)
+ # To avoid create an instance with the same name.
+ time.sleep(1e-6)
+ cls.get_instance(f'overwrite-{time.time()}', scope_name=scope_name)
+ try:
+ yield
+ finally:
+ cls._instance_dict = tmp
diff --git a/testbed/open-mmlab__mmengine/mmengine/registry/registry.py b/testbed/open-mmlab__mmengine/mmengine/registry/registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..66bb4f75f71bbbe771d5cf511a437729a05bf2d7
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/registry/registry.py
@@ -0,0 +1,553 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import inspect
+import logging
+import sys
+from collections.abc import Callable
+from contextlib import contextmanager
+from importlib import import_module
+from typing import Any, Dict, Generator, List, Optional, Tuple, Type, Union
+
+from mmengine.config.utils import PKG2PROJECT
+from mmengine.utils import is_seq_of
+from .default_scope import DefaultScope
+
+
+class Registry:
+ """A registry to map strings to classes or functions.
+
+ Registered object could be built from registry. Meanwhile, registered
+ functions could be called from registry.
+
+ Args:
+ name (str): Registry name.
+ build_func (callable, optional): A function to construct instance
+ from Registry. :func:`build_from_cfg` is used if neither ``parent``
+ or ``build_func`` is specified. If ``parent`` is specified and
+ ``build_func`` is not given, ``build_func`` will be inherited
+ from ``parent``. Defaults to None.
+ parent (:obj:`Registry`, optional): Parent registry. The class
+ registered in children registry could be built from parent.
+ Defaults to None.
+ scope (str, optional): The scope of registry. It is the key to search
+ for children registry. If not specified, scope will be the name of
+ the package where class is defined, e.g. mmdet, mmcls, mmseg.
+ Defaults to None.
+
+ Examples:
+ >>> # define a registry
+ >>> MODELS = Registry('models')
+ >>> # registry the `ResNet` to `MODELS`
+ >>> @MODELS.register_module()
+ >>> class ResNet:
+ >>> pass
+ >>> # build model from `MODELS`
+ >>> resnet = MODELS.build(dict(type='ResNet'))
+ >>> @MODELS.register_module()
+ >>> def resnet50():
+ >>> pass
+ >>> resnet = MODELS.build(dict(type='resnet50'))
+
+ >>> # hierarchical registry
+ >>> DETECTORS = Registry('detectors', parent=MODELS, scope='det')
+ >>> @DETECTORS.register_module()
+ >>> class FasterRCNN:
+ >>> pass
+ >>> fasterrcnn = DETECTORS.build(dict(type='FasterRCNN'))
+
+ More advanced usages can be found at
+ https://mmengine.readthedocs.io/en/latest/tutorials/registry.html.
+ """
+
+ def __init__(self,
+ name: str,
+ build_func: Optional[Callable] = None,
+ parent: Optional['Registry'] = None,
+ scope: Optional[str] = None):
+ from .build_functions import build_from_cfg
+ self._name = name
+ self._module_dict: Dict[str, Type] = dict()
+ self._children: Dict[str, 'Registry'] = dict()
+
+ if scope is not None:
+ assert isinstance(scope, str)
+ self._scope = scope
+ else:
+ self._scope = self.infer_scope()
+
+ # See https://mypy.readthedocs.io/en/stable/common_issues.html#
+ # variables-vs-type-aliases for the use
+ self.parent: Optional['Registry']
+ if parent is not None:
+ assert isinstance(parent, Registry)
+ parent._add_child(self)
+ self.parent = parent
+ else:
+ self.parent = None
+
+ # self.build_func will be set with the following priority:
+ # 1. build_func
+ # 2. parent.build_func
+ # 3. build_from_cfg
+ self.build_func: Callable
+ if build_func is None:
+ if self.parent is not None:
+ self.build_func = self.parent.build_func
+ else:
+ self.build_func = build_from_cfg
+ else:
+ self.build_func = build_func
+
+ def __len__(self):
+ return len(self._module_dict)
+
+ def __contains__(self, key):
+ return self.get(key) is not None
+
+ def __repr__(self):
+ format_str = self.__class__.__name__ + \
+ f'(name={self._name}, ' \
+ f'items={self._module_dict})'
+ return format_str
+
+ @staticmethod
+ def infer_scope() -> str:
+ """Infer the scope of registry.
+
+ The name of the package where registry is defined will be returned.
+
+ Returns:
+ str: The inferred scope name.
+
+ Examples:
+ >>> # in mmdet/models/backbone/resnet.py
+ >>> MODELS = Registry('models')
+ >>> @MODELS.register_module()
+ >>> class ResNet:
+ >>> pass
+ >>> # The scope of ``ResNet`` will be ``mmdet``.
+ """
+ # `sys._getframe` returns the frame object that many calls below the
+ # top of the stack. The call stack for `infer_scope` can be listed as
+ # follow:
+ # frame-0: `infer_scope` itself
+ # frame-1: `__init__` of `Registry` which calls the `infer_scope`
+ # frame-2: Where the `Registry(...)` is called
+ filename = inspect.getmodule(sys._getframe(2)).__name__ # type: ignore
+ split_filename = filename.split('.')
+ return split_filename[0]
+
+ @staticmethod
+ def split_scope_key(key: str) -> Tuple[Optional[str], str]:
+ """Split scope and key.
+
+ The first scope will be split from key.
+
+ Return:
+ tuple[str | None, str]: The former element is the first scope of
+ the key, which can be ``None``. The latter is the remaining key.
+
+ Examples:
+ >>> Registry.split_scope_key('mmdet.ResNet')
+ 'mmdet', 'ResNet'
+ >>> Registry.split_scope_key('ResNet')
+ None, 'ResNet'
+ """
+ split_index = key.find('.')
+ if split_index != -1:
+ return key[:split_index], key[split_index + 1:]
+ else:
+ return None, key
+
+ @property
+ def name(self):
+ return self._name
+
+ @property
+ def scope(self):
+ return self._scope
+
+ @property
+ def module_dict(self):
+ return self._module_dict
+
+ @property
+ def children(self):
+ return self._children
+
+ @property
+ def root(self):
+ return self._get_root_registry()
+
+ @contextmanager
+ def switch_scope_and_registry(self, scope: str) -> Generator:
+ """Temporarily switch default scope to the target scope, and get the
+ corresponding registry.
+
+ If the registry of the corresponding scope exists, yield the
+ registry, otherwise yield the current itself.
+
+ Args:
+ scope (str): The target scope.
+
+ Examples:
+ >>> from mmengine.registry import Registry, DefaultScope, MODELS
+ >>> import time
+ >>> # External Registry
+ >>> MMDET_MODELS = Registry('mmdet_model', scope='mmdet',
+ >>> parent=MODELS)
+ >>> MMCLS_MODELS = Registry('mmcls_model', scope='mmcls',
+ >>> parent=MODELS)
+ >>> # Local Registry
+ >>> CUSTOM_MODELS = Registry('custom_model', scope='custom',
+ >>> parent=MODELS)
+ >>>
+ >>> # Initiate DefaultScope
+ >>> DefaultScope.get_instance(f'scope_{time.time()}',
+ >>> scope_name='custom')
+ >>> # Check default scope
+ >>> DefaultScope.get_current_instance().scope_name
+ custom
+ >>> # Switch to mmcls scope and get `MMCLS_MODELS` registry.
+ >>> with CUSTOM_MODELS.switch_scope_and_registry(scope='mmcls') as registry:
+ >>> DefaultScope.get_current_instance().scope_name
+ mmcls
+ >>> registry.scope
+ mmcls
+ >>> # Nested switch scope
+ >>> with CUSTOM_MODELS.switch_scope_and_registry(scope='mmdet') as mmdet_registry:
+ >>> DefaultScope.get_current_instance().scope_name
+ mmdet
+ >>> mmdet_registry.scope
+ mmdet
+ >>> with CUSTOM_MODELS.switch_scope_and_registry(scope='mmcls') as mmcls_registry:
+ >>> DefaultScope.get_current_instance().scope_name
+ mmcls
+ >>> mmcls_registry.scope
+ mmcls
+ >>>
+ >>> # Check switch back to original scope.
+ >>> DefaultScope.get_current_instance().scope_name
+ custom
+ """ # noqa: E501
+ from ..logging import print_log
+
+ # Switch to the given scope temporarily. If the corresponding registry
+ # can be found in root registry, return the registry under the scope,
+ # otherwise return the registry itself.
+ with DefaultScope.overwrite_default_scope(scope):
+ # Get the global default scope
+ default_scope = DefaultScope.get_current_instance()
+ # Get registry by scope
+ if default_scope is not None:
+ scope_name = default_scope.scope_name
+ if scope_name in PKG2PROJECT:
+ try:
+ module = import_module(f'{scope_name}.utils')
+ module.register_all_modules(False) # type: ignore
+ except (ImportError, AttributeError, ModuleNotFoundError):
+ if scope in PKG2PROJECT:
+ print_log(
+ f'{scope} is not installed and its '
+ 'modules will not be registered. If you '
+ 'want to use modules defined in '
+ f'{scope}, Please install {scope} by '
+ f'`pip install {PKG2PROJECT[scope]}.',
+ logger='current',
+ level=logging.WARNING)
+ else:
+ print_log(
+ f'Failed to import {scope} and register '
+ 'its modules, please make sure you '
+ 'have registered the module manually.',
+ logger='current',
+ level=logging.WARNING)
+ root = self._get_root_registry()
+ registry = root._search_child(scope_name)
+ if registry is None:
+ # if `default_scope` can not be found, fallback to argument
+ # `registry`
+ print_log(
+ f'Failed to search registry with scope "{scope_name}" '
+ f'in the "{root.name}" registry tree. '
+ f'As a workaround, the current "{self.name}" registry '
+ f'in "{self.scope}" is used to build instance. This '
+ 'may cause unexpected failure when running the built '
+ f'modules. Please check whether "{scope_name}" is a '
+ 'correct scope, or whether the registry is '
+ 'initialized.',
+ logger='current',
+ level=logging.WARNING)
+ registry = self
+ # If there is no built default scope, just return current registry.
+ else:
+ registry = self
+ yield registry
+
+ def _get_root_registry(self) -> 'Registry':
+ """Return the root registry."""
+ root = self
+ while root.parent is not None:
+ root = root.parent
+ return root
+
+ def get(self, key: str) -> Optional[Type]:
+ """Get the registry record.
+
+ The method will first parse :attr:`key` and check whether it contains
+ a scope name. The logic to search for :attr:`key`:
+
+ - ``key`` does not contain a scope name, i.e., it is purely a module
+ name like "ResNet": :meth:`get` will search for ``ResNet`` from the
+ current registry to its parent or ancestors until finding it.
+
+ - ``key`` contains a scope name and it is equal to the scope of the
+ current registry (e.g., "mmcls"), e.g., "mmcls.ResNet": :meth:`get`
+ will only search for ``ResNet`` in the current registry.
+
+ - ``key`` contains a scope name and it is not equal to the scope of
+ the current registry (e.g., "mmdet"), e.g., "mmcls.FCNet": If the
+ scope exists in its children, :meth:`get` will get "FCNet" from
+ them. If not, :meth:`get` will first get the root registry and root
+ registry call its own :meth:`get` method.
+
+ Args:
+ key (str): Name of the registered item, e.g., the class name in
+ string format.
+
+ Returns:
+ Type or None: Return the corresponding class if ``key`` exists,
+ otherwise return None.
+
+ Examples:
+ >>> # define a registry
+ >>> MODELS = Registry('models')
+ >>> # register `ResNet` to `MODELS`
+ >>> @MODELS.register_module()
+ >>> class ResNet:
+ >>> pass
+ >>> resnet_cls = MODELS.get('ResNet')
+
+ >>> # hierarchical registry
+ >>> DETECTORS = Registry('detector', parent=MODELS, scope='det')
+ >>> # `ResNet` does not exist in `DETECTORS` but `get` method
+ >>> # will try to search from its parenet or ancestors
+ >>> resnet_cls = DETECTORS.get('ResNet')
+ >>> CLASSIFIER = Registry('classifier', parent=MODELS, scope='cls')
+ >>> @CLASSIFIER.register_module()
+ >>> class MobileNet:
+ >>> pass
+ >>> # `get` from its sibling registries
+ >>> mobilenet_cls = DETECTORS.get('cls.MobileNet')
+ """
+ # Avoid circular import
+ from ..logging import print_log
+
+ scope, real_key = self.split_scope_key(key)
+ obj_cls = None
+ registry_name = self.name
+ scope_name = self.scope
+ if scope is None or scope == self._scope:
+ # get from self
+ if real_key in self._module_dict:
+ obj_cls = self._module_dict[real_key]
+
+ elif scope is None:
+ # try to get the target from its parent or ancestors
+ parent = self.parent
+ while parent is not None:
+ if real_key in parent._module_dict:
+ obj_cls = parent._module_dict[real_key]
+ registry_name = parent.name
+ scope_name = parent.scope
+ break
+ parent = parent.parent
+ else:
+ try:
+ module = import_module(f'{scope}.utils')
+ module.register_all_modules(False) # type: ignore
+ except (ImportError, AttributeError, ModuleNotFoundError):
+ if scope in PKG2PROJECT:
+ print_log(
+ f'{scope} is not installed and its modules '
+ 'will not be registered. If you want to use '
+ f'modules defined in {scope}, Please install '
+ f'{scope} by `pip install {PKG2PROJECT[scope]} ',
+ logger='current',
+ level=logging.WARNING)
+ else:
+ print_log(
+ f'Failed to import "{scope}", and register its '
+ f'modules. Please register {real_key} manually.',
+ logger='current',
+ level=logging.WARNING)
+ # get from self._children
+ if scope in self._children:
+ obj_cls = self._children[scope].get(real_key)
+ registry_name = self._children[scope].name
+ scope_name = scope
+ else:
+ root = self._get_root_registry()
+
+ if scope != root._scope and scope not in root._children:
+ # If not skip directly, `root.get(key)` will recursively
+ # call itself until RecursionError is thrown.
+ pass
+ else:
+ obj_cls = root.get(key)
+
+ if obj_cls is not None:
+ print_log(
+ f'Get class `{obj_cls.__name__}` from "{registry_name}"'
+ f' registry in "{scope_name}"',
+ logger='current',
+ level=logging.DEBUG)
+ return obj_cls
+
+ def _search_child(self, scope: str) -> Optional['Registry']:
+ """Depth-first search for the corresponding registry in its children.
+
+ Note that the method only search for the corresponding registry from
+ the current registry. Therefore, if we want to search from the root
+ registry, :meth:`_get_root_registry` should be called to get the
+ root registry first.
+
+ Args:
+ scope (str): The scope name used for searching for its
+ corresponding registry.
+
+ Returns:
+ Registry or None: Return the corresponding registry if ``scope``
+ exists, otherwise return None.
+ """
+ if self._scope == scope:
+ return self
+
+ for child in self._children.values():
+ registry = child._search_child(scope)
+ if registry is not None:
+ return registry
+
+ return None
+
+ def build(self, cfg: dict, *args, **kwargs) -> Any:
+ """Build an instance.
+
+ Build an instance by calling :attr:`build_func`.
+
+ Args:
+ cfg (dict): Config dict needs to be built.
+
+ Returns:
+ Any: The constructed object.
+
+ Examples:
+ >>> from mmengine import Registry
+ >>> MODELS = Registry('models')
+ >>> @MODELS.register_module()
+ >>> class ResNet:
+ >>> def __init__(self, depth, stages=4):
+ >>> self.depth = depth
+ >>> self.stages = stages
+ >>> cfg = dict(type='ResNet', depth=50)
+ >>> model = MODELS.build(cfg)
+ """
+ return self.build_func(cfg, *args, **kwargs, registry=self)
+
+ def _add_child(self, registry: 'Registry') -> None:
+ """Add a child for a registry.
+
+ Args:
+ registry (:obj:`Registry`): The ``registry`` will be added as a
+ child of the ``self``.
+ """
+
+ assert isinstance(registry, Registry)
+ assert registry.scope is not None
+ assert registry.scope not in self.children, \
+ f'scope {registry.scope} exists in {self.name} registry'
+ self.children[registry.scope] = registry
+
+ def _register_module(self,
+ module: Type,
+ module_name: Optional[Union[str, List[str]]] = None,
+ force: bool = False) -> None:
+ """Register a module.
+
+ Args:
+ module (type): Module class or function to be registered.
+ module_name (str or list of str, optional): The module name to be
+ registered. If not specified, the class name will be used.
+ Defaults to None.
+ force (bool): Whether to override an existing class with the same
+ name. Defaults to False.
+ """
+ if not inspect.isclass(module) and not inspect.isfunction(module):
+ raise TypeError('module must be a class or a function, '
+ f'but got {type(module)}')
+
+ if module_name is None:
+ module_name = module.__name__
+ if isinstance(module_name, str):
+ module_name = [module_name]
+ for name in module_name:
+ if not force and name in self._module_dict:
+ existed_module = self.module_dict[name]
+ raise KeyError(f'{name} is already registered in {self.name} '
+ f'at {existed_module.__module__}')
+ self._module_dict[name] = module
+
+ def register_module(
+ self,
+ name: Optional[Union[str, List[str]]] = None,
+ force: bool = False,
+ module: Optional[Type] = None) -> Union[type, Callable]:
+ """Register a module.
+
+ A record will be added to ``self._module_dict``, whose key is the class
+ name or the specified name, and value is the class itself.
+ It can be used as a decorator or a normal function.
+
+ Args:
+ name (str or list of str, optional): The module name to be
+ registered. If not specified, the class name will be used.
+ force (bool): Whether to override an existing class with the same
+ name. Default to False.
+ module (type, optional): Module class or function to be registered.
+ Defaults to None.
+
+ Examples:
+ >>> backbones = Registry('backbone')
+ >>> # as a decorator
+ >>> @backbones.register_module()
+ >>> class ResNet:
+ >>> pass
+ >>> backbones = Registry('backbone')
+ >>> @backbones.register_module(name='mnet')
+ >>> class MobileNet:
+ >>> pass
+
+ >>> # as a normal function
+ >>> class ResNet:
+ >>> pass
+ >>> backbones.register_module(module=ResNet)
+ """
+ if not isinstance(force, bool):
+ raise TypeError(f'force must be a boolean, but got {type(force)}')
+
+ # raise the error ahead of time
+ if not (name is None or isinstance(name, str) or is_seq_of(name, str)):
+ raise TypeError(
+ 'name must be None, an instance of str, or a sequence of str, '
+ f'but got {type(name)}')
+
+ # use it as a normal method: x.register_module(module=SomeClass)
+ if module is not None:
+ self._register_module(module=module, module_name=name, force=force)
+ return module
+
+ # use it as a decorator: @x.register_module()
+ def _register(module):
+ self._register_module(module=module, module_name=name, force=force)
+ return module
+
+ return _register
diff --git a/testbed/open-mmlab__mmengine/mmengine/registry/root.py b/testbed/open-mmlab__mmengine/mmengine/registry/root.py
new file mode 100644
index 0000000000000000000000000000000000000000..838465b4f178ce45d447c0e15ff9018b6cad98fa
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/registry/root.py
@@ -0,0 +1,58 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+"""MMEngine provides 20 root registries to support using modules across
+projects.
+
+More datails can be found at
+https://mmengine.readthedocs.io/en/latest/tutorials/registry.html.
+"""
+
+from .build_functions import (build_model_from_cfg, build_runner_from_cfg,
+ build_scheduler_from_cfg)
+from .registry import Registry
+
+# manage all kinds of runners like `EpochBasedRunner` and `IterBasedRunner`
+RUNNERS = Registry('runner', build_func=build_runner_from_cfg)
+# manage runner constructors that define how to initialize runners
+RUNNER_CONSTRUCTORS = Registry('runner constructor')
+# manage all kinds of loops like `EpochBasedTrainLoop`
+LOOPS = Registry('loop')
+# manage all kinds of hooks like `CheckpointHook`
+HOOKS = Registry('hook')
+
+# manage data-related modules
+DATASETS = Registry('dataset')
+DATA_SAMPLERS = Registry('data sampler')
+TRANSFORMS = Registry('transform')
+
+# mangage all kinds of modules inheriting `nn.Module`
+MODELS = Registry('model', build_model_from_cfg)
+# mangage all kinds of model wrappers like 'MMDistributedDataParallel'
+MODEL_WRAPPERS = Registry('model_wrapper')
+# mangage all kinds of weight initialization modules like `Uniform`
+WEIGHT_INITIALIZERS = Registry('weight initializer')
+
+# mangage all kinds of optimizers like `SGD` and `Adam`
+OPTIMIZERS = Registry('optimizer')
+# manage optimizer wrapper
+OPTIM_WRAPPERS = Registry('optim_wrapper')
+# manage constructors that customize the optimization hyperparameters.
+OPTIM_WRAPPER_CONSTRUCTORS = Registry('optimizer wrapper constructor')
+# mangage all kinds of parameter schedulers like `MultiStepLR`
+PARAM_SCHEDULERS = Registry(
+ 'parameter scheduler', build_func=build_scheduler_from_cfg)
+
+# manage all kinds of metrics
+METRICS = Registry('metric')
+# manage evaluator
+EVALUATOR = Registry('evaluator')
+
+# manage task-specific modules like anchor generators and box coders
+TASK_UTILS = Registry('task util')
+
+# manage visualizer
+VISUALIZERS = Registry('visualizer')
+# manage visualizer backend
+VISBACKENDS = Registry('vis_backend')
+
+# manage logprocessor
+LOG_PROCESSORS = Registry('log_processor')
diff --git a/testbed/open-mmlab__mmengine/mmengine/registry/utils.py b/testbed/open-mmlab__mmengine/mmengine/registry/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ce11da1557e9984c9c9aca4510156a6f2ec0835
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/registry/utils.py
@@ -0,0 +1,92 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import datetime
+import os.path as osp
+from typing import Optional
+
+from mmengine.fileio import dump
+from mmengine.logging import print_log
+from . import root
+from .registry import Registry
+
+
+def traverse_registry_tree(registry: Registry, verbose: bool = True) -> list:
+ """Traverse the whole registry tree from any given node, and collect
+ information of all registered modules in this registry tree.
+
+ Args:
+ registry (Registry): a registry node in the registry tree.
+ verbose (bool): Whether to print log. Default: True
+
+ Returns:
+ list: Statistic results of all modules in each node of the registry
+ tree.
+ """
+ root_registry = registry.root
+ modules_info = []
+
+ def _dfs_registry(_registry):
+ if isinstance(_registry, Registry):
+ num_modules = len(_registry.module_dict)
+ scope = _registry.scope
+ registry_info = dict(num_modules=num_modules, scope=scope)
+ for name, registered_class in _registry.module_dict.items():
+ folder = '/'.join(registered_class.__module__.split('.')[:-1])
+ if folder in registry_info:
+ registry_info[folder].append(name)
+ else:
+ registry_info[folder] = [name]
+ if verbose:
+ print_log(
+ f"Find {num_modules} modules in {scope}'s "
+ f"'{_registry.name}' registry ",
+ logger='current')
+ modules_info.append(registry_info)
+ else:
+ return
+ for _, child in _registry.children.items():
+ _dfs_registry(child)
+
+ _dfs_registry(root_registry)
+ return modules_info
+
+
+def count_registered_modules(save_path: Optional[str] = None,
+ verbose: bool = True) -> dict:
+ """Scan all modules in MMEngine's root and child registries and dump to
+ json.
+
+ Args:
+ save_path (str, optional): Path to save the json file.
+ verbose (bool): Whether to print log. Defaults to True.
+
+ Returns:
+ dict: Statistic results of all registered modules.
+ """
+ # import modules to trigger registering
+ import mmengine.dataset
+ import mmengine.evaluator
+ import mmengine.hooks
+ import mmengine.model
+ import mmengine.optim
+ import mmengine.runner
+ import mmengine.visualization # noqa: F401
+
+ registries_info = {}
+ # traverse all registries in MMEngine
+ for item in dir(root):
+ if not item.startswith('__'):
+ registry = getattr(root, item)
+ if isinstance(registry, Registry):
+ registries_info[item] = traverse_registry_tree(
+ registry, verbose)
+ scan_data = dict(
+ scan_date=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
+ registries=registries_info)
+ if verbose:
+ print_log(
+ f'Finish registry analysis, got: {scan_data}', logger='current')
+ if save_path is not None:
+ json_path = osp.join(save_path, 'modules_statistic_results.json')
+ dump(scan_data, json_path, indent=2)
+ print_log(f'Result has been saved to {json_path}', logger='current')
+ return scan_data
diff --git a/testbed/open-mmlab__mmengine/mmengine/runner/__init__.py b/testbed/open-mmlab__mmengine/mmengine/runner/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e4f5dfbc8cb3a0e0375d7f203734227ac2102880
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/runner/__init__.py
@@ -0,0 +1,22 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .amp import autocast
+from .base_loop import BaseLoop
+from .checkpoint import (CheckpointLoader, find_latest_checkpoint,
+ get_deprecated_model_names, get_external_models,
+ get_mmcls_models, get_state_dict,
+ get_torchvision_models, load_checkpoint,
+ load_state_dict, save_checkpoint, weights_to_cpu)
+from .log_processor import LogProcessor
+from .loops import EpochBasedTrainLoop, IterBasedTrainLoop, TestLoop, ValLoop
+from .priority import Priority, get_priority
+from .runner import Runner
+from .utils import set_random_seed
+
+__all__ = [
+ 'BaseLoop', 'load_state_dict', 'get_torchvision_models',
+ 'get_external_models', 'get_mmcls_models', 'get_deprecated_model_names',
+ 'CheckpointLoader', 'load_checkpoint', 'weights_to_cpu', 'get_state_dict',
+ 'save_checkpoint', 'EpochBasedTrainLoop', 'IterBasedTrainLoop', 'ValLoop',
+ 'TestLoop', 'Runner', 'get_priority', 'Priority', 'find_latest_checkpoint',
+ 'autocast', 'LogProcessor', 'set_random_seed'
+]
diff --git a/testbed/open-mmlab__mmengine/mmengine/runner/amp.py b/testbed/open-mmlab__mmengine/mmengine/runner/amp.py
new file mode 100644
index 0000000000000000000000000000000000000000..8acf072ac3e49f5db6e70d0fada17a9e693808bc
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/runner/amp.py
@@ -0,0 +1,145 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import logging
+from contextlib import contextmanager
+from typing import Optional
+
+import torch
+
+from mmengine.device import get_device, is_cuda_available, is_npu_available
+from mmengine.logging import print_log
+from mmengine.utils import digit_version
+from mmengine.utils.dl_utils import TORCH_VERSION
+
+
+@contextmanager
+def autocast(device_type: Optional[str] = None,
+ dtype: Optional[torch.dtype] = None,
+ enabled: bool = True,
+ cache_enabled: Optional[bool] = None):
+ """A wrapper of ``torch.autocast`` and ``toch.cuda.amp.autocast``.
+
+ Pytorch 1.5.0 provide ``torch.cuda.amp.autocast`` for running in
+ mixed precision , and update it to ``torch.autocast`` in 1.10.0.
+ Both interfaces have different arguments, and ``torch.autocast``
+ support running with cpu additionally.
+
+ This function provides a unified interface by wrapping
+ ``torch.autocast`` and ``torch.cuda.amp.autocast``, which resolves the
+ compatibility issues that ``torch.cuda.amp.autocast`` does not support
+ running mixed precision with cpu, and both contexts have different
+ arguments. We suggest users using this function in the code
+ to achieve maximized compatibility of different PyTorch versions.
+
+ Note:
+ ``autocast`` requires pytorch version >= 1.5.0. If pytorch version
+ <= 1.10.0 and cuda is not available, it will raise an error with
+ ``enabled=True``, since ``torch.cuda.amp.autocast`` only support cuda
+ mode.
+
+ Examples:
+ >>> # case1: 1.10 > Pytorch version >= 1.5.0
+ >>> with autocast():
+ >>> # run in mixed precision context
+ >>> pass
+ >>> with autocast(device_type='cpu')::
+ >>> # raise error, torch.cuda.amp.autocast only support cuda mode.
+ >>> pass
+ >>> # case2: Pytorch version >= 1.10.0
+ >>> with autocast():
+ >>> # default cuda mixed precision context
+ >>> pass
+ >>> with autocast(device_type='cpu'):
+ >>> # cpu mixed precision context
+ >>> pass
+ >>> with autocast(
+ >>> device_type='cuda', enabled=True, cache_enabled=True):
+ >>> # enable precision context with more specific arguments.
+ >>> pass
+
+ Args:
+ device_type (str, required): Whether to use 'cuda' or 'cpu' device.
+ enabled(bool): Whether autocasting should be enabled in the region.
+ Defaults to True
+ dtype (torch_dtype, optional): Whether to use ``torch.float16`` or
+ ``torch.bfloat16``.
+ cache_enabled(bool, optional): Whether the weight cache inside
+ autocast should be enabled.
+ """
+ # If `enabled` is True, enable an empty context and all calculations
+ # are performed under fp32.
+ assert digit_version(TORCH_VERSION) >= digit_version('1.5.0'), (
+ 'The minimum pytorch version requirements of mmengine is 1.5.0, but '
+ f'got {TORCH_VERSION}')
+
+ if (digit_version('1.5.0') <= digit_version(TORCH_VERSION) <
+ digit_version('1.10.0')):
+ # If pytorch version is between 1.5.0 and 1.10.0, the default value of
+ # dtype for `torch.cuda.amp.autocast` is torch.float16.
+ assert device_type == 'cuda' or device_type is None, (
+ 'Pytorch version under 1.10.0 only supports running automatic '
+ 'mixed training with cuda')
+ if dtype is not None or cache_enabled is not None:
+ print_log(
+ f'{dtype} and {device_type} will not work for '
+ '`autocast` since your Pytorch version: '
+ f'{TORCH_VERSION} <= 1.10.0',
+ logger='current',
+ level=logging.WARNING)
+
+ if is_npu_available():
+ with torch.npu.amp.autocast(enabled=enabled):
+ yield
+ elif is_cuda_available():
+ with torch.cuda.amp.autocast(enabled=enabled):
+ yield
+ else:
+ if not enabled:
+ yield
+ else:
+ raise RuntimeError(
+ 'If pytorch versions is between 1.5.0 and 1.10, '
+ '`autocast` is only available in gpu mode')
+
+ else:
+ # Modified from https://github.com/pytorch/pytorch/blob/master/torch/amp/autocast_mode.py # noqa: E501
+ # This code should update with the `torch.autocast`.
+ if cache_enabled is None:
+ cache_enabled = torch.is_autocast_cache_enabled()
+ device = get_device()
+ device_type = device if device_type is None else device_type
+
+ if device_type == 'cuda':
+ if dtype is None:
+ dtype = torch.get_autocast_gpu_dtype()
+
+ if dtype == torch.bfloat16 and not \
+ torch.cuda.is_bf16_supported():
+ raise RuntimeError(
+ 'Current CUDA Device does not support bfloat16. Please '
+ 'switch dtype to float16.')
+
+ elif device_type == 'cpu':
+ if dtype is None:
+ dtype = torch.bfloat16
+ assert dtype == torch.bfloat16, (
+ 'In CPU autocast, only support `torch.bfloat16` dtype')
+
+ elif device_type == 'mlu':
+ pass
+ else:
+ # Device like MPS does not support fp16 training or testing.
+ # If an inappropriate device is set and fp16 is enabled, an error
+ # will be thrown.
+ if enabled is False:
+ yield
+ return
+ else:
+ raise ValueError('User specified autocast device_type must be '
+ f'cuda or cpu, but got {device_type}')
+
+ with torch.autocast(
+ device_type=device_type,
+ enabled=enabled,
+ dtype=dtype,
+ cache_enabled=cache_enabled):
+ yield
diff --git a/testbed/open-mmlab__mmengine/mmengine/runner/base_loop.py b/testbed/open-mmlab__mmengine/mmengine/runner/base_loop.py
new file mode 100644
index 0000000000000000000000000000000000000000..5bae459a2071b1560ddf159a2922925f6a58bdb7
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/runner/base_loop.py
@@ -0,0 +1,37 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from abc import ABCMeta, abstractmethod
+from typing import Any, Dict, Union
+
+from torch.utils.data import DataLoader
+
+
+class BaseLoop(metaclass=ABCMeta):
+ """Base loop class.
+
+ All subclasses inherited from ``BaseLoop`` should overwrite the
+ :meth:`run` method.
+
+ Args:
+ runner (Runner): A reference of runner.
+ dataloader (Dataloader or dict): An iterator to generate one batch of
+ dataset each iteration.
+ """
+
+ def __init__(self, runner, dataloader: Union[DataLoader, Dict]) -> None:
+ self._runner = runner
+ if isinstance(dataloader, dict):
+ # Determine whether or not different ranks use different seed.
+ diff_rank_seed = runner._randomness_cfg.get(
+ 'diff_rank_seed', False)
+ self.dataloader = runner.build_dataloader(
+ dataloader, seed=runner.seed, diff_rank_seed=diff_rank_seed)
+ else:
+ self.dataloader = dataloader
+
+ @property
+ def runner(self):
+ return self._runner
+
+ @abstractmethod
+ def run(self) -> Any:
+ """Execute loop."""
diff --git a/testbed/open-mmlab__mmengine/mmengine/runner/checkpoint.py b/testbed/open-mmlab__mmengine/mmengine/runner/checkpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a786cfa21baf8672b38c7c405d8f83319e9bcaa
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/runner/checkpoint.py
@@ -0,0 +1,771 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import io
+import logging
+import os
+import os.path as osp
+import pkgutil
+import re
+import warnings
+from collections import OrderedDict
+from importlib import import_module
+from tempfile import TemporaryDirectory
+from typing import Callable, Dict, Optional
+
+import torch
+import torchvision
+
+import mmengine
+from mmengine.dist import get_dist_info
+from mmengine.fileio import FileClient, get_file_backend
+from mmengine.fileio import load as load_file
+from mmengine.logging import print_log
+from mmengine.model import BaseTTAModel, is_model_wrapper
+from mmengine.utils import deprecated_function, digit_version, mkdir_or_exist
+from mmengine.utils.dl_utils import load_url
+
+# `MMENGINE_HOME` is the highest priority directory to save checkpoints
+# downloaded from Internet. If it is not set, as a workaround, using
+# `XDG_CACHE_HOME`` or `~/.cache` instead.
+# Note that `XDG_CACHE_HOME` defines the base directory relative to which
+# user-specific non-essential data files should be stored. If `XDG_CACHE_HOME`
+# is either not set or empty, a default equal to `~/.cache` should be used.
+ENV_MMENGINE_HOME = 'MMENGINE_HOME'
+ENV_XDG_CACHE_HOME = 'XDG_CACHE_HOME'
+DEFAULT_CACHE_DIR = '~/.cache'
+
+
+def _get_mmengine_home():
+ mmengine_home = os.path.expanduser(
+ os.getenv(
+ ENV_MMENGINE_HOME,
+ os.path.join(
+ os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), 'mmengine')))
+
+ mkdir_or_exist(mmengine_home)
+ return mmengine_home
+
+
+def load_state_dict(module, state_dict, strict=False, logger=None):
+ """Load state_dict to a module.
+
+ This method is modified from :meth:`torch.nn.Module.load_state_dict`.
+ Default value for ``strict`` is set to ``False`` and the message for
+ param mismatch will be shown even if strict is False.
+
+ Args:
+ module (Module): Module that receives the state_dict.
+ state_dict (OrderedDict): Weights.
+ strict (bool): whether to strictly enforce that the keys
+ in :attr:`state_dict` match the keys returned by this module's
+ :meth:`~torch.nn.Module.state_dict` function. Default: ``False``.
+ logger (:obj:`logging.Logger`, optional): Logger to log the error
+ message. If not specified, print function will be used.
+ """
+ unexpected_keys = []
+ all_missing_keys = []
+ err_msg = []
+
+ metadata = getattr(state_dict, '_metadata', None)
+ state_dict = state_dict.copy()
+ if metadata is not None:
+ state_dict._metadata = metadata
+
+ # use _load_from_state_dict to enable checkpoint version control
+ def load(module, prefix=''):
+ # recursively check parallel module in case that the model has a
+ # complicated structure, e.g., nn.Module(nn.Module(DDP))
+ if is_model_wrapper(module) or isinstance(module, BaseTTAModel):
+ module = module.module
+ local_metadata = {} if metadata is None else metadata.get(
+ prefix[:-1], {})
+ module._load_from_state_dict(state_dict, prefix, local_metadata, True,
+ all_missing_keys, unexpected_keys,
+ err_msg)
+ for name, child in module._modules.items():
+ if child is not None:
+ load(child, prefix + name + '.')
+
+ load(module)
+ load = None # break load->load reference cycle
+
+ # ignore "num_batches_tracked" of BN layers
+ missing_keys = [
+ key for key in all_missing_keys if 'num_batches_tracked' not in key
+ ]
+
+ if unexpected_keys:
+ err_msg.append('unexpected key in source '
+ f'state_dict: {", ".join(unexpected_keys)}\n')
+ if missing_keys:
+ err_msg.append(
+ f'missing keys in source state_dict: {", ".join(missing_keys)}\n')
+
+ rank, _ = get_dist_info()
+ if len(err_msg) > 0 and rank == 0:
+ err_msg.insert(
+ 0, 'The model and loaded state dict do not match exactly\n')
+ err_msg = '\n'.join(err_msg)
+ if strict:
+ raise RuntimeError(err_msg)
+ else:
+ print_log(err_msg, logger=logger, level=logging.WARNING)
+
+
+def get_torchvision_models():
+ if digit_version(torchvision.__version__) < digit_version('0.13.0a0'):
+ model_urls = dict()
+ # When the version of torchvision is lower than 0.13, the model url is
+ # not declared in `torchvision.model.__init__.py`, so we need to
+ # iterate through `torchvision.models.__path__` to get the url for each
+ # model.
+ for _, name, ispkg in pkgutil.walk_packages(
+ torchvision.models.__path__):
+ if ispkg:
+ continue
+ _zoo = import_module(f'torchvision.models.{name}')
+ if hasattr(_zoo, 'model_urls'):
+ _urls = getattr(_zoo, 'model_urls')
+ model_urls.update(_urls)
+ else:
+ # Since torchvision bumps to v0.13, the weight loading logic,
+ # model keys and model urls have been changed. Here the URLs of old
+ # version is loaded to avoid breaking back compatibility. If the
+ # torchvision version>=0.13.0, new URLs will be added. Users can get
+ # the resnet50 checkpoint by setting 'resnet50.imagent1k_v1',
+ # 'resnet50' or 'ResNet50_Weights.IMAGENET1K_V1' in the config.
+ json_path = osp.join(mmengine.__path__[0], 'hub/torchvision_0.12.json')
+ model_urls = mmengine.load(json_path)
+ if digit_version(torchvision.__version__) < digit_version('0.14.0a0'):
+ weights_list = [
+ cls for cls_name, cls in torchvision.models.__dict__.items()
+ if cls_name.endswith('_Weights')
+ ]
+ else:
+ weights_list = [
+ torchvision.models.get_model_weights(model)
+ for model in torchvision.models.list_models(torchvision.models)
+ ]
+
+ for cls in weights_list:
+ # The name of torchvision model weights classes ends with
+ # `_Weights` such as `ResNet18_Weights`. However, some model weight
+ # classes, such as `MNASNet0_75_Weights` does not have any urls in
+ # torchvision 0.13.0 and cannot be iterated. Here we simply check
+ # `DEFAULT` attribute to ensure the class is not empty.
+ if not hasattr(cls, 'DEFAULT'):
+ continue
+ # Since `cls.DEFAULT` can not be accessed by iterating cls, we set
+ # default urls explicitly.
+ cls_name = cls.__name__
+ cls_key = cls_name.replace('_Weights', '').lower()
+ model_urls[f'{cls_key}.default'] = cls.DEFAULT.url
+ for weight_enum in cls:
+ cls_key = cls_name.replace('_Weights', '').lower()
+ cls_key = f'{cls_key}.{weight_enum.name.lower()}'
+ model_urls[cls_key] = weight_enum.url
+
+ return model_urls
+
+
+def get_external_models():
+ mmengine_home = _get_mmengine_home()
+ default_json_path = osp.join(mmengine.__path__[0], 'hub/openmmlab.json')
+ default_urls = load_file(default_json_path)
+ assert isinstance(default_urls, dict)
+ external_json_path = osp.join(mmengine_home, 'open_mmlab.json')
+ if osp.exists(external_json_path):
+ external_urls = load_file(external_json_path)
+ assert isinstance(external_urls, dict)
+ default_urls.update(external_urls)
+
+ return default_urls
+
+
+def get_mmcls_models():
+ mmcls_json_path = osp.join(mmengine.__path__[0], 'hub/mmcls.json')
+ mmcls_urls = load_file(mmcls_json_path)
+
+ return mmcls_urls
+
+
+def get_deprecated_model_names():
+ deprecate_json_path = osp.join(mmengine.__path__[0], 'hub/deprecated.json')
+ deprecate_urls = load_file(deprecate_json_path)
+ assert isinstance(deprecate_urls, dict)
+
+ return deprecate_urls
+
+
+def _process_mmcls_checkpoint(checkpoint):
+ if 'state_dict' in checkpoint:
+ state_dict = checkpoint['state_dict']
+ else:
+ # Some checkpoints converted from 3rd-party repo don't
+ # have the "state_dict" key.
+ state_dict = checkpoint
+ new_state_dict = OrderedDict()
+ for k, v in state_dict.items():
+ if k.startswith('backbone.'):
+ new_state_dict[k[9:]] = v
+ new_checkpoint = dict(state_dict=new_state_dict)
+
+ return new_checkpoint
+
+
+class CheckpointLoader:
+ """A general checkpoint loader to manage all schemes."""
+
+ _schemes: Dict[str, Callable] = {}
+
+ @classmethod
+ def _register_scheme(cls, prefixes, loader, force=False):
+ if isinstance(prefixes, str):
+ prefixes = [prefixes]
+ else:
+ assert isinstance(prefixes, (list, tuple))
+ for prefix in prefixes:
+ if (prefix not in cls._schemes) or force:
+ cls._schemes[prefix] = loader
+ else:
+ raise KeyError(
+ f'{prefix} is already registered as a loader backend, '
+ 'add "force=True" if you want to override it')
+ # sort, longer prefixes take priority
+ cls._schemes = OrderedDict(
+ sorted(cls._schemes.items(), key=lambda t: t[0], reverse=True))
+
+ @classmethod
+ def register_scheme(cls, prefixes, loader=None, force=False):
+ """Register a loader to CheckpointLoader.
+
+ This method can be used as a normal class method or a decorator.
+
+ Args:
+ prefixes (str or list[str] or tuple[str]):
+ The prefix of the registered loader.
+ loader (function, optional): The loader function to be registered.
+ When this method is used as a decorator, loader is None.
+ Defaults to None.
+ force (bool, optional): Whether to override the loader
+ if the prefix has already been registered. Defaults to False.
+ """
+
+ if loader is not None:
+ cls._register_scheme(prefixes, loader, force=force)
+ return
+
+ def _register(loader_cls):
+ cls._register_scheme(prefixes, loader_cls, force=force)
+ return loader_cls
+
+ return _register
+
+ @classmethod
+ def _get_checkpoint_loader(cls, path):
+ """Finds a loader that supports the given path. Falls back to the local
+ loader if no other loader is found.
+
+ Args:
+ path (str): checkpoint path
+
+ Returns:
+ callable: checkpoint loader
+ """
+ for p in cls._schemes:
+ # use regular match to handle some cases that where the prefix of
+ # loader has a prefix. For example, both 's3://path' and
+ # 'open-mmlab:s3://path' should return `load_from_ceph`
+ if re.match(p, path) is not None:
+ return cls._schemes[p]
+
+ @classmethod
+ def load_checkpoint(cls, filename, map_location=None, logger='current'):
+ """load checkpoint through URL scheme path.
+
+ Args:
+ filename (str): checkpoint file name with given prefix
+ map_location (str, optional): Same as :func:`torch.load`.
+ Default: None
+ logger (str): The logger for message. Defaults to 'current'.
+
+ Returns:
+ dict or OrderedDict: The loaded checkpoint.
+ """
+
+ checkpoint_loader = cls._get_checkpoint_loader(filename)
+ class_name = checkpoint_loader.__name__
+ print_log(
+ f'Loads checkpoint by {class_name[10:]} backend from path: '
+ f'{filename}',
+ logger=logger)
+ return checkpoint_loader(filename, map_location)
+
+
+@CheckpointLoader.register_scheme(prefixes='')
+def load_from_local(filename, map_location):
+ """load checkpoint by local file path.
+
+ Args:
+ filename (str): local checkpoint file path
+ map_location (str, optional): Same as :func:`torch.load`.
+
+ Returns:
+ dict or OrderedDict: The loaded checkpoint.
+ """
+ filename = osp.expanduser(filename)
+ if not osp.isfile(filename):
+ raise FileNotFoundError(f'{filename} can not be found.')
+ checkpoint = torch.load(filename, map_location=map_location)
+ return checkpoint
+
+
+@CheckpointLoader.register_scheme(prefixes=('http://', 'https://'))
+def load_from_http(filename, map_location=None, model_dir=None):
+ """load checkpoint through HTTP or HTTPS scheme path. In distributed
+ setting, this function only download checkpoint at local rank 0.
+
+ Args:
+ filename (str): checkpoint file path with modelzoo or
+ torchvision prefix
+ map_location (str, optional): Same as :func:`torch.load`.
+ model_dir (string, optional): directory in which to save the object,
+ Default: None
+
+ Returns:
+ dict or OrderedDict: The loaded checkpoint.
+ """
+ rank, world_size = get_dist_info()
+ if rank == 0:
+ checkpoint = load_url(
+ filename, model_dir=model_dir, map_location=map_location)
+ if world_size > 1:
+ torch.distributed.barrier()
+ if rank > 0:
+ checkpoint = load_url(
+ filename, model_dir=model_dir, map_location=map_location)
+ return checkpoint
+
+
+@CheckpointLoader.register_scheme(prefixes='pavi://')
+def load_from_pavi(filename, map_location=None):
+ """load checkpoint through the file path prefixed with pavi. In distributed
+ setting, this function download ckpt at all ranks to different temporary
+ directories.
+
+ Args:
+ filename (str): checkpoint file path with pavi prefix
+ map_location (str, optional): Same as :func:`torch.load`.
+ Default: None
+
+ Returns:
+ dict or OrderedDict: The loaded checkpoint.
+ """
+ assert filename.startswith('pavi://'), \
+ f'Expected filename startswith `pavi://`, but get {filename}'
+ model_path = filename[7:]
+
+ try:
+ from pavi import modelcloud
+ except ImportError:
+ raise ImportError(
+ 'Please install pavi to load checkpoint from modelcloud.')
+
+ model = modelcloud.get(model_path)
+ with TemporaryDirectory() as tmp_dir:
+ downloaded_file = osp.join(tmp_dir, model.name)
+ model.download(downloaded_file)
+ checkpoint = torch.load(downloaded_file, map_location=map_location)
+ return checkpoint
+
+
+@CheckpointLoader.register_scheme(
+ prefixes=[r'(\S+\:)?s3://', r'(\S+\:)?petrel://'])
+def load_from_ceph(filename, map_location=None, backend='petrel'):
+ """load checkpoint through the file path prefixed with s3. In distributed
+ setting, this function download ckpt at all ranks to different temporary
+ directories.
+
+ Args:
+ filename (str): checkpoint file path with s3 prefix
+ map_location (str, optional): Same as :func:`torch.load`.
+ backend (str, optional): The storage backend type.
+ Defaults to 'petrel'.
+
+ Returns:
+ dict or OrderedDict: The loaded checkpoint.
+ """
+ file_backend = get_file_backend(
+ filename, backend_args={'backend': backend})
+ with io.BytesIO(file_backend.get(filename)) as buffer:
+ checkpoint = torch.load(buffer, map_location=map_location)
+ return checkpoint
+
+
+@CheckpointLoader.register_scheme(prefixes=('modelzoo://', 'torchvision://'))
+def load_from_torchvision(filename, map_location=None):
+ """load checkpoint through the file path prefixed with modelzoo or
+ torchvision.
+
+ Args:
+ filename (str): checkpoint file path with modelzoo or
+ torchvision prefix
+ map_location (str, optional): Same as :func:`torch.load`.
+
+ Returns:
+ dict or OrderedDict: The loaded checkpoint.
+ """
+ model_urls = get_torchvision_models()
+ if filename.startswith('modelzoo://'):
+ warnings.warn(
+ 'The URL scheme of "modelzoo://" is deprecated, please '
+ 'use "torchvision://" instead', DeprecationWarning)
+ model_name = filename[11:]
+ else:
+ model_name = filename[14:]
+ return load_from_http(model_urls[model_name], map_location=map_location)
+
+
+@CheckpointLoader.register_scheme(prefixes=('open-mmlab://', 'openmmlab://'))
+def load_from_openmmlab(filename, map_location=None):
+ """load checkpoint through the file path prefixed with open-mmlab or
+ openmmlab.
+
+ Args:
+ filename (str): checkpoint file path with open-mmlab or
+ openmmlab prefix
+ map_location (str, optional): Same as :func:`torch.load`.
+ Default: None
+
+ Returns:
+ dict or OrderedDict: The loaded checkpoint.
+ """
+
+ model_urls = get_external_models()
+ prefix_str = 'open-mmlab://'
+ if filename.startswith(prefix_str):
+ model_name = filename[13:]
+ else:
+ model_name = filename[12:]
+ prefix_str = 'openmmlab://'
+
+ deprecated_urls = get_deprecated_model_names()
+ if model_name in deprecated_urls:
+ warnings.warn(
+ f'{prefix_str}{model_name} is deprecated in favor '
+ f'of {prefix_str}{deprecated_urls[model_name]}',
+ DeprecationWarning)
+ model_name = deprecated_urls[model_name]
+ model_url = model_urls[model_name]
+ # check if is url
+ if model_url.startswith(('http://', 'https://')):
+ checkpoint = load_from_http(model_url, map_location=map_location)
+ else:
+ filename = osp.join(_get_mmengine_home(), model_url)
+ if not osp.isfile(filename):
+ raise FileNotFoundError(f'{filename} can not be found.')
+ checkpoint = torch.load(filename, map_location=map_location)
+ return checkpoint
+
+
+@CheckpointLoader.register_scheme(prefixes='mmcls://')
+def load_from_mmcls(filename, map_location=None):
+ """load checkpoint through the file path prefixed with mmcls.
+
+ Args:
+ filename (str): checkpoint file path with mmcls prefix
+ map_location (str, optional): Same as :func:`torch.load`.
+
+ Returns:
+ dict or OrderedDict: The loaded checkpoint.
+ """
+
+ model_urls = get_mmcls_models()
+ model_name = filename[8:]
+ checkpoint = load_from_http(
+ model_urls[model_name], map_location=map_location)
+ checkpoint = _process_mmcls_checkpoint(checkpoint)
+ return checkpoint
+
+
+def _load_checkpoint(filename, map_location=None, logger=None):
+ """Load checkpoint from somewhere (modelzoo, file, url).
+
+ Args:
+ filename (str): Accept local filepath, URL, ``torchvision://xxx``,
+ ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for
+ details.
+ map_location (str, optional): Same as :func:`torch.load`.
+ Default: None.
+ logger (:mod:`logging.Logger`, optional): The logger for error message.
+ Default: None
+
+ Returns:
+ dict or OrderedDict: The loaded checkpoint. It can be either an
+ OrderedDict storing model weights or a dict containing other
+ information, which depends on the checkpoint.
+ """
+ return CheckpointLoader.load_checkpoint(filename, map_location, logger)
+
+
+def _load_checkpoint_with_prefix(prefix, filename, map_location=None):
+ """Load partial pretrained model with specific prefix.
+
+ Args:
+ prefix (str): The prefix of sub-module.
+ filename (str): Accept local filepath, URL, ``torchvision://xxx``,
+ ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for
+ details.
+ map_location (str | None): Same as :func:`torch.load`. Default: None.
+
+ Returns:
+ dict or OrderedDict: The loaded checkpoint.
+ """
+
+ checkpoint = _load_checkpoint(filename, map_location=map_location)
+
+ if 'state_dict' in checkpoint:
+ state_dict = checkpoint['state_dict']
+ else:
+ state_dict = checkpoint
+ if not prefix.endswith('.'):
+ prefix += '.'
+ prefix_len = len(prefix)
+
+ state_dict = {
+ k[prefix_len:]: v
+ for k, v in state_dict.items() if k.startswith(prefix)
+ }
+
+ assert state_dict, f'{prefix} is not in the pretrained model'
+ return state_dict
+
+
+def _load_checkpoint_to_model(model,
+ checkpoint,
+ strict=False,
+ logger=None,
+ revise_keys=[(r'^module\.', '')]):
+
+ # get state_dict from checkpoint
+ if 'state_dict' in checkpoint:
+ state_dict = checkpoint['state_dict']
+ else:
+ state_dict = checkpoint
+
+ # strip prefix of state_dict
+ metadata = getattr(state_dict, '_metadata', OrderedDict())
+ for p, r in revise_keys:
+ state_dict = OrderedDict(
+ {re.sub(p, r, k): v
+ for k, v in state_dict.items()})
+ # Keep metadata in state_dict
+ state_dict._metadata = metadata
+
+ # load state_dict
+ load_state_dict(model, state_dict, strict, logger)
+ return checkpoint
+
+
+def load_checkpoint(model,
+ filename,
+ map_location=None,
+ strict=False,
+ logger=None,
+ revise_keys=[(r'^module\.', '')]):
+ """Load checkpoint from a file or URI.
+
+ Args:
+ model (Module): Module to load checkpoint.
+ filename (str): Accept local filepath, URL, ``torchvision://xxx``,
+ ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for
+ details.
+ map_location (str): Same as :func:`torch.load`.
+ strict (bool): Whether to allow different params for the model and
+ checkpoint.
+ logger (:mod:`logging.Logger` or None): The logger for error message.
+ revise_keys (list): A list of customized keywords to modify the
+ state_dict in checkpoint. Each item is a (pattern, replacement)
+ pair of the regular expression operations. Default: strip
+ the prefix 'module.' by [(r'^module\\.', '')].
+
+ Returns:
+ dict or OrderedDict: The loaded checkpoint.
+ """
+ checkpoint = _load_checkpoint(filename, map_location, logger)
+ # OrderedDict is a subclass of dict
+ if not isinstance(checkpoint, dict):
+ raise RuntimeError(
+ f'No state_dict found in checkpoint file {filename}')
+
+ return _load_checkpoint_to_model(model, checkpoint, strict, logger,
+ revise_keys)
+
+
+def weights_to_cpu(state_dict):
+ """Copy a model state_dict to cpu.
+
+ Args:
+ state_dict (OrderedDict): Model weights on GPU.
+
+ Returns:
+ OrderedDict: Model weights on GPU.
+ """
+ state_dict_cpu = OrderedDict()
+ for key, val in state_dict.items():
+ state_dict_cpu[key] = val.cpu()
+ # Keep metadata in state_dict
+ state_dict_cpu._metadata = getattr(state_dict, '_metadata', OrderedDict())
+ return state_dict_cpu
+
+
+@deprecated_function(
+ since='0.3.0',
+ removed_in='0.5.0',
+ instructions='`_save_to_state_dict` will be deprecated in the future, '
+ 'please use `nn.Module._save_to_state_dict` directly.')
+def _save_to_state_dict(module, destination, prefix, keep_vars):
+ """Saves module state to `destination` dictionary.
+
+ This method is modified from :meth:`torch.nn.Module._save_to_state_dict`.
+
+ Args:
+ module (nn.Module): The module to generate state_dict.
+ destination (dict): A dict where state will be stored.
+ prefix (str): The prefix for parameters and buffers used in this
+ module.
+ keep_vars (bool): Whether to keep the variable property of the
+ parameters.
+ """
+ for name, param in module._parameters.items():
+ if param is not None:
+ destination[prefix + name] = param if keep_vars else param.detach()
+ for name, buf in module._buffers.items():
+ if buf is not None and name not in module._non_persistent_buffers_set:
+ destination[prefix + name] = buf if keep_vars else buf.detach()
+
+
+def get_state_dict(module, destination=None, prefix='', keep_vars=False):
+ """Returns a dictionary containing a whole state of the module.
+
+ Both parameters and persistent buffers (e.g. running averages) are
+ included. Keys are corresponding parameter and buffer names.
+ This method is modified from :meth:`torch.nn.Module.state_dict` to
+ recursively check parallel module in case that the model has a complicated
+ structure, e.g., nn.Module(nn.Module(DDP)).
+
+ Args:
+ module (nn.Module): The module to generate state_dict.
+ destination (OrderedDict): Returned dict for the state of the
+ module.
+ prefix (str): Prefix of the key.
+ keep_vars (bool): Whether to keep the variable property of the
+ parameters. Default: False.
+
+ Returns:
+ dict: A dictionary containing a whole state of the module.
+ """
+ # recursively check parallel module in case that the model has a
+ # complicated structure, e.g., nn.Module(nn.Module(DDP))
+ if is_model_wrapper(module):
+ module = module.module
+
+ # below is the same as torch.nn.Module.state_dict()
+ if destination is None:
+ destination = OrderedDict()
+ destination._metadata = OrderedDict()
+ destination._metadata[prefix[:-1]] = local_metadata = dict(
+ version=module._version)
+ module._save_to_state_dict(destination, prefix, keep_vars)
+ for name, child in module._modules.items():
+ if child is not None:
+ get_state_dict(
+ child, destination, prefix + name + '.', keep_vars=keep_vars)
+ for hook in module._state_dict_hooks.values():
+ hook_result = hook(module, destination, prefix, local_metadata)
+ if hook_result is not None:
+ destination = hook_result
+ return destination
+
+
+def save_checkpoint(checkpoint,
+ filename,
+ file_client_args=None,
+ backend_args=None):
+ """Save checkpoint to file.
+
+ Args:
+ checkpoint (dict): Module whose params are to be saved.
+ filename (str): Checkpoint filename.
+ file_client_args (dict, optional): Arguments to instantiate a
+ FileClient. See :class:`mmengine.fileio.FileClient` for details.
+ Defaults to None. It will be deprecated in future. Please use
+ `backend_args` instead.
+ backend_args (dict, optional): Arguments to instantiate the
+ preifx of uri corresponding backend. Defaults to None.
+ New in v0.2.0.
+ """
+ if file_client_args is not None:
+ warnings.warn(
+ '"file_client_args" will be deprecated in future. '
+ 'Please use "backend_args" instead', DeprecationWarning)
+ if backend_args is not None:
+ raise ValueError(
+ '"file_client_args" and "backend_args" cannot be set '
+ 'at the same time.')
+
+ if filename.startswith('pavi://'):
+ if file_client_args is not None or backend_args is not None:
+ raise ValueError(
+ '"file_client_args" or "backend_args" should be "None" if '
+ 'filename starts with "pavi://"')
+ try:
+ from pavi import exception, modelcloud
+ except ImportError:
+ raise ImportError(
+ 'Please install pavi to load checkpoint from modelcloud.')
+ model_path = filename[7:]
+ root = modelcloud.Folder()
+ model_dir, model_name = osp.split(model_path)
+ try:
+ model = modelcloud.get(model_dir)
+ except exception.NodeNotFoundError:
+ model = root.create_training_model(model_dir)
+ with TemporaryDirectory() as tmp_dir:
+ checkpoint_file = osp.join(tmp_dir, model_name)
+ with open(checkpoint_file, 'wb') as f:
+ torch.save(checkpoint, f)
+ f.flush()
+ model.create_file(checkpoint_file, name=model_name)
+ else:
+ file_client = FileClient.infer_client(file_client_args, filename)
+ if file_client_args is None:
+ file_backend = get_file_backend(
+ filename, backend_args=backend_args)
+ else:
+ file_backend = file_client
+
+ with io.BytesIO() as f:
+ torch.save(checkpoint, f)
+ file_backend.put(f.getvalue(), filename)
+
+
+def find_latest_checkpoint(path: str) -> Optional[str]:
+ """Find the latest checkpoint from the given path.
+
+ Refer to https://github.com/facebookresearch/fvcore/blob/main/fvcore/common/checkpoint.py # noqa: E501
+
+ Args:
+ path(str): The path to find checkpoints.
+
+ Returns:
+ str or None: File path of the latest checkpoint.
+ """
+ save_file = osp.join(path, 'last_checkpoint')
+ last_saved: Optional[str]
+ if os.path.exists(save_file):
+ with open(save_file) as f:
+ last_saved = f.read().strip()
+ else:
+ print_log('Did not find last_checkpoint to be resumed.')
+ last_saved = None
+ return last_saved
diff --git a/testbed/open-mmlab__mmengine/mmengine/runner/log_processor.py b/testbed/open-mmlab__mmengine/mmengine/runner/log_processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1e408f4b91cf39cc1b1a7ea7b1f395f8608297f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/runner/log_processor.py
@@ -0,0 +1,436 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import datetime
+from collections import OrderedDict
+from typing import List, Optional, Tuple
+
+from mmengine.device import get_max_cuda_memory, is_cuda_available
+from mmengine.registry import LOG_PROCESSORS
+
+
+@LOG_PROCESSORS.register_module() # type: ignore
+class LogProcessor:
+ """A log processor used to format log information collected from
+ ``runner.message_hub.log_scalars``.
+
+ ``LogProcessor`` instance is built by runner and will format
+ ``runner.message_hub.log_scalars`` to ``tag`` and ``log_str``, which can
+ directly used by ``LoggerHook`` and ``MMLogger``. Besides, the argument
+ ``custom_cfg`` of constructor can control the statistics method of logs.
+
+ Args:
+ window_size (int): default smooth interval Defaults to 10.
+ by_epoch (bool): Whether to format logs with epoch stype. Defaults to
+ True.
+ custom_cfg (list[dict], optional): Contains multiple log config dict,
+ in which key means the data source name of log and value means the
+ statistic method and corresponding arguments used to count the
+ data source. Defaults to None.
+
+ - If custom_cfg is None, all logs will be formatted via default
+ methods, such as smoothing loss by default window_size. If
+ custom_cfg is defined as a list of config dict, for example:
+ [dict(data_src=loss, method='mean', log_name='global_loss',
+ window_size='global')]. It means the log item ``loss`` will be
+ counted as global mean and additionally logged as ``global_loss``
+ (defined by ``log_name``). If ``log_name`` is not defined in
+ config dict, the original logged key will be overwritten.
+
+ - The original log item cannot be overwritten twice. Here is
+ an error example:
+ [dict(data_src=loss, method='mean', window_size='global'),
+ dict(data_src=loss, method='mean', window_size='epoch')].
+ Both log config dict in custom_cfg do not have ``log_name`` key,
+ which means the loss item will be overwritten twice.
+
+ - For those statistic methods with the ``window_size`` argument,
+ if ``by_epoch`` is set to False, ``windows_size`` should not be
+ `epoch` to statistics log value by epoch.
+ num_digits (int): The number of significant digit shown in the
+ logging message.
+
+ Examples:
+ >>> # `log_name` is defined, `loss_large_window` will be an additional
+ >>> # record.
+ >>> log_processor = dict(
+ >>> window_size=10,
+ >>> by_epoch=True,
+ >>> custom_cfg=[dict(data_src='loss',
+ >>> log_name='loss_large_window',
+ >>> method_name='mean',
+ >>> window_size=100)])
+ >>> # `log_name` is not defined. `loss` will be overwritten.
+ >>> log_processor = dict(
+ >>> window_size=10,
+ >>> by_epoch=True,
+ >>> custom_cfg=[dict(data_src='loss',
+ >>> method_name='mean',
+ >>> window_size=100)])
+ >>> # Record loss with different statistics methods.
+ >>> log_processor = dict(
+ >>> window_size=10,
+ >>> by_epoch=True,
+ >>> custom_cfg=[dict(data_src='loss',
+ >>> log_name='loss_large_window',
+ >>> method_name='mean',
+ >>> window_size=100),
+ >>> dict(data_src='loss',
+ >>> method_name='mean',
+ >>> window_size=100)])
+ >>> # Overwrite loss item twice will raise an error.
+ >>> log_processor = dict(
+ >>> window_size=10,
+ >>> by_epoch=True,
+ >>> custom_cfg=[dict(data_src='loss',
+ >>> method_name='mean',
+ >>> window_size=100),
+ >>> dict(data_src='loss',
+ >>> method_name='max',
+ >>> window_size=100)])
+ AssertionError
+ """
+
+ def __init__(self,
+ window_size=10,
+ by_epoch=True,
+ custom_cfg: Optional[List[dict]] = None,
+ num_digits: int = 4):
+ self.window_size = window_size
+ self.by_epoch = by_epoch
+ self.custom_cfg = custom_cfg if custom_cfg else []
+ self.num_digits = num_digits
+ self._check_custom_cfg()
+
+ def get_log_after_iter(self, runner, batch_idx: int,
+ mode: str) -> Tuple[dict, str]:
+ """Format log string after training, validation or testing epoch.
+
+ Args:
+ runner (Runner): The runner of training phase.
+ batch_idx (int): The index of the current batch in the current
+ loop.
+ mode (str): Current mode of runner, train, test or val.
+
+ Return:
+ Tuple(dict, str): Formatted log dict/string which will be
+ recorded by :obj:`runner.message_hub` and :obj:`runner.visualizer`.
+ """
+ assert mode in ['train', 'test', 'val']
+ current_loop = self._get_cur_loop(runner, mode)
+ cur_iter = self._get_iter(runner, batch_idx=batch_idx)
+ # Overwrite ``window_size`` defined in ``custom_cfg`` to int value.
+ custom_cfg_copy = self._parse_windows_size(runner, batch_idx)
+ # tag is used to write log information to different backends.
+ tag = self._collect_scalars(custom_cfg_copy, runner, mode)
+ # `log_tag` will pop 'lr' and loop other keys to `log_str`.
+ log_tag = copy.deepcopy(tag)
+ # Record learning rate.
+ lr_str_list = []
+ for key, value in tag.items():
+ if key.endswith('lr'):
+ log_tag.pop(key)
+ lr_str_list.append(f'{key}: '
+ f'{value:.{self.num_digits}e}')
+ lr_str = ' '.join(lr_str_list)
+ # Format log header.
+ # by_epoch == True
+ # train/val: Epoch [5][5/10] ...
+ # test: Epoch [5/10]
+ # by_epoch == False
+ # train: Epoch [5/10000] ... (divided by `max_iter`)
+ # val/test: Epoch [5/2000] ... (divided by length of dataloader)
+ if self.by_epoch:
+ # Align the iteration log:
+ # Epoch(train) [ 9][010/270]
+ # ... ||| |||
+ # Epoch(train) [ 10][100/270]
+ dataloader_len = len(current_loop.dataloader)
+ cur_iter_str = str(cur_iter).rjust(len(str(dataloader_len)))
+
+ if mode in ['train', 'val']:
+ # Right Align the epoch log:
+ # Epoch(train) [9][100/270]
+ # ... ||
+ # Epoch(train) [100][100/270]
+ cur_epoch = self._get_epoch(runner, mode)
+ max_epochs = runner.max_epochs
+ # 3 means the three characters: "[", "]", and " " occupied in
+ # " [{max_epochs}]"
+ cur_epoch_str = f'[{cur_epoch}]'.rjust(
+ len(str(max_epochs)) + 3, ' ')
+ tag['epoch'] = cur_epoch
+ log_str = (f'Epoch({mode}){cur_epoch_str}'
+ f'[{cur_iter_str}/{dataloader_len}] ')
+ else:
+ log_str = (f'Epoch({mode}) '
+ f'[{cur_iter_str}/{dataloader_len}] ')
+ else:
+ if mode == 'train':
+ cur_iter_str = str(cur_iter).rjust(len(str(runner.max_iters)))
+ log_str = (f'Iter({mode}) '
+ f'[{cur_iter_str}/{runner.max_iters}] ')
+ else:
+ dataloader_len = len(current_loop.dataloader)
+ cur_iter_str = str(batch_idx + 1).rjust(
+ len(str(dataloader_len)))
+ log_str = (f'Iter({mode}) [{cur_iter_str}'
+ f'/{len(current_loop.dataloader)}] ')
+ # Concatenate lr, momentum string with log header.
+ log_str += f'{lr_str} '
+ # If IterTimerHook used in runner, eta, time, and data_time should be
+ # recorded.
+ if (all(item in tag for item in ['time', 'data_time'])
+ and 'eta' in runner.message_hub.runtime_info):
+ eta = runner.message_hub.get_info('eta')
+ eta_str = str(datetime.timedelta(seconds=int(eta)))
+ log_str += f'eta: {eta_str} '
+ log_str += (f'time: {tag["time"]:.{self.num_digits}f} '
+ f'data_time: '
+ f'{tag["data_time"]:.{self.num_digits}f} ')
+ # Pop recorded keys
+ log_tag.pop('time')
+ log_tag.pop('data_time')
+
+ # If cuda is available, the max memory occupied should be calculated.
+ if is_cuda_available():
+ log_str += f'memory: {self._get_max_memory(runner)} '
+ # Loop left keys to fill `log_str`.
+ if mode in ('train', 'val'):
+ log_items = []
+ for name, val in log_tag.items():
+ if mode == 'val' and not name.startswith('val/loss'):
+ continue
+ if isinstance(val, float):
+ val = f'{val:.{self.num_digits}f}'
+ log_items.append(f'{name}: {val}')
+ log_str += ' '.join(log_items)
+ return tag, log_str
+
+ def get_log_after_epoch(self, runner, batch_idx: int,
+ mode: str) -> Tuple[dict, str]:
+ """Format log string after validation or testing epoch.
+
+ Args:
+ runner (Runner): The runner of validation/testing phase.
+ batch_idx (int): The index of the current batch in the current
+ loop.
+ mode (str): Current mode of runner.
+
+ Return:
+ Tuple(dict, str): Formatted log dict/string which will be
+ recorded by :obj:`runner.message_hub` and :obj:`runner.visualizer`.
+ """
+ assert mode in [
+ 'test', 'val'
+ ], ('`_get_metric_log_str` only accept val or test mode, but got '
+ f'{mode}')
+ cur_loop = self._get_cur_loop(runner, mode)
+ dataloader_len = len(cur_loop.dataloader)
+
+ custom_cfg_copy = self._parse_windows_size(runner, batch_idx)
+ # tag is used to write log information to different backends.
+ tag = self._collect_scalars(custom_cfg_copy, runner, mode)
+ tag.pop('time', None)
+ tag.pop('data_time', None)
+ # By epoch:
+ # Epoch(val) [10][1000/1000] ...
+ # Epoch(test) [1000/1000] ...
+ # By iteration:
+ # Iteration(val) [1000/1000] ...
+ # Iteration(test) [1000/1000] ...
+ if self.by_epoch:
+ if mode == 'val':
+ cur_epoch = self._get_epoch(runner, mode)
+ log_str = (f'Epoch({mode}) [{cur_epoch}][{dataloader_len}/'
+ f'{dataloader_len}] ')
+ else:
+ log_str = (
+ f'Epoch({mode}) [{dataloader_len}/{dataloader_len}] ')
+
+ else:
+ log_str = (f'Iter({mode}) [{dataloader_len}/{dataloader_len}] ')
+ # `time` and `data_time` will not be recorded in after epoch log
+ # message.
+ log_items = []
+ for name, val in tag.items():
+ if isinstance(val, float):
+ val = f'{val:.{self.num_digits}f}'
+ log_items.append(f'{name}: {val}')
+ log_str += ' '.join(log_items)
+ return tag, log_str
+
+ def _collect_scalars(self, custom_cfg: List[dict], runner,
+ mode: str) -> dict:
+ """Collect log information to compose a dict according to mode.
+
+ Args:
+ custom_cfg (List[dict]): A copy of ``self.custom_cfg`` with int
+ ``window_size``.
+ runner (Runner): The runner of the training/testing/validation
+ process.
+ mode (str): Current mode of runner.
+
+ Returns:
+ dict: Statistical values of logs.
+ """
+ tag = OrderedDict()
+ # history_scalars of train/val/test phase.
+ history_scalars = runner.message_hub.log_scalars
+ # corresponding mode history_scalars
+ mode_history_scalars = OrderedDict()
+ # extract log scalars and remove prefix to `mode_history_scalars`
+ # according to mode.
+ for prefix_key, log_buffer in history_scalars.items():
+ if prefix_key.startswith(mode):
+ key = prefix_key.partition('/')[-1]
+ mode_history_scalars[key] = log_buffer
+ for key in mode_history_scalars:
+ # Update the latest learning rate and smoothed time logs.
+ if 'loss' in key or key in ('time', 'data_time', 'grad_norm'):
+ tag[key] = mode_history_scalars[key].mean(self.window_size)
+ else:
+ # Default statistic method is current.
+ tag[key] = mode_history_scalars[key].current()
+ # Update custom keys.
+ for log_cfg in custom_cfg:
+ data_src = log_cfg.pop('data_src')
+ if 'log_name' in log_cfg:
+ log_name = log_cfg.pop('log_name')
+ else:
+ log_name = data_src
+ # log item in custom_cfg could only exist in train or val
+ # mode.
+ if data_src in mode_history_scalars:
+ tag[log_name] = mode_history_scalars[data_src].statistics(
+ **log_cfg)
+ return tag
+
+ def _check_custom_cfg(self) -> None:
+ """Check the legality of ``self.custom_cfg``."""
+
+ def _check_window_size():
+ for log_cfg in self.custom_cfg:
+ if not self.by_epoch:
+ assert log_cfg['window_size'] != 'epoch', \
+ 'window_size cannot be epoch if LoggerHook.by_epoch' \
+ ' is False.'
+
+ def _check_repeated_log_name():
+ # The `log_name` of the same data_src should not be repeated.
+ # If `log_name` is not specified, `data_src` will be overwritten.
+ # But only allowed to be overwritten once.
+ check_set = set()
+ for log_cfg in self.custom_cfg:
+ assert 'data_src' in log_cfg
+ data_src = log_cfg['data_src']
+ log_name = log_cfg.get('log_name', data_src)
+ assert log_name not in check_set, (
+ f'Found duplicate {log_name} for {data_src}. Please check'
+ 'your `custom_cfg` for `log_processor`. You should '
+ f'neither define duplicate `{log_name}` for {data_src} '
+ f'nor do not define any {log_name} for multiple '
+ f'{data_src}, See more information in the docstring of '
+ 'LogProcessor')
+
+ check_set.add(log_name)
+
+ _check_repeated_log_name()
+ _check_window_size()
+
+ def _parse_windows_size(self, runner, batch_idx: int) -> list:
+ """Parse window_size defined in custom_cfg to int value.
+
+ Args:
+ runner (Runner): The runner of the training/testing/validation
+ process.
+ batch_idx (int): The iteration index of current dataloader.
+ """
+ custom_cfg_copy = copy.deepcopy(self.custom_cfg)
+ for log_cfg in custom_cfg_copy:
+ window_size = log_cfg.get('window_size', None)
+ if window_size is None or isinstance(window_size, int):
+ continue
+ elif window_size == 'epoch':
+ log_cfg['window_size'] = batch_idx + 1
+ elif window_size == 'global':
+ log_cfg['window_size'] = runner.iter + 1
+ else:
+ raise TypeError(
+ 'window_size should be int, epoch or global, but got '
+ f'invalid {window_size}')
+ return custom_cfg_copy
+
+ def _get_max_memory(self, runner) -> int:
+ """Returns the maximum GPU memory occupied by tensors in megabytes (MB)
+ for a given device.
+
+ Args:
+ runner (Runner): The runner of the training/testing/validation
+ process.
+
+ Returns:
+ The maximum GPU memory occupied by tensors in megabytes for a given
+ device.
+ """
+
+ device = getattr(runner.model, 'output_device', None)
+ return get_max_cuda_memory(device)
+
+ def _get_iter(self, runner, batch_idx: int = None) -> int:
+ """Get current iteration index.
+
+ Args:
+ runner (Runner): The runner of the training/testing/validation
+ process.
+ batch_idx (int, optional): The iteration index of current
+ dataloader. Defaults to None.
+
+ Returns:
+ int: The current global iter or inner iter.
+ """
+ if self.by_epoch and batch_idx is not None:
+ current_iter = batch_idx + 1
+ else:
+ current_iter = runner.iter + 1
+ return current_iter
+
+ def _get_epoch(self, runner, mode: str) -> int:
+ """Get current epoch according to mode.
+
+ Args:
+ runner (Runner): The runner of the training/testing/validation
+ process.
+ mode (str): Current mode of runner.
+
+ Returns:
+ int: The current epoch.
+ """
+ if mode == 'train':
+ epoch = runner.epoch + 1
+ elif mode == 'val':
+ # normal val mode
+ # runner.epoch += 1 has been done before validation
+ epoch = runner.epoch
+ else:
+ raise ValueError(
+ f"runner mode should be 'train' or 'val', but got {mode}")
+ return epoch
+
+ def _get_cur_loop(self, runner, mode: str):
+ """Get current loop according to mode.
+
+ Args:
+ runner (Runner): The runner of the training/validation/testing
+ process.
+ mode (str): Current mode of runner.
+
+ Returns:
+ BaseLoop: Current loop of runner.
+ """
+ # returns type hint will occur circular import
+ if mode == 'train':
+ return runner.train_loop
+ elif mode == 'val':
+ return runner.val_loop
+ else:
+ return runner.test_loop
diff --git a/testbed/open-mmlab__mmengine/mmengine/runner/loops.py b/testbed/open-mmlab__mmengine/mmengine/runner/loops.py
new file mode 100644
index 0000000000000000000000000000000000000000..67b8d5b6e31d44d9f48631f10a038a57bb901316
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/runner/loops.py
@@ -0,0 +1,442 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import bisect
+import time
+import warnings
+from typing import Dict, List, Optional, Sequence, Tuple, Union
+
+import torch
+from torch.utils.data import DataLoader
+
+from mmengine.evaluator import Evaluator
+from mmengine.registry import LOOPS
+from .amp import autocast
+from .base_loop import BaseLoop
+from .utils import calc_dynamic_intervals
+
+
+@LOOPS.register_module()
+class EpochBasedTrainLoop(BaseLoop):
+ """Loop for epoch-based training.
+
+ Args:
+ runner (Runner): A reference of runner.
+ dataloader (Dataloader or dict): A dataloader object or a dict to
+ build a dataloader.
+ max_epochs (int): Total training epochs.
+ val_begin (int): The epoch that begins validating.
+ Defaults to 1.
+ val_interval (int): Validation interval. Defaults to 1.
+ dynamic_intervals (List[Tuple[int, int]], optional): The
+ first element in the tuple is a milestone and the second
+ element is a interval. The interval is used after the
+ corresponding milestone. Defaults to None.
+ """
+
+ def __init__(
+ self,
+ runner,
+ dataloader: Union[DataLoader, Dict],
+ max_epochs: int,
+ val_begin: int = 1,
+ val_interval: int = 1,
+ dynamic_intervals: Optional[List[Tuple[int, int]]] = None) -> None:
+ super().__init__(runner, dataloader)
+ self._max_epochs = int(max_epochs)
+ assert self._max_epochs == max_epochs, \
+ f'`max_epochs` should be a integer number, but get {max_epochs}.'
+ self._max_iters = self._max_epochs * len(self.dataloader)
+ self._epoch = 0
+ self._iter = 0
+ self.val_begin = val_begin
+ self.val_interval = val_interval
+ if hasattr(self.dataloader.dataset, 'metainfo'):
+ self.runner.visualizer.dataset_meta = \
+ self.dataloader.dataset.metainfo
+ else:
+ warnings.warn(
+ f'Dataset {self.dataloader.dataset.__class__.__name__} has no '
+ 'metainfo. ``dataset_meta`` in visualizer will be '
+ 'None.')
+
+ self.dynamic_milestones, self.dynamic_intervals = \
+ calc_dynamic_intervals(
+ self.val_interval, dynamic_intervals)
+
+ @property
+ def max_epochs(self):
+ """int: Total epochs to train model."""
+ return self._max_epochs
+
+ @property
+ def max_iters(self):
+ """int: Total iterations to train model."""
+ return self._max_iters
+
+ @property
+ def epoch(self):
+ """int: Current epoch."""
+ return self._epoch
+
+ @property
+ def iter(self):
+ """int: Current iteration."""
+ return self._iter
+
+ def run(self) -> torch.nn.Module:
+ """Launch training."""
+ self.runner.call_hook('before_train')
+
+ while self._epoch < self._max_epochs:
+ self.run_epoch()
+
+ self._decide_current_val_interval()
+ if (self.runner.val_loop is not None
+ and self._epoch >= self.val_begin
+ and self._epoch % self.val_interval == 0):
+ self.runner.val_loop.run()
+
+ self.runner.call_hook('after_train')
+ return self.runner.model
+
+ def run_epoch(self) -> None:
+ """Iterate one epoch."""
+ self.runner.call_hook('before_train_epoch')
+ self.runner.model.train()
+ for idx, data_batch in enumerate(self.dataloader):
+ self.run_iter(idx, data_batch)
+
+ self.runner.call_hook('after_train_epoch')
+ self._epoch += 1
+
+ def run_iter(self, idx, data_batch: Sequence[dict]) -> None:
+ """Iterate one min-batch.
+
+ Args:
+ data_batch (Sequence[dict]): Batch of data from dataloader.
+ """
+ self.runner.call_hook(
+ 'before_train_iter', batch_idx=idx, data_batch=data_batch)
+ # Enable gradient accumulation mode and avoid unnecessary gradient
+ # synchronization during gradient accumulation process.
+ # outputs should be a dict of loss.
+ outputs = self.runner.model.train_step(
+ data_batch, optim_wrapper=self.runner.optim_wrapper)
+
+ self.runner.call_hook(
+ 'after_train_iter',
+ batch_idx=idx,
+ data_batch=data_batch,
+ outputs=outputs)
+ self._iter += 1
+
+ def _decide_current_val_interval(self) -> None:
+ """Dynamically modify the ``val_interval``."""
+ step = bisect.bisect(self.dynamic_milestones, (self.epoch + 1))
+ self.val_interval = self.dynamic_intervals[step - 1]
+
+
+class _InfiniteDataloaderIterator:
+ """An infinite dataloader iterator wrapper for IterBasedTrainLoop.
+
+ It resets the dataloader to continue iterating when the iterator has
+ iterated over all the data. However, this approach is not efficient, as the
+ workers need to be restarted every time the dataloader is reset. It is
+ recommended to use `mmengine.dataset.InfiniteSampler` to enable the
+ dataloader to iterate infinitely.
+ """
+
+ def __init__(self, dataloader: DataLoader) -> None:
+ self._dataloader = dataloader
+ self._iterator = iter(self._dataloader)
+ self._epoch = 0
+
+ def __iter__(self):
+ return self
+
+ def __next__(self) -> Sequence[dict]:
+ try:
+ data = next(self._iterator)
+ except StopIteration:
+ warnings.warn('Reach the end of the dataloader, it will be '
+ 'restarted and continue to iterate. It is '
+ 'recommended to use '
+ '`mmengine.dataset.InfiniteSampler` to enable the '
+ 'dataloader to iterate infinitely.')
+ self._epoch += 1
+ if hasattr(self._dataloader, 'sampler') and hasattr(
+ self._dataloader.sampler, 'set_epoch'):
+ # In case the` _SingleProcessDataLoaderIter` has no sampler,
+ # or data loader uses `SequentialSampler` in Pytorch.
+ self._dataloader.sampler.set_epoch(self._epoch)
+
+ elif hasattr(self._dataloader, 'batch_sampler') and hasattr(
+ self._dataloader.batch_sampler.sampler, 'set_epoch'):
+ # In case the` _SingleProcessDataLoaderIter` has no batch
+ # sampler. batch sampler in pytorch warps the sampler as its
+ # attributes.
+ self._dataloader.batch_sampler.sampler.set_epoch(self._epoch)
+ time.sleep(2) # Prevent possible deadlock during epoch transition
+ self._iterator = iter(self._dataloader)
+ data = next(self._iterator)
+ return data
+
+
+@LOOPS.register_module()
+class IterBasedTrainLoop(BaseLoop):
+ """Loop for iter-based training.
+
+ Args:
+ runner (Runner): A reference of runner.
+ dataloader (Dataloader or dict): A dataloader object or a dict to
+ build a dataloader.
+ max_iters (int): Total training iterations.
+ val_begin (int): The iteration that begins validating.
+ Defaults to 1.
+ val_interval (int): Validation interval. Defaults to 1000.
+ dynamic_intervals (List[Tuple[int, int]], optional): The
+ first element in the tuple is a milestone and the second
+ element is a interval. The interval is used after the
+ corresponding milestone. Defaults to None.
+ """
+
+ def __init__(
+ self,
+ runner,
+ dataloader: Union[DataLoader, Dict],
+ max_iters: int,
+ val_begin: int = 1,
+ val_interval: int = 1000,
+ dynamic_intervals: Optional[List[Tuple[int, int]]] = None) -> None:
+ super().__init__(runner, dataloader)
+ self._max_iters = int(max_iters)
+ assert self._max_iters == max_iters, \
+ f'`max_iters` should be a integer number, but get {max_iters}'
+ self._max_epochs = 1 # for compatibility with EpochBasedTrainLoop
+ self._epoch = 0
+ self._iter = 0
+ self.val_begin = val_begin
+ self.val_interval = val_interval
+ if hasattr(self.dataloader.dataset, 'metainfo'):
+ self.runner.visualizer.dataset_meta = \
+ self.dataloader.dataset.metainfo
+ else:
+ warnings.warn(
+ f'Dataset {self.dataloader.dataset.__class__.__name__} has no '
+ 'metainfo. ``dataset_meta`` in visualizer will be '
+ 'None.')
+ # get the iterator of the dataloader
+ self.dataloader_iterator = _InfiniteDataloaderIterator(self.dataloader)
+
+ self.dynamic_milestones, self.dynamic_intervals = \
+ calc_dynamic_intervals(
+ self.val_interval, dynamic_intervals)
+
+ @property
+ def max_epochs(self):
+ """int: Total epochs to train model."""
+ return self._max_epochs
+
+ @property
+ def max_iters(self):
+ """int: Total iterations to train model."""
+ return self._max_iters
+
+ @property
+ def epoch(self):
+ """int: Current epoch."""
+ return self._epoch
+
+ @property
+ def iter(self):
+ """int: Current iteration."""
+ return self._iter
+
+ def run(self) -> None:
+ """Launch training."""
+ self.runner.call_hook('before_train')
+ # In iteration-based training loop, we treat the whole training process
+ # as a big epoch and execute the corresponding hook.
+ self.runner.call_hook('before_train_epoch')
+ while self._iter < self._max_iters:
+ self.runner.model.train()
+
+ data_batch = next(self.dataloader_iterator)
+ self.run_iter(data_batch)
+
+ self._decide_current_val_interval()
+ if (self.runner.val_loop is not None
+ and self._iter >= self.val_begin
+ and self._iter % self.val_interval == 0):
+ self.runner.val_loop.run()
+
+ self.runner.call_hook('after_train_epoch')
+ self.runner.call_hook('after_train')
+ return self.runner.model
+
+ def run_iter(self, data_batch: Sequence[dict]) -> None:
+ """Iterate one mini-batch.
+
+ Args:
+ data_batch (Sequence[dict]): Batch of data from dataloader.
+ """
+ self.runner.call_hook(
+ 'before_train_iter', batch_idx=self._iter, data_batch=data_batch)
+ # Enable gradient accumulation mode and avoid unnecessary gradient
+ # synchronization during gradient accumulation process.
+ # outputs should be a dict of loss.
+ outputs = self.runner.model.train_step(
+ data_batch, optim_wrapper=self.runner.optim_wrapper)
+
+ self.runner.call_hook(
+ 'after_train_iter',
+ batch_idx=self._iter,
+ data_batch=data_batch,
+ outputs=outputs)
+ self._iter += 1
+
+ def _decide_current_val_interval(self) -> None:
+ """Dynamically modify the ``val_interval``."""
+ step = bisect.bisect(self.dynamic_milestones, (self._iter + 1))
+ self.val_interval = self.dynamic_intervals[step - 1]
+
+
+@LOOPS.register_module()
+class ValLoop(BaseLoop):
+ """Loop for validation.
+
+ Args:
+ runner (Runner): A reference of runner.
+ dataloader (Dataloader or dict): A dataloader object or a dict to
+ build a dataloader.
+ evaluator (Evaluator or dict or list): Used for computing metrics.
+ fp16 (bool): Whether to enable fp16 validation. Defaults to
+ False.
+ """
+
+ def __init__(self,
+ runner,
+ dataloader: Union[DataLoader, Dict],
+ evaluator: Union[Evaluator, Dict, List],
+ fp16: bool = False) -> None:
+ super().__init__(runner, dataloader)
+
+ if isinstance(evaluator, dict) or isinstance(evaluator, list):
+ self.evaluator = runner.build_evaluator(evaluator) # type: ignore
+ else:
+ assert isinstance(evaluator, Evaluator), (
+ 'evaluator must be one of dict, list or Evaluator instance, '
+ f'but got {type(evaluator)}.')
+ self.evaluator = evaluator # type: ignore
+ if hasattr(self.dataloader.dataset, 'metainfo'):
+ self.evaluator.dataset_meta = self.dataloader.dataset.metainfo
+ self.runner.visualizer.dataset_meta = \
+ self.dataloader.dataset.metainfo
+ else:
+ warnings.warn(
+ f'Dataset {self.dataloader.dataset.__class__.__name__} has no '
+ 'metainfo. ``dataset_meta`` in evaluator, metric and '
+ 'visualizer will be None.')
+ self.fp16 = fp16
+
+ def run(self) -> dict:
+ """Launch validation."""
+ self.runner.call_hook('before_val')
+ self.runner.call_hook('before_val_epoch')
+ self.runner.model.eval()
+ for idx, data_batch in enumerate(self.dataloader):
+ self.run_iter(idx, data_batch)
+
+ # compute metrics
+ metrics = self.evaluator.evaluate(len(self.dataloader.dataset))
+ self.runner.call_hook('after_val_epoch', metrics=metrics)
+ self.runner.call_hook('after_val')
+ return metrics
+
+ @torch.no_grad()
+ def run_iter(self, idx, data_batch: Sequence[dict]):
+ """Iterate one mini-batch.
+
+ Args:
+ data_batch (Sequence[dict]): Batch of data
+ from dataloader.
+ """
+ self.runner.call_hook(
+ 'before_val_iter', batch_idx=idx, data_batch=data_batch)
+ # outputs should be sequence of BaseDataElement
+ with autocast(enabled=self.fp16):
+ outputs = self.runner.model.val_step(data_batch)
+ self.evaluator.process(data_samples=outputs, data_batch=data_batch)
+ self.runner.call_hook(
+ 'after_val_iter',
+ batch_idx=idx,
+ data_batch=data_batch,
+ outputs=outputs)
+
+
+@LOOPS.register_module()
+class TestLoop(BaseLoop):
+ """Loop for test.
+
+ Args:
+ runner (Runner): A reference of runner.
+ dataloader (Dataloader or dict): A dataloader object or a dict to
+ build a dataloader.
+ evaluator (Evaluator or dict or list): Used for computing metrics.
+ fp16 (bool): Whether to enable fp16 testing. Defaults to
+ False.
+ """
+
+ def __init__(self,
+ runner,
+ dataloader: Union[DataLoader, Dict],
+ evaluator: Union[Evaluator, Dict, List],
+ fp16: bool = False):
+ super().__init__(runner, dataloader)
+
+ if isinstance(evaluator, dict) or isinstance(evaluator, list):
+ self.evaluator = runner.build_evaluator(evaluator) # type: ignore
+ else:
+ self.evaluator = evaluator # type: ignore
+ if hasattr(self.dataloader.dataset, 'metainfo'):
+ self.evaluator.dataset_meta = self.dataloader.dataset.metainfo
+ self.runner.visualizer.dataset_meta = \
+ self.dataloader.dataset.metainfo
+ else:
+ warnings.warn(
+ f'Dataset {self.dataloader.dataset.__class__.__name__} has no '
+ 'metainfo. ``dataset_meta`` in evaluator, metric and '
+ 'visualizer will be None.')
+ self.fp16 = fp16
+
+ def run(self) -> dict:
+ """Launch test."""
+ self.runner.call_hook('before_test')
+ self.runner.call_hook('before_test_epoch')
+ self.runner.model.eval()
+ for idx, data_batch in enumerate(self.dataloader):
+ self.run_iter(idx, data_batch)
+
+ # compute metrics
+ metrics = self.evaluator.evaluate(len(self.dataloader.dataset))
+ self.runner.call_hook('after_test_epoch', metrics=metrics)
+ self.runner.call_hook('after_test')
+ return metrics
+
+ @torch.no_grad()
+ def run_iter(self, idx, data_batch: Sequence[dict]) -> None:
+ """Iterate one mini-batch.
+
+ Args:
+ data_batch (Sequence[dict]): Batch of data from dataloader.
+ """
+ self.runner.call_hook(
+ 'before_test_iter', batch_idx=idx, data_batch=data_batch)
+ # predictions should be sequence of BaseDataElement
+ with autocast(enabled=self.fp16):
+ outputs = self.runner.model.test_step(data_batch)
+ self.evaluator.process(data_samples=outputs, data_batch=data_batch)
+ self.runner.call_hook(
+ 'after_test_iter',
+ batch_idx=idx,
+ data_batch=data_batch,
+ outputs=outputs)
diff --git a/testbed/open-mmlab__mmengine/mmengine/runner/priority.py b/testbed/open-mmlab__mmengine/mmengine/runner/priority.py
new file mode 100644
index 0000000000000000000000000000000000000000..ff644043b810c49dbe673e2ba5e35900650c3f02
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/runner/priority.py
@@ -0,0 +1,61 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from enum import Enum
+from typing import Union
+
+
+class Priority(Enum):
+ """Hook priority levels.
+
+ +--------------+------------+
+ | Level | Value |
+ +==============+============+
+ | HIGHEST | 0 |
+ +--------------+------------+
+ | VERY_HIGH | 10 |
+ +--------------+------------+
+ | HIGH | 30 |
+ +--------------+------------+
+ | ABOVE_NORMAL | 40 |
+ +--------------+------------+
+ | NORMAL | 50 |
+ +--------------+------------+
+ | BELOW_NORMAL | 60 |
+ +--------------+------------+
+ | LOW | 70 |
+ +--------------+------------+
+ | VERY_LOW | 90 |
+ +--------------+------------+
+ | LOWEST | 100 |
+ +--------------+------------+
+ """
+
+ HIGHEST = 0
+ VERY_HIGH = 10
+ HIGH = 30
+ ABOVE_NORMAL = 40
+ NORMAL = 50
+ BELOW_NORMAL = 60
+ LOW = 70
+ VERY_LOW = 90
+ LOWEST = 100
+
+
+def get_priority(priority: Union[int, str, Priority]) -> int:
+ """Get priority value.
+
+ Args:
+ priority (int or str or :obj:`Priority`): Priority.
+
+ Returns:
+ int: The priority value.
+ """
+ if isinstance(priority, int):
+ if priority < 0 or priority > 100:
+ raise ValueError('priority must be between 0 and 100')
+ return priority
+ elif isinstance(priority, Priority):
+ return priority.value
+ elif isinstance(priority, str):
+ return Priority[priority.upper()].value
+ else:
+ raise TypeError('priority must be an integer or Priority enum value')
diff --git a/testbed/open-mmlab__mmengine/mmengine/runner/runner.py b/testbed/open-mmlab__mmengine/mmengine/runner/runner.py
new file mode 100644
index 0000000000000000000000000000000000000000..edb404c7b329dfbc2586cd705bfbb482d3347f7c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/runner/runner.py
@@ -0,0 +1,2280 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import logging
+import os
+import os.path as osp
+import pickle
+import platform
+import time
+import warnings
+from collections import OrderedDict
+from functools import partial
+from typing import Callable, Dict, List, Optional, Sequence, Union
+
+import torch
+import torch.nn as nn
+from torch.nn.parallel.distributed import DistributedDataParallel
+from torch.optim import Optimizer
+from torch.utils.data import DataLoader
+
+import mmengine
+from mmengine.config import Config, ConfigDict
+from mmengine.dataset import COLLATE_FUNCTIONS, worker_init_fn
+from mmengine.device import get_device
+from mmengine.dist import (broadcast, get_dist_info, get_rank, init_dist,
+ is_distributed, master_only)
+from mmengine.evaluator import Evaluator
+from mmengine.fileio import FileClient, join_path
+from mmengine.hooks import Hook
+from mmengine.logging import MessageHub, MMLogger, print_log
+from mmengine.model import (MMDistributedDataParallel, convert_sync_batchnorm,
+ is_model_wrapper, revert_sync_batchnorm)
+from mmengine.optim import (OptimWrapper, OptimWrapperDict, _ParamScheduler,
+ build_optim_wrapper)
+from mmengine.registry import (DATA_SAMPLERS, DATASETS, EVALUATOR, HOOKS,
+ LOG_PROCESSORS, LOOPS, MODEL_WRAPPERS, MODELS,
+ OPTIM_WRAPPERS, PARAM_SCHEDULERS, RUNNERS,
+ VISUALIZERS, DefaultScope,
+ count_registered_modules)
+from mmengine.utils import digit_version, get_git_hash, is_seq_of
+from mmengine.utils.dl_utils import (TORCH_VERSION, collect_env,
+ set_multi_processing)
+from mmengine.visualization import Visualizer
+from .base_loop import BaseLoop
+from .checkpoint import (_load_checkpoint, _load_checkpoint_to_model,
+ find_latest_checkpoint, get_state_dict,
+ save_checkpoint, weights_to_cpu)
+from .log_processor import LogProcessor
+from .loops import EpochBasedTrainLoop, IterBasedTrainLoop, TestLoop, ValLoop
+from .priority import Priority, get_priority
+from .utils import set_random_seed
+
+ConfigType = Union[Dict, Config, ConfigDict]
+ParamSchedulerType = Union[List[_ParamScheduler], Dict[str,
+ List[_ParamScheduler]]]
+OptimWrapperType = Union[OptimWrapper, OptimWrapperDict]
+
+
+@RUNNERS.register_module()
+class Runner:
+ """A training helper for PyTorch.
+
+ Runner object can be built from config by ``runner = Runner.from_cfg(cfg)``
+ where the ``cfg`` usually contains training, validation, and test-related
+ configurations to build corresponding components. We usually use the
+ same config to launch training, testing, and validation tasks. However,
+ only some of these components are necessary at the same time, e.g.,
+ testing a model does not need training or validation-related components.
+
+ To avoid repeatedly modifying config, the construction of ``Runner`` adopts
+ lazy initialization to only initialize components when they are going to be
+ used. Therefore, the model is always initialized at the beginning, and
+ training, validation, and, testing related components are only initialized
+ when calling ``runner.train()``, ``runner.val()``, and ``runner.test()``,
+ respectively.
+
+ Args:
+ model (:obj:`torch.nn.Module` or dict): The model to be run. It can be
+ a dict used for build a model.
+ work_dir (str): The working directory to save checkpoints. The logs
+ will be saved in the subdirectory of `work_dir` named
+ :attr:`timestamp`.
+ train_dataloader (Dataloader or dict, optional): A dataloader object or
+ a dict to build a dataloader. If ``None`` is given, it means
+ skipping training steps. Defaults to None.
+ See :meth:`build_dataloader` for more details.
+ val_dataloader (Dataloader or dict, optional): A dataloader object or
+ a dict to build a dataloader. If ``None`` is given, it means
+ skipping validation steps. Defaults to None.
+ See :meth:`build_dataloader` for more details.
+ test_dataloader (Dataloader or dict, optional): A dataloader object or
+ a dict to build a dataloader. If ``None`` is given, it means
+ skipping test steps. Defaults to None.
+ See :meth:`build_dataloader` for more details.
+ train_cfg (dict, optional): A dict to build a training loop. If it does
+ not provide "type" key, it should contain "by_epoch" to decide
+ which type of training loop :class:`EpochBasedTrainLoop` or
+ :class:`IterBasedTrainLoop` should be used. If ``train_cfg``
+ specified, :attr:`train_dataloader` should also be specified.
+ Defaults to None. See :meth:`build_train_loop` for more details.
+ val_cfg (dict, optional): A dict to build a validation loop. If it does
+ not provide "type" key, :class:`ValLoop` will be used by default.
+ If ``val_cfg`` specified, :attr:`val_dataloader` should also be
+ specified. If ``ValLoop`` is built with `fp16=True``,
+ ``runner.val()`` will be performed under fp16 precision.
+ Defaults to None. See :meth:`build_val_loop` for more details.
+ test_cfg (dict, optional): A dict to build a test loop. If it does
+ not provide "type" key, :class:`TestLoop` will be used by default.
+ If ``test_cfg`` specified, :attr:`test_dataloader` should also be
+ specified. If ``ValLoop`` is built with `fp16=True``,
+ ``runner.val()`` will be performed under fp16 precision.
+ Defaults to None. See :meth:`build_test_loop` for more details.
+ auto_scale_lr (dict, Optional): Config to scale the learning rate
+ automatically. It includes ``base_batch_size`` and ``enable``.
+ ``base_batch_size`` is the batch size that the optimizer lr is
+ based on. ``enable`` is the switch to turn on and off the feature.
+ optim_wrapper (OptimWrapper or dict, optional):
+ Computing gradient of model parameters. If specified,
+ :attr:`train_dataloader` should also be specified. If automatic
+ mixed precision or gradient accmulation
+ training is required. The type of ``optim_wrapper`` should be
+ AmpOptimizerWrapper. See :meth:`build_optim_wrapper` for
+ examples. Defaults to None.
+ param_scheduler (_ParamScheduler or dict or list, optional):
+ Parameter scheduler for updating optimizer parameters. If
+ specified, :attr:`optimizer` should also be specified.
+ Defaults to None.
+ See :meth:`build_param_scheduler` for examples.
+ val_evaluator (Evaluator or dict or list, optional): A evaluator object
+ used for computing metrics for validation. It can be a dict or a
+ list of dict to build a evaluator. If specified,
+ :attr:`val_dataloader` should also be specified. Defaults to None.
+ test_evaluator (Evaluator or dict or list, optional): A evaluator
+ object used for computing metrics for test steps. It can be a dict
+ or a list of dict to build a evaluator. If specified,
+ :attr:`test_dataloader` should also be specified. Defaults to None.
+ default_hooks (dict[str, dict] or dict[str, Hook], optional): Hooks to
+ execute default actions like updating model parameters and saving
+ checkpoints. Default hooks are ``OptimizerHook``,
+ ``IterTimerHook``, ``LoggerHook``, ``ParamSchedulerHook`` and
+ ``CheckpointHook``. Defaults to None.
+ See :meth:`register_default_hooks` for more details.
+ custom_hooks (list[dict] or list[Hook], optional): Hooks to execute
+ custom actions like visualizing images processed by pipeline.
+ Defaults to None.
+ data_preprocessor (dict, optional): The pre-process config of
+ :class:`BaseDataPreprocessor`. If the ``model`` argument is a dict
+ and doesn't contain the key ``data_preprocessor``, set the argument
+ as the ``data_preprocessor`` of the ``model`` dict.
+ Defaults to None.
+ load_from (str, optional): The checkpoint file to load from.
+ Defaults to None.
+ resume (bool): Whether to resume training. Defaults to False. If
+ ``resume`` is True and ``load_from`` is None, automatically to
+ find latest checkpoint from ``work_dir``. If not found, resuming
+ does nothing.
+ launcher (str): Way to launcher multi-process. Supported launchers
+ are 'pytorch', 'mpi', 'slurm' and 'none'. If 'none' is provided,
+ non-distributed environment will be launched.
+ env_cfg (dict): A dict used for setting environment. Defaults to
+ dict(dist_cfg=dict(backend='nccl')).
+ log_processor (dict, optional): A processor to format logs. Defaults to
+ None.
+ log_level (int or str): The log level of MMLogger handlers.
+ Defaults to 'INFO'.
+ visualizer (Visualizer or dict, optional): A Visualizer object or a
+ dict build Visualizer object. Defaults to None. If not
+ specified, default config will be used.
+ default_scope (str): Used to reset registries location.
+ Defaults to "mmengine".
+ randomness (dict): Some settings to make the experiment as reproducible
+ as possible like seed and deterministic.
+ Defaults to ``dict(seed=None)``. If seed is None, a random number
+ will be generated and it will be broadcasted to all other processes
+ if in distributed environment. If ``cudnn_benchmarch`` is
+ ``True`` in ``env_cfg`` but ``deterministic`` is ``True`` in
+ ``randomness``, the value of ``torch.backends.cudnn.benchmark``
+ will be ``False`` finally.
+ experiment_name (str, optional): Name of current experiment. If not
+ specified, timestamp will be used as ``experiment_name``.
+ Defaults to None.
+ cfg (dict or Configdict or :obj:`Config`, optional): Full config.
+ Defaults to None.
+
+ Examples:
+ >>> from mmengine.runner import Runner
+ >>> cfg = dict(
+ >>> model=dict(type='ToyModel'),
+ >>> work_dir='path/of/work_dir',
+ >>> train_dataloader=dict(
+ >>> dataset=dict(type='ToyDataset'),
+ >>> sampler=dict(type='DefaultSampler', shuffle=True),
+ >>> batch_size=1,
+ >>> num_workers=0),
+ >>> val_dataloader=dict(
+ >>> dataset=dict(type='ToyDataset'),
+ >>> sampler=dict(type='DefaultSampler', shuffle=False),
+ >>> batch_size=1,
+ >>> num_workers=0),
+ >>> test_dataloader=dict(
+ >>> dataset=dict(type='ToyDataset'),
+ >>> sampler=dict(type='DefaultSampler', shuffle=False),
+ >>> batch_size=1,
+ >>> num_workers=0),
+ >>> auto_scale_lr=dict(base_batch_size=16, enable=False),
+ >>> optim_wrapper=dict(type='OptimizerWrapper', optimizer=dict(
+ >>> type='SGD', lr=0.01)),
+ >>> param_scheduler=dict(type='MultiStepLR', milestones=[1, 2]),
+ >>> val_evaluator=dict(type='ToyEvaluator'),
+ >>> test_evaluator=dict(type='ToyEvaluator'),
+ >>> train_cfg=dict(by_epoch=True, max_epochs=3, val_interval=1),
+ >>> val_cfg=dict(),
+ >>> test_cfg=dict(),
+ >>> custom_hooks=[],
+ >>> default_hooks=dict(
+ >>> timer=dict(type='IterTimerHook'),
+ >>> checkpoint=dict(type='CheckpointHook', interval=1),
+ >>> logger=dict(type='LoggerHook'),
+ >>> optimizer=dict(type='OptimizerHook', grad_clip=False),
+ >>> param_scheduler=dict(type='ParamSchedulerHook')),
+ >>> launcher='none',
+ >>> env_cfg=dict(dist_cfg=dict(backend='nccl')),
+ >>> log_processor=dict(window_size=20),
+ >>> visualizer=dict(type='Visualizer',
+ >>> vis_backends=[dict(type='LocalVisBackend',
+ >>> save_dir='temp_dir')])
+ >>> )
+ >>> runner = Runner.from_cfg(cfg)
+ >>> runner.train()
+ >>> runner.test()
+ """
+ cfg: Config
+ _train_loop: Optional[Union[BaseLoop, Dict]]
+ _val_loop: Optional[Union[BaseLoop, Dict]]
+ _test_loop: Optional[Union[BaseLoop, Dict]]
+
+ def __init__(
+ self,
+ model: Union[nn.Module, Dict],
+ work_dir: str,
+ train_dataloader: Optional[Union[DataLoader, Dict]] = None,
+ val_dataloader: Optional[Union[DataLoader, Dict]] = None,
+ test_dataloader: Optional[Union[DataLoader, Dict]] = None,
+ train_cfg: Optional[Dict] = None,
+ val_cfg: Optional[Dict] = None,
+ test_cfg: Optional[Dict] = None,
+ auto_scale_lr: Optional[Dict] = None,
+ optim_wrapper: Optional[Union[OptimWrapper, Dict]] = None,
+ param_scheduler: Optional[Union[_ParamScheduler, Dict, List]] = None,
+ val_evaluator: Optional[Union[Evaluator, Dict, List]] = None,
+ test_evaluator: Optional[Union[Evaluator, Dict, List]] = None,
+ default_hooks: Optional[Dict[str, Union[Hook, Dict]]] = None,
+ custom_hooks: Optional[List[Union[Hook, Dict]]] = None,
+ data_preprocessor: Union[nn.Module, Dict, None] = None,
+ load_from: Optional[str] = None,
+ resume: bool = False,
+ launcher: str = 'none',
+ env_cfg: Dict = dict(dist_cfg=dict(backend='nccl')),
+ log_processor: Optional[Dict] = None,
+ log_level: str = 'INFO',
+ visualizer: Optional[Union[Visualizer, Dict]] = None,
+ default_scope: str = 'mmengine',
+ randomness: Dict = dict(seed=None),
+ experiment_name: Optional[str] = None,
+ cfg: Optional[ConfigType] = None,
+ ):
+ self._work_dir = osp.abspath(work_dir)
+ mmengine.mkdir_or_exist(self._work_dir)
+
+ # recursively copy the `cfg` because `self.cfg` will be modified
+ # everywhere.
+ if cfg is not None:
+ if isinstance(cfg, Config):
+ self.cfg = copy.deepcopy(cfg)
+ elif isinstance(cfg, dict):
+ self.cfg = Config(cfg)
+ else:
+ self.cfg = Config(dict())
+
+ # lazy initialization
+ training_related = [train_dataloader, train_cfg, optim_wrapper]
+ if not (all(item is None for item in training_related)
+ or all(item is not None for item in training_related)):
+ raise ValueError(
+ 'train_dataloader, train_cfg, and optim_wrapper should be '
+ 'either all None or not None, but got '
+ f'train_dataloader={train_dataloader}, '
+ f'train_cfg={train_cfg}, '
+ f'optim_wrapper={optim_wrapper}.')
+ self._train_dataloader = train_dataloader
+ self._train_loop = train_cfg
+
+ self.optim_wrapper: Optional[Union[OptimWrapper, dict]]
+ self.optim_wrapper = optim_wrapper
+
+ self.auto_scale_lr = auto_scale_lr
+
+ # If there is no need to adjust learning rate, momentum or other
+ # parameters of optimizer, param_scheduler can be None
+ if param_scheduler is not None and self.optim_wrapper is None:
+ raise ValueError(
+ 'param_scheduler should be None when optim_wrapper is None, '
+ f'but got {param_scheduler}')
+
+ # Parse `param_scheduler` to a list or a dict. If `optim_wrapper` is a
+ # `dict` with single optimizer, parsed param_scheduler will be a
+ # list of parameter schedulers. If `optim_wrapper` is
+ # a `dict` with multiple optimizers, parsed `param_scheduler` will be
+ # dict with multiple list of parameter schedulers.
+ self._check_scheduler_cfg(param_scheduler)
+ self.param_schedulers = param_scheduler
+
+ val_related = [val_dataloader, val_cfg, val_evaluator]
+ if not (all(item is None
+ for item in val_related) or all(item is not None
+ for item in val_related)):
+ raise ValueError(
+ 'val_dataloader, val_cfg, and val_evaluator should be either '
+ 'all None or not None, but got '
+ f'val_dataloader={val_dataloader}, val_cfg={val_cfg}, '
+ f'val_evaluator={val_evaluator}')
+ self._val_dataloader = val_dataloader
+ self._val_loop = val_cfg
+ self._val_evaluator = val_evaluator
+
+ test_related = [test_dataloader, test_cfg, test_evaluator]
+ if not (all(item is None for item in test_related)
+ or all(item is not None for item in test_related)):
+ raise ValueError(
+ 'test_dataloader, test_cfg, and test_evaluator should be '
+ 'either all None or not None, but got '
+ f'test_dataloader={test_dataloader}, test_cfg={test_cfg}, '
+ f'test_evaluator={test_evaluator}')
+ self._test_dataloader = test_dataloader
+ self._test_loop = test_cfg
+ self._test_evaluator = test_evaluator
+
+ self._launcher = launcher
+ if self._launcher == 'none':
+ self._distributed = False
+ else:
+ self._distributed = True
+
+ # self._timestamp will be set in the `setup_env` method. Besides,
+ # it also will initialize multi-process and (or) distributed
+ # environment.
+ self.setup_env(env_cfg)
+ # self._deterministic and self._seed will be set in the
+ # `set_randomness`` method
+ self._randomness_cfg = randomness
+ self.set_randomness(**randomness)
+
+ if experiment_name is not None:
+ self._experiment_name = f'{experiment_name}_{self._timestamp}'
+ elif self.cfg.filename is not None:
+ filename_no_ext = osp.splitext(osp.basename(self.cfg.filename))[0]
+ self._experiment_name = f'{filename_no_ext}_{self._timestamp}'
+ else:
+ self._experiment_name = self.timestamp
+ self._log_dir = osp.join(self.work_dir, self.timestamp)
+ mmengine.mkdir_or_exist(self._log_dir)
+ # Used to reset registries location. See :meth:`Registry.build` for
+ # more details.
+ self.default_scope = DefaultScope.get_instance(
+ self._experiment_name, scope_name=default_scope)
+ # Build log processor to format message.
+ log_processor = dict() if log_processor is None else log_processor
+ self.log_processor = self.build_log_processor(log_processor)
+ # Since `get_instance` could return any subclass of ManagerMixin. The
+ # corresponding attribute needs a type hint.
+ self.logger = self.build_logger(log_level=log_level)
+
+ # Collect and log environment information.
+ self._log_env(env_cfg)
+
+ # collect information of all modules registered in the registries
+ registries_info = count_registered_modules(
+ self.work_dir if self.rank == 0 else None, verbose=False)
+ self.logger.debug(registries_info)
+
+ # Build `message_hub` for communication among components.
+ # `message_hub` can store log scalars (loss, learning rate) and
+ # runtime information (iter and epoch). Those components that do not
+ # have access to the runner can get iteration or epoch information
+ # from `message_hub`. For example, models can get the latest created
+ # `message_hub` by
+ # `self.message_hub=MessageHub.get_current_instance()` and then get
+ # current epoch by `cur_epoch = self.message_hub.get_info('epoch')`.
+ # See `MessageHub` and `ManagerMixin` for more details.
+ self.message_hub = self.build_message_hub()
+ # visualizer used for writing log or visualizing all kinds of data
+ self.visualizer = self.build_visualizer(visualizer)
+ if self.cfg:
+ self.visualizer.add_config(self.cfg)
+
+ self._load_from = load_from
+ self._resume = resume
+ # flag to mark whether checkpoint has been loaded or resumed
+ self._has_loaded = False
+
+ # build a model
+ if isinstance(model, dict) and data_preprocessor is not None:
+ # Merge the data_preprocessor to model config.
+ model.setdefault('data_preprocessor', data_preprocessor)
+ self.model = self.build_model(model)
+ # wrap model
+ self.model = self.wrap_model(
+ self.cfg.get('model_wrapper_cfg'), self.model)
+
+ # get model name from the model class
+ if hasattr(self.model, 'module'):
+ self._model_name = self.model.module.__class__.__name__
+ else:
+ self._model_name = self.model.__class__.__name__
+
+ self._hooks: List[Hook] = []
+ # register hooks to `self._hooks`
+ self.register_hooks(default_hooks, custom_hooks)
+ # log hooks information
+ self.logger.info(f'Hooks will be executed in the following '
+ f'order:\n{self.get_hooks_info()}')
+
+ # dump `cfg` to `work_dir`
+ self.dump_config()
+
+ @classmethod
+ def from_cfg(cls, cfg: ConfigType) -> 'Runner':
+ """Build a runner from config.
+
+ Args:
+ cfg (ConfigType): A config used for building runner. Keys of
+ ``cfg`` can see :meth:`__init__`.
+
+ Returns:
+ Runner: A runner build from ``cfg``.
+ """
+ cfg = copy.deepcopy(cfg)
+ runner = cls(
+ model=cfg['model'],
+ work_dir=cfg['work_dir'],
+ train_dataloader=cfg.get('train_dataloader'),
+ val_dataloader=cfg.get('val_dataloader'),
+ test_dataloader=cfg.get('test_dataloader'),
+ train_cfg=cfg.get('train_cfg'),
+ val_cfg=cfg.get('val_cfg'),
+ test_cfg=cfg.get('test_cfg'),
+ auto_scale_lr=cfg.get('auto_scale_lr'),
+ optim_wrapper=cfg.get('optim_wrapper'),
+ param_scheduler=cfg.get('param_scheduler'),
+ val_evaluator=cfg.get('val_evaluator'),
+ test_evaluator=cfg.get('test_evaluator'),
+ default_hooks=cfg.get('default_hooks'),
+ custom_hooks=cfg.get('custom_hooks'),
+ data_preprocessor=cfg.get('data_preprocessor'),
+ load_from=cfg.get('load_from'),
+ resume=cfg.get('resume', False),
+ launcher=cfg.get('launcher', 'none'),
+ env_cfg=cfg.get('env_cfg'), # type: ignore
+ log_processor=cfg.get('log_processor'),
+ log_level=cfg.get('log_level', 'INFO'),
+ visualizer=cfg.get('visualizer'),
+ default_scope=cfg.get('default_scope', 'mmengine'),
+ randomness=cfg.get('randomness', dict(seed=None)),
+ experiment_name=cfg.get('experiment_name'),
+ cfg=cfg,
+ )
+
+ return runner
+
+ @property
+ def experiment_name(self):
+ """str: Name of experiment."""
+ return self._experiment_name
+
+ @property
+ def model_name(self):
+ """str: Name of the model, usually the module class name."""
+ return self._model_name
+
+ @property
+ def work_dir(self):
+ """str: The working directory to save checkpoints and logs."""
+ return self._work_dir
+
+ @property
+ def log_dir(self):
+ return self._log_dir
+
+ @property
+ def max_epochs(self):
+ """int: Total epochs to train model."""
+ if isinstance(self.train_loop, BaseLoop):
+ return self.train_loop.max_epochs
+ else:
+ return 0
+
+ @property
+ def max_iters(self):
+ """int: Total iterations to train model."""
+ if isinstance(self.train_loop, BaseLoop):
+ return self.train_loop.max_iters
+ else:
+ return 0
+
+ @property
+ def epoch(self):
+ """int: Current epoch."""
+ if isinstance(self.train_loop, BaseLoop):
+ return self.train_loop.epoch
+ else:
+ return 0
+
+ @property
+ def iter(self):
+ """int: Current iteration."""
+ if isinstance(self.train_loop, BaseLoop):
+ return self.train_loop.iter
+ else:
+ return 0
+
+ @property
+ def launcher(self):
+ """str: Way to launcher multi processes."""
+ return self._launcher
+
+ @property
+ def distributed(self):
+ """bool: Whether current environment is distributed."""
+ return self._distributed
+
+ @property
+ def rank(self):
+ """int: Rank of current process."""
+ return self._rank
+
+ @property
+ def world_size(self):
+ """int: Number of processes participating in the job."""
+ return self._world_size
+
+ @property
+ def deterministic(self):
+ """int: Whether cudnn to select deterministic algorithms."""
+ return self._deterministic
+
+ @property
+ def seed(self):
+ """int: A number to set random modules."""
+ return self._seed
+
+ @property
+ def timestamp(self):
+ """str: Timestamp when creating experiment."""
+ return self._timestamp
+
+ @property
+ def hooks(self):
+ """list[:obj:`Hook`]: A list of registered hooks."""
+ return self._hooks
+
+ @property
+ def train_loop(self):
+ """:obj:`BaseLoop`: A loop to run training."""
+ if isinstance(self._train_loop, BaseLoop) or self._train_loop is None:
+ return self._train_loop
+ else:
+ self._train_loop = self.build_train_loop(self._train_loop)
+ return self._train_loop
+
+ @property
+ def val_loop(self):
+ """:obj:`BaseLoop`: A loop to run validation."""
+ if isinstance(self._val_loop, BaseLoop) or self._val_loop is None:
+ return self._val_loop
+ else:
+ self._val_loop = self.build_val_loop(self._val_loop)
+ return self._val_loop
+
+ @property
+ def test_loop(self):
+ """:obj:`BaseLoop`: A loop to run testing."""
+ if isinstance(self._test_loop, BaseLoop) or self._test_loop is None:
+ return self._test_loop
+ else:
+ self._test_loop = self.build_test_loop(self._test_loop)
+ return self._test_loop
+
+ @property
+ def train_dataloader(self):
+ """The data loader for training."""
+ return self.train_loop.dataloader
+
+ @property
+ def val_dataloader(self):
+ """The data loader for validation."""
+ return self.val_loop.dataloader
+
+ @property
+ def test_dataloader(self):
+ """The data loader for testing."""
+ return self.test_loop.dataloader
+
+ @property
+ def val_evaluator(self):
+ """:obj:`Evaluator`: An evaluator for validation."""
+ return self.val_loop.evaluator
+
+ @property
+ def test_evaluator(self):
+ """:obj:`Evaluator`: An evaluator for testing."""
+ return self.test_loop.evaluator
+
+ @property
+ def val_interval(self):
+ """int: Interval to run validation during training."""
+ return self.train_loop.val_interval
+
+ @property
+ def val_begin(self):
+ """int: The epoch/iteration to start running validation during
+ training."""
+ return self.train_loop.val_begin
+
+ def setup_env(self, env_cfg: Dict) -> None:
+ """Setup environment.
+
+ An example of ``env_cfg``::
+
+ env_cfg = dict(
+ cudnn_benchmark=True,
+ mp_cfg=dict(
+ mp_start_method='fork',
+ opencv_num_threads=0
+ ),
+ dist_cfg=dict(backend='nccl'),
+ resource_limit=4096
+ )
+
+ Args:
+ env_cfg (dict): Config for setting environment.
+ """
+ if env_cfg.get('cudnn_benchmark'):
+ torch.backends.cudnn.benchmark = True
+
+ mp_cfg: dict = env_cfg.get('mp_cfg', {})
+ set_multi_processing(**mp_cfg, distributed=self.distributed)
+
+ # init distributed env first, since logger depends on the dist info.
+ if self.distributed and not is_distributed():
+ dist_cfg: dict = env_cfg.get('dist_cfg', {})
+ init_dist(self.launcher, **dist_cfg)
+
+ self._rank, self._world_size = get_dist_info()
+
+ timestamp = torch.tensor(time.time(), dtype=torch.float64)
+ # broadcast timestamp from 0 process to other processes
+ broadcast(timestamp)
+ self._timestamp = time.strftime('%Y%m%d_%H%M%S',
+ time.localtime(timestamp.item()))
+
+ # https://github.com/pytorch/pytorch/issues/973
+ # set resource limit
+ if platform.system() != 'Windows':
+ import resource
+ rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)
+ base_soft_limit = rlimit[0]
+ hard_limit = rlimit[1]
+ soft_limit = min(
+ max(env_cfg.get('resource_limit', 4096), base_soft_limit),
+ hard_limit)
+ resource.setrlimit(resource.RLIMIT_NOFILE,
+ (soft_limit, hard_limit))
+
+ def set_randomness(self,
+ seed,
+ diff_rank_seed: bool = False,
+ deterministic: bool = False) -> None:
+ """Set random seed to guarantee reproducible results.
+
+ Args:
+ seed (int): A number to set random modules.
+ diff_rank_seed (bool): Whether or not set different seeds according
+ to global rank. Defaults to False.
+ deterministic (bool): Whether to set the deterministic option for
+ CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`
+ to True and `torch.backends.cudnn.benchmark` to False.
+ Defaults to False.
+ See https://pytorch.org/docs/stable/notes/randomness.html for
+ more details.
+ """
+ self._deterministic = deterministic
+ self._seed = set_random_seed(
+ seed=seed,
+ deterministic=deterministic,
+ diff_rank_seed=diff_rank_seed)
+
+ def build_logger(self,
+ log_level: Union[int, str] = 'INFO',
+ log_file: str = None,
+ **kwargs) -> MMLogger:
+ """Build a global asscessable MMLogger.
+
+ Args:
+ log_level (int or str): The log level of MMLogger handlers.
+ Defaults to 'INFO'.
+ log_file (str, optional): Path of filename to save log.
+ Defaults to None.
+ **kwargs: Remaining parameters passed to ``MMLogger``.
+
+ Returns:
+ MMLogger: A MMLogger object build from ``logger``.
+ """
+ if log_file is None:
+ log_file = osp.join(self._log_dir, f'{self.timestamp}.log')
+
+ log_cfg = dict(log_level=log_level, log_file=log_file, **kwargs)
+ log_cfg.setdefault('name', self._experiment_name)
+
+ return MMLogger.get_instance(**log_cfg) # type: ignore
+
+ def build_message_hub(self,
+ message_hub: Optional[Dict] = None) -> MessageHub:
+ """Build a global asscessable MessageHub.
+
+ Args:
+ message_hub (dict, optional): A dict to build MessageHub object.
+ If not specified, default config will be used to build
+ MessageHub object. Defaults to None.
+
+ Returns:
+ MessageHub: A MessageHub object build from ``message_hub``.
+ """
+ if message_hub is None:
+ message_hub = dict(name=self._experiment_name)
+ elif isinstance(message_hub, dict):
+ # ensure message_hub containing name key
+ message_hub.setdefault('name', self._experiment_name)
+ else:
+ raise TypeError(
+ f'message_hub should be dict or None, but got {message_hub}')
+
+ return MessageHub.get_instance(**message_hub)
+
+ def build_visualizer(
+ self,
+ visualizer: Optional[Union[Visualizer,
+ Dict]] = None) -> Visualizer:
+ """Build a global asscessable Visualizer.
+
+ Args:
+ visualizer (Visualizer or dict, optional): A Visualizer object
+ or a dict to build Visualizer object. If ``visualizer`` is a
+ Visualizer object, just returns itself. If not specified,
+ default config will be used to build Visualizer object.
+ Defaults to None.
+
+ Returns:
+ Visualizer: A Visualizer object build from ``visualizer``.
+ """
+ if visualizer is None:
+ visualizer = dict(
+ name=self._experiment_name,
+ vis_backends=[dict(type='LocalVisBackend')],
+ save_dir=self._log_dir)
+ return Visualizer.get_instance(**visualizer)
+
+ if isinstance(visualizer, Visualizer):
+ return visualizer
+
+ if isinstance(visualizer, dict):
+ # ensure visualizer containing name key
+ visualizer.setdefault('name', self._experiment_name)
+ visualizer.setdefault('save_dir', self._log_dir)
+ return VISUALIZERS.build(visualizer)
+ else:
+ raise TypeError(
+ 'visualizer should be Visualizer object, a dict or None, '
+ f'but got {visualizer}')
+
+ def build_model(self, model: Union[nn.Module, Dict]) -> nn.Module:
+ """Build model.
+
+ If ``model`` is a dict, it will be used to build a nn.Module object.
+ Else, if ``model`` is a nn.Module object it will be returned directly.
+
+ An example of ``model``::
+
+ model = dict(type='ResNet')
+
+ Args:
+ model (nn.Module or dict): A ``nn.Module`` object or a dict to
+ build nn.Module object. If ``model`` is a nn.Module object,
+ just returns itself.
+
+ Note:
+ The returned model must implement ``train_step``, ``test_step``
+ if ``runner.train`` or ``runner.test`` will be called. If
+ ``runner.val`` will be called or ``val_cfg`` is configured,
+ model must implement `val_step`.
+
+ Returns:
+ nn.Module: Model build from ``model``.
+ """
+ if isinstance(model, nn.Module):
+ return model
+ elif isinstance(model, dict):
+ model = MODELS.build(model)
+ return model # type: ignore
+ else:
+ raise TypeError('model should be a nn.Module object or dict, '
+ f'but got {model}')
+
+ def wrap_model(
+ self, model_wrapper_cfg: Optional[Dict],
+ model: nn.Module) -> Union[DistributedDataParallel, nn.Module]:
+ """Wrap the model to :obj:``MMDistributedDataParallel`` or other custom
+ distributed data-parallel module wrappers.
+
+ An example of ``model_wrapper_cfg``::
+
+ model_wrapper_cfg = dict(
+ broadcast_buffers=False,
+ find_unused_parameters=False
+ )
+
+ Args:
+ model_wrapper_cfg (dict, optional): Config to wrap model. If not
+ specified, ``DistributedDataParallel`` will be used in
+ distributed environment. Defaults to None.
+ model (nn.Module): Model to be wrapped.
+
+ Returns:
+ nn.Module or DistributedDataParallel: nn.Module or subclass of
+ ``DistributedDataParallel``.
+ """
+ if is_model_wrapper(model):
+ if model_wrapper_cfg is not None:
+ raise TypeError(
+ 'model has been wrapped and "model_wrapper_cfg" should be '
+ f'None, but got {model_wrapper_cfg}')
+
+ return model
+
+ # Set `export CUDA_VISIBLE_DEVICES=-1` to enable CPU training.
+ model = model.to(get_device())
+
+ if not self.distributed:
+ self.logger.info(
+ 'Distributed training is not used, all SyncBatchNorm (SyncBN) '
+ 'layers in the model will be automatically reverted to '
+ 'BatchNormXd layers if they are used.')
+ model = revert_sync_batchnorm(model)
+ return model # type: ignore
+ else:
+ sync_bn = self.cfg.get('sync_bn', None)
+ if sync_bn is not None:
+ try:
+ model = convert_sync_batchnorm(model, sync_bn)
+ except ValueError as e:
+ self.logger.error('cfg.sync_bn should be "torch" or '
+ f'"mmcv", but got {sync_bn}')
+ raise e
+ if model_wrapper_cfg is None:
+ find_unused_parameters = self.cfg.get('find_unused_parameters',
+ False)
+ # Sets the `find_unused_parameters` parameter in
+ # torch.nn.parallel.DistributedDataParallel
+ # TODO: may use a more elegant way to get local device ID.
+ model = MMDistributedDataParallel(
+ module=model,
+ device_ids=[int(os.environ['LOCAL_RANK'])],
+ broadcast_buffers=False,
+ find_unused_parameters=find_unused_parameters)
+ else:
+ model_wrapper_type = MODEL_WRAPPERS.get(
+ model_wrapper_cfg.get('type')) # type: ignore
+ default_args: dict = dict()
+ if issubclass(
+ model_wrapper_type, # type: ignore
+ DistributedDataParallel):
+ default_args['device_ids'] = [int(os.environ['LOCAL_RANK'])]
+ default_args['module'] = model
+ model = MODEL_WRAPPERS.build(
+ model_wrapper_cfg, default_args=default_args)
+ return model
+
+ def _init_model_weights(self) -> None:
+ """Initialize the model weights if the model has
+ :meth:`init_weights`"""
+ model = self.model.module if is_model_wrapper(
+ self.model) else self.model
+ if hasattr(model, 'init_weights'):
+ model.init_weights()
+ # sync params and buffers
+ for name, params in model.state_dict().items():
+ broadcast(params)
+
+ def scale_lr(self,
+ optim_wrapper: OptimWrapper,
+ auto_scale_lr: Optional[Dict] = None) -> None:
+ """Automatically scaling learning rate in training according to the
+ ratio of ``base_batch_size`` in ``autoscalelr_cfg`` and real batch
+ size.
+
+ It scales the learning rate linearly according to the
+ `paper `_.
+
+ Note:
+ ``scale_lr`` must be called after building optimizer wrappers
+ and before building parameter schedulers.
+
+ Args:
+ optim_wrapper (OptimWrapper): An OptimWrapper object whose
+ parameter groups' learning rate need to be scaled.
+ auto_scale_lr (Dict, Optional): Config to scale the learning
+ rate automatically. It includes ``base_batch_size`` and
+ ``enable``. ``base_batch_size`` is the batch size that the
+ optimizer lr is based on. ``enable`` is the switch to turn on
+ and off the feature.
+ """
+ if (auto_scale_lr is None or not auto_scale_lr.get('enable', False)):
+ return None
+
+ assert 'base_batch_size' in auto_scale_lr, \
+ 'Lack of `base_batch_size` in `auto_scale_lr`.'
+ dataloader: Union[DataLoader, Dict] = self._train_dataloader
+ bs = dataloader.batch_size if isinstance(
+ dataloader, DataLoader) else dataloader['batch_size']
+ real_bs = self.world_size * bs
+ base_bs = auto_scale_lr['base_batch_size']
+ ratio = float(real_bs) / float(base_bs)
+ self.logger.info(f'LR is set based on batch size of {base_bs} '
+ f'and the current batch size is {real_bs}. '
+ f'Scaling the original LR by {ratio}.')
+
+ def _is_built(schedulers):
+ if isinstance(schedulers, dict):
+ return False if 'type' in schedulers else any(
+ _is_built(s) for s in schedulers.values())
+ if isinstance(schedulers, list):
+ return any(_is_built(s) for s in schedulers)
+ return isinstance(schedulers, _ParamScheduler)
+
+ if _is_built(self.param_schedulers):
+ raise RuntimeError('`scale_lr` should be called before building '
+ 'ParamScheduler because ParamScheduler will '
+ 'store initial lr from optimizer wrappers')
+
+ assert isinstance(optim_wrapper, OptimWrapper), \
+ '`scale_lr should be called after building OptimWrapper'
+ wrappers = list(optim_wrapper.values()) if isinstance(
+ optim_wrapper, OptimWrapperDict) else [optim_wrapper]
+ for wrapper in wrappers:
+ for group in wrapper.optimizer.param_groups:
+ group['lr'] = group['lr'] * ratio
+
+ def build_optim_wrapper(
+ self, optim_wrapper: Union[Optimizer, OptimWrapper, Dict]
+ ) -> Union[OptimWrapper, OptimWrapperDict]:
+ """Build optimizer wrapper.
+
+ If ``optim_wrapper`` is a config dict for only one optimizer,
+ the keys must contain ``optimizer``, and ``type`` is optional.
+ It will build a :obj:`OptimWrapper` by default.
+
+ If ``optim_wrapper`` is a config dict for multiple optimizers, i.e.,
+ it has multiple keys and each key is for an optimizer wrapper. The
+ constructor must be specified since
+ :obj:`DefaultOptimizerConstructor` cannot handle the building of
+ training with multiple optimizers.
+
+ If ``optim_wrapper`` is a dict of pre-built optimizer wrappers, i.e.,
+ each value of ``optim_wrapper`` represents an ``OptimWrapper``
+ instance. ``build_optim_wrapper`` will directly build the
+ :obj:`OptimWrapperDict` instance from ``optim_wrapper``.
+
+ Args:
+ optim_wrapper (OptimWrapper or dict): An OptimWrapper object or a
+ dict to build OptimWrapper objects. If ``optim_wrapper`` is an
+ OptimWrapper, just return an ``OptimizeWrapper`` instance.
+
+ Note:
+ For single optimizer training, if `optim_wrapper` is a config
+ dict, `type` is optional(defaults to :obj:`OptimWrapper`) and it
+ must contain `optimizer` to build the corresponding optimizer.
+
+ Examples:
+ >>> # build an optimizer
+ >>> optim_wrapper_cfg = dict(type='OptimWrapper', optimizer=dict(
+ ... type='SGD', lr=0.01))
+ >>> # optim_wrapper_cfg = dict(optimizer=dict(type='SGD', lr=0.01))
+ >>> # is also valid.
+ >>> optim_wrapper = runner.build_optim_wrapper(optim_wrapper_cfg)
+ >>> optim_wrapper
+ Type: OptimWrapper
+ accumulative_counts: 1
+ optimizer:
+ SGD (
+ Parameter Group 0
+ dampening: 0
+ lr: 0.01
+ momentum: 0
+ nesterov: False
+ weight_decay: 0
+ )
+ >>> # build optimizer without `type`
+ >>> optim_wrapper_cfg = dict(optimizer=dict(type='SGD', lr=0.01))
+ >>> optim_wrapper = runner.build_optim_wrapper(optim_wrapper_cfg)
+ >>> optim_wrapper
+ Type: OptimWrapper
+ accumulative_counts: 1
+ optimizer:
+ SGD (
+ Parameter Group 0
+ dampening: 0
+ lr: 0.01
+ maximize: False
+ momentum: 0
+ nesterov: False
+ weight_decay: 0
+ )
+ >>> # build multiple optimizers
+ >>> optim_wrapper_cfg = dict(
+ ... generator=dict(type='OptimWrapper', optimizer=dict(
+ ... type='SGD', lr=0.01)),
+ ... discriminator=dict(type='OptimWrapper', optimizer=dict(
+ ... type='Adam', lr=0.001))
+ ... # need to customize a multiple optimizer constructor
+ ... constructor='CustomMultiOptimizerConstructor',
+ ...)
+ >>> optim_wrapper = runner.optim_wrapper(optim_wrapper_cfg)
+ >>> optim_wrapper
+ name: generator
+ Type: OptimWrapper
+ accumulative_counts: 1
+ optimizer:
+ SGD (
+ Parameter Group 0
+ dampening: 0
+ lr: 0.1
+ momentum: 0
+ nesterov: False
+ weight_decay: 0
+ )
+ name: discriminator
+ Type: OptimWrapper
+ accumulative_counts: 1
+ optimizer:
+ 'discriminator': Adam (
+ Parameter Group 0
+ dampening: 0
+ lr: 0.02
+ momentum: 0
+ nesterov: False
+ weight_decay: 0
+ )
+
+ Important:
+ If you need to build multiple optimizers, you should implement a
+ MultiOptimWrapperConstructor which gets parameters passed to
+ corresponding optimizers and compose the ``OptimWrapperDict``.
+ More details about how to customize OptimizerConstructor can be
+ found at `optimizer-docs `_.
+
+ Returns:
+ OptimWrapper: Optimizer wrapper build from ``optimizer_cfg``.
+ """ # noqa: E501
+ if isinstance(optim_wrapper, OptimWrapper):
+ return optim_wrapper
+ if isinstance(optim_wrapper, (dict, ConfigDict, Config)):
+ # optimizer must be defined for single optimizer training.
+ optimizer = optim_wrapper.get('optimizer', None)
+
+ # If optimizer is a built `Optimizer` instance, the optimizer
+ # wrapper should be built by `OPTIM_WRAPPERS` registry.
+ if isinstance(optimizer, Optimizer):
+ optim_wrapper.setdefault('type', 'OptimWrapper')
+ return OPTIM_WRAPPERS.build(optim_wrapper) # type: ignore
+
+ # If `optimizer` is not None or `constructor` is defined, it means,
+ # optimizer wrapper will be built by optimizer wrapper
+ # constructor. Therefore, `build_optim_wrapper` should be called.
+ if optimizer is not None or 'constructor' in optim_wrapper:
+ return build_optim_wrapper(self.model, optim_wrapper)
+ else:
+ # if `optimizer` is not defined, it should be the case of
+ # training with multiple optimizers. If `constructor` is not
+ # defined either, Each value of `optim_wrapper` must be an
+ # `OptimWrapper` instance since `DefaultOptimizerConstructor`
+ # will not handle the case of training with multiple
+ # optimizers. `build_optim_wrapper` will directly build the
+ # `OptimWrapperDict` instance from `optim_wrapper.`
+ optim_wrappers = OrderedDict()
+ for name, optim in optim_wrapper.items():
+ if not isinstance(optim, OptimWrapper):
+ raise ValueError(
+ 'each item mush be an optimizer object when '
+ '"type" and "constructor" are not in '
+ f'optimizer, but got {name}={optim}')
+ optim_wrappers[name] = optim
+ return OptimWrapperDict(**optim_wrappers)
+ else:
+ raise TypeError('optimizer wrapper should be an OptimWrapper '
+ f'object or dict, but got {optim_wrapper}')
+
+ def _build_param_scheduler(
+ self, scheduler: Union[_ParamScheduler, Dict, List],
+ optim_wrapper: OptimWrapper) -> List[_ParamScheduler]:
+ """Build parameter schedulers for a single optimizer.
+
+ Args:
+ scheduler (_ParamScheduler or dict or list): A Param Scheduler
+ object or a dict or list of dict to build parameter schedulers.
+ optim_wrapper (OptimWrapper): An optimizer wrapper object is
+ passed to construct ParamScheduler object.
+
+ Returns:
+ list[_ParamScheduler]: List of parameter schedulers build from
+ ``scheduler``.
+
+ Note:
+ If the train loop is built, when building parameter schedulers,
+ it supports setting the max epochs/iters as the default ``end``
+ of schedulers, and supports converting epoch-based schedulers
+ to iter-based according to the ``convert_to_iter_based`` key.
+ """
+ if not isinstance(scheduler, Sequence):
+ schedulers = [scheduler]
+ else:
+ schedulers = scheduler
+
+ param_schedulers = []
+ for scheduler in schedulers:
+ if isinstance(scheduler, _ParamScheduler):
+ param_schedulers.append(scheduler)
+ elif isinstance(scheduler, dict):
+ _scheduler = copy.deepcopy(scheduler)
+
+ # Set default end
+ if isinstance(self._train_loop, BaseLoop):
+ default_end = self.max_epochs if _scheduler.get(
+ 'by_epoch', True) else self.max_iters
+ _scheduler.setdefault('end', default_end)
+ self.logger.debug(
+ f'The `end` of {_scheduler["type"]} is not set. '
+ 'Use the max epochs/iters of train loop as default.')
+
+ param_schedulers.append(
+ PARAM_SCHEDULERS.build(
+ _scheduler,
+ default_args=dict(
+ optimizer=optim_wrapper,
+ epoch_length=len(self.train_dataloader))))
+ else:
+ raise TypeError(
+ 'scheduler should be a _ParamScheduler object or dict, '
+ f'but got {scheduler}')
+ return param_schedulers
+
+ def build_param_scheduler(
+ self, scheduler: Union[_ParamScheduler, Dict,
+ List]) -> ParamSchedulerType:
+ """Build parameter schedulers.
+
+ ``build_param_scheduler`` should be called after
+ ``build_optim_wrapper`` because the building logic will change
+ according to the number of optimizers built by the runner.
+ The cases are as below:
+
+ - Single optimizer: When only one optimizer is built and used in the
+ runner, ``build_param_scheduler`` will return a list of
+ parameter schedulers.
+ - Multiple optimizers: When two or more optimizers are built and used
+ in runner, ``build_param_scheduler`` will return a dict containing
+ the same keys with multiple optimizers and each value is a list of
+ parameter schedulers. Note that, if you want different optimizers to
+ use different parameter shedulers to update optimizer's
+ hyper-parameters, the input parameter ``scheduler`` also needs to be
+ a dict and its key are consistent with multiple optimizers.
+ Otherwise, the same parameter schedulers will be used to update
+ optimizer's hyper-parameters.
+
+ Args:
+ scheduler (_ParamScheduler or dict or list): A Param Scheduler
+ object or a dict or list of dict to build parameter schedulers.
+
+ Examples:
+ >>> # build one scheduler
+ >>> optim_cfg = dict(dict(type='SGD', lr=0.01))
+ >>> runner.optim_wrapper = runner.build_optim_wrapper(
+ >>> optim_cfg)
+ >>> scheduler_cfg = dict(type='MultiStepLR', milestones=[1, 2])
+ >>> schedulers = runner.build_param_scheduler(scheduler_cfg)
+ >>> schedulers
+ [] # noqa: E501
+
+ >>> # build multiple schedulers
+ >>> scheduler_cfg = [
+ ... dict(type='MultiStepLR', milestones=[1, 2]),
+ ... dict(type='StepLR', step_size=1)
+ ... ]
+ >>> schedulers = runner.build_param_scheduler(scheduler_cfg)
+ >>> schedulers
+ [, # noqa: E501
+ ]
+
+ Above examples only provide the case of one optimizer and one scheduler
+ or multiple shedulers. If you want to know how to set parameter
+ scheduler when using multiple optimizers, you can find more examples
+ `optimizer-docs`_.
+
+ Returns:
+ list[_ParamScheduler] or dict[str, list[_ParamScheduler]]: List of
+ parameter schedulers or a dictionary contains list of parameter
+ schedulers build from ``scheduler``.
+
+ .. _optimizer-docs:
+ https://mmengine.readthedocs.io/en/latest/tutorials/optimizer.html
+ """
+ param_schedulers: ParamSchedulerType
+ if not isinstance(self.optim_wrapper, OptimWrapperDict):
+ # Since `OptimWrapperDict` inherits from `OptimWrapper`,
+ # `isinstance(self.optim_wrapper, OptimWrapper)` cannot tell
+ # whether `self.optim_wrapper` is an `OptimizerWrapper` or
+ # `OptimWrapperDict` instance. Therefore, here we simply check
+ # self.optim_wrapper is not an `OptimWrapperDict` instance and
+ # then assert it is an OptimWrapper instance.
+ assert isinstance(self.optim_wrapper, OptimWrapper), (
+ '`build_optimizer` should be called before'
+ '`build_param_scheduler` because the latter depends '
+ 'on the former')
+ param_schedulers = self._build_param_scheduler(
+ scheduler, self.optim_wrapper) # type: ignore
+ return param_schedulers
+ else:
+ param_schedulers = dict()
+ for name, optimizer in self.optim_wrapper.items():
+ if isinstance(scheduler, dict) and 'type' not in scheduler:
+ # scheduler is a dict and each item is a ParamScheduler
+ # object or a config to build ParamScheduler objects
+ param_schedulers[name] = self._build_param_scheduler(
+ scheduler[name], optimizer)
+ else:
+ param_schedulers[name] = self._build_param_scheduler(
+ scheduler, optimizer)
+
+ return param_schedulers
+
+ def build_evaluator(self, evaluator: Union[Dict, List,
+ Evaluator]) -> Evaluator:
+ """Build evaluator.
+
+ Examples of ``evaluator``::
+
+ # evaluator could be a built Evaluator instance
+ evaluator = Evaluator(metrics=[ToyMetric()])
+
+ # evaluator can also be a list of dict
+ evaluator = [
+ dict(type='ToyMetric1'),
+ dict(type='ToyEvaluator2')
+ ]
+
+ # evaluator can also be a list of built metric
+ evaluator = [ToyMetric1(), ToyMetric2()]
+
+ # evaluator can also be a dict with key metrics
+ evaluator = dict(metrics=ToyMetric())
+ # metric is a list
+ evaluator = dict(metrics=[ToyMetric()])
+
+ Args:
+ evaluator (Evaluator or dict or list): An Evaluator object or a
+ config dict or list of config dict used to build an Evaluator.
+
+ Returns:
+ Evaluator: Evaluator build from ``evaluator``.
+ """
+ if isinstance(evaluator, Evaluator):
+ return evaluator
+ elif isinstance(evaluator, dict):
+ # if `metrics` in dict keys, it means to build customized evalutor
+ if 'metrics' in evaluator:
+ evaluator.setdefault('type', 'Evaluator')
+ return EVALUATOR.build(evaluator)
+ # otherwise, default evalutor will be built
+ else:
+ return Evaluator(evaluator) # type: ignore
+ elif isinstance(evaluator, list):
+ # use the default `Evaluator`
+ return Evaluator(evaluator) # type: ignore
+ else:
+ raise TypeError(
+ 'evaluator should be one of dict, list of dict, and Evaluator'
+ f', but got {evaluator}')
+
+ @staticmethod
+ def build_dataloader(dataloader: Union[DataLoader, Dict],
+ seed: Optional[int] = None,
+ diff_rank_seed: bool = False) -> DataLoader:
+ """Build dataloader.
+
+ The method builds three components:
+
+ - Dataset
+ - Sampler
+ - Dataloader
+
+ An example of ``dataloader``::
+
+ dataloader = dict(
+ dataset=dict(type='ToyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ batch_size=1,
+ num_workers=9
+ )
+
+ Args:
+ dataloader (DataLoader or dict): A Dataloader object or a dict to
+ build Dataloader object. If ``dataloader`` is a Dataloader
+ object, just returns itself.
+ seed (int, optional): Random seed. Defaults to None.
+ diff_rank_seed (bool): Whether or not set different seeds to
+ different ranks. If True, the seed passed to sampler is set
+ to None, in order to synchronize the seeds used in samplers
+ across different ranks.
+
+
+ Returns:
+ Dataloader: DataLoader build from ``dataloader_cfg``.
+ """
+ if isinstance(dataloader, DataLoader):
+ return dataloader
+
+ dataloader_cfg = copy.deepcopy(dataloader)
+
+ # build dataset
+ dataset_cfg = dataloader_cfg.pop('dataset')
+ if isinstance(dataset_cfg, dict):
+ dataset = DATASETS.build(dataset_cfg)
+ if hasattr(dataset, 'full_init'):
+ dataset.full_init()
+ else:
+ # fallback to raise error in dataloader
+ # if `dataset_cfg` is not a valid type
+ dataset = dataset_cfg
+
+ # build sampler
+ sampler_cfg = dataloader_cfg.pop('sampler')
+ if isinstance(sampler_cfg, dict):
+ sampler_seed = None if diff_rank_seed else seed
+ sampler = DATA_SAMPLERS.build(
+ sampler_cfg,
+ default_args=dict(dataset=dataset, seed=sampler_seed))
+ else:
+ # fallback to raise error in dataloader
+ # if `sampler_cfg` is not a valid type
+ sampler = sampler_cfg
+
+ # build batch sampler
+ batch_sampler_cfg = dataloader_cfg.pop('batch_sampler', None)
+ if batch_sampler_cfg is None:
+ batch_sampler = None
+ elif isinstance(batch_sampler_cfg, dict):
+ batch_sampler = DATA_SAMPLERS.build(
+ batch_sampler_cfg,
+ default_args=dict(
+ sampler=sampler,
+ batch_size=dataloader_cfg.pop('batch_size')))
+ else:
+ # fallback to raise error in dataloader
+ # if `batch_sampler_cfg` is not a valid type
+ batch_sampler = batch_sampler_cfg
+
+ # build dataloader
+ init_fn: Optional[partial]
+ if seed is not None:
+ init_fn = partial(
+ worker_init_fn,
+ num_workers=dataloader_cfg.get('num_workers'),
+ rank=get_rank(),
+ seed=seed)
+ else:
+ init_fn = None
+
+ # `persistent_workers` requires pytorch version >= 1.7
+ if ('persistent_workers' in dataloader_cfg
+ and digit_version(TORCH_VERSION) < digit_version('1.7.0')):
+ warnings.warn('`persistent_workers` is only available when '
+ 'pytorch version >= 1.7')
+ dataloader_cfg.pop('persistent_workers')
+
+ # The default behavior of `collat_fn` in dataloader is to
+ # merge a list of samples to form a mini-batch of Tensor(s).
+ # However, in mmengine, if `collate_fn` is not defined in
+ # dataloader_cfg, `pseudo_collate` will only convert the list of
+ # samples into a dict without stacking the batch tensor.
+ collate_fn_cfg = dataloader_cfg.pop('collate_fn',
+ dict(type='pseudo_collate'))
+ collate_fn_type = collate_fn_cfg.pop('type')
+ collate_fn = COLLATE_FUNCTIONS.get(collate_fn_type)
+ collate_fn = partial(collate_fn, **collate_fn_cfg) # type: ignore
+ data_loader = DataLoader(
+ dataset=dataset,
+ sampler=sampler if batch_sampler is None else None,
+ batch_sampler=batch_sampler,
+ collate_fn=collate_fn,
+ worker_init_fn=init_fn,
+ **dataloader_cfg)
+ return data_loader
+
+ def build_train_loop(self, loop: Union[BaseLoop, Dict]) -> BaseLoop:
+ """Build training loop.
+
+ Examples of ``loop``::
+
+ # `EpochBasedTrainLoop` will be used
+ loop = dict(by_epoch=True, max_epochs=3)
+
+ # `IterBasedTrainLoop` will be used
+ loop = dict(by_epoch=False, max_epochs=3)
+
+ # custom training loop
+ loop = dict(type='CustomTrainLoop', max_epochs=3)
+
+ Args:
+ loop (BaseLoop or dict): A training loop or a dict to build
+ training loop. If ``loop`` is a training loop object, just
+ returns itself.
+
+ Returns:
+ :obj:`BaseLoop`: Training loop object build from ``loop``.
+ """
+ if isinstance(loop, BaseLoop):
+ return loop
+ elif not isinstance(loop, dict):
+ raise TypeError(
+ f'loop should be a Loop object or dict, but got {loop}')
+
+ loop_cfg = copy.deepcopy(loop)
+
+ if 'type' in loop_cfg and 'by_epoch' in loop_cfg:
+ raise RuntimeError(
+ 'Only one of `type` or `by_epoch` can exist in `loop_cfg`.')
+
+ if 'type' in loop_cfg:
+ loop = LOOPS.build(
+ loop_cfg,
+ default_args=dict(
+ runner=self, dataloader=self._train_dataloader))
+ else:
+ by_epoch = loop_cfg.pop('by_epoch')
+ if by_epoch:
+ loop = EpochBasedTrainLoop(
+ **loop_cfg, runner=self, dataloader=self._train_dataloader)
+ else:
+ loop = IterBasedTrainLoop(
+ **loop_cfg, runner=self, dataloader=self._train_dataloader)
+ return loop # type: ignore
+
+ def build_val_loop(self, loop: Union[BaseLoop, Dict]) -> BaseLoop:
+ """Build validation loop.
+
+ Examples of ``loop``:
+
+ # `ValLoop` will be used
+ loop = dict()
+
+ # custom validation loop
+ loop = dict(type='CustomValLoop')
+
+ Args:
+ loop (BaseLoop or dict): A validation loop or a dict to build
+ validation loop. If ``loop`` is a validation loop object, just
+ returns itself.
+
+ Returns:
+ :obj:`BaseLoop`: Validation loop object build from ``loop``.
+ """
+ if isinstance(loop, BaseLoop):
+ return loop
+ elif not isinstance(loop, dict):
+ raise TypeError(
+ f'train_loop should be a Loop object or dict, but got {loop}')
+
+ loop_cfg = copy.deepcopy(loop)
+
+ if 'type' in loop_cfg:
+ loop = LOOPS.build(
+ loop_cfg,
+ default_args=dict(
+ runner=self,
+ dataloader=self._val_dataloader,
+ evaluator=self._val_evaluator))
+ else:
+ loop = ValLoop(
+ **loop_cfg,
+ runner=self,
+ dataloader=self._val_dataloader,
+ evaluator=self._val_evaluator) # type: ignore
+
+ return loop # type: ignore
+
+ def build_test_loop(self, loop: Union[BaseLoop, Dict]) -> BaseLoop:
+ """Build test loop.
+
+ Examples of ``loop``::
+
+ # `TestLoop` will be used
+ loop = dict()
+
+ # custom test loop
+ loop = dict(type='CustomTestLoop')
+
+ Args:
+ loop (BaseLoop or dict): A test loop or a dict to build test loop.
+ If ``loop`` is a test loop object, just returns itself.
+
+ Returns:
+ :obj:`BaseLoop`: Test loop object build from ``loop_cfg``.
+ """
+ if isinstance(loop, BaseLoop):
+ return loop
+ elif not isinstance(loop, dict):
+ raise TypeError(
+ f'train_loop should be a Loop object or dict, but got {loop}')
+
+ loop_cfg = copy.deepcopy(loop) # type: ignore
+
+ if 'type' in loop_cfg:
+ loop = LOOPS.build(
+ loop_cfg,
+ default_args=dict(
+ runner=self,
+ dataloader=self._test_dataloader,
+ evaluator=self._test_evaluator))
+ else:
+ loop = TestLoop(
+ **loop_cfg,
+ runner=self,
+ dataloader=self._test_dataloader,
+ evaluator=self._test_evaluator) # type: ignore
+
+ return loop # type: ignore
+
+ def build_log_processor(
+ self, log_processor: Union[LogProcessor, Dict]) -> LogProcessor:
+ """Build test log_processor.
+
+ Examples of ``log_processor``:
+
+ # `LogProcessor` will be used
+ log_processor = dict()
+
+ # custom log_processor
+ log_processor = dict(type='CustomLogProcessor')
+
+ Args:
+ log_processor (LogProcessor or dict): A log processor or a dict
+ to build log processor. If ``log_processor`` is a log processor
+ object, just returns itself.
+
+ Returns:
+ :obj:`LogProcessor`: Log processor object build from
+ ``log_processor_cfg``.
+ """
+ if isinstance(log_processor, LogProcessor):
+ return log_processor
+ elif not isinstance(log_processor, dict):
+ raise TypeError(
+ 'log processor should be a LogProcessor object or dict, but'
+ f'got {log_processor}')
+
+ log_processor_cfg = copy.deepcopy(log_processor) # type: ignore
+
+ if 'type' in log_processor_cfg:
+ log_processor = LOG_PROCESSORS.build(log_processor_cfg)
+ else:
+ log_processor = LogProcessor(**log_processor_cfg) # type: ignore
+
+ return log_processor # type: ignore
+
+ def get_hooks_info(self) -> str:
+ # Get hooks info in each stage
+ stage_hook_map: Dict[str, list] = {stage: [] for stage in Hook.stages}
+ for hook in self.hooks:
+ try:
+ priority = Priority(hook.priority).name # type: ignore
+ except ValueError:
+ priority = hook.priority # type: ignore
+ classname = hook.__class__.__name__
+ hook_info = f'({priority:<12}) {classname:<35}'
+ for trigger_stage in hook.get_triggered_stages():
+ stage_hook_map[trigger_stage].append(hook_info)
+
+ stage_hook_infos = []
+ for stage in Hook.stages:
+ hook_infos = stage_hook_map[stage]
+ if len(hook_infos) > 0:
+ info = f'{stage}:\n'
+ info += '\n'.join(hook_infos)
+ info += '\n -------------------- '
+ stage_hook_infos.append(info)
+ return '\n'.join(stage_hook_infos)
+
+ def load_or_resume(self) -> None:
+ """load or resume checkpoint."""
+ if self._has_loaded:
+ return None
+
+ # decide to load from checkpoint or resume from checkpoint
+ resume_from = None
+ if self._resume and self._load_from is None:
+ # auto resume from the latest checkpoint
+ resume_from = find_latest_checkpoint(self.work_dir)
+ self.logger.info(
+ f'Auto resumed from the latest checkpoint {resume_from}.')
+ elif self._resume and self._load_from is not None:
+ # resume from the specified checkpoint
+ resume_from = self._load_from
+
+ if resume_from is not None:
+ self.resume(resume_from)
+ self._has_loaded = True
+ elif self._load_from is not None:
+ self.load_checkpoint(self._load_from)
+ self._has_loaded = True
+
+ def train(self) -> nn.Module:
+ """Launch training.
+
+ Returns:
+ nn.Module: The model after training.
+ """
+ if is_model_wrapper(self.model):
+ ori_model = self.model.module
+ else:
+ ori_model = self.model
+ assert hasattr(ori_model, 'train_step'), (
+ 'If you want to train your model, please make sure your model '
+ 'has implemented `train_step`.')
+
+ if self._val_loop is not None:
+ assert hasattr(ori_model, 'val_step'), (
+ 'If you want to validate your model, please make sure your '
+ 'model has implemented `val_step`.')
+
+ if self._train_loop is None:
+ raise RuntimeError(
+ '`self._train_loop` should not be None when calling train '
+ 'method. Please provide `train_dataloader`, `train_cfg`, '
+ '`optimizer` and `param_scheduler` arguments when '
+ 'initializing runner.')
+
+ self._train_loop = self.build_train_loop(
+ self._train_loop) # type: ignore
+
+ # `build_optimizer` should be called before `build_param_scheduler`
+ # because the latter depends on the former
+ self.optim_wrapper = self.build_optim_wrapper(self.optim_wrapper)
+ # Automatically scaling lr by linear scaling rule
+ self.scale_lr(self.optim_wrapper, self.auto_scale_lr)
+
+ if self.param_schedulers is not None:
+ self.param_schedulers = self.build_param_scheduler( # type: ignore
+ self.param_schedulers) # type: ignore
+
+ if self._val_loop is not None:
+ self._val_loop = self.build_val_loop(
+ self._val_loop) # type: ignore
+ # TODO: add a contextmanager to avoid calling `before_run` many times
+ self.call_hook('before_run')
+
+ # initialize the model weights
+ self._init_model_weights()
+ # make sure checkpoint-related hooks are triggered after `before_run`
+ self.load_or_resume()
+
+ # Initiate inner count of `optim_wrapper`.
+ self.optim_wrapper.initialize_count_status(
+ self.model,
+ self._train_loop.iter, # type: ignore
+ self._train_loop.max_iters) # type: ignore
+
+ model = self.train_loop.run() # type: ignore
+ self.call_hook('after_run')
+ return model
+
+ def val(self) -> dict:
+ """Launch validation.
+
+ Returns:
+ dict: A dict of metrics on validation set.
+ """
+ if self._val_loop is None:
+ raise RuntimeError(
+ '`self._val_loop` should not be None when calling val method.'
+ 'Please provide `val_dataloader`, `val_cfg` and '
+ '`val_evaluator` arguments when initializing runner.')
+
+ self._val_loop = self.build_val_loop(self._val_loop) # type: ignore
+
+ self.call_hook('before_run')
+
+ # make sure checkpoint-related hooks are triggered after `before_run`
+ self.load_or_resume()
+
+ metrics = self.val_loop.run() # type: ignore
+ self.call_hook('after_run')
+ return metrics
+
+ def test(self) -> dict:
+ """Launch test.
+
+ Returns:
+ dict: A dict of metrics on testing set.
+ """
+ if self._test_loop is None:
+ raise RuntimeError(
+ '`self._test_loop` should not be None when calling test '
+ 'method. Please provide `test_dataloader`, `test_cfg` and '
+ '`test_evaluator` arguments when initializing runner.')
+
+ self._test_loop = self.build_test_loop(self._test_loop) # type: ignore
+
+ self.call_hook('before_run')
+
+ # make sure checkpoint-related hooks are triggered after `before_run`
+ self.load_or_resume()
+
+ metrics = self.test_loop.run() # type: ignore
+ self.call_hook('after_run')
+ return metrics
+
+ def call_hook(self, fn_name: str, **kwargs) -> None:
+ """Call all hooks.
+
+ Args:
+ fn_name (str): The function name in each hook to be called, such as
+ "before_train_epoch".
+ **kwargs: Keyword arguments passed to hook.
+ """
+ for hook in self._hooks:
+ # support adding additional custom hook methods
+ if hasattr(hook, fn_name):
+ try:
+ getattr(hook, fn_name)(self, **kwargs)
+ except TypeError as e:
+ raise TypeError(f'{e} in {hook}') from None
+
+ def register_hook(
+ self,
+ hook: Union[Hook, Dict],
+ priority: Optional[Union[str, int, Priority]] = None) -> None:
+ """Register a hook into the hook list.
+
+ The hook will be inserted into a priority queue, with the specified
+ priority (See :class:`Priority` for details of priorities).
+ For hooks with the same priority, they will be triggered in the same
+ order as they are registered.
+
+ Priority of hook will be decided with the following priority:
+
+ - ``priority`` argument. If ``priority`` is given, it will be priority
+ of hook.
+ - If ``hook`` argument is a dict and ``priority`` in it, the priority
+ will be the value of ``hook['priority']``.
+ - If ``hook`` argument is a dict but ``priority`` not in it or ``hook``
+ is an instance of ``hook``, the priority will be ``hook.priority``.
+
+ Args:
+ hook (:obj:`Hook` or dict): The hook to be registered.
+ priority (int or str or :obj:`Priority`, optional): Hook priority.
+ Lower value means higher priority.
+ """
+ if not isinstance(hook, (Hook, dict)):
+ raise TypeError(
+ f'hook should be an instance of Hook or dict, but got {hook}')
+
+ _priority = None
+ if isinstance(hook, dict):
+ if 'priority' in hook:
+ _priority = hook.pop('priority')
+
+ hook_obj = HOOKS.build(hook)
+ else:
+ hook_obj = hook
+
+ if priority is not None:
+ hook_obj.priority = priority
+ elif _priority is not None:
+ hook_obj.priority = _priority
+
+ inserted = False
+ for i in range(len(self._hooks) - 1, -1, -1):
+ if get_priority(hook_obj.priority) >= get_priority(
+ self._hooks[i].priority):
+ self._hooks.insert(i + 1, hook_obj)
+ inserted = True
+ break
+ if not inserted:
+ self._hooks.insert(0, hook_obj)
+
+ def register_default_hooks(
+ self,
+ hooks: Optional[Dict[str, Union[Hook, Dict]]] = None) -> None:
+ """Register default hooks into hook list.
+
+ ``hooks`` will be registered into runner to execute some default
+ actions like updating model parameters or saving checkpoints.
+
+ Default hooks and their priorities:
+
+ +----------------------+-------------------------+
+ | Hooks | Priority |
+ +======================+=========================+
+ | RuntimeInfoHook | VERY_HIGH (10) |
+ +----------------------+-------------------------+
+ | IterTimerHook | NORMAL (50) |
+ +----------------------+-------------------------+
+ | DistSamplerSeedHook | NORMAL (50) |
+ +----------------------+-------------------------+
+ | LoggerHook | BELOW_NORMAL (60) |
+ +----------------------+-------------------------+
+ | ParamSchedulerHook | LOW (70) |
+ +----------------------+-------------------------+
+ | CheckpointHook | VERY_LOW (90) |
+ +----------------------+-------------------------+
+
+ If ``hooks`` is None, above hooks will be registered by
+ default::
+
+ default_hooks = dict(
+ runtime_info=dict(type='RuntimeInfoHook'),
+ timer=dict(type='IterTimerHook'),
+ sampler_seed=dict(type='DistSamplerSeedHook'),
+ logger=dict(type='LoggerHook'),
+ param_scheduler=dict(type='ParamSchedulerHook'),
+ checkpoint=dict(type='CheckpointHook', interval=1),
+ )
+
+ If not None, ``hooks`` will be merged into ``default_hooks``.
+ If there are None value in default_hooks, the corresponding item will
+ be popped from ``default_hooks``::
+
+ hooks = dict(timer=None)
+
+ The final registered default hooks will be :obj:`RuntimeInfoHook`,
+ :obj:`DistSamplerSeedHook`, :obj:`LoggerHook`,
+ :obj:`ParamSchedulerHook` and :obj:`CheckpointHook`.
+
+ Args:
+ hooks (dict[str, Hook or dict], optional): Default hooks or configs
+ to be registered.
+ """
+ default_hooks: dict = dict(
+ runtime_info=dict(type='RuntimeInfoHook'),
+ timer=dict(type='IterTimerHook'),
+ sampler_seed=dict(type='DistSamplerSeedHook'),
+ logger=dict(type='LoggerHook'),
+ param_scheduler=dict(type='ParamSchedulerHook'),
+ checkpoint=dict(type='CheckpointHook', interval=1),
+ )
+ if hooks is not None:
+ for name, hook in hooks.items():
+ if name in default_hooks and hook is None:
+ # remove hook from _default_hooks
+ default_hooks.pop(name)
+ else:
+ assert hook is not None
+ default_hooks[name] = hook
+
+ for hook in default_hooks.values():
+ self.register_hook(hook)
+
+ def register_custom_hooks(self, hooks: List[Union[Hook, Dict]]) -> None:
+ """Register custom hooks into hook list.
+
+ Args:
+ hooks (list[Hook | dict]): List of hooks or configs to be
+ registered.
+ """
+ for hook in hooks:
+ self.register_hook(hook)
+
+ def register_hooks(
+ self,
+ default_hooks: Optional[Dict[str, Union[Hook, Dict]]] = None,
+ custom_hooks: Optional[List[Union[Hook, Dict]]] = None) -> None:
+ """Register default hooks and custom hooks into hook list.
+
+ Args:
+ default_hooks (dict[str, dict] or dict[str, Hook], optional): Hooks
+ to execute default actions like updating model parameters and
+ saving checkpoints. Defaults to None.
+ custom_hooks (list[dict] or list[Hook], optional): Hooks to execute
+ custom actions like visualizing images processed by pipeline.
+ Defaults to None.
+ """
+ self.register_default_hooks(default_hooks)
+
+ if custom_hooks is not None:
+ self.register_custom_hooks(custom_hooks)
+
+ def resume(self,
+ filename: str,
+ resume_optimizer: bool = True,
+ resume_param_scheduler: bool = True,
+ map_location: Union[str, Callable] = 'default') -> None:
+ """Resume model from checkpoint.
+
+ Args:
+ filename (str): Accept local filepath, URL, ``torchvision://xxx``,
+ ``open-mmlab://xxx``.
+ resume_optimizer (bool): Whether to resume optimizer state.
+ Defaults to True.
+ resume_param_scheduler (bool): Whether to resume param scheduler
+ state. Defaults to True.
+ map_location (str or callable):A string or a callable function to
+ specifying how to remap storage locations.
+ Defaults to 'default'.
+ """
+ if map_location == 'default':
+ device = get_device()
+ checkpoint = self.load_checkpoint(filename, map_location=device)
+ else:
+ checkpoint = self.load_checkpoint(
+ filename, map_location=map_location)
+
+ self.train_loop._epoch = checkpoint['meta']['epoch']
+ self.train_loop._iter = checkpoint['meta']['iter']
+
+ # check whether the number of GPU used for current experiment
+ # is consistent with resuming from checkpoint
+ if 'config' in checkpoint['meta']:
+ config = mmengine.Config.fromstring(
+ checkpoint['meta']['config'], file_format='.py')
+ previous_gpu_ids = config.get('gpu_ids', None)
+ if (previous_gpu_ids is not None and len(previous_gpu_ids) > 0
+ and len(previous_gpu_ids) != self._world_size):
+ # TODO, should we modify the iteration?
+ self.logger.info(
+ 'Number of GPU used for current experiment is not '
+ 'consistent with resuming from checkpoint')
+ if (self.auto_scale_lr is None
+ or not self.auto_scale_lr.get('enable', False)):
+ raise RuntimeError(
+ 'Cannot automatically rescale lr in resuming. Please '
+ 'make sure the number of GPU is consistent with the '
+ 'previous training state resuming from the checkpoint '
+ 'or set `enable` in `auto_scale_lr to False.')
+
+ # resume random seed
+ resumed_seed = checkpoint['meta'].get('seed', None)
+ current_seed = self._randomness_cfg.get('seed')
+ if resumed_seed is not None and resumed_seed != current_seed:
+ if current_seed is not None:
+ warnings.warn(f'The value of random seed in the '
+ f'checkpoint "{resumed_seed}" is '
+ f'different from the value in '
+ f'`randomness` config "{current_seed}"')
+ self._randomness_cfg.update(seed=resumed_seed)
+ self.set_randomness(**self._randomness_cfg)
+
+ resumed_dataset_meta = checkpoint['meta'].get('dataset_meta', None)
+ dataset_meta = getattr(self.train_dataloader.dataset, 'metainfo', None)
+
+ # `resumed_dataset_meta` and `dataset_meta` could be object like
+ # np.ndarray, which cannot be directly judged as equal or not,
+ # therefore we just compared their dumped results.
+ if pickle.dumps(resumed_dataset_meta) != pickle.dumps(dataset_meta):
+ warnings.warn(
+ 'The dataset metainfo from the resumed checkpoint is '
+ 'different from the current training dataset, please '
+ 'check the correctness of the checkpoint or the training '
+ 'dataset.')
+
+ self.message_hub.load_state_dict(checkpoint['message_hub'])
+
+ # resume optimizer
+ if 'optimizer' in checkpoint and resume_optimizer:
+ self.optim_wrapper = self.build_optim_wrapper(self.optim_wrapper)
+ self.optim_wrapper.load_state_dict( # type: ignore
+ checkpoint['optimizer'])
+
+ # resume param scheduler
+ if resume_param_scheduler and self.param_schedulers is None:
+ print_log(
+ '`resume_param_scheduler` is True but `self.param_schedulers` '
+ 'is None, so skip resuming parameter schedulers',
+ logger='current',
+ level=logging.WARNING)
+ resume_param_scheduler = False
+ if 'param_schedulers' in checkpoint and resume_param_scheduler:
+ self.param_schedulers = self.build_param_scheduler( # type: ignore
+ self.param_schedulers) # type: ignore
+ if isinstance(self.param_schedulers, dict):
+ for name, schedulers in self.param_schedulers.items():
+ for scheduler, ckpt_scheduler in zip(
+ schedulers, checkpoint['param_schedulers'][name]):
+ scheduler.load_state_dict(ckpt_scheduler)
+ else:
+ for scheduler, ckpt_scheduler in zip(
+ self.param_schedulers, # type: ignore
+ checkpoint['param_schedulers']):
+ scheduler.load_state_dict(ckpt_scheduler)
+
+ self._has_loaded = True
+
+ self.logger.info(f'resumed epoch: {self.epoch}, iter: {self.iter}')
+
+ def load_checkpoint(self,
+ filename: str,
+ map_location: Union[str, Callable] = 'cpu',
+ strict: bool = False,
+ revise_keys: list = [(r'^module.', '')]):
+ """Load checkpoint from given ``filename``.
+
+ Args:
+ filename (str): Accept local filepath, URL, ``torchvision://xxx``,
+ ``open-mmlab://xxx``.
+ map_location (str or callable): A string or a callable function to
+ specifying how to remap storage locations.
+ Defaults to 'cpu'.
+ strict (bool): strict (bool): Whether to allow different params for
+ the model and checkpoint.
+ revise_keys (list): A list of customized keywords to modify the
+ state_dict in checkpoint. Each item is a (pattern, replacement)
+ pair of the regular expression operations. Default: strip
+ the prefix 'module.' by [(r'^module\\.', '')].
+ """
+ checkpoint = _load_checkpoint(filename, map_location=map_location)
+
+ # Add comments to describe the usage of `after_load_ckpt`
+ self.call_hook('after_load_checkpoint', checkpoint=checkpoint)
+
+ if is_model_wrapper(self.model):
+ model = self.model.module
+ else:
+ model = self.model
+
+ checkpoint = _load_checkpoint_to_model(
+ model, checkpoint, strict, revise_keys=revise_keys)
+
+ self._has_loaded = True
+
+ self.logger.info(f'Load checkpoint from {filename}')
+
+ return checkpoint
+
+ @master_only
+ def save_checkpoint(
+ self,
+ out_dir: str,
+ filename: str,
+ file_client_args: Optional[dict] = None,
+ save_optimizer: bool = True,
+ save_param_scheduler: bool = True,
+ meta: dict = None,
+ by_epoch: bool = True,
+ backend_args: Optional[dict] = None,
+ ):
+ """Save checkpoints.
+
+ ``CheckpointHook`` invokes this method to save checkpoints
+ periodically.
+
+ Args:
+ out_dir (str): The directory that checkpoints are saved.
+ filename (str): The checkpoint filename.
+ file_client_args (dict, optional): Arguments to instantiate a
+ FileClient. See :class:`mmengine.fileio.FileClient` for
+ details. Defaults to None. It will be deprecated in future.
+ Please use `backend_args` instead.
+ save_optimizer (bool): Whether to save the optimizer to
+ the checkpoint. Defaults to True.
+ save_param_scheduler (bool): Whether to save the param_scheduler
+ to the checkpoint. Defaults to True.
+ meta (dict, optional): The meta information to be saved in the
+ checkpoint. Defaults to None.
+ by_epoch (bool): Whether the scheduled momentum is updated by
+ epochs. Defaults to True.
+ backend_args (dict, optional): Arguments to instantiate the
+ preifx of uri corresponding backend. Defaults to None.
+ New in v0.2.0.
+ """
+ if meta is None:
+ meta = {}
+ elif not isinstance(meta, dict):
+ raise TypeError(
+ f'meta should be a dict or None, but got {type(meta)}')
+
+ if by_epoch:
+ # self.epoch increments 1 after
+ # `self.call_hook('after_train_epoch)` but `save_checkpoint` is
+ # called by `after_train_epoch`` method of `CheckpointHook` so
+ # `epoch` should be `self.epoch + 1`
+ meta.update(epoch=self.epoch + 1, iter=self.iter)
+ else:
+ meta.update(epoch=self.epoch, iter=self.iter + 1)
+
+ if file_client_args is not None:
+ warnings.warn(
+ '"file_client_args" will be deprecated in future. '
+ 'Please use "backend_args" instead', DeprecationWarning)
+ if backend_args is not None:
+ raise ValueError(
+ '"file_client_args" and "backend_args" cannot be set at '
+ 'the same time.')
+
+ file_client = FileClient.infer_client(file_client_args, out_dir)
+ filepath = file_client.join_path(out_dir, filename)
+ else:
+ filepath = join_path( # type: ignore
+ out_dir, filename, backend_args=backend_args)
+
+ meta.update(
+ cfg=self.cfg.pretty_text,
+ seed=self.seed,
+ experiment_name=self.experiment_name,
+ time=time.strftime('%Y%m%d_%H%M%S', time.localtime()),
+ mmengine_version=mmengine.__version__ + get_git_hash())
+
+ if hasattr(self.train_dataloader.dataset, 'metainfo'):
+ meta.update(dataset_meta=self.train_dataloader.dataset.metainfo)
+
+ if is_model_wrapper(self.model):
+ model = self.model.module
+ else:
+ model = self.model
+
+ checkpoint = {
+ 'meta': meta,
+ 'state_dict': weights_to_cpu(get_state_dict(model)),
+ 'message_hub': self.message_hub.state_dict()
+ }
+ # save optimizer state dict to checkpoint
+ if save_optimizer:
+ if isinstance(self.optim_wrapper, OptimWrapper):
+ checkpoint['optimizer'] = self.optim_wrapper.state_dict()
+ else:
+ raise TypeError(
+ 'self.optim_wrapper should be an `OptimWrapper` '
+ 'or `OptimWrapperDict` instance, but got '
+ f'{self.optim_wrapper}')
+
+ # save param scheduler state dict
+ if save_param_scheduler and self.param_schedulers is None:
+ print_log(
+ '`save_param_scheduler` is True but `self.param_schedulers` '
+ 'is None, so skip saving parameter schedulers',
+ logger='current',
+ level=logging.WARNING)
+ save_param_scheduler = False
+ if save_param_scheduler:
+ if isinstance(self.param_schedulers, dict):
+ checkpoint['param_schedulers'] = dict()
+ for name, schedulers in self.param_schedulers.items():
+ checkpoint['param_schedulers'][name] = []
+ for scheduler in schedulers:
+ state_dict = scheduler.state_dict()
+ checkpoint['param_schedulers'][name].append(state_dict)
+ else:
+ checkpoint['param_schedulers'] = []
+ for scheduler in self.param_schedulers: # type: ignore
+ state_dict = scheduler.state_dict() # type: ignore
+ checkpoint['param_schedulers'].append(state_dict)
+
+ self.call_hook('before_save_checkpoint', checkpoint=checkpoint)
+ save_checkpoint(checkpoint, filepath)
+
+ @master_only
+ def dump_config(self) -> None:
+ """Dump config to `work_dir`."""
+ if self.cfg.filename is not None:
+ filename = osp.basename(self.cfg.filename)
+ else:
+ filename = f'{self.timestamp}.py'
+ self.cfg.dump(osp.join(self.work_dir, filename))
+
+ def _check_scheduler_cfg(
+ self, param_scheduler: Optional[Union[dict, list,
+ _ParamScheduler]]) -> None:
+ """Parse `param_scheduler` to a list of parameter schedulers, or a
+ `dict` of which each value is a list of parameter schedulers.
+
+ If only one optimizer is used, the parsed config should be a
+ list of parameter scheduler configs or instances. If multiple
+ optimizers are used, the parsed config should be `dict`.
+ Its key should be consistent with the optimizer `dict` and its value
+ should be a list of parameter scheduler configs or instances. See
+ :meth:`build_param_scheduler` for more details.
+
+ Examples:
+ >>> # valid scheduler:
+ >>> # empty scheduler
+ >>> scheduler = None
+ >>> # Single scheduler
+ >>> scheduler = dict(type='MultiStepLR', milestones=[1, 2])
+ >>> # Single list schedulers
+ >>> scheduler = [dict(type='MultiStepLR', milestones=[1, 2]),
+ >>> dict(type='MultiStepLR', milestones=[2, 3])]
+ >>> # `dict` of schedulers
+ >>> scheduler = dict(linear1=dict(type='MultiStepLR', milestones=[1, 2]),
+ >>> linear2=dict(type='MultiStepLR', milestones=[1, 2]))
+ >>> # `dict` of `list` of schedulers
+ >>> scheduler = dict(linear1=[dict(type='MultiStepLR', milestones=[1, 2])],
+ >>> linear2=[dict(type='MultiStepLR', milestones=[1, 2])])
+ >>> # Single built scheduler
+ >>> from mmengine.optim import MultiStepLR
+ >>> scheduler = MultiStepLR(milestones=[1, 2], optimizer=optimizer)
+ >>> # Single built list schedulers
+ >>> scheduler = [MultiStepLR(milestones=[1, 2], optimizer=optimizer)]
+ >>> # dict of built scheduler
+ >>> scheduler = dict(linear1=MultiStepLR(milestones=[1, 2], optimizer=optimizer),
+ >>> linear2=MultiStepLR(milestones=[1, 2], optimizer=optimizer))
+ >>> # dict of built list schedulers
+ >>> scheduler = dict(linear1=[MultiStepLR(milestones=[1, 2], optimizer=optimizer)],
+ >>> linear2=[MultiStepLR(milestones=[1, 2], optimizer=optimizer)])
+
+ Args:
+ param_scheduler (dict or list): The original parameter scheduler.
+ """ # noqa: E501
+ param_schedulers: Union[dict, list, _ParamScheduler]
+ if param_scheduler is None:
+ return
+ if isinstance(param_scheduler, _ParamScheduler):
+ return
+ if is_seq_of(param_scheduler, _ParamScheduler):
+ return
+
+ if is_seq_of(param_scheduler, dict):
+ for _param_scheduler in param_scheduler:
+ assert 'type' in _param_scheduler, (
+ 'Each parameter sheduler should contain the key type, '
+ f'but got {_param_scheduler}')
+ elif isinstance(param_scheduler, dict):
+ if 'type' not in param_scheduler:
+ for key, _param_scheduler in param_scheduler.items():
+ assert isinstance(
+ _param_scheduler,
+ (dict, tuple, list, _ParamScheduler)), (
+ 'Each value of `param_scheduler` should be a '
+ f'dict or a list, but got {_param_scheduler} with '
+ f'type {type(_ParamScheduler)}')
+
+ else:
+ raise TypeError(
+ '`param_scheduler` should be a `_ParamScheduler`, `dict`, '
+ f'list or a tuple, but got {type(param_scheduler)}. If '
+ '`param_scheduler` is a list of dict, it means a list of '
+ 'scheduler configs for single optimizer. If it is a dict and '
+ 'contains key `type`, it means a scheduler config for a '
+ 'single optimizer. If it does not contain key `type`, it '
+ 'means multiple lists of schedulers for multiple optimizers.')
+
+ def _log_env(self, env_cfg: dict) -> None:
+ """Logging environment information of the current task.
+
+ Args:
+ env_cfg (dict): The environment config of the runner.
+ """
+ # Collect and log environment information.
+ env = collect_env()
+ runtime_env = OrderedDict()
+ runtime_env.update(env_cfg)
+ runtime_env.update(self._randomness_cfg)
+ runtime_env['Distributed launcher'] = self._launcher
+ runtime_env['Distributed training'] = self._distributed
+ runtime_env['GPU number'] = self._world_size
+
+ env_info = '\n ' + '\n '.join(f'{k}: {v}'
+ for k, v in env.items())
+ runtime_env_info = '\n ' + '\n '.join(
+ f'{k}: {v}' for k, v in runtime_env.items())
+ dash_line = '-' * 60
+ self.logger.info('\n' + dash_line + '\nSystem environment:' +
+ env_info + '\n'
+ '\nRuntime environment:' + runtime_env_info + '\n' +
+ dash_line + '\n')
+ self.logger.info(f'Config:\n{self.cfg.pretty_text}')
diff --git a/testbed/open-mmlab__mmengine/mmengine/runner/utils.py b/testbed/open-mmlab__mmengine/mmengine/runner/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..db034df7ada8f4d0eedb51d250ceafa32f101906
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/runner/utils.py
@@ -0,0 +1,86 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import logging
+import random
+from typing import List, Optional, Tuple
+
+import numpy as np
+import torch
+
+from mmengine.dist import get_rank, sync_random_seed
+from mmengine.logging import print_log
+from mmengine.utils import digit_version, is_list_of
+from mmengine.utils.dl_utils import TORCH_VERSION
+
+
+def calc_dynamic_intervals(
+ start_interval: int,
+ dynamic_interval_list: Optional[List[Tuple[int, int]]] = None
+) -> Tuple[List[int], List[int]]:
+ """Calculate dynamic intervals.
+
+ Args:
+ start_interval (int): The interval used in the beginning.
+ dynamic_interval_list (List[Tuple[int, int]], optional): The
+ first element in the tuple is a milestone and the second
+ element is a interval. The interval is used after the
+ corresponding milestone. Defaults to None.
+
+ Returns:
+ Tuple[List[int], List[int]]: a list of milestone and its corresponding
+ intervals.
+ """
+ if dynamic_interval_list is None:
+ return [0], [start_interval]
+
+ assert is_list_of(dynamic_interval_list, tuple)
+
+ dynamic_milestones = [0]
+ dynamic_milestones.extend(
+ [dynamic_interval[0] for dynamic_interval in dynamic_interval_list])
+ dynamic_intervals = [start_interval]
+ dynamic_intervals.extend(
+ [dynamic_interval[1] for dynamic_interval in dynamic_interval_list])
+ return dynamic_milestones, dynamic_intervals
+
+
+def set_random_seed(seed: Optional[int] = None,
+ deterministic: bool = False,
+ diff_rank_seed: bool = False) -> int:
+ """Set random seed.
+
+ Args:
+ seed (int, optional): Seed to be used.
+ deterministic (bool): Whether to set the deterministic option for
+ CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`
+ to True and `torch.backends.cudnn.benchmark` to False.
+ Default: False.
+ diff_rank_seed (bool): Whether to add rank number to the random seed to
+ have different random seed in different threads. Default: False.
+ """
+ if seed is None:
+ seed = sync_random_seed()
+
+ if diff_rank_seed:
+ rank = get_rank()
+ seed += rank
+
+ random.seed(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+ # torch.cuda.manual_seed(seed)
+ torch.cuda.manual_seed_all(seed)
+ # os.environ['PYTHONHASHSEED'] = str(seed)
+ if deterministic:
+ if torch.backends.cudnn.benchmark:
+ print_log(
+ 'torch.backends.cudnn.benchmark is going to be set as '
+ '`False` to cause cuDNN to deterministically select an '
+ 'algorithm',
+ logger='current',
+ level=logging.WARNING)
+ torch.backends.cudnn.deterministic = True
+ torch.backends.cudnn.benchmark = False
+
+ if digit_version(TORCH_VERSION) >= digit_version('1.10.0'):
+ torch.use_deterministic_algorithms(True)
+ return seed
diff --git a/testbed/open-mmlab__mmengine/mmengine/structures/__init__.py b/testbed/open-mmlab__mmengine/mmengine/structures/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4d94fd1f78aa52186b6ebe8229ea70c95fc5a2f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/structures/__init__.py
@@ -0,0 +1,7 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .base_data_element import BaseDataElement
+from .instance_data import InstanceData
+from .label_data import LabelData
+from .pixel_data import PixelData
+
+__all__ = ['BaseDataElement', 'InstanceData', 'LabelData', 'PixelData']
diff --git a/testbed/open-mmlab__mmengine/mmengine/structures/base_data_element.py b/testbed/open-mmlab__mmengine/mmengine/structures/base_data_element.py
new file mode 100644
index 0000000000000000000000000000000000000000..042a9df6737306ceb39ed97c73a0818f9a690b83
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/structures/base_data_element.py
@@ -0,0 +1,604 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import sys
+from typing import Any, Iterator, Optional, Tuple, Type, Union
+
+import numpy as np
+import torch
+
+
+class BaseDataElement:
+ """A base data interface that supports Tensor-like and dict-like
+ operations.
+
+ A typical data elements refer to predicted results or ground truth labels
+ on a task, such as predicted bboxes, instance masks, semantic
+ segmentation masks, etc. Because groundtruth labels and predicted results
+ often have similar properties (for example, the predicted bboxes and the
+ groundtruth bboxes), MMEngine uses the same abstract data interface to
+ encapsulate predicted results and groundtruth labels, and it is recommended
+ to use different name conventions to distinguish them, such as using
+ ``gt_instances`` and ``pred_instances`` to distinguish between labels and
+ predicted results. Additionally, we distinguish data elements at instance
+ level, pixel level, and label level. Each of these types has its own
+ characteristics. Therefore, MMEngine defines the base class
+ ``BaseDataElement``, and implement ``InstanceData``, ``PixelData``, and
+ ``LabelData`` inheriting from ``BaseDataElement`` to represent different
+ types of ground truth labels or predictions.
+
+ Another common data element is sample data. A sample data consists of input
+ data (such as an image) and its annotations and predictions. In general,
+ an image can have multiple types of annotations and/or predictions at the
+ same time (for example, both pixel-level semantic segmentation annotations
+ and instance-level detection bboxes annotations). All labels and
+ predictions of a training sample are often passed between Dataset, Model,
+ Visualizer, and Evaluator components. In order to simplify the interface
+ between components, we can treat them as a large data element and
+ encapsulate them. Such data elements are generally called XXDataSample in
+ the OpenMMLab. Therefore, Similar to `nn.Module`, the `BaseDataElement`
+ allows `BaseDataElement` as its attribute. Such a class generally
+ encapsulates all the data of a sample in the algorithm library, and its
+ attributes generally are various types of data elements. For example,
+ MMDetection is assigned by the BaseDataElement to encapsulate all the data
+ elements of the sample labeling and prediction of a sample in the
+ algorithm library.
+
+ The attributes in ``BaseDataElement`` are divided into two parts,
+ the ``metainfo`` and the ``data`` respectively.
+
+ - ``metainfo``: Usually contains the
+ information about the image such as filename,
+ image_shape, pad_shape, etc. The attributes can be accessed or
+ modified by dict-like or object-like operations, such as
+ ``.`` (for data access and modification), ``in``, ``del``,
+ ``pop(str)``, ``get(str)``, ``metainfo_keys()``,
+ ``metainfo_values()``, ``metainfo_items()``, ``set_metainfo()`` (for
+ set or change key-value pairs in metainfo).
+
+ - ``data``: Annotations or model predictions are
+ stored. The attributes can be accessed or modified by
+ dict-like or object-like operations, such as
+ ``.``, ``in``, ``del``, ``pop(str)``, ``get(str)``, ``keys()``,
+ ``values()``, ``items()``. Users can also apply tensor-like
+ methods to all :obj:`torch.Tensor` in the ``data_fields``,
+ such as ``.cuda()``, ``.cpu()``, ``.numpy()``, ``.to()``,
+ ``to_tensor()``, ``.detach()``.
+
+ Args:
+ metainfo (dict, optional): A dict contains the meta information
+ of single image, such as ``dict(img_shape=(512, 512, 3),
+ scale_factor=(1, 1, 1, 1))``. Defaults to None.
+ kwargs (dict, optional): A dict contains annotations of single image or
+ model predictions. Defaults to None.
+
+ Examples:
+ >>> import torch
+ >>> from mmengine.structures import BaseDataElement
+ >>> gt_instances = BaseDataElement()
+ >>> bboxes = torch.rand((5, 4))
+ >>> scores = torch.rand((5,))
+ >>> img_id = 0
+ >>> img_shape = (800, 1333)
+ >>> gt_instances = BaseDataElement(
+ ... metainfo=dict(img_id=img_id, img_shape=img_shape),
+ ... bboxes=bboxes, scores=scores)
+ >>> gt_instances = BaseDataElement(
+ ... metainfo=dict(img_id=img_id, img_shape=(640, 640)))
+
+ >>> # new
+ >>> gt_instances1 = gt_instances.new(
+ ... metainfo=dict(img_id=1, img_shape=(640, 640)),
+ ... bboxes=torch.rand((5, 4)),
+ ... scores=torch.rand((5,)))
+ >>> gt_instances2 = gt_instances1.new()
+
+ >>> # add and process property
+ >>> gt_instances = BaseDataElement()
+ >>> gt_instances.set_metainfo(dict(img_id=9, img_shape=(100, 100)))
+ >>> assert 'img_shape' in gt_instances.metainfo_keys()
+ >>> assert 'img_shape' in gt_instances
+ >>> assert 'img_shape' not in gt_instances.keys()
+ >>> assert 'img_shape' in gt_instances.all_keys()
+ >>> print(gt_instances.img_shape)
+ (100, 100)
+ >>> gt_instances.scores = torch.rand((5,))
+ >>> assert 'scores' in gt_instances.keys()
+ >>> assert 'scores' in gt_instances
+ >>> assert 'scores' in gt_instances.all_keys()
+ >>> assert 'scores' not in gt_instances.metainfo_keys()
+ >>> print(gt_instances.scores)
+ tensor([0.5230, 0.7885, 0.2426, 0.3911, 0.4876])
+ >>> gt_instances.bboxes = torch.rand((5, 4))
+ >>> assert 'bboxes' in gt_instances.keys()
+ >>> assert 'bboxes' in gt_instances
+ >>> assert 'bboxes' in gt_instances.all_keys()
+ >>> assert 'bboxes' not in gt_instances.metainfo_keys()
+ >>> print(gt_instances.bboxes)
+ tensor([[0.0900, 0.0424, 0.1755, 0.4469],
+ [0.8648, 0.0592, 0.3484, 0.0913],
+ [0.5808, 0.1909, 0.6165, 0.7088],
+ [0.5490, 0.4209, 0.9416, 0.2374],
+ [0.3652, 0.1218, 0.8805, 0.7523]])
+
+ >>> # delete and change property
+ >>> gt_instances = BaseDataElement(
+ ... metainfo=dict(img_id=0, img_shape=(640, 640)),
+ ... bboxes=torch.rand((6, 4)), scores=torch.rand((6,)))
+ >>> gt_instances.set_metainfo(dict(img_shape=(1280, 1280)))
+ >>> gt_instances.img_shape # (1280, 1280)
+ >>> gt_instances.bboxes = gt_instances.bboxes * 2
+ >>> gt_instances.get('img_shape', None) # (1280, 1280)
+ >>> gt_instances.get('bboxes', None) # 6x4 tensor
+ >>> del gt_instances.img_shape
+ >>> del gt_instances.bboxes
+ >>> assert 'img_shape' not in gt_instances
+ >>> assert 'bboxes' not in gt_instances
+ >>> gt_instances.pop('img_shape', None) # None
+ >>> gt_instances.pop('bboxes', None) # None
+
+ >>> # Tensor-like
+ >>> cuda_instances = gt_instances.cuda()
+ >>> cuda_instances = gt_instances.to('cuda:0')
+ >>> cpu_instances = cuda_instances.cpu()
+ >>> cpu_instances = cuda_instances.to('cpu')
+ >>> fp16_instances = cuda_instances.to(
+ ... device=None, dtype=torch.float16, non_blocking=False,
+ ... copy=False, memory_format=torch.preserve_format)
+ >>> cpu_instances = cuda_instances.detach()
+ >>> np_instances = cpu_instances.numpy()
+
+ >>> # print
+ >>> metainfo = dict(img_shape=(800, 1196, 3))
+ >>> gt_instances = BaseDataElement(
+ ... metainfo=metainfo, det_labels=torch.LongTensor([0, 1, 2, 3]))
+ >>> sample = BaseDataElement(metainfo=metainfo,
+ ... gt_instances=gt_instances)
+ >>> print(sample)
+
+ ) at 0x7f0fea49e130>
+
+ >>> # inheritance
+ >>> class DetDataSample(BaseDataElement):
+ ... @property
+ ... def proposals(self):
+ ... return self._proposals
+ ... @proposals.setter
+ ... def proposals(self, value):
+ ... self.set_field(value, '_proposals', dtype=BaseDataElement)
+ ... @proposals.deleter
+ ... def proposals(self):
+ ... del self._proposals
+ ... @property
+ ... def gt_instances(self):
+ ... return self._gt_instances
+ ... @gt_instances.setter
+ ... def gt_instances(self, value):
+ ... self.set_field(value, '_gt_instances',
+ ... dtype=BaseDataElement)
+ ... @gt_instances.deleter
+ ... def gt_instances(self):
+ ... del self._gt_instances
+ ... @property
+ ... def pred_instances(self):
+ ... return self._pred_instances
+ ... @pred_instances.setter
+ ... def pred_instances(self, value):
+ ... self.set_field(value, '_pred_instances',
+ ... dtype=BaseDataElement)
+ ... @pred_instances.deleter
+ ... def pred_instances(self):
+ ... del self._pred_instances
+ >>> det_sample = DetDataSample()
+ >>> proposals = BaseDataElement(bboxes=torch.rand((5, 4)))
+ >>> det_sample.proposals = proposals
+ >>> assert 'proposals' in det_sample
+ >>> assert det_sample.proposals == proposals
+ >>> del det_sample.proposals
+ >>> assert 'proposals' not in det_sample
+ >>> with self.assertRaises(AssertionError):
+ ... det_sample.proposals = torch.rand((5, 4))
+ """
+
+ def __init__(self, *, metainfo: Optional[dict] = None, **kwargs) -> None:
+
+ self._metainfo_fields: set = set()
+ self._data_fields: set = set()
+
+ if metainfo is not None:
+ self.set_metainfo(metainfo=metainfo)
+ if kwargs:
+ self.set_data(kwargs)
+
+ def set_metainfo(self, metainfo: dict) -> None:
+ """Set or change key-value pairs in ``metainfo_field`` by parameter
+ ``metainfo``.
+
+ Args:
+ metainfo (dict): A dict contains the meta information
+ of image, such as ``img_shape``, ``scale_factor``, etc.
+ """
+ assert isinstance(
+ metainfo,
+ dict), f'metainfo should be a ``dict`` but got {type(metainfo)}'
+ meta = copy.deepcopy(metainfo)
+ for k, v in meta.items():
+ self.set_field(name=k, value=v, field_type='metainfo', dtype=None)
+
+ def set_data(self, data: dict) -> None:
+ """Set or change key-value pairs in ``data_field`` by parameter
+ ``data``.
+
+ Args:
+ data (dict): A dict contains annotations of image or
+ model predictions.
+ """
+ assert isinstance(data,
+ dict), f'data should be a `dict` but got {data}'
+ for k, v in data.items():
+ # Use `setattr()` rather than `self.set_field` to allow `set_data`
+ # to set property method.
+ setattr(self, k, v)
+
+ def update(self, instance: 'BaseDataElement') -> None:
+ """The update() method updates the BaseDataElement with the elements
+ from another BaseDataElement object.
+
+ Args:
+ instance (BaseDataElement): Another BaseDataElement object for
+ update the current object.
+ """
+ assert isinstance(
+ instance, BaseDataElement
+ ), f'instance should be a `BaseDataElement` but got {type(instance)}'
+ self.set_metainfo(dict(instance.metainfo_items()))
+ self.set_data(dict(instance.items()))
+
+ def new(self,
+ *,
+ metainfo: Optional[dict] = None,
+ **kwargs) -> 'BaseDataElement':
+ """Return a new data element with same type. If ``metainfo`` and
+ ``data`` are None, the new data element will have same metainfo and
+ data. If metainfo or data is not None, the new result will overwrite it
+ with the input value.
+
+ Args:
+ metainfo (dict, optional): A dict contains the meta information
+ of image, such as ``img_shape``, ``scale_factor``, etc.
+ Defaults to None.
+ kwargs (dict): A dict contains annotations of image or
+ model predictions.
+
+ Returns:
+ BaseDataElement: A new data element with same type.
+ """
+ new_data = self.__class__()
+
+ if metainfo is not None:
+ new_data.set_metainfo(metainfo)
+ else:
+ new_data.set_metainfo(dict(self.metainfo_items()))
+ if kwargs:
+ new_data.set_data(kwargs)
+ else:
+ new_data.set_data(dict(self.items()))
+ return new_data
+
+ def clone(self):
+ """Deep copy the current data element.
+
+ Returns:
+ BaseDataElement: The copy of current data element.
+ """
+ clone_data = self.__class__()
+ clone_data.set_metainfo(dict(self.metainfo_items()))
+ clone_data.set_data(dict(self.items()))
+ return clone_data
+
+ def keys(self) -> list:
+ """
+ Returns:
+ list: Contains all keys in data_fields.
+ """
+ return list(self._data_fields)
+
+ def metainfo_keys(self) -> list:
+ """
+ Returns:
+ list: Contains all keys in metainfo_fields.
+ """
+ return list(self._metainfo_fields)
+
+ def values(self) -> list:
+ """
+ Returns:
+ list: Contains all values in data.
+ """
+ return [getattr(self, k) for k in self.keys()]
+
+ def metainfo_values(self) -> list:
+ """
+ Returns:
+ list: Contains all values in metainfo.
+ """
+ return [getattr(self, k) for k in self.metainfo_keys()]
+
+ def all_keys(self) -> list:
+ """
+ Returns:
+ list: Contains all keys in metainfo and data.
+ """
+ return self.metainfo_keys() + self.keys()
+
+ def all_values(self) -> list:
+ """
+ Returns:
+ list: Contains all values in metainfo and data.
+ """
+ return self.metainfo_values() + self.values()
+
+ def all_items(self) -> Iterator[Tuple[str, Any]]:
+ """
+ Returns:
+ iterator: An iterator object whose element is (key, value) tuple
+ pairs for ``metainfo`` and ``data``.
+ """
+ for k in self.all_keys():
+ yield (k, getattr(self, k))
+
+ def items(self) -> Iterator[Tuple[str, Any]]:
+ """
+ Returns:
+ iterator: An iterator object whose element is (key, value) tuple
+ pairs for ``data``.
+ """
+ for k in self.keys():
+ yield (k, getattr(self, k))
+
+ def metainfo_items(self) -> Iterator[Tuple[str, Any]]:
+ """
+ Returns:
+ iterator: An iterator object whose element is (key, value) tuple
+ pairs for ``metainfo``.
+ """
+ for k in self.metainfo_keys():
+ yield (k, getattr(self, k))
+
+ @property
+ def metainfo(self) -> dict:
+ """dict: A dict contains metainfo of current data element."""
+ return dict(self.metainfo_items())
+
+ def __setattr__(self, name: str, value: Any):
+ """setattr is only used to set data."""
+ if name in ('_metainfo_fields', '_data_fields'):
+ if not hasattr(self, name):
+ super().__setattr__(name, value)
+ else:
+ raise AttributeError(f'{name} has been used as a '
+ 'private attribute, which is immutable.')
+ else:
+ self.set_field(
+ name=name, value=value, field_type='data', dtype=None)
+
+ def __delattr__(self, item: str):
+ """Delete the item in dataelement.
+
+ Args:
+ item (str): The key to delete.
+ """
+ if item in ('_metainfo_fields', '_data_fields'):
+ raise AttributeError(f'{item} has been used as a '
+ 'private attribute, which is immutable.')
+ super().__delattr__(item)
+ if item in self._metainfo_fields:
+ self._metainfo_fields.remove(item)
+ elif item in self._data_fields:
+ self._data_fields.remove(item)
+
+ # dict-like methods
+ __delitem__ = __delattr__
+
+ def get(self, key, default=None) -> Any:
+ """Get property in data and metainfo as the same as python."""
+ # Use `getattr()` rather than `self.__dict__.get()` to allow getting
+ # properties.
+ return getattr(self, key, default)
+
+ def pop(self, *args) -> Any:
+ """Pop property in data and metainfo as the same as python."""
+ assert len(args) < 3, '``pop`` get more than 2 arguments'
+ name = args[0]
+ if name in self._metainfo_fields:
+ self._metainfo_fields.remove(args[0])
+ return self.__dict__.pop(*args)
+
+ elif name in self._data_fields:
+ self._data_fields.remove(args[0])
+ return self.__dict__.pop(*args)
+
+ # with default value
+ elif len(args) == 2:
+ return args[1]
+ else:
+ # don't just use 'self.__dict__.pop(*args)' for only popping key in
+ # metainfo or data
+ raise KeyError(f'{args[0]} is not contained in metainfo or data')
+
+ def __contains__(self, item: str) -> bool:
+ """Whether the item is in dataelement.
+
+ Args:
+ item (str): The key to inquire.
+ """
+ return item in self._data_fields or item in self._metainfo_fields
+
+ def set_field(self,
+ value: Any,
+ name: str,
+ dtype: Optional[Union[Type, Tuple[Type, ...]]] = None,
+ field_type: str = 'data') -> None:
+ """Special method for set union field, used as property.setter
+ functions."""
+ assert field_type in ['metainfo', 'data']
+ if dtype is not None:
+ assert isinstance(
+ value,
+ dtype), f'{value} should be a {dtype} but got {type(value)}'
+
+ if field_type == 'metainfo':
+ if name in self._data_fields:
+ raise AttributeError(
+ f'Cannot set {name} to be a field of metainfo '
+ f'because {name} is already a data field')
+ self._metainfo_fields.add(name)
+ else:
+ if name in self._metainfo_fields:
+ raise AttributeError(
+ f'Cannot set {name} to be a field of data '
+ f'because {name} is already a metainfo field')
+ # The name only added to `data_fields` when it is not the
+ # attribute related to property(methods decorated by @property).
+ if not isinstance(
+ getattr(type(self),
+ sys._getframe(1).f_code.co_name, None), property):
+ self._data_fields.add(name)
+ super().__setattr__(name, value)
+
+ # Tensor-like methods
+ def to(self, *args, **kwargs) -> 'BaseDataElement':
+ """Apply same name function to all tensors in data_fields."""
+ new_data = self.new()
+ for k, v in self.items():
+ if hasattr(v, 'to'):
+ v = v.to(*args, **kwargs)
+ data = {k: v}
+ new_data.set_data(data)
+ return new_data
+
+ # Tensor-like methods
+ def cpu(self) -> 'BaseDataElement':
+ """Convert all tensors to CPU in data."""
+ new_data = self.new()
+ for k, v in self.items():
+ if isinstance(v, (torch.Tensor, BaseDataElement)):
+ v = v.cpu()
+ data = {k: v}
+ new_data.set_data(data)
+ return new_data
+
+ # Tensor-like methods
+ def cuda(self) -> 'BaseDataElement':
+ """Convert all tensors to GPU in data."""
+ new_data = self.new()
+ for k, v in self.items():
+ if isinstance(v, (torch.Tensor, BaseDataElement)):
+ v = v.cuda()
+ data = {k: v}
+ new_data.set_data(data)
+ return new_data
+
+ # Tensor-like methods
+ def detach(self) -> 'BaseDataElement':
+ """Detach all tensors in data."""
+ new_data = self.new()
+ for k, v in self.items():
+ if isinstance(v, (torch.Tensor, BaseDataElement)):
+ v = v.detach()
+ data = {k: v}
+ new_data.set_data(data)
+ return new_data
+
+ # Tensor-like methods
+ def numpy(self) -> 'BaseDataElement':
+ """Convert all tensors to np.ndarray in data."""
+ new_data = self.new()
+ for k, v in self.items():
+ if isinstance(v, (torch.Tensor, BaseDataElement)):
+ v = v.detach().cpu().numpy()
+ data = {k: v}
+ new_data.set_data(data)
+ return new_data
+
+ def to_tensor(self) -> 'BaseDataElement':
+ """Convert all np.ndarray to tensor in data."""
+ new_data = self.new()
+ for k, v in self.items():
+ data = {}
+ if isinstance(v, np.ndarray):
+ v = torch.from_numpy(v)
+ data[k] = v
+ elif isinstance(v, BaseDataElement):
+ v = v.to_tensor()
+ data[k] = v
+ new_data.set_data(data)
+ return new_data
+
+ def to_dict(self) -> dict:
+ """Convert BaseDataElement to dict."""
+ return {
+ k: v.to_dict() if isinstance(v, BaseDataElement) else v
+ for k, v in self.all_items()
+ }
+
+ def __repr__(self) -> str:
+ """Represent the object."""
+
+ def _addindent(s_: str, num_spaces: int) -> str:
+ """This func is modified from `pytorch` https://github.com/pytorch/
+ pytorch/blob/b17b2b1cc7b017c3daaeff8cc7ec0f514d42ec37/torch/nn/modu
+ les/module.py#L29.
+
+ Args:
+ s_ (str): The string to add spaces.
+ num_spaces (int): The num of space to add.
+
+ Returns:
+ str: The string after add indent.
+ """
+ s = s_.split('\n')
+ # don't do anything for single-line stuff
+ if len(s) == 1:
+ return s_
+ first = s.pop(0)
+ s = [(num_spaces * ' ') + line for line in s]
+ s = '\n'.join(s) # type: ignore
+ s = first + '\n' + s # type: ignore
+ return s # type: ignore
+
+ def dump(obj: Any) -> str:
+ """Represent the object.
+
+ Args:
+ obj (Any): The obj to represent.
+
+ Returns:
+ str: The represented str.
+ """
+ _repr = ''
+ if isinstance(obj, dict):
+ for k, v in obj.items():
+ _repr += f'\n{k}: {_addindent(dump(v), 4)}'
+ elif isinstance(obj, BaseDataElement):
+ _repr += '\n\n META INFORMATION'
+ metainfo_items = dict(obj.metainfo_items())
+ _repr += _addindent(dump(metainfo_items), 4)
+ _repr += '\n\n DATA FIELDS'
+ items = dict(obj.items())
+ _repr += _addindent(dump(items), 4)
+ classname = obj.__class__.__name__
+ _repr = f'<{classname}({_repr}\n) at {hex(id(obj))}>'
+ else:
+ _repr += repr(obj)
+ return _repr
+
+ return dump(self)
diff --git a/testbed/open-mmlab__mmengine/mmengine/structures/instance_data.py b/testbed/open-mmlab__mmengine/mmengine/structures/instance_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..36c60fd15587d669d39e367d45c85c60af81b01c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/structures/instance_data.py
@@ -0,0 +1,298 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import itertools
+from collections.abc import Sized
+from typing import List, Union
+
+import numpy as np
+import torch
+
+from .base_data_element import BaseDataElement
+
+IndexType = Union[str, slice, int, list, torch.LongTensor,
+ torch.cuda.LongTensor, torch.BoolTensor,
+ torch.cuda.BoolTensor, np.ndarray]
+
+
+# Modified from
+# https://github.com/open-mmlab/mmdetection/blob/master/mmdet/core/data_structures/instance_data.py # noqa
+class InstanceData(BaseDataElement):
+ """Data structure for instance-level annotations or predictions.
+
+ Subclass of :class:`BaseDataElement`. All value in `data_fields`
+ should have the same length. This design refer to
+ https://github.com/facebookresearch/detectron2/blob/master/detectron2/structures/instances.py # noqa E501
+ InstanceData also support extra functions: ``index``, ``slice`` and ``cat`` for data field. The type of value
+ in data field can be base data structure such as `torch.Tensor`, `numpy.ndarray`, `list`, `str`, `tuple`,
+ and can be customized data structure that has ``__len__``, ``__getitem__`` and ``cat`` attributes.
+
+ Examples:
+ >>> # custom data structure
+ >>> class TmpObject:
+ ... def __init__(self, tmp) -> None:
+ ... assert isinstance(tmp, list)
+ ... self.tmp = tmp
+ ... def __len__(self):
+ ... return len(self.tmp)
+ ... def __getitem__(self, item):
+ ... if isinstance(item, int):
+ ... if item >= len(self) or item < -len(self): # type:ignore
+ ... raise IndexError(f'Index {item} out of range!')
+ ... else:
+ ... # keep the dimension
+ ... item = slice(item, None, len(self))
+ ... return TmpObject(self.tmp[item])
+ ... @staticmethod
+ ... def cat(tmp_objs):
+ ... assert all(isinstance(results, TmpObject) for results in tmp_objs)
+ ... if len(tmp_objs) == 1:
+ ... return tmp_objs[0]
+ ... tmp_list = [tmp_obj.tmp for tmp_obj in tmp_objs]
+ ... tmp_list = list(itertools.chain(*tmp_list))
+ ... new_data = TmpObject(tmp_list)
+ ... return new_data
+ ... def __repr__(self):
+ ... return str(self.tmp)
+ >>> from mmengine.structures import InstanceData
+ >>> import numpy as np
+ >>> import torch
+ >>> img_meta = dict(img_shape=(800, 1196, 3), pad_shape=(800, 1216, 3))
+ >>> instance_data = InstanceData(metainfo=img_meta)
+ >>> 'img_shape' in instance_data
+ True
+ >>> instance_data.det_labels = torch.LongTensor([2, 3])
+ >>> instance_data["det_scores"] = torch.Tensor([0.8, 0.7])
+ >>> instance_data.bboxes = torch.rand((2, 4))
+ >>> instance_data.polygons = TmpObject([[1, 2, 3, 4], [5, 6, 7, 8]])
+ >>> len(instance_data)
+ 2
+ >>> print(instance_data)
+
+ >>> sorted_results = instance_data[instance_data.det_scores.sort().indices]
+ >>> sorted_results.det_scores
+ tensor([0.7000, 0.8000])
+ >>> print(instance_data[instance_data.det_scores > 0.75])
+
+ >>> print(instance_data[instance_data.det_scores > 1])
+
+ >>> print(instance_data.cat([instance_data, instance_data]))
+
+ """
+
+ def __setattr__(self, name: str, value: Sized):
+ """setattr is only used to set data.
+
+ The value must have the attribute of `__len__` and have the same length
+ of `InstanceData`.
+ """
+ if name in ('_metainfo_fields', '_data_fields'):
+ if not hasattr(self, name):
+ super().__setattr__(name, value)
+ else:
+ raise AttributeError(f'{name} has been used as a '
+ 'private attribute, which is immutable.')
+
+ else:
+ assert isinstance(value,
+ Sized), 'value must contain `__len__` attribute'
+
+ if len(self) > 0:
+ assert len(value) == len(self), 'The length of ' \
+ f'values {len(value)} is ' \
+ 'not consistent with ' \
+ 'the length of this ' \
+ ':obj:`InstanceData` ' \
+ f'{len(self)}'
+ super().__setattr__(name, value)
+
+ __setitem__ = __setattr__
+
+ def __getitem__(self, item: IndexType) -> 'InstanceData':
+ """
+ Args:
+ item (str, int, list, :obj:`slice`, :obj:`numpy.ndarray`,
+ :obj:`torch.LongTensor`, :obj:`torch.BoolTensor`):
+ Get the corresponding values according to item.
+
+ Returns:
+ :obj:`InstanceData`: Corresponding values.
+ """
+ if isinstance(item, list):
+ item = np.array(item)
+ if isinstance(item, np.ndarray):
+ # The default int type of numpy is platform dependent, int32 for
+ # windows and int64 for linux. `torch.Tensor` requires the index
+ # should be int64, therefore we simply convert it to int64 here.
+ # More details in https://github.com/numpy/numpy/issues/9464
+ item = item.astype(np.int64) if item.dtype == np.int32 else item
+ item = torch.from_numpy(item)
+ assert isinstance(
+ item, (str, slice, int, torch.LongTensor, torch.cuda.LongTensor,
+ torch.BoolTensor, torch.cuda.BoolTensor))
+
+ if isinstance(item, str):
+ return getattr(self, item)
+
+ if isinstance(item, int):
+ if item >= len(self) or item < -len(self): # type:ignore
+ raise IndexError(f'Index {item} out of range!')
+ else:
+ # keep the dimension
+ item = slice(item, None, len(self))
+
+ new_data = self.__class__(metainfo=self.metainfo)
+ if isinstance(item, torch.Tensor):
+ assert item.dim() == 1, 'Only support to get the' \
+ ' values along the first dimension.'
+ if isinstance(item, (torch.BoolTensor, torch.cuda.BoolTensor)):
+ assert len(item) == len(self), 'The shape of the ' \
+ 'input(BoolTensor) ' \
+ f'{len(item)} ' \
+ 'does not match the shape ' \
+ 'of the indexed tensor ' \
+ 'in results_field ' \
+ f'{len(self)} at ' \
+ 'first dimension.'
+
+ for k, v in self.items():
+ if isinstance(v, torch.Tensor):
+ new_data[k] = v[item]
+ elif isinstance(v, np.ndarray):
+ new_data[k] = v[item.cpu().numpy()]
+ elif isinstance(
+ v, (str, list, tuple)) or (hasattr(v, '__getitem__')
+ and hasattr(v, 'cat')):
+ # convert to indexes from BoolTensor
+ if isinstance(item,
+ (torch.BoolTensor, torch.cuda.BoolTensor)):
+ indexes = torch.nonzero(item).view(
+ -1).cpu().numpy().tolist()
+ else:
+ indexes = item.cpu().numpy().tolist()
+ slice_list = []
+ if indexes:
+ for index in indexes:
+ slice_list.append(slice(index, None, len(v)))
+ else:
+ slice_list.append(slice(None, 0, None))
+ r_list = [v[s] for s in slice_list]
+ if isinstance(v, (str, list, tuple)):
+ new_value = r_list[0]
+ for r in r_list[1:]:
+ new_value = new_value + r
+ else:
+ new_value = v.cat(r_list)
+ new_data[k] = new_value
+ else:
+ raise ValueError(
+ f'The type of `{k}` is `{type(v)}`, which has no '
+ 'attribute of `cat`, so it does not '
+ 'support slice with `bool`')
+
+ else:
+ # item is a slice
+ for k, v in self.items():
+ new_data[k] = v[item]
+ return new_data # type:ignore
+
+ @staticmethod
+ def cat(instances_list: List['InstanceData']) -> 'InstanceData':
+ """Concat the instances of all :obj:`InstanceData` in the list.
+
+ Note: To ensure that cat returns as expected, make sure that
+ all elements in the list must have exactly the same keys.
+
+ Args:
+ instances_list (list[:obj:`InstanceData`]): A list
+ of :obj:`InstanceData`.
+
+ Returns:
+ :obj:`InstanceData`
+ """
+ assert all(
+ isinstance(results, InstanceData) for results in instances_list)
+ assert len(instances_list) > 0
+ if len(instances_list) == 1:
+ return instances_list[0]
+
+ # metainfo and data_fields must be exactly the
+ # same for each element to avoid exceptions.
+ field_keys_list = [
+ instances.all_keys() for instances in instances_list
+ ]
+ assert len({len(field_keys) for field_keys in field_keys_list}) \
+ == 1 and len(set(itertools.chain(*field_keys_list))) \
+ == len(field_keys_list[0]), 'There are different keys in ' \
+ '`instances_list`, which may ' \
+ 'cause the cat operation ' \
+ 'to fail. Please make sure all ' \
+ 'elements in `instances_list` ' \
+ 'have the exact same key.'
+
+ new_data = instances_list[0].__class__(
+ metainfo=instances_list[0].metainfo)
+ for k in instances_list[0].keys():
+ values = [results[k] for results in instances_list]
+ v0 = values[0]
+ if isinstance(v0, torch.Tensor):
+ new_values = torch.cat(values, dim=0)
+ elif isinstance(v0, np.ndarray):
+ new_values = np.concatenate(values, axis=0)
+ elif isinstance(v0, (str, list, tuple)):
+ new_values = v0[:]
+ for v in values[1:]:
+ new_values += v
+ elif hasattr(v0, 'cat'):
+ new_values = v0.cat(values)
+ else:
+ raise ValueError(
+ f'The type of `{k}` is `{type(v0)}` which has no '
+ 'attribute of `cat`')
+ new_data[k] = new_values
+ return new_data # type:ignore
+
+ def __len__(self) -> int:
+ """int: The length of InstanceData."""
+ if len(self._data_fields) > 0:
+ return len(self.values()[0])
+ else:
+ return 0
diff --git a/testbed/open-mmlab__mmengine/mmengine/structures/label_data.py b/testbed/open-mmlab__mmengine/mmengine/structures/label_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..de178e07a011d4b9d45844113f1052b6d6da01aa
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/structures/label_data.py
@@ -0,0 +1,46 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+
+import torch
+
+from .base_data_element import BaseDataElement
+
+
+class LabelData(BaseDataElement):
+ """Data structure for label-level annotations or predictions."""
+
+ @staticmethod
+ def onehot_to_label(onehot: torch.Tensor) -> torch.Tensor:
+ """Convert the one-hot input to label.
+
+ Args:
+ onehot (torch.Tensor, optional): The one-hot input. The format
+ of input must be one-hot.
+
+ Returns:
+ torch.Tensor: The converted results.
+ """
+ assert isinstance(onehot, torch.Tensor)
+ if (onehot.ndim == 1 and onehot.max().item() <= 1
+ and onehot.min().item() >= 0):
+ return onehot.nonzero().squeeze(-1)
+ else:
+ raise ValueError(
+ 'input is not one-hot and can not convert to label')
+
+ @staticmethod
+ def label_to_onehot(label: torch.Tensor, num_classes: int) -> torch.Tensor:
+ """Convert the label-format input to one-hot.
+
+ Args:
+ label (torch.Tensor): The label-format input. The format
+ of item must be label-format.
+ num_classes (int): The number of classes.
+
+ Returns:
+ torch.Tensor: The converted results.
+ """
+ assert isinstance(label, torch.Tensor)
+ onehot = label.new_zeros((num_classes, ))
+ assert max(label, default=torch.tensor(0)).item() < num_classes
+ onehot[label] = 1
+ return onehot
diff --git a/testbed/open-mmlab__mmengine/mmengine/structures/pixel_data.py b/testbed/open-mmlab__mmengine/mmengine/structures/pixel_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..d550f5c0c6512306c94a9a6bf9c8b40fb6b5a89e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/structures/pixel_data.py
@@ -0,0 +1,130 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import warnings
+from typing import List, Sequence, Union
+
+import numpy as np
+import torch
+
+from .base_data_element import BaseDataElement
+
+
+class PixelData(BaseDataElement):
+ """Data structure for pixel-level annotations or predictions.
+
+ All data items in ``data_fields`` of ``PixelData`` meet the following
+ requirements:
+
+ - They all have 3 dimensions in orders of channel, height, and width.
+ - They should have the same height and width.
+
+ Examples:
+ >>> metainfo = dict(
+ ... img_id=random.randint(0, 100),
+ ... img_shape=(random.randint(400, 600), random.randint(400, 600)))
+ >>> image = np.random.randint(0, 255, (4, 20, 40))
+ >>> featmap = torch.randint(0, 255, (10, 20, 40))
+ >>> pixel_data = PixelData(metainfo=metainfo,
+ ... image=image,
+ ... featmap=featmap)
+ >>> print(pixel_data.shape)
+ (20, 40)
+
+ >>> # slice
+ >>> slice_data = pixel_data[10:20, 20:40]
+ >>> assert slice_data.shape == (10, 20)
+ >>> slice_data = pixel_data[10, 20]
+ >>> assert slice_data.shape == (1, 1)
+
+ >>> # set
+ >>> pixel_data.map3 = torch.randint(0, 255, (20, 40))
+ >>> assert tuple(pixel_data.map3.shape) == (1, 20, 40)
+ >>> with self.assertRaises(AssertionError):
+ ... # The dimension must be 3 or 2
+ ... pixel_data.map2 = torch.randint(0, 255, (1, 3, 20, 40))
+ """
+
+ def __setattr__(self, name: str, value: Union[torch.Tensor, np.ndarray]):
+ """Set attributes of ``PixelData``.
+
+ If the dimension of value is 2 and its shape meet the demand, it
+ will automatically expand its channel-dimension.
+
+ Args:
+ name (str): The key to access the value, stored in `PixelData`.
+ value (Union[torch.Tensor, np.ndarray]): The value to store in.
+ The type of value must be `torch.Tensor` or `np.ndarray`,
+ and its shape must meet the requirements of `PixelData`.
+ """
+ if name in ('_metainfo_fields', '_data_fields'):
+ if not hasattr(self, name):
+ super().__setattr__(name, value)
+ else:
+ raise AttributeError(f'{name} has been used as a '
+ 'private attribute, which is immutable.')
+
+ else:
+ assert isinstance(value, (torch.Tensor, np.ndarray)), \
+ f'Can not set {type(value)}, only support' \
+ f' {(torch.Tensor, np.ndarray)}'
+
+ if self.shape:
+ assert tuple(value.shape[-2:]) == self.shape, (
+ 'The height and width of '
+ f'values {tuple(value.shape[-2:])} is '
+ 'not consistent with '
+ 'the shape of this '
+ ':obj:`PixelData` '
+ f'{self.shape}')
+ assert value.ndim in [
+ 2, 3
+ ], f'The dim of value must be 2 or 3, but got {value.ndim}'
+ if value.ndim == 2:
+ value = value[None]
+ warnings.warn('The shape of value will convert from '
+ f'{value.shape[-2:]} to {value.shape}')
+ super().__setattr__(name, value)
+
+ # TODO torch.Long/bool
+ def __getitem__(self, item: Sequence[Union[int, slice]]) -> 'PixelData':
+ """
+ Args:
+ item (Sequence[Union[int, slice]]): Get the corresponding values
+ according to item.
+
+ Returns:
+ :obj:`PixelData`: Corresponding values.
+ """
+
+ new_data = self.__class__(metainfo=self.metainfo)
+ if isinstance(item, tuple):
+
+ assert len(item) == 2, 'Only support to slice height and width'
+ tmp_item: List[slice] = list()
+ for index, single_item in enumerate(item[::-1]):
+ if isinstance(single_item, int):
+ tmp_item.insert(
+ 0, slice(single_item, None, self.shape[-index - 1]))
+ elif isinstance(single_item, slice):
+ tmp_item.insert(0, single_item)
+ else:
+ raise TypeError(
+ 'The type of element in input must be int or slice, '
+ f'but got {type(single_item)}')
+ tmp_item.insert(0, slice(None, None, None))
+ item = tuple(tmp_item)
+ for k, v in self.items():
+ setattr(new_data, k, v[item])
+ else:
+ raise TypeError(
+ f'Unsupported type {type(item)} for slicing PixelData')
+ return new_data
+
+ @property
+ def shape(self):
+ """The shape of pixel data."""
+ if len(self._data_fields) > 0:
+ return tuple(self.values()[0].shape[-2:])
+ else:
+ return None
+
+ # TODO padding, resize
diff --git a/testbed/open-mmlab__mmengine/mmengine/testing/__init__.py b/testbed/open-mmlab__mmengine/mmengine/testing/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7e4da354323ffe2401de2ab01ca9f4a51f932ef
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/testing/__init__.py
@@ -0,0 +1,12 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .compare import (assert_allclose, assert_attrs_equal,
+ assert_dict_contains_subset, assert_dict_has_keys,
+ assert_is_norm_layer, assert_keys_equal,
+ assert_params_all_zeros, check_python_script)
+from .runner_test_case import RunnerTestCase
+
+__all__ = [
+ 'assert_allclose', 'assert_dict_contains_subset', 'assert_keys_equal',
+ 'assert_attrs_equal', 'assert_dict_has_keys', 'assert_is_norm_layer',
+ 'assert_params_all_zeros', 'check_python_script', 'RunnerTestCase'
+]
diff --git a/testbed/open-mmlab__mmengine/mmengine/testing/_internal/__init__.py b/testbed/open-mmlab__mmengine/mmengine/testing/_internal/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4528659a8ff0e342012da67cc5e88fe99c1afa4
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/testing/_internal/__init__.py
@@ -0,0 +1,4 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .distributed import MultiProcessTestCase
+
+__all__ = ['MultiProcessTestCase']
diff --git a/testbed/open-mmlab__mmengine/mmengine/testing/_internal/distributed.py b/testbed/open-mmlab__mmengine/mmengine/testing/_internal/distributed.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e5020fa1268863173ea346f644e93dc98da774e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/testing/_internal/distributed.py
@@ -0,0 +1,355 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+# Copyright (c) https://github.com/pytorch/pytorch
+# Modified from https://github.com/pytorch/pytorch/blob/master/torch/testing/_internal/common_distributed.py # noqa: E501
+
+import faulthandler
+import logging
+import multiprocessing
+import sys
+import tempfile
+import threading
+import time
+import traceback
+import types
+import unittest
+from enum import Enum
+from functools import wraps
+from typing import NamedTuple
+from unittest import TestCase
+
+import torch
+from torch.multiprocessing import active_children
+
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+
+class TestSkip(NamedTuple):
+ exit_code: int
+ message: str
+
+
+TEST_SKIPS = {
+ 'backend_unavailable':
+ TestSkip(10, 'Skipped because distributed backend is not available.'),
+ 'no_cuda':
+ TestSkip(11, 'CUDA is not available.'),
+ 'multi-gpu-2':
+ TestSkip(12, 'Need at least 2 CUDA device'),
+ 'generic':
+ TestSkip(
+ 13, 'Test skipped at subprocess level, look at subprocess log for '
+ 'skip reason'),
+}
+
+# [How does MultiProcessTestCase work?]
+# Each MultiProcessTestCase instance uses 1 + `world_size()` processes, by
+# default `world_size()` returns 2. Let's take `test_rpc_spawn.py` as an
+# example which inherits from this class. Its `Setup()` methods calls into
+# `MultiProcessTestCase._spawn_processes()` which spawns `world_size()`
+# subprocesses. During the spawn, the main process passes the test name to
+# subprocesses, and the name is acquired from self.id(). The subprocesses
+# then use the provided test function name to retrieve the function attribute
+# from the test instance and run it. The main process simply waits for all
+# subprocesses to join.
+
+
+class MultiProcessTestCase(TestCase):
+ MAIN_PROCESS_RANK = -1
+
+ # This exit code is used to indicate that the test code had an error and
+ # exited abnormally. There are certain tests that might use sys.exit() to
+ # simulate failures and in those cases, we can't have an exit code of 0,
+ # but we still want to ensure we didn't run into any other errors.
+ TEST_ERROR_EXIT_CODE = 10
+
+ # do not early terminate for distributed tests.
+ def _should_stop_test_suite(self) -> bool:
+ return False
+
+ @property
+ def world_size(self) -> int:
+ return 2
+
+ @property
+ def timeout(self) -> int:
+ return 1000
+
+ def join_or_run(self, fn):
+
+ @wraps(fn)
+ def wrapper(self):
+ if self.rank == self.MAIN_PROCESS_RANK:
+ self._join_processes(fn)
+ else:
+ fn()
+
+ return types.MethodType(wrapper, self)
+
+ # The main process spawns N subprocesses that run the test.
+ # Constructor patches current instance test method to
+ # assume the role of the main process and join its subprocesses,
+ # or run the underlying test function.
+ def __init__(self, method_name: str = 'runTest') -> None:
+ super().__init__(method_name)
+ fn = getattr(self, method_name)
+ setattr(self, method_name, self.join_or_run(fn))
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.skip_return_code_checks = [] # type: ignore[var-annotated]
+ self.processes = [] # type: ignore[var-annotated]
+ self.rank = self.MAIN_PROCESS_RANK
+ self.file_name = tempfile.NamedTemporaryFile(delete=False).name
+ # pid to pipe consisting of error message from process.
+ self.pid_to_pipe = {} # type: ignore[var-annotated]
+
+ def tearDown(self) -> None:
+ super().tearDown()
+ for p in self.processes:
+ p.terminate()
+ # Each Process instance holds a few open file descriptors. The unittest
+ # runner creates a new TestCase instance for each test method and keeps
+ # it alive until the end of the entire suite. We must thus reset the
+ # processes to prevent an effective file descriptor leak.
+ self.processes = []
+
+ def _current_test_name(self) -> str:
+ # self.id()
+ # e.g. '__main__.TestDistributed.TestAdditive.test_get_rank'
+ return self.id().split('.')[-1]
+
+ def _start_processes(self, proc) -> None:
+ self.processes = []
+ for rank in range(int(self.world_size)):
+ parent_conn, child_conn = torch.multiprocessing.Pipe()
+ process = proc(
+ target=self.__class__._run,
+ name='process ' + str(rank),
+ args=(rank, self._current_test_name(), self.file_name,
+ child_conn),
+ )
+ process.start()
+ self.pid_to_pipe[process.pid] = parent_conn
+ self.processes.append(process)
+
+ def _spawn_processes(self) -> None:
+ proc = torch.multiprocessing.get_context('spawn').Process
+ self._start_processes(proc)
+
+ class Event(Enum):
+ GET_TRACEBACK = 1
+
+ @staticmethod
+ def _event_listener(parent_pipe, signal_pipe, rank: int):
+ while True:
+ ready_pipes = multiprocessing.connection.wait(
+ [parent_pipe, signal_pipe])
+
+ if parent_pipe in ready_pipes:
+
+ if parent_pipe.closed:
+ return
+
+ event = parent_pipe.recv()
+
+ if event == MultiProcessTestCase.Event.GET_TRACEBACK:
+ # Return traceback to the parent process.
+ with tempfile.NamedTemporaryFile(mode='r+') as tmp_file:
+ faulthandler.dump_traceback(tmp_file)
+ # Flush buffers and seek to read from the beginning
+ tmp_file.flush()
+ tmp_file.seek(0)
+ parent_pipe.send(tmp_file.read())
+
+ if signal_pipe in ready_pipes:
+ return
+
+ @classmethod
+ def _run(cls, rank: int, test_name: str, file_name: str,
+ parent_pipe) -> None:
+ self = cls(test_name)
+
+ self.rank = rank
+ self.file_name = file_name
+ self.run_test(test_name, parent_pipe)
+
+ def run_test(self, test_name: str, parent_pipe) -> None:
+ # Start event listener thread.
+ signal_recv_pipe, signal_send_pipe = torch.multiprocessing.Pipe(
+ duplex=False)
+ event_listener_thread = threading.Thread(
+ target=MultiProcessTestCase._event_listener,
+ args=(parent_pipe, signal_recv_pipe, self.rank),
+ daemon=True,
+ )
+ event_listener_thread.start()
+
+ # self.id() == e.g. '__main__.TestDistributed.test_get_rank'
+ # We're retrieving a corresponding test and executing it.
+ try:
+ getattr(self, test_name)()
+ except unittest.SkipTest as se:
+ logger.info(f'Process {self.rank} skipping test {test_name} for '
+ f'following reason: {str(se)}')
+ sys.exit(TEST_SKIPS['generic'].exit_code)
+ except Exception:
+ logger.error(
+ f'Caught exception: \n{traceback.format_exc()} exiting '
+ f'process {self.rank} with exit code: '
+ f'{MultiProcessTestCase.TEST_ERROR_EXIT_CODE}')
+ # Send error to parent process.
+ parent_pipe.send(traceback.format_exc())
+ sys.exit(MultiProcessTestCase.TEST_ERROR_EXIT_CODE)
+ finally:
+ if signal_send_pipe is not None:
+ signal_send_pipe.send(None)
+
+ assert event_listener_thread is not None
+ event_listener_thread.join()
+ # Close pipe after done with test.
+ parent_pipe.close()
+
+ def _get_timedout_process_traceback(self) -> None:
+ pipes = []
+ for i, process in enumerate(self.processes):
+ if process.exitcode is None:
+ pipe = self.pid_to_pipe[process.pid]
+ try:
+ pipe.send(MultiProcessTestCase.Event.GET_TRACEBACK)
+ pipes.append((i, pipe))
+ except ConnectionError as e:
+ logger.error(
+ 'Encountered error while trying to get traceback '
+ f'for process {i}: {e}')
+
+ # Wait for results.
+ for rank, pipe in pipes:
+ try:
+ # Wait for traceback
+ if pipe.poll(5):
+ if pipe.closed:
+ logger.info(
+ f'Pipe closed for process {rank}, cannot retrieve '
+ 'traceback')
+ continue
+
+ traceback = pipe.recv()
+ logger.error(f'Process {rank} timed out with traceback: '
+ f'\n\n{traceback}')
+ else:
+ logger.error('Could not retrieve traceback for timed out '
+ f'process: {rank}')
+ except ConnectionError as e:
+ logger.error(
+ 'Encountered error while trying to get traceback for '
+ f'process {rank}: {e}')
+
+ def _join_processes(self, fn) -> None:
+ start_time = time.time()
+ subprocess_error = False
+ try:
+ while True:
+ # check to see if any subprocess exited with an error early.
+ for (i, p) in enumerate(self.processes):
+ # This is the exit code processes exit with if they
+ # encountered an exception.
+ if p.exitcode == MultiProcessTestCase.TEST_ERROR_EXIT_CODE:
+ print(
+ f'Process {i} terminated with exit code '
+ f'{p.exitcode}, terminating remaining processes.')
+ _active_children = active_children()
+ for ac in _active_children:
+ ac.terminate()
+ subprocess_error = True
+ break
+ if subprocess_error:
+ break
+ # All processes have joined cleanly if they all a valid
+ # exitcode
+ if all([p.exitcode is not None for p in self.processes]):
+ break
+ # Check if we should time out the test. If so, we terminate
+ # each process.
+ elapsed = time.time() - start_time
+ if elapsed > self.timeout:
+ self._get_timedout_process_traceback()
+ print(f'Timing out after {self.timeout} seconds and '
+ 'killing subprocesses.')
+ for p in self.processes:
+ p.terminate()
+ break
+ # Sleep to avoid excessive busy polling.
+ time.sleep(0.1)
+
+ elapsed_time = time.time() - start_time
+
+ if fn in self.skip_return_code_checks:
+ self._check_no_test_errors(elapsed_time)
+ else:
+ self._check_return_codes(elapsed_time)
+ finally:
+ # Close all pipes
+ for pid, pipe in self.pid_to_pipe.items():
+ pipe.close()
+
+ def _check_no_test_errors(self, elapsed_time) -> None:
+ """Checks that we didn't have any errors thrown in the child
+ processes."""
+ for i, p in enumerate(self.processes):
+ if p.exitcode is None:
+ raise RuntimeError(
+ 'Process {} timed out after {} seconds'.format(
+ i, elapsed_time))
+ self.assertNotEqual(self.TEST_ERROR_EXIT_CODE, p.exitcode)
+
+ def _check_return_codes(self, elapsed_time) -> None:
+ """Checks that the return codes of all spawned processes match, and
+ skips tests if they returned a return code indicating a skipping
+ condition."""
+ first_process = self.processes[0]
+ # first, we check if there are errors in actual processes
+ # (via TEST_ERROR_EXIT CODE), and raise an exception for those.
+ # the reason we do this is to attempt to raise a more helpful error
+ # message than "Process x terminated/timed out"
+ # TODO: we should pipe the exception of the failed subprocess here.
+ # Currently, the actual exception is displayed as a logging output.
+ errored_processes = [
+ (i, p) for i, p in enumerate(self.processes)
+ if p.exitcode == MultiProcessTestCase.TEST_ERROR_EXIT_CODE
+ ]
+ if errored_processes:
+ error = ''
+ for i, process in errored_processes:
+ # Get error from pipe.
+ error_message = self.pid_to_pipe[process.pid].recv()
+ error += (
+ 'Process {} exited with error code {} and exception:\n{}\n'
+ .format(i, MultiProcessTestCase.TEST_ERROR_EXIT_CODE,
+ error_message))
+
+ raise RuntimeError(error)
+ # If no process exited uncleanly, we check for timeouts, and then
+ # ensure each process exited cleanly.
+ for i, p in enumerate(self.processes):
+ if p.exitcode is None:
+ raise RuntimeError(
+ f'Process {i} terminated or timed out after '
+ '{elapsed_time} seconds')
+ self.assertEqual(
+ p.exitcode,
+ first_process.exitcode,
+ msg=f'Expect process {i} exit code to match Process 0 exit '
+ 'code of {first_process.exitcode}, but got {p.exitcode}')
+ for skip in TEST_SKIPS.values():
+ if first_process.exitcode == skip.exit_code:
+ raise unittest.SkipTest(skip.message)
+ self.assertEqual(
+ first_process.exitcode,
+ 0,
+ msg=f'Expected zero exit code but got {first_process.exitcode} '
+ f'for pid: {first_process.pid}')
+
+ @property
+ def is_master(self) -> bool:
+ return self.rank == 0
diff --git a/testbed/open-mmlab__mmengine/mmengine/testing/compare.py b/testbed/open-mmlab__mmengine/mmengine/testing/compare.py
new file mode 100644
index 0000000000000000000000000000000000000000..14c7a97ba73ee98600102ab28d649b01aab8f3bc
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/testing/compare.py
@@ -0,0 +1,188 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import sys
+from collections.abc import Iterable
+from runpy import run_path
+from shlex import split
+from typing import Any, Callable, Dict, List, Optional, Union
+from unittest.mock import patch
+
+from torch.nn import GroupNorm, LayerNorm
+from torch.testing import assert_allclose as _assert_allclose
+
+from mmengine.utils import digit_version
+from mmengine.utils.dl_utils import TORCH_VERSION
+from mmengine.utils.dl_utils.parrots_wrapper import _BatchNorm, _InstanceNorm
+
+
+def assert_allclose(
+ actual: Any,
+ expected: Any,
+ rtol: Optional[float] = None,
+ atol: Optional[float] = None,
+ equal_nan: bool = True,
+ msg: Optional[Union[str, Callable]] = '',
+) -> None:
+ """Asserts that ``actual`` and ``expected`` are close. A wrapper function
+ of ``torch.testing.assert_allclose``.
+
+ Args:
+ actual (Any): Actual input.
+ expected (Any): Expected input.
+ rtol (Optional[float]): Relative tolerance. If specified ``atol`` must
+ also be specified. If omitted, default values based on the
+ :attr:`~torch.Tensor.dtype` are selected with the below table.
+ atol (Optional[float]): Absolute tolerance. If specified :attr:`rtol`
+ must also be specified. If omitted, default values based on the
+ :attr:`~torch.Tensor.dtype` are selected with the below table.
+ equal_nan (bool): If ``True``, two ``NaN`` values will be considered
+ equal.
+ msg (Optional[Union[str, Callable]]): Optional error message to use if
+ the values of corresponding tensors mismatch. Unused when PyTorch
+ < 1.6.
+ """
+ if 'parrots' not in TORCH_VERSION and \
+ digit_version(TORCH_VERSION) >= digit_version('1.6'):
+ _assert_allclose(
+ actual,
+ expected,
+ rtol=rtol,
+ atol=atol,
+ equal_nan=equal_nan,
+ msg=msg)
+ else:
+ # torch.testing.assert_allclose has no ``msg`` argument
+ # when PyTorch < 1.6
+ _assert_allclose(
+ actual, expected, rtol=rtol, atol=atol, equal_nan=equal_nan)
+
+
+def check_python_script(cmd):
+ """Run the python cmd script with `__main__`. The difference between
+ `os.system` is that, this function exectues code in the current process, so
+ that it can be tracked by coverage tools. Currently it supports two forms:
+
+ - ./tests/data/scripts/hello.py zz
+ - python tests/data/scripts/hello.py zz
+ """
+ args = split(cmd)
+ if args[0] == 'python':
+ args = args[1:]
+ with patch.object(sys, 'argv', args):
+ run_path(args[0], run_name='__main__')
+
+
+def _any(judge_result):
+ """Since built-in ``any`` works only when the element of iterable is not
+ iterable, implement the function."""
+ if not isinstance(judge_result, Iterable):
+ return judge_result
+
+ try:
+ for element in judge_result:
+ if _any(element):
+ return True
+ except TypeError:
+ # Maybe encounter the case: torch.tensor(True) | torch.tensor(False)
+ if judge_result:
+ return True
+ return False
+
+
+def assert_dict_contains_subset(dict_obj: Dict[Any, Any],
+ expected_subset: Dict[Any, Any]) -> bool:
+ """Check if the dict_obj contains the expected_subset.
+
+ Args:
+ dict_obj (Dict[Any, Any]): Dict object to be checked.
+ expected_subset (Dict[Any, Any]): Subset expected to be contained in
+ dict_obj.
+
+ Returns:
+ bool: Whether the dict_obj contains the expected_subset.
+ """
+
+ for key, value in expected_subset.items():
+ if key not in dict_obj.keys() or _any(dict_obj[key] != value):
+ return False
+ return True
+
+
+def assert_attrs_equal(obj: Any, expected_attrs: Dict[str, Any]) -> bool:
+ """Check if attribute of class object is correct.
+
+ Args:
+ obj (object): Class object to be checked.
+ expected_attrs (Dict[str, Any]): Dict of the expected attrs.
+
+ Returns:
+ bool: Whether the attribute of class object is correct.
+ """
+ for attr, value in expected_attrs.items():
+ if not hasattr(obj, attr) or _any(getattr(obj, attr) != value):
+ return False
+ return True
+
+
+def assert_dict_has_keys(obj: Dict[str, Any],
+ expected_keys: List[str]) -> bool:
+ """Check if the obj has all the expected_keys.
+
+ Args:
+ obj (Dict[str, Any]): Object to be checked.
+ expected_keys (List[str]): Keys expected to contained in the keys of
+ the obj.
+
+ Returns:
+ bool: Whether the obj has the expected keys.
+ """
+ return set(expected_keys).issubset(set(obj.keys()))
+
+
+def assert_keys_equal(result_keys: List[str], target_keys: List[str]) -> bool:
+ """Check if target_keys is equal to result_keys.
+
+ Args:
+ result_keys (List[str]): Result keys to be checked.
+ target_keys (List[str]): Target keys to be checked.
+
+ Returns:
+ bool: Whether target_keys is equal to result_keys.
+ """
+ return set(result_keys) == set(target_keys)
+
+
+def assert_is_norm_layer(module) -> bool:
+ """Check if the module is a norm layer.
+
+ Args:
+ module (nn.Module): The module to be checked.
+
+ Returns:
+ bool: Whether the module is a norm layer.
+ """
+
+ norm_layer_candidates = (_BatchNorm, _InstanceNorm, GroupNorm, LayerNorm)
+ return isinstance(module, norm_layer_candidates)
+
+
+def assert_params_all_zeros(module) -> bool:
+ """Check if the parameters of the module is all zeros.
+
+ Args:
+ module (nn.Module): The module to be checked.
+
+ Returns:
+ bool: Whether the parameters of the module is all zeros.
+ """
+ weight_data = module.weight.data
+ is_weight_zero = weight_data.allclose(
+ weight_data.new_zeros(weight_data.size()))
+
+ if hasattr(module, 'bias') and module.bias is not None:
+ bias_data = module.bias.data
+ is_bias_zero = bias_data.allclose(
+ bias_data.new_zeros(bias_data.size()))
+ else:
+ is_bias_zero = True
+
+ return is_weight_zero and is_bias_zero
diff --git a/testbed/open-mmlab__mmengine/mmengine/testing/runner_test_case.py b/testbed/open-mmlab__mmengine/mmengine/testing/runner_test_case.py
new file mode 100644
index 0000000000000000000000000000000000000000..16f91700a224085990f2ec485c6236f8fc66c854
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/testing/runner_test_case.py
@@ -0,0 +1,186 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import logging
+import os
+import tempfile
+import time
+from unittest import TestCase
+from uuid import uuid4
+
+import torch
+import torch.nn as nn
+from torch.distributed import destroy_process_group
+from torch.utils.data import Dataset
+
+import mmengine.hooks # noqa F401
+import mmengine.optim # noqa F401
+from mmengine.config import Config
+from mmengine.dist import is_distributed
+from mmengine.evaluator import BaseMetric
+from mmengine.logging import MessageHub, MMLogger
+from mmengine.model import BaseModel
+from mmengine.registry import DATASETS, METRICS, MODELS, DefaultScope
+from mmengine.runner import Runner
+from mmengine.visualization import Visualizer
+
+
+class ToyModel(BaseModel):
+
+ def __init__(self, data_preprocessor=None):
+ super().__init__(data_preprocessor=data_preprocessor)
+ self.linear1 = nn.Linear(2, 2)
+ self.linear2 = nn.Linear(2, 1)
+
+ def forward(self, inputs, data_samples, mode='tensor'):
+ if isinstance(inputs, list):
+ inputs = torch.stack(inputs)
+ if isinstance(data_samples, list):
+ data_sample = torch.stack(data_samples)
+ outputs = self.linear1(inputs)
+ outputs = self.linear2(outputs)
+
+ if mode == 'tensor':
+ return outputs
+ elif mode == 'loss':
+ loss = (data_sample - outputs).sum()
+ outputs = dict(loss=loss)
+ return outputs
+ elif mode == 'predict':
+ return outputs
+
+
+class ToyDataset(Dataset):
+ METAINFO = dict() # type: ignore
+ data = torch.randn(12, 2)
+ label = torch.ones(12)
+
+ @property
+ def metainfo(self):
+ return self.METAINFO
+
+ def __len__(self):
+ return self.data.size(0)
+
+ def __getitem__(self, index):
+ return dict(inputs=self.data[index], data_samples=self.label[index])
+
+
+class ToyMetric(BaseMetric):
+
+ def __init__(self, collect_device='cpu', dummy_metrics=None):
+ super().__init__(collect_device=collect_device)
+ self.dummy_metrics = dummy_metrics
+
+ def process(self, data_batch, predictions):
+ result = {'acc': 1}
+ self.results.append(result)
+
+ def compute_metrics(self, results):
+ return dict(acc=1)
+
+
+class RunnerTestCase(TestCase):
+ """A test case to build runner easily.
+
+ `RunnerTestCase` will do the following things:
+
+ 1. Registers a toy model, a toy metric, and a toy dataset, which can be
+ used to run the `Runner` successfully.
+ 2. Provides epoch based and iteration based cfg to build runner.
+ 3. Provides `build_runner` method to build runner easily.
+ 4. Clean the global variable used by the runner.
+ """
+ dist_cfg = dict(
+ MASTER_ADDR='127.0.0.1',
+ MASTER_PORT=29600,
+ RANK='0',
+ WORLD_SIZE='1',
+ LOCAL_RANK='0')
+
+ def setUp(self) -> None:
+ self.temp_dir = tempfile.TemporaryDirectory()
+ # Prevent from registering module with the same name by other unit
+ # test. These registries will be cleared in `tearDown`
+ MODELS.register_module(module=ToyModel, force=True)
+ METRICS.register_module(module=ToyMetric, force=True)
+ DATASETS.register_module(module=ToyDataset, force=True)
+ epoch_based_cfg = dict(
+ work_dir=self.temp_dir.name,
+ model=dict(type='ToyModel'),
+ train_dataloader=dict(
+ dataset=dict(type='ToyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ batch_size=3,
+ num_workers=0),
+ val_dataloader=dict(
+ dataset=dict(type='ToyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=False),
+ batch_size=3,
+ num_workers=0),
+ val_evaluator=[dict(type='ToyMetric')],
+ test_dataloader=dict(
+ dataset=dict(type='ToyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=False),
+ batch_size=3,
+ num_workers=0),
+ test_evaluator=[dict(type='ToyMetric')],
+ optim_wrapper=dict(optimizer=dict(type='SGD', lr=0.1)),
+ train_cfg=dict(by_epoch=True, max_epochs=2, val_interval=1),
+ val_cfg=dict(),
+ test_cfg=dict(),
+ default_hooks=dict(logger=dict(type='LoggerHook', interval=1)),
+ custom_hooks=[],
+ env_cfg=dict(dist_cfg=dict(backend='nccl')),
+ experiment_name='test1')
+ self.epoch_based_cfg = Config(epoch_based_cfg)
+
+ # prepare iter based cfg.
+ self.iter_based_cfg: Config = copy.deepcopy(self.epoch_based_cfg)
+ self.iter_based_cfg.train_dataloader = dict(
+ dataset=dict(type='ToyDataset'),
+ sampler=dict(type='InfiniteSampler', shuffle=True),
+ batch_size=3,
+ num_workers=0)
+ self.iter_based_cfg.log_processor = dict(by_epoch=False)
+
+ self.iter_based_cfg.train_cfg = dict(by_epoch=False, max_iters=12)
+ self.iter_based_cfg.default_hooks = dict(
+ logger=dict(type='LoggerHook', interval=1),
+ checkpoint=dict(
+ type='CheckpointHook', interval=12, by_epoch=False))
+
+ def tearDown(self):
+ # `FileHandler` should be closed in Windows, otherwise we cannot
+ # delete the temporary directory
+ logging.shutdown()
+ MMLogger._instance_dict.clear()
+ Visualizer._instance_dict.clear()
+ DefaultScope._instance_dict.clear()
+ MessageHub._instance_dict.clear()
+ MODELS.module_dict.pop('ToyModel', None)
+ METRICS.module_dict.pop('ToyMetric', None)
+ DATASETS.module_dict.pop('ToyDataset', None)
+ self.temp_dir.cleanup()
+ if is_distributed():
+ destroy_process_group()
+
+ def build_runner(self, cfg: Config):
+ cfg.experiment_name = self.experiment_name
+ runner = Runner.from_cfg(cfg)
+ return runner
+
+ @property
+ def experiment_name(self):
+ # Since runners could be built too fast to have a unique experiment
+ # name(timestamp is the same), here we use uuid to make sure each
+ # runner has the unique experiment name.
+ return f'{self._testMethodName}_{time.time()} + ' \
+ f'{uuid4()}'
+
+ def setup_dist_env(self):
+ self.dist_cfg['MASTER_PORT'] += 1
+ os.environ['MASTER_PORT'] = str(self.dist_cfg['MASTER_PORT'])
+ os.environ['MASTER_ADDR'] = self.dist_cfg['MASTER_ADDR']
+ os.environ['RANK'] = self.dist_cfg['RANK']
+ os.environ['WORLD_SIZE'] = self.dist_cfg['WORLD_SIZE']
+ os.environ['LOCAL_RANK'] = self.dist_cfg['LOCAL_RANK']
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/__init__.py b/testbed/open-mmlab__mmengine/mmengine/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ad47dda3908e73056d6e0aa1c00cd9918fff332
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/__init__.py
@@ -0,0 +1,31 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .manager import ManagerMeta, ManagerMixin
+from .misc import (check_prerequisites, concat_list, deprecated_api_warning,
+ deprecated_function, has_method,
+ import_modules_from_strings, is_list_of,
+ is_method_overridden, is_seq_of, is_str, is_tuple_of,
+ iter_cast, list_cast, requires_executable, requires_package,
+ slice_list, to_1tuple, to_2tuple, to_3tuple, to_4tuple,
+ to_ntuple, tuple_cast)
+from .package_utils import (call_command, get_installed_path, install_package,
+ is_installed)
+from .path import (check_file_exist, fopen, is_abs, is_filepath,
+ mkdir_or_exist, scandir, symlink)
+from .progressbar import (ProgressBar, track_iter_progress,
+ track_parallel_progress, track_progress)
+from .timer import Timer, TimerError, check_time
+from .version_utils import digit_version, get_git_hash
+
+__all__ = [
+ 'is_str', 'iter_cast', 'list_cast', 'tuple_cast', 'is_seq_of',
+ 'is_list_of', 'is_tuple_of', 'slice_list', 'concat_list',
+ 'check_prerequisites', 'requires_package', 'requires_executable',
+ 'is_filepath', 'fopen', 'check_file_exist', 'mkdir_or_exist', 'symlink',
+ 'scandir', 'deprecated_api_warning', 'import_modules_from_strings',
+ 'to_1tuple', 'to_2tuple', 'to_3tuple', 'to_4tuple', 'to_ntuple',
+ 'is_installed', 'call_command', 'get_installed_path', 'install_package',
+ 'is_abs', 'is_method_overridden', 'has_method', 'digit_version',
+ 'get_git_hash', 'ManagerMeta', 'ManagerMixin', 'Timer', 'check_time',
+ 'TimerError', 'ProgressBar', 'track_iter_progress',
+ 'track_parallel_progress', 'track_progress', 'deprecated_function'
+]
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/__init__.py b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..305ea898904e359d61e3aab8e51897a9d035b08e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/__init__.py
@@ -0,0 +1,16 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+
+from .collect_env import collect_env
+from .hub import load_url
+from .misc import has_batch_norm, is_norm, mmcv_full_available, tensor2imgs
+from .parrots_wrapper import TORCH_VERSION
+from .setup_env import set_multi_processing
+from .time_counter import TimeCounter
+from .torch_ops import torch_meshgrid
+from .trace import is_jit_tracing
+
+__all__ = [
+ 'load_url', 'TORCH_VERSION', 'set_multi_processing', 'has_batch_norm',
+ 'is_norm', 'tensor2imgs', 'mmcv_full_available', 'collect_env',
+ 'torch_meshgrid', 'is_jit_tracing', 'TimeCounter'
+]
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/collect_env.py b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/collect_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..c04b8df18a588af4ab14f1b2cb786d1ae4265f66
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/collect_env.py
@@ -0,0 +1,134 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+"""This file holding some environment constant for sharing by other files."""
+import os.path as osp
+import subprocess
+import sys
+from collections import OrderedDict, defaultdict
+from distutils import errors
+
+import cv2
+import numpy as np
+import torch
+
+import mmengine
+from .parrots_wrapper import TORCH_VERSION, get_build_config, is_rocm_pytorch
+
+
+def _get_cuda_home():
+ if TORCH_VERSION == 'parrots':
+ from parrots.utils.build_extension import CUDA_HOME
+ else:
+ if is_rocm_pytorch():
+ from torch.utils.cpp_extension import ROCM_HOME
+ CUDA_HOME = ROCM_HOME
+ else:
+ from torch.utils.cpp_extension import CUDA_HOME
+ return CUDA_HOME
+
+
+def collect_env():
+ """Collect the information of the running environments.
+
+ Returns:
+ dict: The environment information. The following fields are contained.
+
+ - sys.platform: The variable of ``sys.platform``.
+ - Python: Python version.
+ - CUDA available: Bool, indicating if CUDA is available.
+ - GPU devices: Device type of each GPU.
+ - CUDA_HOME (optional): The env var ``CUDA_HOME``.
+ - NVCC (optional): NVCC version.
+ - GCC: GCC version, "n/a" if GCC is not installed.
+ - MSVC: Microsoft Virtual C++ Compiler version, Windows only.
+ - PyTorch: PyTorch version.
+ - PyTorch compiling details: The output of \
+ ``torch.__config__.show()``.
+ - TorchVision (optional): TorchVision version.
+ - OpenCV (optional): OpenCV version.
+ - MMENGINE: MMENGINE version.
+ """
+ env_info = OrderedDict()
+ env_info['sys.platform'] = sys.platform
+ env_info['Python'] = sys.version.replace('\n', '')
+
+ cuda_available = torch.cuda.is_available()
+ env_info['CUDA available'] = cuda_available
+
+ env_info['numpy_random_seed'] = np.random.get_state()[1][0]
+
+ if cuda_available:
+ devices = defaultdict(list)
+ for k in range(torch.cuda.device_count()):
+ devices[torch.cuda.get_device_name(k)].append(str(k))
+ for name, device_ids in devices.items():
+ env_info['GPU ' + ','.join(device_ids)] = name
+
+ CUDA_HOME = _get_cuda_home()
+ env_info['CUDA_HOME'] = CUDA_HOME
+
+ if CUDA_HOME is not None and osp.isdir(CUDA_HOME):
+ if CUDA_HOME == '/opt/rocm':
+ try:
+ nvcc = osp.join(CUDA_HOME, 'hip/bin/hipcc')
+ nvcc = subprocess.check_output(
+ f'"{nvcc}" --version', shell=True)
+ nvcc = nvcc.decode('utf-8').strip()
+ release = nvcc.rfind('HIP version:')
+ build = nvcc.rfind('')
+ nvcc = nvcc[release:build].strip()
+ except subprocess.SubprocessError:
+ nvcc = 'Not Available'
+ else:
+ try:
+ nvcc = osp.join(CUDA_HOME, 'bin/nvcc')
+ nvcc = subprocess.check_output(f'"{nvcc}" -V', shell=True)
+ nvcc = nvcc.decode('utf-8').strip()
+ release = nvcc.rfind('Cuda compilation tools')
+ build = nvcc.rfind('Build ')
+ nvcc = nvcc[release:build].strip()
+ except subprocess.SubprocessError:
+ nvcc = 'Not Available'
+ env_info['NVCC'] = nvcc
+
+ try:
+ # Check C++ Compiler.
+ # For Unix-like, sysconfig has 'CC' variable like 'gcc -pthread ...',
+ # indicating the compiler used, we use this to get the compiler name
+ import sysconfig
+ cc = sysconfig.get_config_var('CC')
+ if cc:
+ cc = osp.basename(cc.split()[0])
+ cc_info = subprocess.check_output(f'{cc} --version', shell=True)
+ env_info['GCC'] = cc_info.decode('utf-8').partition(
+ '\n')[0].strip()
+ else:
+ # on Windows, cl.exe is not in PATH. We need to find the path.
+ # distutils.ccompiler.new_compiler() returns a msvccompiler
+ # object and after initialization, path to cl.exe is found.
+ import locale
+ import os
+ from distutils.ccompiler import new_compiler
+ ccompiler = new_compiler()
+ ccompiler.initialize()
+ cc = subprocess.check_output(
+ f'{ccompiler.cc}', stderr=subprocess.STDOUT, shell=True)
+ encoding = os.device_encoding(
+ sys.stdout.fileno()) or locale.getpreferredencoding()
+ env_info['MSVC'] = cc.decode(encoding).partition('\n')[0].strip()
+ env_info['GCC'] = 'n/a'
+ except (subprocess.CalledProcessError, errors.DistutilsPlatformError):
+ env_info['GCC'] = 'n/a'
+
+ env_info['PyTorch'] = torch.__version__
+ env_info['PyTorch compiling details'] = get_build_config()
+
+ try:
+ import torchvision
+ env_info['TorchVision'] = torchvision.__version__
+ except ModuleNotFoundError:
+ pass
+
+ env_info['OpenCV'] = cv2.__version__
+ env_info['MMEngine'] = mmengine.__version__
+
+ return env_info
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/hub.py b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/hub.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb801168c29bcb750da3a3f0d70a78906e2a048e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/hub.py
@@ -0,0 +1,128 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+# The 1.6 release of PyTorch switched torch.save to use a new zipfile-based
+# file format. It will cause RuntimeError when a checkpoint was saved in
+# torch >= 1.6.0 but loaded in torch < 1.7.0.
+# More details at https://github.com/open-mmlab/mmpose/issues/904
+
+from ..path import mkdir_or_exist
+from ..version_utils import digit_version
+from .parrots_wrapper import TORCH_VERSION
+
+if TORCH_VERSION != 'parrots' and digit_version(TORCH_VERSION) < digit_version(
+ '1.7.0'):
+ # Modified from https://github.com/pytorch/pytorch/blob/master/torch/hub.py
+ import os
+ import sys
+ import warnings
+ import zipfile
+ from urllib.parse import urlparse
+
+ import torch
+ from torch.hub import HASH_REGEX, _get_torch_home, download_url_to_file
+
+ # Hub used to support automatically extracts from zipfile manually
+ # compressed by users. The legacy zip format expects only one file from
+ # torch.save() < 1.6 in the zip. We should remove this support since
+ # zipfile is now default zipfile format for torch.save().
+ def _is_legacy_zip_format(filename):
+ if zipfile.is_zipfile(filename):
+ infolist = zipfile.ZipFile(filename).infolist()
+ return len(infolist) == 1 and not infolist[0].is_dir()
+ return False
+
+ def _legacy_zip_load(filename, model_dir, map_location):
+ warnings.warn(
+ 'Falling back to the old format < 1.6. This support will'
+ ' be deprecated in favor of default zipfile format '
+ 'introduced in 1.6. Please redo torch.save() to save it '
+ 'in the new zipfile format.', DeprecationWarning)
+ # Note: extractall() defaults to overwrite file if exists. No need to
+ # clean up beforehand. We deliberately don't handle tarfile here
+ # since our legacy serialization format was in tar.
+ # E.g. resnet18-5c106cde.pth which is widely used.
+ with zipfile.ZipFile(filename) as f:
+ members = f.infolist()
+ if len(members) != 1:
+ raise RuntimeError(
+ 'Only one file(not dir) is allowed in the zipfile')
+ f.extractall(model_dir)
+ extraced_name = members[0].filename
+ extracted_file = os.path.join(model_dir, extraced_name)
+ return torch.load(extracted_file, map_location=map_location)
+
+ def load_url(url,
+ model_dir=None,
+ map_location=None,
+ progress=True,
+ check_hash=False,
+ file_name=None):
+ r"""Loads the Torch serialized object at the given URL.
+ If downloaded file is a zip file, it will be automatically decompressed
+ If the object is already present in `model_dir`, it's deserialized and
+ returned.
+ The default value of ``model_dir`` is ``/checkpoints`` where
+ ``hub_dir`` is the directory returned by :func:`~torch.hub.get_dir`.
+ Args:
+ url (str): URL of the object to download
+ model_dir (str, optional): directory in which to save the object
+ map_location (optional): a function or a dict specifying how to
+ remap storage locations (see torch.load)
+ progress (bool, optional): whether or not to display a progress bar
+ to stderr. Default: True
+ check_hash(bool, optional): If True, the filename part of the URL
+ should follow the naming convention ``filename-.ext``
+ where ```` is the first eight or more digits of the
+ SHA256 hash of the contents of the file. The hash is used to
+ ensure unique names and to verify the contents of the file.
+ Default: False
+ file_name (str, optional): name for the downloaded file. Filename
+ from ``url`` will be used if not set. Default: None.
+ Example:
+ >>> url = ('https://s3.amazonaws.com/pytorch/models/resnet18-5c106'
+ ... 'cde.pth')
+ >>> state_dict = torch.hub.load_state_dict_from_url(url)
+ """
+ # Issue warning to move data if old env is set
+ if os.getenv('TORCH_MODEL_ZOO'):
+ warnings.warn(
+ 'TORCH_MODEL_ZOO is deprecated, please use env '
+ 'TORCH_HOME instead', DeprecationWarning)
+
+ if model_dir is None:
+ torch_home = _get_torch_home()
+ model_dir = os.path.join(torch_home, 'checkpoints')
+
+ mkdir_or_exist(model_dir)
+
+ parts = urlparse(url)
+ filename = os.path.basename(parts.path)
+ if file_name is not None:
+ filename = file_name
+ cached_file = os.path.join(model_dir, filename)
+ if not os.path.exists(cached_file):
+ sys.stderr.write('Downloading: "{}" to {}\n'.format(
+ url, cached_file))
+ hash_prefix = None
+ if check_hash:
+ r = HASH_REGEX.search(filename) # r is Optional[Match[str]]
+ hash_prefix = r.group(1) if r else None
+ download_url_to_file(
+ url, cached_file, hash_prefix, progress=progress)
+
+ if _is_legacy_zip_format(cached_file):
+ return _legacy_zip_load(cached_file, model_dir, map_location)
+
+ try:
+ return torch.load(cached_file, map_location=map_location)
+ except RuntimeError as error:
+ if digit_version(TORCH_VERSION) < digit_version('1.5.0'):
+ warnings.warn(
+ f'If the error is the same as "{cached_file} is a zip '
+ 'archive (did you mean to use torch.jit.load()?)", you can'
+ ' upgrade your torch to 1.5.0 or higher (current torch '
+ f'version is {TORCH_VERSION}). The error was raised '
+ ' because the checkpoint was saved in torch>=1.6.0 but '
+ 'loaded in torch<1.5.')
+ raise error
+else:
+ from torch.utils.model_zoo import load_url # type: ignore # noqa: F401
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/misc.py b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce52d22c3b225abafdc11c43ad1083f3b93b75e0
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/misc.py
@@ -0,0 +1,110 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import pkgutil
+from typing import Optional, Tuple, Union
+
+import numpy as np
+import torch
+import torch.nn as nn
+
+from ..misc import is_tuple_of
+from .parrots_wrapper import _BatchNorm, _InstanceNorm
+
+
+def is_norm(layer: nn.Module,
+ exclude: Optional[Union[type, Tuple[type]]] = None) -> bool:
+ """Check if a layer is a normalization layer.
+
+ Args:
+ layer (nn.Module): The layer to be checked.
+ exclude (type, tuple[type], optional): Types to be excluded.
+
+ Returns:
+ bool: Whether the layer is a norm layer.
+ """
+ if exclude is not None:
+ if not isinstance(exclude, tuple):
+ exclude = (exclude, )
+ if not is_tuple_of(exclude, type):
+ raise TypeError(
+ f'"exclude" must be either None or type or a tuple of types, '
+ f'but got {type(exclude)}: {exclude}')
+
+ if exclude and isinstance(layer, exclude):
+ return False
+
+ all_norm_bases = (_BatchNorm, _InstanceNorm, nn.GroupNorm, nn.LayerNorm)
+ return isinstance(layer, all_norm_bases)
+
+
+def tensor2imgs(tensor: torch.Tensor,
+ mean: Optional[Tuple[float, float, float]] = None,
+ std: Optional[Tuple[float, float, float]] = None,
+ to_bgr: bool = True):
+ """Convert tensor to 3-channel images or 1-channel gray images.
+
+ Args:
+ tensor (torch.Tensor): Tensor that contains multiple images, shape (
+ N, C, H, W). :math:`C` can be either 3 or 1. If C is 3, the format
+ should be RGB.
+ mean (tuple[float], optional): Mean of images. If None,
+ (0, 0, 0) will be used for tensor with 3-channel,
+ while (0, ) for tensor with 1-channel. Defaults to None.
+ std (tuple[float], optional): Standard deviation of images. If None,
+ (1, 1, 1) will be used for tensor with 3-channel,
+ while (1, ) for tensor with 1-channel. Defaults to None.
+ to_bgr (bool): For the tensor with 3 channel, convert its format to
+ BGR. For the tensor with 1 channel, it must be False. Defaults to
+ True.
+
+ Returns:
+ list[np.ndarray]: A list that contains multiple images.
+ """
+
+ assert torch.is_tensor(tensor) and tensor.ndim == 4
+ channels = tensor.size(1)
+ assert channels in [1, 3]
+ if mean is None:
+ mean = (0, ) * channels
+ if std is None:
+ std = (1, ) * channels
+ assert (channels == len(mean) == len(std) == 3) or \
+ (channels == len(mean) == len(std) == 1 and not to_bgr)
+ mean = tensor.new_tensor(mean).view(1, -1)
+ std = tensor.new_tensor(std).view(1, -1)
+ tensor = tensor.permute(0, 2, 3, 1) * std + mean
+ imgs = tensor.detach().cpu().numpy()
+ if to_bgr and channels == 3:
+ imgs = imgs[:, :, :, (2, 1, 0)] # RGB2BGR
+ imgs = [np.ascontiguousarray(img) for img in imgs]
+ return imgs
+
+
+def has_batch_norm(model: nn.Module) -> bool:
+ """Detect whether model has a BatchNormalization layer.
+
+ Args:
+ model (nn.Module): training model.
+
+ Returns:
+ bool: whether model has a BatchNormalization layer
+ """
+ if isinstance(model, _BatchNorm):
+ return True
+ for m in model.children():
+ if has_batch_norm(m):
+ return True
+ return False
+
+
+def mmcv_full_available() -> bool:
+ """Check whether mmcv-full is installed.
+
+ Returns:
+ bool: True if mmcv-full is installed else False.
+ """
+ try:
+ import mmcv # noqa: F401
+ except ImportError:
+ return False
+ ext_loader = pkgutil.find_loader('mmcv._ext')
+ return ext_loader is not None
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/parrots_wrapper.py b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/parrots_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..edda5bdcda808fb55a2fe6265b5285e65d49a398
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/parrots_wrapper.py
@@ -0,0 +1,119 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from functools import partial
+from typing import Optional
+
+import torch
+
+TORCH_VERSION = torch.__version__
+
+
+def is_rocm_pytorch() -> bool:
+ """Check whether the PyTorch is compiled on ROCm."""
+ is_rocm = False
+ if TORCH_VERSION != 'parrots':
+ try:
+ from torch.utils.cpp_extension import ROCM_HOME
+ is_rocm = True if ((torch.version.hip is not None) and
+ (ROCM_HOME is not None)) else False
+ except ImportError:
+ pass
+ return is_rocm
+
+
+def _get_cuda_home() -> Optional[str]:
+ """Obtain the path of CUDA home."""
+ if TORCH_VERSION == 'parrots':
+ from parrots.utils.build_extension import CUDA_HOME
+ else:
+ if is_rocm_pytorch():
+ from torch.utils.cpp_extension import ROCM_HOME
+ CUDA_HOME = ROCM_HOME
+ else:
+ from torch.utils.cpp_extension import CUDA_HOME
+ return CUDA_HOME
+
+
+def get_build_config():
+ """Obtain the build information of PyTorch or Parrots."""
+ if TORCH_VERSION == 'parrots':
+ from parrots.config import get_build_info
+ return get_build_info()
+ else:
+ return torch.__config__.show()
+
+
+def _get_conv() -> tuple:
+ """A wrapper to obtain base classes of Conv layers from PyTorch or
+ Parrots."""
+ if TORCH_VERSION == 'parrots':
+ from parrots.nn.modules.conv import _ConvNd, _ConvTransposeMixin
+ else:
+ from torch.nn.modules.conv import _ConvNd, _ConvTransposeMixin
+ return _ConvNd, _ConvTransposeMixin
+
+
+def _get_dataloader() -> tuple:
+ """A wrapper to obtain DataLoader class from PyTorch or Parrots."""
+ if TORCH_VERSION == 'parrots':
+ from torch.utils.data import DataLoader, PoolDataLoader
+ else:
+ from torch.utils.data import DataLoader
+ PoolDataLoader = DataLoader
+ return DataLoader, PoolDataLoader
+
+
+def _get_extension():
+ """A wrapper to obtain extension class from PyTorch or Parrots."""
+ if TORCH_VERSION == 'parrots':
+ from parrots.utils.build_extension import BuildExtension, Extension
+ CppExtension = partial(Extension, cuda=False)
+ CUDAExtension = partial(Extension, cuda=True)
+ else:
+ from torch.utils.cpp_extension import (BuildExtension, CppExtension,
+ CUDAExtension)
+ return BuildExtension, CppExtension, CUDAExtension
+
+
+def _get_pool() -> tuple:
+ """A wrapper to obtain base classes of pooling layers from PyTorch or
+ Parrots."""
+ if TORCH_VERSION == 'parrots':
+ from parrots.nn.modules.pool import (_AdaptiveAvgPoolNd,
+ _AdaptiveMaxPoolNd, _AvgPoolNd,
+ _MaxPoolNd)
+ else:
+ from torch.nn.modules.pooling import (_AdaptiveAvgPoolNd,
+ _AdaptiveMaxPoolNd, _AvgPoolNd,
+ _MaxPoolNd)
+ return _AdaptiveAvgPoolNd, _AdaptiveMaxPoolNd, _AvgPoolNd, _MaxPoolNd
+
+
+def _get_norm() -> tuple:
+ """A wrapper to obtain base classes of normalization layers from PyTorch or
+ Parrots."""
+ if TORCH_VERSION == 'parrots':
+ from parrots.nn.modules.batchnorm import _BatchNorm, _InstanceNorm
+ SyncBatchNorm_ = torch.nn.SyncBatchNorm2d
+ else:
+ from torch.nn.modules.batchnorm import _BatchNorm
+ from torch.nn.modules.instancenorm import _InstanceNorm
+ SyncBatchNorm_ = torch.nn.SyncBatchNorm
+ return _BatchNorm, _InstanceNorm, SyncBatchNorm_
+
+
+_ConvNd, _ConvTransposeMixin = _get_conv()
+DataLoader, PoolDataLoader = _get_dataloader()
+BuildExtension, CppExtension, CUDAExtension = _get_extension()
+_BatchNorm, _InstanceNorm, SyncBatchNorm_ = _get_norm()
+_AdaptiveAvgPoolNd, _AdaptiveMaxPoolNd, _AvgPoolNd, _MaxPoolNd = _get_pool()
+
+
+class SyncBatchNorm(SyncBatchNorm_): # type: ignore
+
+ def _check_input_dim(self, input):
+ if TORCH_VERSION == 'parrots':
+ if input.dim() < 2:
+ raise ValueError(
+ f'expected at least 2D input (got {input.dim()}D input)')
+ else:
+ super()._check_input_dim(input)
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/setup_env.py b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/setup_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c23a56a1342b6dc4312e6e98ef1d356e84faef4
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/setup_env.py
@@ -0,0 +1,61 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import platform
+import warnings
+
+import torch.multiprocessing as mp
+
+
+def set_multi_processing(mp_start_method: str = 'fork',
+ opencv_num_threads: int = 0,
+ distributed: bool = False) -> None:
+ """Set multi-processing related environment.
+
+ Args:
+ mp_start_method (str): Set the method which should be used to start
+ child processes. Defaults to 'fork'.
+ opencv_num_threads (int): Number of threads for opencv.
+ Defaults to 0.
+ distributed (bool): True if distributed environment.
+ Defaults to False.
+ """
+ # set multi-process start method as `fork` to speed up the training
+ if platform.system() != 'Windows':
+ current_method = mp.get_start_method(allow_none=True)
+ if (current_method is not None and current_method != mp_start_method):
+ warnings.warn(
+ f'Multi-processing start method `{mp_start_method}` is '
+ f'different from the previous setting `{current_method}`.'
+ f'It will be force set to `{mp_start_method}`. You can '
+ 'change this behavior by changing `mp_start_method` in '
+ 'your config.')
+ mp.set_start_method(mp_start_method, force=True)
+
+ try:
+ import cv2
+
+ # disable opencv multithreading to avoid system being overloaded
+ cv2.setNumThreads(opencv_num_threads)
+ except ImportError:
+ pass
+
+ # setup OMP threads
+ # This code is referred from https://github.com/pytorch/pytorch/blob/master/torch/distributed/run.py # noqa
+ if 'OMP_NUM_THREADS' not in os.environ and distributed:
+ omp_num_threads = 1
+ warnings.warn(
+ 'Setting OMP_NUM_THREADS environment variable for each process'
+ f' to be {omp_num_threads} in default, to avoid your system '
+ 'being overloaded, please further tune the variable for '
+ 'optimal performance in your application as needed.')
+ os.environ['OMP_NUM_THREADS'] = str(omp_num_threads)
+
+ # setup MKL threads
+ if 'MKL_NUM_THREADS' not in os.environ and distributed:
+ mkl_num_threads = 1
+ warnings.warn(
+ 'Setting MKL_NUM_THREADS environment variable for each process'
+ f' to be {mkl_num_threads} in default, to avoid your system '
+ 'being overloaded, please further tune the variable for '
+ 'optimal performance in your application as needed.')
+ os.environ['MKL_NUM_THREADS'] = str(mkl_num_threads)
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/time_counter.py b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/time_counter.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a1fb42ee0406d1c00bce354691da523df575cfd
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/time_counter.py
@@ -0,0 +1,134 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import time
+from typing import Optional, Union
+
+import torch
+
+from mmengine.dist.utils import master_only
+from mmengine.logging import MMLogger, print_log
+
+
+class TimeCounter:
+ """A tool that counts the average running time of a function or a method.
+ Users can use it as a decorator or context manager to calculate the average
+ running time of code blocks.
+
+ Args:
+ log_interval (int): The interval of logging. Defaults to 1.
+ warmup_interval (int): The interval of warmup. Defaults to 1.
+ with_sync (bool): Whether to synchronize cuda. Defaults to True.
+ tag (str, optional): Function tag. Used to distinguish between
+ different functions or methods being called. Defaults to None.
+ logger (MMLogger, optional): Formatted logger used to record messages.
+ Defaults to None.
+
+ Examples:
+ >>> import time
+ >>> from mmengine.utils.dl_utils import TimeCounter
+ >>> @TimeCounter()
+ ... def fun1():
+ ... time.sleep(0.1)
+ ... fun1()
+ [fun1]-time per run averaged in the past 1 runs: 100.0 ms
+
+ >>> @@TimeCounter(log_interval=2, tag='fun')
+ ... def fun2():
+ ... time.sleep(0.2)
+ >>> for _ in range(3):
+ ... fun2()
+ [fun]-time per run averaged in the past 2 runs: 200.0 ms
+
+ >>> with TimeCounter(tag='fun3'):
+ ... time.sleep(0.3)
+ [fun3]-time per run averaged in the past 1 runs: 300.0 ms
+ """
+
+ instance_dict: dict = dict()
+
+ log_interval: int
+ warmup_interval: int
+ logger: Optional[MMLogger]
+ __count: int
+ __pure_inf_time: float
+
+ def __new__(cls,
+ log_interval: int = 1,
+ warmup_interval: int = 1,
+ with_sync: bool = True,
+ tag: Optional[str] = None,
+ logger: Optional[MMLogger] = None):
+ assert warmup_interval >= 1
+ if tag is not None and tag in cls.instance_dict:
+ return cls.instance_dict[tag]
+
+ instance = super().__new__(cls)
+ cls.instance_dict[tag] = instance
+
+ instance.log_interval = log_interval
+ instance.warmup_interval = warmup_interval
+ instance.with_sync = with_sync
+ instance.tag = tag
+ instance.logger = logger
+
+ instance.__count = 0
+ instance.__pure_inf_time = 0.
+ instance.__start_time = 0.
+
+ return instance
+
+ @master_only
+ def __call__(self, fn):
+ if self.tag is None:
+ self.tag = fn.__name__
+
+ def wrapper(*args, **kwargs):
+ self.__count += 1
+
+ if self.with_sync and torch.cuda.is_available():
+ torch.cuda.synchronize()
+ start_time = time.perf_counter()
+
+ result = fn(*args, **kwargs)
+
+ if self.with_sync and torch.cuda.is_available():
+ torch.cuda.synchronize()
+
+ elapsed = time.perf_counter() - start_time
+ self.print_time(elapsed)
+
+ return result
+
+ return wrapper
+
+ @master_only
+ def __enter__(self):
+ assert self.tag is not None, 'In order to clearly distinguish ' \
+ 'printing information in different ' \
+ 'contexts, please specify the ' \
+ 'tag parameter'
+
+ self.__count += 1
+
+ if self.with_sync and torch.cuda.is_available():
+ torch.cuda.synchronize()
+ self.__start_time = time.perf_counter()
+
+ @master_only
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ if self.with_sync and torch.cuda.is_available():
+ torch.cuda.synchronize()
+ elapsed = time.perf_counter() - self.__start_time
+ self.print_time(elapsed)
+
+ def print_time(self, elapsed: Union[int, float]) -> None:
+ """print times per count."""
+ if self.__count >= self.warmup_interval:
+ self.__pure_inf_time += elapsed
+
+ if self.__count % self.log_interval == 0:
+ times_per_count = 1000 * self.__pure_inf_time / (
+ self.__count - self.warmup_interval + 1)
+ print_log(
+ f'[{self.tag}]-time per run averaged in the past '
+ f'{self.__count} runs: {times_per_count:.1f} ms',
+ self.logger)
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/torch_ops.py b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/torch_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..2550ae6986e0fcfe7627b96eb575f26ef601c935
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/torch_ops.py
@@ -0,0 +1,29 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch
+
+from ..version_utils import digit_version
+from .parrots_wrapper import TORCH_VERSION
+
+_torch_version_meshgrid_indexing = (
+ 'parrots' not in TORCH_VERSION
+ and digit_version(TORCH_VERSION) >= digit_version('1.10.0a0'))
+
+
+def torch_meshgrid(*tensors):
+ """A wrapper of torch.meshgrid to compat different PyTorch versions.
+
+ Since PyTorch 1.10.0a0, torch.meshgrid supports the arguments ``indexing``.
+ So we implement a wrapper here to avoid warning when using high-version
+ PyTorch and avoid compatibility issues when using previous versions of
+ PyTorch.
+
+ Args:
+ tensors (List[Tensor]): List of scalars or 1 dimensional tensors.
+
+ Returns:
+ Sequence[Tensor]: Sequence of meshgrid tensors.
+ """
+ if _torch_version_meshgrid_indexing:
+ return torch.meshgrid(*tensors, indexing='ij')
+ else:
+ return torch.meshgrid(*tensors) # Uses indexing='ij' by default
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/trace.py b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/trace.py
new file mode 100644
index 0000000000000000000000000000000000000000..c12bebf5d12ef7b26f1361a7e54fc120364db469
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/trace.py
@@ -0,0 +1,24 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import warnings
+
+import torch
+
+from ..version_utils import digit_version
+
+
+def is_jit_tracing() -> bool:
+ if (torch.__version__ != 'parrots'
+ and digit_version(torch.__version__) >= digit_version('1.6.0')):
+ on_trace = torch.jit.is_tracing()
+ # In PyTorch 1.6, torch.jit.is_tracing has a bug.
+ # Refers to https://github.com/pytorch/pytorch/issues/42448
+ if isinstance(on_trace, bool):
+ return on_trace
+ else:
+ return torch._C._is_tracing()
+ else:
+ warnings.warn(
+ 'torch.jit.is_tracing is only supported after v1.6.0. '
+ 'Therefore is_tracing returns False automatically. Please '
+ 'set on_trace manually if you are using trace.', UserWarning)
+ return False
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/visualize.py b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/visualize.py
new file mode 100644
index 0000000000000000000000000000000000000000..f3361e1d50a4dafb8518d6bbd66f9131b441bd80
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/dl_utils/visualize.py
@@ -0,0 +1,63 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from unittest.mock import patch
+
+import torch
+import torch.nn as nn
+
+from mmengine.model import BaseModel
+from mmengine.registry import MODELS
+
+
+@MODELS.register_module()
+class ToyModel(BaseModel):
+
+ def __init__(self, *args, **kwargs):
+ super().__init__()
+ self.conv = nn.Conv2d(1, 1, 1)
+
+ def forward(self, *args, **kwargs):
+ return {'loss': torch.tensor(0.0)}
+
+
+def update_params_step(self, loss):
+ pass
+
+
+def runtimeinfo_step(self, runner, batch_idx, data_batch=None):
+ runner.message_hub.update_info('iter', runner.iter)
+ lr_dict = runner.optim_wrapper.get_lr()
+ for name, lr in lr_dict.items():
+ runner.message_hub.update_scalar(f'train/{name}', lr[0])
+
+ momentum_dict = runner.optim_wrapper.get_momentum()
+ for name, momentum in momentum_dict.items():
+ runner.message_hub.update_scalar(f'train/{name}', momentum[0])
+
+
+@patch('mmengine.optim.optimizer.OptimWrapper.update_params',
+ update_params_step)
+@patch('mmengine.hooks.RuntimeInfoHook.before_train_iter', runtimeinfo_step)
+def fake_run(cfg):
+ from mmengine.runner import Runner
+ cfg.pop('model')
+ cfg.pop('visualizer')
+ cfg.pop('val_dataloader')
+ cfg.pop('val_evaluator')
+ cfg.pop('val_cfg')
+ cfg.pop('test_dataloader')
+ cfg.pop('test_evaluator')
+ cfg.pop('test_cfg')
+ extra_cfg = dict(
+ model=dict(type='ToyModel'),
+ visualizer=dict(
+ type='Visualizer',
+ vis_backends=[
+ dict(type='TensorboardVisBackend', save_dir='temp_dir')
+ ]),
+ )
+ cfg.merge_from_dict(extra_cfg)
+ # build the runner from config
+ runner = Runner.from_cfg(cfg)
+
+ # start training
+ runner.train()
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/manager.py b/testbed/open-mmlab__mmengine/mmengine/utils/manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..68f3409a6a03f79871189afea2f76224502c11b9
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/manager.py
@@ -0,0 +1,167 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import inspect
+import threading
+from collections import OrderedDict
+from typing import Type, TypeVar
+
+_lock = threading.RLock()
+T = TypeVar('T')
+
+
+def _accquire_lock() -> None:
+ """Acquire the module-level lock for serializing access to shared data.
+
+ This should be released with _release_lock().
+ """
+ if _lock:
+ _lock.acquire()
+
+
+def _release_lock() -> None:
+ """Release the module-level lock acquired by calling _accquire_lock()."""
+ if _lock:
+ _lock.release()
+
+
+class ManagerMeta(type):
+ """The metaclass for global accessible class.
+
+ The subclasses inheriting from ``ManagerMeta`` will manage their
+ own ``_instance_dict`` and root instances. The constructors of subclasses
+ must contain the ``name`` argument.
+
+ Examples:
+ >>> class SubClass1(metaclass=ManagerMeta):
+ >>> def __init__(self, *args, **kwargs):
+ >>> pass
+ AssertionError: .__init__ must have the
+ name argument.
+ >>> class SubClass2(metaclass=ManagerMeta):
+ >>> def __init__(self, name):
+ >>> pass
+ >>> # valid format.
+ """
+
+ def __init__(cls, *args):
+ cls._instance_dict = OrderedDict()
+ params = inspect.getfullargspec(cls)
+ params_names = params[0] if params[0] else []
+ assert 'name' in params_names, f'{cls} must have the `name` argument'
+ super().__init__(*args)
+
+
+class ManagerMixin(metaclass=ManagerMeta):
+ """``ManagerMixin`` is the base class for classes that have global access
+ requirements.
+
+ The subclasses inheriting from ``ManagerMixin`` can get their
+ global instances.
+
+ Examples:
+ >>> class GlobalAccessible(ManagerMixin):
+ >>> def __init__(self, name=''):
+ >>> super().__init__(name)
+ >>>
+ >>> GlobalAccessible.get_instance('name')
+ >>> instance_1 = GlobalAccessible.get_instance('name')
+ >>> instance_2 = GlobalAccessible.get_instance('name')
+ >>> assert id(instance_1) == id(instance_2)
+
+ Args:
+ name (str): Name of the instance. Defaults to ''.
+ """
+
+ def __init__(self, name: str = '', **kwargs):
+ assert isinstance(name, str) and name, \
+ 'name argument must be an non-empty string.'
+ self._instance_name = name
+
+ @classmethod
+ def get_instance(cls: Type[T], name: str, **kwargs) -> T:
+ """Get subclass instance by name if the name exists.
+
+ If corresponding name instance has not been created, ``get_instance``
+ will create an instance, otherwise ``get_instance`` will return the
+ corresponding instance.
+
+ Examples
+ >>> instance1 = GlobalAccessible.get_instance('name1')
+ >>> # Create name1 instance.
+ >>> instance.instance_name
+ name1
+ >>> instance2 = GlobalAccessible.get_instance('name1')
+ >>> # Get name1 instance.
+ >>> assert id(instance1) == id(instance2)
+
+ Args:
+ name (str): Name of instance. Defaults to ''.
+
+ Returns:
+ object: Corresponding name instance, the latest instance, or root
+ instance.
+ """
+ _accquire_lock()
+ assert isinstance(name, str), \
+ f'type of name should be str, but got {type(cls)}'
+ instance_dict = cls._instance_dict # type: ignore
+ # Get the instance by name.
+ if name not in instance_dict:
+ instance = cls(name=name, **kwargs) # type: ignore
+ instance_dict[name] = instance # type: ignore
+ else:
+ assert not kwargs, (
+ f'{cls} instance named of {name} has been created, the method '
+ '`get_instance` should not access any other arguments')
+ # Get latest instantiated instance or root instance.
+ _release_lock()
+ return instance_dict[name]
+
+ @classmethod
+ def get_current_instance(cls):
+ """Get latest created instance.
+
+ Before calling ``get_current_instance``, The subclass must have called
+ ``get_instance(xxx)`` at least once.
+
+ Examples
+ >>> instance = GlobalAccessible.get_current_instance()
+ AssertionError: At least one of name and current needs to be set
+ >>> instance = GlobalAccessible.get_instance('name1')
+ >>> instance.instance_name
+ name1
+ >>> instance = GlobalAccessible.get_current_instance()
+ >>> instance.instance_name
+ name1
+
+ Returns:
+ object: Latest created instance.
+ """
+ _accquire_lock()
+ if not cls._instance_dict:
+ raise RuntimeError(
+ f'Before calling {cls.__name__}.get_current_instance(), you '
+ 'should call get_instance(name=xxx) at least once.')
+ name = next(iter(reversed(cls._instance_dict)))
+ _release_lock()
+ return cls._instance_dict[name]
+
+ @classmethod
+ def check_instance_created(cls, name: str) -> bool:
+ """Check whether the name corresponding instance exists.
+
+ Args:
+ name (str): Name of instance.
+
+ Returns:
+ bool: Whether the name corresponding instance exists.
+ """
+ return name in cls._instance_dict
+
+ @property
+ def instance_name(self) -> str:
+ """Get the name of instance.
+
+ Returns:
+ str: Name of instance.
+ """
+ return self._instance_name
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/misc.py b/testbed/open-mmlab__mmengine/mmengine/utils/misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..d7fa1fb39b17cd95070885230a3de2087a1204e9
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/misc.py
@@ -0,0 +1,461 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import collections.abc
+import functools
+import itertools
+import logging
+import re
+import subprocess
+import textwrap
+import warnings
+from collections import abc
+from importlib import import_module
+from inspect import getfullargspec
+from itertools import repeat
+from typing import Any, Callable, Optional, Type, Union
+
+
+# From PyTorch internals
+def _ntuple(n):
+
+ def parse(x):
+ if isinstance(x, collections.abc.Iterable):
+ return x
+ return tuple(repeat(x, n))
+
+ return parse
+
+
+to_1tuple = _ntuple(1)
+to_2tuple = _ntuple(2)
+to_3tuple = _ntuple(3)
+to_4tuple = _ntuple(4)
+to_ntuple = _ntuple
+
+
+def is_str(x):
+ """Whether the input is an string instance.
+
+ Note: This method is deprecated since python 2 is no longer supported.
+ """
+ return isinstance(x, str)
+
+
+def import_modules_from_strings(imports, allow_failed_imports=False):
+ """Import modules from the given list of strings.
+
+ Args:
+ imports (list | str | None): The given module names to be imported.
+ allow_failed_imports (bool): If True, the failed imports will return
+ None. Otherwise, an ImportError is raise. Default: False.
+
+ Returns:
+ list[module] | module | None: The imported modules.
+
+ Examples:
+ >>> osp, sys = import_modules_from_strings(
+ ... ['os.path', 'sys'])
+ >>> import os.path as osp_
+ >>> import sys as sys_
+ >>> assert osp == osp_
+ >>> assert sys == sys_
+ """
+ if not imports:
+ return
+ single_import = False
+ if isinstance(imports, str):
+ single_import = True
+ imports = [imports]
+ if not isinstance(imports, list):
+ raise TypeError(
+ f'custom_imports must be a list but got type {type(imports)}')
+ imported = []
+ for imp in imports:
+ if not isinstance(imp, str):
+ raise TypeError(
+ f'{imp} is of type {type(imp)} and cannot be imported.')
+ try:
+ imported_tmp = import_module(imp)
+ except ImportError:
+ if allow_failed_imports:
+ warnings.warn(f'{imp} failed to import and is ignored.',
+ UserWarning)
+ imported_tmp = None
+ else:
+ raise ImportError(f'Failed to import {imp}')
+ imported.append(imported_tmp)
+ if single_import:
+ imported = imported[0]
+ return imported
+
+
+def iter_cast(inputs, dst_type, return_type=None):
+ """Cast elements of an iterable object into some type.
+
+ Args:
+ inputs (Iterable): The input object.
+ dst_type (type): Destination type.
+ return_type (type, optional): If specified, the output object will be
+ converted to this type, otherwise an iterator.
+
+ Returns:
+ iterator or specified type: The converted object.
+ """
+ if not isinstance(inputs, abc.Iterable):
+ raise TypeError('inputs must be an iterable object')
+ if not isinstance(dst_type, type):
+ raise TypeError('"dst_type" must be a valid type')
+
+ out_iterable = map(dst_type, inputs)
+
+ if return_type is None:
+ return out_iterable
+ else:
+ return return_type(out_iterable)
+
+
+def list_cast(inputs, dst_type):
+ """Cast elements of an iterable object into a list of some type.
+
+ A partial method of :func:`iter_cast`.
+ """
+ return iter_cast(inputs, dst_type, return_type=list)
+
+
+def tuple_cast(inputs, dst_type):
+ """Cast elements of an iterable object into a tuple of some type.
+
+ A partial method of :func:`iter_cast`.
+ """
+ return iter_cast(inputs, dst_type, return_type=tuple)
+
+
+def is_seq_of(seq: Any,
+ expected_type: Union[Type, tuple],
+ seq_type: Type = None) -> bool:
+ """Check whether it is a sequence of some type.
+
+ Args:
+ seq (Sequence): The sequence to be checked.
+ expected_type (type or tuple): Expected type of sequence items.
+ seq_type (type, optional): Expected sequence type. Defaults to None.
+
+ Returns:
+ bool: Return True if ``seq`` is valid else False.
+
+ Examples:
+ >>> from mmengine.utils import is_seq_of
+ >>> seq = ['a', 'b', 'c']
+ >>> is_seq_of(seq, str)
+ True
+ >>> is_seq_of(seq, int)
+ False
+ """
+ if seq_type is None:
+ exp_seq_type = abc.Sequence
+ else:
+ assert isinstance(seq_type, type)
+ exp_seq_type = seq_type
+ if not isinstance(seq, exp_seq_type):
+ return False
+ for item in seq:
+ if not isinstance(item, expected_type):
+ return False
+ return True
+
+
+def is_list_of(seq, expected_type):
+ """Check whether it is a list of some type.
+
+ A partial method of :func:`is_seq_of`.
+ """
+ return is_seq_of(seq, expected_type, seq_type=list)
+
+
+def is_tuple_of(seq, expected_type):
+ """Check whether it is a tuple of some type.
+
+ A partial method of :func:`is_seq_of`.
+ """
+ return is_seq_of(seq, expected_type, seq_type=tuple)
+
+
+def slice_list(in_list, lens):
+ """Slice a list into several sub lists by a list of given length.
+
+ Args:
+ in_list (list): The list to be sliced.
+ lens(int or list): The expected length of each out list.
+
+ Returns:
+ list: A list of sliced list.
+ """
+ if isinstance(lens, int):
+ assert len(in_list) % lens == 0
+ lens = [lens] * int(len(in_list) / lens)
+ if not isinstance(lens, list):
+ raise TypeError('"indices" must be an integer or a list of integers')
+ elif sum(lens) != len(in_list):
+ raise ValueError('sum of lens and list length does not '
+ f'match: {sum(lens)} != {len(in_list)}')
+ out_list = []
+ idx = 0
+ for i in range(len(lens)):
+ out_list.append(in_list[idx:idx + lens[i]])
+ idx += lens[i]
+ return out_list
+
+
+def concat_list(in_list):
+ """Concatenate a list of list into a single list.
+
+ Args:
+ in_list (list): The list of list to be merged.
+
+ Returns:
+ list: The concatenated flat list.
+ """
+ return list(itertools.chain(*in_list))
+
+
+def check_prerequisites(
+ prerequisites,
+ checker,
+ msg_tmpl='Prerequisites "{}" are required in method "{}" but not '
+ 'found, please install them first.'): # yapf: disable
+ """A decorator factory to check if prerequisites are satisfied.
+
+ Args:
+ prerequisites (str of list[str]): Prerequisites to be checked.
+ checker (callable): The checker method that returns True if a
+ prerequisite is meet, False otherwise.
+ msg_tmpl (str): The message template with two variables.
+
+ Returns:
+ decorator: A specific decorator.
+ """
+
+ def wrap(func):
+
+ @functools.wraps(func)
+ def wrapped_func(*args, **kwargs):
+ requirements = [prerequisites] if isinstance(
+ prerequisites, str) else prerequisites
+ missing = []
+ for item in requirements:
+ if not checker(item):
+ missing.append(item)
+ if missing:
+ print(msg_tmpl.format(', '.join(missing), func.__name__))
+ raise RuntimeError('Prerequisites not meet.')
+ else:
+ return func(*args, **kwargs)
+
+ return wrapped_func
+
+ return wrap
+
+
+def _check_py_package(package):
+ try:
+ import_module(package)
+ except ImportError:
+ return False
+ else:
+ return True
+
+
+def _check_executable(cmd):
+ if subprocess.call(f'which {cmd}', shell=True) != 0:
+ return False
+ else:
+ return True
+
+
+def requires_package(prerequisites):
+ """A decorator to check if some python packages are installed.
+
+ Example:
+ >>> @requires_package('numpy')
+ >>> func(arg1, args):
+ >>> return numpy.zeros(1)
+ array([0.])
+ >>> @requires_package(['numpy', 'non_package'])
+ >>> func(arg1, args):
+ >>> return numpy.zeros(1)
+ ImportError
+ """
+ return check_prerequisites(prerequisites, checker=_check_py_package)
+
+
+def requires_executable(prerequisites):
+ """A decorator to check if some executable files are installed.
+
+ Example:
+ >>> @requires_executable('ffmpeg')
+ >>> func(arg1, args):
+ >>> print(1)
+ 1
+ """
+ return check_prerequisites(prerequisites, checker=_check_executable)
+
+
+def deprecated_api_warning(name_dict: dict,
+ cls_name: Optional[str] = None) -> Callable:
+ """A decorator to check if some arguments are deprecate and try to replace
+ deprecate src_arg_name to dst_arg_name.
+
+ Args:
+ name_dict(dict):
+ key (str): Deprecate argument names.
+ val (str): Expected argument names.
+
+ Returns:
+ func: New function.
+ """
+
+ def api_warning_wrapper(old_func):
+
+ @functools.wraps(old_func)
+ def new_func(*args, **kwargs):
+ # get the arg spec of the decorated method
+ args_info = getfullargspec(old_func)
+ # get name of the function
+ func_name = old_func.__name__
+ if cls_name is not None:
+ func_name = f'{cls_name}.{func_name}'
+ if args:
+ arg_names = args_info.args[:len(args)]
+ for src_arg_name, dst_arg_name in name_dict.items():
+ if src_arg_name in arg_names:
+ warnings.warn(
+ f'"{src_arg_name}" is deprecated in '
+ f'`{func_name}`, please use "{dst_arg_name}" '
+ 'instead', DeprecationWarning)
+ arg_names[arg_names.index(src_arg_name)] = dst_arg_name
+ if kwargs:
+ for src_arg_name, dst_arg_name in name_dict.items():
+ if src_arg_name in kwargs:
+ assert dst_arg_name not in kwargs, (
+ f'The expected behavior is to replace '
+ f'the deprecated key `{src_arg_name}` to '
+ f'new key `{dst_arg_name}`, but got them '
+ f'in the arguments at the same time, which '
+ f'is confusing. `{src_arg_name} will be '
+ f'deprecated in the future, please '
+ f'use `{dst_arg_name}` instead.')
+
+ warnings.warn(
+ f'"{src_arg_name}" is deprecated in '
+ f'`{func_name}`, please use "{dst_arg_name}" '
+ 'instead', DeprecationWarning)
+ kwargs[dst_arg_name] = kwargs.pop(src_arg_name)
+
+ # apply converted arguments to the decorated method
+ output = old_func(*args, **kwargs)
+ return output
+
+ return new_func
+
+ return api_warning_wrapper
+
+
+def is_method_overridden(method: str, base_class: type,
+ derived_class: Union[type, Any]) -> bool:
+ """Check if a method of base class is overridden in derived class.
+
+ Args:
+ method (str): the method name to check.
+ base_class (type): the class of the base class.
+ derived_class (type | Any): the class or instance of the derived class.
+ """
+ assert isinstance(base_class, type), \
+ "base_class doesn't accept instance, Please pass class instead."
+
+ if not isinstance(derived_class, type):
+ derived_class = derived_class.__class__
+
+ base_method = getattr(base_class, method)
+ derived_method = getattr(derived_class, method)
+ return derived_method != base_method
+
+
+def has_method(obj: object, method: str) -> bool:
+ """Check whether the object has a method.
+
+ Args:
+ method (str): The method name to check.
+ obj (object): The object to check.
+
+ Returns:
+ bool: True if the object has the method else False.
+ """
+ return hasattr(obj, method) and callable(getattr(obj, method))
+
+
+def deprecated_function(since: str, removed_in: str,
+ instructions: str) -> Callable:
+ """Marks functions as deprecated.
+
+ Throw a warning when a deprecated function is called, and add a note in the
+ docstring. Modified from https://github.com/pytorch/pytorch/blob/master/torch/onnx/_deprecation.py
+
+ Args:
+ since (str): The version when the function was first deprecated.
+ removed_in (str): The version when the function will be removed.
+ instructions (str): The action users should take.
+
+ Returns:
+ Callable: A new function, which will be deprecated soon.
+ """ # noqa: E501
+ from mmengine import print_log
+
+ def decorator(function):
+
+ @functools.wraps(function)
+ def wrapper(*args, **kwargs):
+ print_log(
+ f"'{function.__module__}.{function.__name__}' "
+ f'is deprecated in version {since} and will be '
+ f'removed in version {removed_in}. Please {instructions}.',
+ logger='current',
+ level=logging.WARNING,
+ )
+ return function(*args, **kwargs)
+
+ indent = ' '
+ # Add a deprecation note to the docstring.
+ docstring = function.__doc__ or ''
+ # Add a note to the docstring.
+ deprecation_note = textwrap.dedent(f"""\
+ .. deprecated:: {since}
+ Deprecated and will be removed in version {removed_in}.
+ Please {instructions}.
+ """)
+ # Split docstring at first occurrence of newline
+ pattern = '\n\n'
+ summary_and_body = re.split(pattern, docstring, 1)
+
+ if len(summary_and_body) > 1:
+ summary, body = summary_and_body
+ body = textwrap.indent(textwrap.dedent(body), indent)
+ summary = '\n'.join(
+ [textwrap.dedent(string) for string in summary.split('\n')])
+ summary = textwrap.indent(summary, prefix=indent)
+ # Dedent the body. We cannot do this with the presence of the
+ # summary because the body contains leading whitespaces when the
+ # summary does not.
+ new_docstring_parts = [
+ deprecation_note, '\n\n', summary, '\n\n', body
+ ]
+ else:
+ summary = summary_and_body[0]
+ summary = '\n'.join(
+ [textwrap.dedent(string) for string in summary.split('\n')])
+ summary = textwrap.indent(summary, prefix=indent)
+ new_docstring_parts = [deprecation_note, '\n\n', summary]
+
+ wrapper.__doc__ = ''.join(new_docstring_parts)
+
+ return wrapper
+
+ return decorator
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/package_utils.py b/testbed/open-mmlab__mmengine/mmengine/utils/package_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..53fe944a2274d2b67fd457bc032e9b2e4ba3c1b0
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/package_utils.py
@@ -0,0 +1,71 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import importlib
+import os.path as osp
+import subprocess
+
+import pkg_resources
+from pkg_resources import get_distribution
+
+
+def is_installed(package: str) -> bool:
+ """Check package whether installed.
+
+ Args:
+ package (str): Name of package to be checked.
+ """
+ # refresh the pkg_resources
+ # more datails at https://github.com/pypa/setuptools/issues/373
+ importlib.reload(pkg_resources)
+ try:
+ get_distribution(package)
+ return True
+ except pkg_resources.DistributionNotFound:
+ return False
+
+
+def get_installed_path(package: str) -> str:
+ """Get installed path of package.
+
+ Args:
+ package (str): Name of package.
+
+ Example:
+ >>> get_installed_path('mmcls')
+ >>> '.../lib/python3.7/site-packages/mmcls'
+ """
+ # if the package name is not the same as module name, module name should be
+ # inferred. For example, mmcv-full is the package name, but mmcv is module
+ # name. If we want to get the installed path of mmcv-full, we should concat
+ # the pkg.location and module name
+ pkg = get_distribution(package)
+ possible_path = osp.join(pkg.location, package)
+ if osp.exists(possible_path):
+ return possible_path
+ else:
+ return osp.join(pkg.location, package2module(package))
+
+
+def package2module(package: str):
+ """Infer module name from package.
+
+ Args:
+ package (str): Package to infer module name.
+ """
+ pkg = get_distribution(package)
+ if pkg.has_metadata('top_level.txt'):
+ module_name = pkg.get_metadata('top_level.txt').split('\n')[0]
+ return module_name
+ else:
+ raise ValueError(f'can not infer the module name of {package}')
+
+
+def call_command(cmd: list) -> None:
+ try:
+ subprocess.check_call(cmd)
+ except Exception as e:
+ raise e # type: ignore
+
+
+def install_package(package: str):
+ if not is_installed(package):
+ call_command(['python', '-m', 'pip', 'install', package])
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/path.py b/testbed/open-mmlab__mmengine/mmengine/utils/path.py
new file mode 100644
index 0000000000000000000000000000000000000000..b08feb7d08c9581fdee3d48263151df88f680565
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/path.py
@@ -0,0 +1,116 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import os.path as osp
+from pathlib import Path
+
+from .misc import is_str
+
+
+def is_filepath(x):
+ return is_str(x) or isinstance(x, Path)
+
+
+def fopen(filepath, *args, **kwargs):
+ if is_str(filepath):
+ return open(filepath, *args, **kwargs)
+ elif isinstance(filepath, Path):
+ return filepath.open(*args, **kwargs)
+ raise ValueError('`filepath` should be a string or a Path')
+
+
+def check_file_exist(filename, msg_tmpl='file "{}" does not exist'):
+ if not osp.isfile(filename):
+ raise FileNotFoundError(msg_tmpl.format(filename))
+
+
+def mkdir_or_exist(dir_name, mode=0o777):
+ if dir_name == '':
+ return
+ dir_name = osp.expanduser(dir_name)
+ os.makedirs(dir_name, mode=mode, exist_ok=True)
+
+
+def symlink(src, dst, overwrite=True, **kwargs):
+ if os.path.lexists(dst) and overwrite:
+ os.remove(dst)
+ os.symlink(src, dst, **kwargs)
+
+
+def scandir(dir_path, suffix=None, recursive=False, case_sensitive=True):
+ """Scan a directory to find the interested files.
+
+ Args:
+ dir_path (str | :obj:`Path`): Path of the directory.
+ suffix (str | tuple(str), optional): File suffix that we are
+ interested in. Default: None.
+ recursive (bool, optional): If set to True, recursively scan the
+ directory. Default: False.
+ case_sensitive (bool, optional) : If set to False, ignore the case of
+ suffix. Default: True.
+
+ Returns:
+ A generator for all the interested files with relative paths.
+ """
+ if isinstance(dir_path, (str, Path)):
+ dir_path = str(dir_path)
+ else:
+ raise TypeError('"dir_path" must be a string or Path object')
+
+ if (suffix is not None) and not isinstance(suffix, (str, tuple)):
+ raise TypeError('"suffix" must be a string or tuple of strings')
+
+ if suffix is not None and not case_sensitive:
+ suffix = suffix.lower() if isinstance(suffix, str) else tuple(
+ item.lower() for item in suffix)
+
+ root = dir_path
+
+ def _scandir(dir_path, suffix, recursive, case_sensitive):
+ for entry in os.scandir(dir_path):
+ if not entry.name.startswith('.') and entry.is_file():
+ rel_path = osp.relpath(entry.path, root)
+ _rel_path = rel_path if case_sensitive else rel_path.lower()
+ if suffix is None or _rel_path.endswith(suffix):
+ yield rel_path
+ elif recursive and os.path.isdir(entry.path):
+ # scan recursively if entry.path is a directory
+ yield from _scandir(entry.path, suffix, recursive,
+ case_sensitive)
+
+ return _scandir(dir_path, suffix, recursive, case_sensitive)
+
+
+def find_vcs_root(path, markers=('.git', )):
+ """Finds the root directory (including itself) of specified markers.
+
+ Args:
+ path (str): Path of directory or file.
+ markers (list[str], optional): List of file or directory names.
+
+ Returns:
+ The directory contained one of the markers or None if not found.
+ """
+ if osp.isfile(path):
+ path = osp.dirname(path)
+
+ prev, cur = None, osp.abspath(osp.expanduser(path))
+ while cur != prev:
+ if any(osp.exists(osp.join(cur, marker)) for marker in markers):
+ return cur
+ prev, cur = cur, osp.split(cur)[0]
+ return None
+
+
+def is_abs(path: str) -> bool:
+ """Check if path is an absolute path in different backends.
+
+ Args:
+ path (str): path of directory or file.
+
+ Returns:
+ bool: whether path is an absolute path.
+ """
+ if osp.isabs(path) or path.startswith(('http://', 'https://', 's3://')):
+ return True
+ else:
+ return False
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/progressbar.py b/testbed/open-mmlab__mmengine/mmengine/utils/progressbar.py
new file mode 100644
index 0000000000000000000000000000000000000000..0062f670dd94fa9da559ab26ef85517dcf5211c7
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/progressbar.py
@@ -0,0 +1,208 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import sys
+from collections.abc import Iterable
+from multiprocessing import Pool
+from shutil import get_terminal_size
+
+from .timer import Timer
+
+
+class ProgressBar:
+ """A progress bar which can print the progress."""
+
+ def __init__(self, task_num=0, bar_width=50, start=True, file=sys.stdout):
+ self.task_num = task_num
+ self.bar_width = bar_width
+ self.completed = 0
+ self.file = file
+ if start:
+ self.start()
+
+ @property
+ def terminal_width(self):
+ width, _ = get_terminal_size()
+ return width
+
+ def start(self):
+ if self.task_num > 0:
+ self.file.write(f'[{" " * self.bar_width}] 0/{self.task_num}, '
+ 'elapsed: 0s, ETA:')
+ else:
+ self.file.write('completed: 0, elapsed: 0s')
+ self.file.flush()
+ self.timer = Timer()
+
+ def update(self, num_tasks=1):
+ assert num_tasks > 0
+ self.completed += num_tasks
+ elapsed = self.timer.since_start()
+ if elapsed > 0:
+ fps = self.completed / elapsed
+ else:
+ fps = float('inf')
+ if self.task_num > 0:
+ percentage = self.completed / float(self.task_num)
+ eta = int(elapsed * (1 - percentage) / percentage + 0.5)
+ msg = f'\r[{{}}] {self.completed}/{self.task_num}, ' \
+ f'{fps:.1f} task/s, elapsed: {int(elapsed + 0.5)}s, ' \
+ f'ETA: {eta:5}s'
+
+ bar_width = min(self.bar_width,
+ int(self.terminal_width - len(msg)) + 2,
+ int(self.terminal_width * 0.6))
+ bar_width = max(2, bar_width)
+ mark_width = int(bar_width * percentage)
+ bar_chars = '>' * mark_width + ' ' * (bar_width - mark_width)
+ self.file.write(msg.format(bar_chars))
+ else:
+ self.file.write(
+ f'completed: {self.completed}, elapsed: {int(elapsed + 0.5)}s,'
+ f' {fps:.1f} tasks/s')
+ self.file.flush()
+
+
+def track_progress(func, tasks, bar_width=50, file=sys.stdout, **kwargs):
+ """Track the progress of tasks execution with a progress bar.
+
+ Tasks are done with a simple for-loop.
+
+ Args:
+ func (callable): The function to be applied to each task.
+ tasks (list or tuple[Iterable, int]): A list of tasks or
+ (tasks, total num).
+ bar_width (int): Width of progress bar.
+
+ Returns:
+ list: The task results.
+ """
+ if isinstance(tasks, tuple):
+ assert len(tasks) == 2
+ assert isinstance(tasks[0], Iterable)
+ assert isinstance(tasks[1], int)
+ task_num = tasks[1]
+ tasks = tasks[0]
+ elif isinstance(tasks, Iterable):
+ task_num = len(tasks)
+ else:
+ raise TypeError(
+ '"tasks" must be an iterable object or a (iterator, int) tuple')
+ prog_bar = ProgressBar(task_num, bar_width, file=file)
+ results = []
+ for task in tasks:
+ results.append(func(task, **kwargs))
+ prog_bar.update()
+ prog_bar.file.write('\n')
+ return results
+
+
+def init_pool(process_num, initializer=None, initargs=None):
+ if initializer is None:
+ return Pool(process_num)
+ elif initargs is None:
+ return Pool(process_num, initializer)
+ else:
+ if not isinstance(initargs, tuple):
+ raise TypeError('"initargs" must be a tuple')
+ return Pool(process_num, initializer, initargs)
+
+
+def track_parallel_progress(func,
+ tasks,
+ nproc,
+ initializer=None,
+ initargs=None,
+ bar_width=50,
+ chunksize=1,
+ skip_first=False,
+ keep_order=True,
+ file=sys.stdout):
+ """Track the progress of parallel task execution with a progress bar.
+
+ The built-in :mod:`multiprocessing` module is used for process pools and
+ tasks are done with :func:`Pool.map` or :func:`Pool.imap_unordered`.
+
+ Args:
+ func (callable): The function to be applied to each task.
+ tasks (list or tuple[Iterable, int]): A list of tasks or
+ (tasks, total num).
+ nproc (int): Process (worker) number.
+ initializer (None or callable): Refer to :class:`multiprocessing.Pool`
+ for details.
+ initargs (None or tuple): Refer to :class:`multiprocessing.Pool` for
+ details.
+ chunksize (int): Refer to :class:`multiprocessing.Pool` for details.
+ bar_width (int): Width of progress bar.
+ skip_first (bool): Whether to skip the first sample for each worker
+ when estimating fps, since the initialization step may takes
+ longer.
+ keep_order (bool): If True, :func:`Pool.imap` is used, otherwise
+ :func:`Pool.imap_unordered` is used.
+
+ Returns:
+ list: The task results.
+ """
+ if isinstance(tasks, tuple):
+ assert len(tasks) == 2
+ assert isinstance(tasks[0], Iterable)
+ assert isinstance(tasks[1], int)
+ task_num = tasks[1]
+ tasks = tasks[0]
+ elif isinstance(tasks, Iterable):
+ task_num = len(tasks)
+ else:
+ raise TypeError(
+ '"tasks" must be an iterable object or a (iterator, int) tuple')
+ pool = init_pool(nproc, initializer, initargs)
+ start = not skip_first
+ task_num -= nproc * chunksize * int(skip_first)
+ prog_bar = ProgressBar(task_num, bar_width, start, file=file)
+ results = []
+ if keep_order:
+ gen = pool.imap(func, tasks, chunksize)
+ else:
+ gen = pool.imap_unordered(func, tasks, chunksize)
+ for result in gen:
+ results.append(result)
+ if skip_first:
+ if len(results) < nproc * chunksize:
+ continue
+ elif len(results) == nproc * chunksize:
+ prog_bar.start()
+ continue
+ prog_bar.update()
+ prog_bar.file.write('\n')
+ pool.close()
+ pool.join()
+ return results
+
+
+def track_iter_progress(tasks, bar_width=50, file=sys.stdout):
+ """Track the progress of tasks iteration or enumeration with a progress
+ bar.
+
+ Tasks are yielded with a simple for-loop.
+
+ Args:
+ tasks (list or tuple[Iterable, int]): A list of tasks or
+ (tasks, total num).
+ bar_width (int): Width of progress bar.
+
+ Yields:
+ list: The task results.
+ """
+ if isinstance(tasks, tuple):
+ assert len(tasks) == 2
+ assert isinstance(tasks[0], Iterable)
+ assert isinstance(tasks[1], int)
+ task_num = tasks[1]
+ tasks = tasks[0]
+ elif isinstance(tasks, Iterable):
+ task_num = len(tasks)
+ else:
+ raise TypeError(
+ '"tasks" must be an iterable object or a (iterator, int) tuple')
+ prog_bar = ProgressBar(task_num, bar_width, file=file)
+ for task in tasks:
+ yield task
+ prog_bar.update()
+ prog_bar.file.write('\n')
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/timer.py b/testbed/open-mmlab__mmengine/mmengine/utils/timer.py
new file mode 100644
index 0000000000000000000000000000000000000000..087a969cfabe30ce0ed3080fd6eb6b81e232502f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/timer.py
@@ -0,0 +1,118 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from time import time
+
+
+class TimerError(Exception):
+
+ def __init__(self, message):
+ self.message = message
+ super().__init__(message)
+
+
+class Timer:
+ """A flexible Timer class.
+
+ Examples:
+ >>> import time
+ >>> import mmcv
+ >>> with mmcv.Timer():
+ >>> # simulate a code block that will run for 1s
+ >>> time.sleep(1)
+ 1.000
+ >>> with mmcv.Timer(print_tmpl='it takes {:.1f} seconds'):
+ >>> # simulate a code block that will run for 1s
+ >>> time.sleep(1)
+ it takes 1.0 seconds
+ >>> timer = mmcv.Timer()
+ >>> time.sleep(0.5)
+ >>> print(timer.since_start())
+ 0.500
+ >>> time.sleep(0.5)
+ >>> print(timer.since_last_check())
+ 0.500
+ >>> print(timer.since_start())
+ 1.000
+ """
+
+ def __init__(self, start=True, print_tmpl=None):
+ self._is_running = False
+ self.print_tmpl = print_tmpl if print_tmpl else '{:.3f}'
+ if start:
+ self.start()
+
+ @property
+ def is_running(self):
+ """bool: indicate whether the timer is running"""
+ return self._is_running
+
+ def __enter__(self):
+ self.start()
+ return self
+
+ def __exit__(self, type, value, traceback):
+ print(self.print_tmpl.format(self.since_last_check()))
+ self._is_running = False
+
+ def start(self):
+ """Start the timer."""
+ if not self._is_running:
+ self._t_start = time()
+ self._is_running = True
+ self._t_last = time()
+
+ def since_start(self):
+ """Total time since the timer is started.
+
+ Returns:
+ float: Time in seconds.
+ """
+ if not self._is_running:
+ raise TimerError('timer is not running')
+ self._t_last = time()
+ return self._t_last - self._t_start
+
+ def since_last_check(self):
+ """Time since the last checking.
+
+ Either :func:`since_start` or :func:`since_last_check` is a checking
+ operation.
+
+ Returns:
+ float: Time in seconds.
+ """
+ if not self._is_running:
+ raise TimerError('timer is not running')
+ dur = time() - self._t_last
+ self._t_last = time()
+ return dur
+
+
+_g_timers = {} # global timers
+
+
+def check_time(timer_id):
+ """Add check points in a single line.
+
+ This method is suitable for running a task on a list of items. A timer will
+ be registered when the method is called for the first time.
+
+ Examples:
+ >>> import time
+ >>> import mmcv
+ >>> for i in range(1, 6):
+ >>> # simulate a code block
+ >>> time.sleep(i)
+ >>> mmcv.check_time('task1')
+ 2.000
+ 3.000
+ 4.000
+ 5.000
+
+ Args:
+ str: Timer identifier.
+ """
+ if timer_id not in _g_timers:
+ _g_timers[timer_id] = Timer()
+ return 0
+ else:
+ return _g_timers[timer_id].since_last_check()
diff --git a/testbed/open-mmlab__mmengine/mmengine/utils/version_utils.py b/testbed/open-mmlab__mmengine/mmengine/utils/version_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..85ef9becbd3f9a2c0fda1a61f24c0b18b1afb615
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/utils/version_utils.py
@@ -0,0 +1,91 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import subprocess
+import warnings
+
+from packaging.version import parse
+
+
+def digit_version(version_str: str, length: int = 4):
+ """Convert a version string into a tuple of integers.
+
+ This method is usually used for comparing two versions. For pre-release
+ versions: alpha < beta < rc.
+
+ Args:
+ version_str (str): The version string.
+ length (int): The maximum number of version levels. Default: 4.
+
+ Returns:
+ tuple[int]: The version info in digits (integers).
+ """
+ assert 'parrots' not in version_str
+ version = parse(version_str)
+ assert version.release, f'failed to parse version {version_str}'
+ release = list(version.release)
+ release = release[:length]
+ if len(release) < length:
+ release = release + [0] * (length - len(release))
+ if version.is_prerelease:
+ mapping = {'a': -3, 'b': -2, 'rc': -1}
+ val = -4
+ # version.pre can be None
+ if version.pre:
+ if version.pre[0] not in mapping:
+ warnings.warn(f'unknown prerelease version {version.pre[0]}, '
+ 'version checking may go wrong')
+ else:
+ val = mapping[version.pre[0]]
+ release.extend([val, version.pre[-1]])
+ else:
+ release.extend([val, 0])
+
+ elif version.is_postrelease:
+ release.extend([1, version.post]) # type: ignore
+ else:
+ release.extend([0, 0])
+ return tuple(release)
+
+
+def _minimal_ext_cmd(cmd):
+ # construct minimal environment
+ env = {}
+ for k in ['SYSTEMROOT', 'PATH', 'HOME']:
+ v = os.environ.get(k)
+ if v is not None:
+ env[k] = v
+ # LANGUAGE is used on win32
+ env['LANGUAGE'] = 'C'
+ env['LANG'] = 'C'
+ env['LC_ALL'] = 'C'
+ out, err = subprocess.Popen(
+ cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ env=env).communicate()
+ return out
+
+
+def get_git_hash(fallback='unknown', digits=None):
+ """Get the git hash of the current repo.
+
+ Args:
+ fallback (str, optional): The fallback string when git hash is
+ unavailable. Defaults to 'unknown'.
+ digits (int, optional): kept digits of the hash. Defaults to None,
+ meaning all digits are kept.
+
+ Returns:
+ str: Git commit hash.
+ """
+
+ if digits is not None and not isinstance(digits, int):
+ raise TypeError('digits must be None or an integer')
+
+ try:
+ out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
+ sha = out.strip().decode('ascii')
+ if digits is not None:
+ sha = sha[:digits]
+ except OSError:
+ sha = fallback
+
+ return sha
diff --git a/testbed/open-mmlab__mmengine/mmengine/version.py b/testbed/open-mmlab__mmengine/mmengine/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac88ca0ac2b8677826bd2b47b8e6021cdab848b7
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/version.py
@@ -0,0 +1,26 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+
+__version__ = '0.3.2'
+
+
+def parse_version_info(version_str):
+ """Parse the version information.
+
+ Args:
+ version_str (str): version string like '0.1.0'.
+
+ Returns:
+ tuple: version information contains major, minor, micro version.
+ """
+ version_info = []
+ for x in version_str.split('.'):
+ if x.isdigit():
+ version_info.append(int(x))
+ elif x.find('rc') != -1:
+ patch_version = x.split('rc')
+ version_info.append(int(patch_version[0]))
+ version_info.append(f'rc{patch_version[1]}')
+ return tuple(version_info)
+
+
+version_info = parse_version_info(__version__)
diff --git a/testbed/open-mmlab__mmengine/mmengine/visualization/__init__.py b/testbed/open-mmlab__mmengine/mmengine/visualization/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c8b0bb5464fcb96b0b865a2328b088d68190ab3
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/visualization/__init__.py
@@ -0,0 +1,9 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .vis_backend import (BaseVisBackend, LocalVisBackend,
+ TensorboardVisBackend, WandbVisBackend)
+from .visualizer import Visualizer
+
+__all__ = [
+ 'Visualizer', 'BaseVisBackend', 'LocalVisBackend', 'WandbVisBackend',
+ 'TensorboardVisBackend'
+]
diff --git a/testbed/open-mmlab__mmengine/mmengine/visualization/utils.py b/testbed/open-mmlab__mmengine/mmengine/visualization/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce8bba22c2235c31ef91a079cb96e93d4a902724
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/visualization/utils.py
@@ -0,0 +1,242 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+
+from typing import Any, List, Optional, Tuple, Type, Union
+
+import cv2
+import matplotlib
+import matplotlib.pyplot as plt
+import numpy as np
+import torch
+from matplotlib.backend_bases import CloseEvent
+from matplotlib.backends.backend_agg import FigureCanvasAgg
+
+
+def tensor2ndarray(value: Union[np.ndarray, torch.Tensor]) -> np.ndarray:
+ """If the type of value is torch.Tensor, convert the value to np.ndarray.
+
+ Args:
+ value (np.ndarray, torch.Tensor): value.
+
+ Returns:
+ Any: value.
+ """
+ if isinstance(value, torch.Tensor):
+ value = value.detach().cpu().numpy()
+ return value
+
+
+def value2list(value: Any, valid_type: Union[Type, Tuple[Type, ...]],
+ expand_dim: int) -> List[Any]:
+ """If the type of ``value`` is ``valid_type``, convert the value to list
+ and expand to ``expand_dim``.
+
+ Args:
+ value (Any): value.
+ valid_type (Union[Type, Tuple[Type, ...]): valid type.
+ expand_dim (int): expand dim.
+
+ Returns:
+ List[Any]: value.
+ """
+ if isinstance(value, valid_type):
+ value = [value] * expand_dim
+ return value
+
+
+def check_type(name: str, value: Any,
+ valid_type: Union[Type, Tuple[Type, ...]]) -> None:
+ """Check whether the type of value is in ``valid_type``.
+
+ Args:
+ name (str): value name.
+ value (Any): value.
+ valid_type (Type, Tuple[Type, ...]): expected type.
+ """
+ if not isinstance(value, valid_type):
+ raise TypeError(f'`{name}` should be {valid_type} '
+ f' but got {type(value)}')
+
+
+def check_length(name: str, value: Any, valid_length: int) -> None:
+ """If type of the ``value`` is list, check whether its length is equal with
+ or greater than ``valid_length``.
+
+ Args:
+ name (str): value name.
+ value (Any): value.
+ valid_length (int): expected length.
+ """
+ if isinstance(value, list):
+ if len(value) < valid_length:
+ raise AssertionError(
+ f'The length of {name} must equal with or '
+ f'greater than {valid_length}, but got {len(value)}')
+
+
+def check_type_and_length(name: str, value: Any,
+ valid_type: Union[Type, Tuple[Type, ...]],
+ valid_length: int) -> None:
+ """Check whether the type of value is in ``valid_type``. If type of the
+ ``value`` is list, check whether its length is equal with or greater than
+ ``valid_length``.
+
+ Args:
+ value (Any): value.
+ legal_type (Type, Tuple[Type, ...]): legal type.
+ valid_length (int): expected length.
+
+ Returns:
+ List[Any]: value.
+ """
+ check_type(name, value, valid_type)
+ check_length(name, value, valid_length)
+
+
+def color_val_matplotlib(
+ colors: Union[str, tuple, List[Union[str, tuple]]]
+) -> Union[str, tuple, List[Union[str, tuple]]]:
+ """Convert various input in RGB order to normalized RGB matplotlib color
+ tuples,
+ Args:
+ colors (Union[str, tuple, List[Union[str, tuple]]]): Color inputs
+ Returns:
+ Union[str, tuple, List[Union[str, tuple]]]: A tuple of 3 normalized
+ floats indicating RGB channels.
+ """
+ if isinstance(colors, str):
+ return colors
+ elif isinstance(colors, tuple):
+ assert len(colors) == 3
+ for channel in colors:
+ assert 0 <= channel <= 255
+ colors = [channel / 255 for channel in colors]
+ return tuple(colors)
+ elif isinstance(colors, list):
+ colors = [
+ color_val_matplotlib(color) # type:ignore
+ for color in colors
+ ]
+ return colors
+ else:
+ raise TypeError(f'Invalid type for color: {type(colors)}')
+
+
+def color_str2rgb(color: str) -> tuple:
+ """Convert Matplotlib str color to an RGB color which range is 0 to 255,
+ silently dropping the alpha channel.
+
+ Args:
+ color (str): Matplotlib color.
+
+ Returns:
+ tuple: RGB color.
+ """
+ rgb_color: tuple = matplotlib.colors.to_rgb(color)
+ rgb_color = tuple(int(c * 255) for c in rgb_color)
+ return rgb_color
+
+
+def convert_overlay_heatmap(feat_map: Union[np.ndarray, torch.Tensor],
+ img: Optional[np.ndarray] = None,
+ alpha: float = 0.5) -> np.ndarray:
+ """Convert feat_map to heatmap and overlay on image, if image is not None.
+
+ Args:
+ feat_map (np.ndarray, torch.Tensor): The feat_map to convert
+ with of shape (H, W), where H is the image height and W is
+ the image width.
+ img (np.ndarray, optional): The origin image. The format
+ should be RGB. Defaults to None.
+ alpha (float): The transparency of featmap. Defaults to 0.5.
+
+ Returns:
+ np.ndarray: heatmap
+ """
+ assert feat_map.ndim == 2 or (feat_map.ndim == 3
+ and feat_map.shape[0] in [1, 3])
+ if isinstance(feat_map, torch.Tensor):
+ feat_map = feat_map.detach().cpu().numpy()
+
+ if feat_map.ndim == 3:
+ feat_map = feat_map.transpose(1, 2, 0)
+
+ norm_img = np.zeros(feat_map.shape)
+ norm_img = cv2.normalize(feat_map, norm_img, 0, 255, cv2.NORM_MINMAX)
+ norm_img = np.asarray(norm_img, dtype=np.uint8)
+ heat_img = cv2.applyColorMap(norm_img, cv2.COLORMAP_JET)
+ heat_img = cv2.cvtColor(heat_img, cv2.COLOR_BGR2RGB)
+ if img is not None:
+ heat_img = cv2.addWeighted(img, 1 - alpha, heat_img, alpha, 0)
+ return heat_img
+
+
+def wait_continue(figure, timeout: int = 0, continue_key: str = ' ') -> int:
+ """Show the image and wait for the user's input.
+
+ This implementation refers to
+ https://github.com/matplotlib/matplotlib/blob/v3.5.x/lib/matplotlib/_blocking_input.py
+
+ Args:
+ timeout (int): If positive, continue after ``timeout`` seconds.
+ Defaults to 0.
+ continue_key (str): The key for users to continue. Defaults to
+ the space key.
+
+ Returns:
+ int: If zero, means time out or the user pressed ``continue_key``,
+ and if one, means the user closed the show figure.
+ """ # noqa: E501
+ is_inline = 'inline' in plt.get_backend()
+ if is_inline:
+ # If use inline backend, interactive input and timeout is no use.
+ return 0
+
+ if figure.canvas.manager: # type: ignore
+ # Ensure that the figure is shown
+ figure.show() # type: ignore
+
+ while True:
+
+ # Connect the events to the handler function call.
+ event = None
+
+ def handler(ev):
+ # Set external event variable
+ nonlocal event
+ # Qt backend may fire two events at the same time,
+ # use a condition to avoid missing close event.
+ event = ev if not isinstance(event, CloseEvent) else event
+ figure.canvas.stop_event_loop()
+
+ cids = [
+ figure.canvas.mpl_connect(name, handler) # type: ignore
+ for name in ('key_press_event', 'close_event')
+ ]
+
+ try:
+ figure.canvas.start_event_loop(timeout) # type: ignore
+ finally: # Run even on exception like ctrl-c.
+ # Disconnect the callbacks.
+ for cid in cids:
+ figure.canvas.mpl_disconnect(cid) # type: ignore
+
+ if isinstance(event, CloseEvent):
+ return 1 # Quit for close.
+ elif event is None or event.key == continue_key:
+ return 0 # Quit for continue.
+
+
+def img_from_canvas(canvas: FigureCanvasAgg) -> np.ndarray:
+ """Get RGB image from ``FigureCanvasAgg``.
+
+ Args:
+ canvas (FigureCanvasAgg): The canvas to get image.
+
+ Returns:
+ np.ndarray: the output of image in RGB.
+ """ # noqa: E501
+ s, (width, height) = canvas.print_to_buffer()
+ buffer = np.frombuffer(s, dtype='uint8')
+ img_rgba = buffer.reshape(height, width, 4)
+ rgb, alpha = np.split(img_rgba, [3], axis=2)
+ return rgb.astype('uint8')
diff --git a/testbed/open-mmlab__mmengine/mmengine/visualization/vis_backend.py b/testbed/open-mmlab__mmengine/mmengine/visualization/vis_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..1dc9c3031acd31cda8882fe6e952bb590b253e4e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/visualization/vis_backend.py
@@ -0,0 +1,612 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import functools
+import os
+import os.path as osp
+import warnings
+from abc import ABCMeta, abstractmethod
+from typing import Any, Callable, Optional, Sequence, Union
+
+import cv2
+import numpy as np
+import torch
+
+from mmengine.config import Config
+from mmengine.fileio import dump
+from mmengine.logging import MMLogger
+from mmengine.registry import VISBACKENDS
+from mmengine.utils.dl_utils import TORCH_VERSION
+
+
+def force_init_env(old_func: Callable) -> Any:
+ """Those methods decorated by ``force_init_env`` will be forced to call
+ ``_init_env`` if the instance has not been fully initiated. This function
+ will decorated all the `add_xxx` method and `experiment` method, because
+ `VisBackend` is initialized only when used its API.
+
+ Args:
+ old_func (Callable): Decorated function, make sure the first arg is an
+ instance with ``_init_env`` method.
+
+ Returns:
+ Any: Depends on old_func.
+ """
+
+ @functools.wraps(old_func)
+ def wrapper(obj: object, *args, **kwargs):
+ # The instance must have `_init_env` method.
+ if not hasattr(obj, '_init_env'):
+ raise AttributeError(f'{type(obj)} does not have _init_env '
+ 'method.')
+ # If instance does not have `_env_initialized` attribute or
+ # `_env_initialized` is False, call `_init_env` and set
+ # `_env_initialized` to True
+ if not getattr(obj, '_env_initialized', False):
+ logger = MMLogger.get_current_instance()
+ logger.debug('Attribute `_env_initialized` is not defined in '
+ f'{type(obj)} or `{type(obj)}._env_initialized is '
+ 'False, `_init_env` will be called and '
+ f'{type(obj)}._env_initialized will be set to '
+ 'True')
+ obj._init_env() # type: ignore
+ obj._env_initialized = True # type: ignore
+
+ return old_func(obj, *args, **kwargs)
+
+ return wrapper
+
+
+class BaseVisBackend(metaclass=ABCMeta):
+ """Base class for visualization backend.
+
+ All backends must inherit ``BaseVisBackend`` and implement
+ the required functions.
+
+ Args:
+ save_dir (str, optional): The root directory to save
+ the files produced by the backend.
+ """
+
+ def __init__(self, save_dir: str):
+ self._save_dir = save_dir
+ self._env_initialized = False
+
+ @property
+ @abstractmethod
+ def experiment(self) -> Any:
+ """Return the experiment object associated with this visualization
+ backend.
+
+ The experiment attribute can get the visualization backend, such as
+ wandb, tensorboard. If you want to write other data, such as writing a
+ table, you can directly get the visualization backend through
+ experiment.
+ """
+ pass
+
+ @abstractmethod
+ def _init_env(self) -> Any:
+ """Setup env for VisBackend."""
+ pass
+
+ def add_config(self, config: Config, **kwargs) -> None:
+ """Record the config.
+
+ Args:
+ config (Config): The Config object
+ """
+ pass
+
+ def add_graph(self, model: torch.nn.Module, data_batch: Sequence[dict],
+ **kwargs) -> None:
+ """Record the model graph.
+
+ Args:
+ model (torch.nn.Module): Model to draw.
+ data_batch (Sequence[dict]): Batch of data from dataloader.
+ """
+ pass
+
+ def add_image(self,
+ name: str,
+ image: np.ndarray,
+ step: int = 0,
+ **kwargs) -> None:
+ """Record the image.
+
+ Args:
+ name (str): The image identifier.
+ image (np.ndarray): The image to be saved. The format
+ should be RGB. Default to None.
+ step (int): Global step value to record. Default to 0.
+ """
+ pass
+
+ def add_scalar(self,
+ name: str,
+ value: Union[int, float],
+ step: int = 0,
+ **kwargs) -> None:
+ """Record the scalar.
+
+ Args:
+ name (str): The scalar identifier.
+ value (int, float): Value to save.
+ step (int): Global step value to record. Default to 0.
+ """
+ pass
+
+ def add_scalars(self,
+ scalar_dict: dict,
+ step: int = 0,
+ file_path: Optional[str] = None,
+ **kwargs) -> None:
+ """Record the scalars' data.
+
+ Args:
+ scalar_dict (dict): Key-value pair storing the tag and
+ corresponding values.
+ step (int): Global step value to record. Default to 0.
+ file_path (str, optional): The scalar's data will be
+ saved to the `file_path` file at the same time
+ if the `file_path` parameter is specified.
+ Default to None.
+ """
+ pass
+
+ def close(self) -> None:
+ """close an opened object."""
+ pass
+
+
+@VISBACKENDS.register_module()
+class LocalVisBackend(BaseVisBackend):
+ """Local visualization backend class.
+
+ It can write image, config, scalars, etc.
+ to the local hard disk. You can get the drawing backend
+ through the experiment property for custom drawing.
+
+ Examples:
+ >>> from mmengine.visualization import LocalVisBackend
+ >>> import numpy as np
+ >>> local_vis_backend = LocalVisBackend(save_dir='temp_dir')
+ >>> img = np.random.randint(0, 256, size=(10, 10, 3))
+ >>> local_vis_backend.add_image('img', img)
+ >>> local_vis_backend.add_scalar('mAP', 0.6)
+ >>> local_vis_backend.add_scalars({'loss': [1, 2, 3], 'acc': 0.8})
+ >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1])))
+ >>> local_vis_backend.add_config(cfg)
+
+ Args:
+ save_dir (str, optional): The root directory to save the files
+ produced by the visualizer. If it is none, it means no data
+ is stored.
+ img_save_dir (str): The directory to save images.
+ Default to 'vis_image'.
+ config_save_file (str): The file name to save config.
+ Default to 'config.py'.
+ scalar_save_file (str): The file name to save scalar values.
+ Default to 'scalars.json'.
+ """
+
+ def __init__(self,
+ save_dir: str,
+ img_save_dir: str = 'vis_image',
+ config_save_file: str = 'config.py',
+ scalar_save_file: str = 'scalars.json'):
+ assert config_save_file.split('.')[-1] == 'py'
+ assert scalar_save_file.split('.')[-1] == 'json'
+ super().__init__(save_dir)
+ self._img_save_dir = img_save_dir
+ self._config_save_file = config_save_file
+ self._scalar_save_file = scalar_save_file
+
+ def _init_env(self):
+ """Init save dir."""
+ if not os.path.exists(self._save_dir):
+ os.makedirs(self._save_dir, exist_ok=True)
+ self._img_save_dir = osp.join(
+ self._save_dir, # type: ignore
+ self._img_save_dir)
+ self._config_save_file = osp.join(
+ self._save_dir, # type: ignore
+ self._config_save_file)
+ self._scalar_save_file = osp.join(
+ self._save_dir, # type: ignore
+ self._scalar_save_file)
+
+ @property # type: ignore
+ @force_init_env
+ def experiment(self) -> 'LocalVisBackend':
+ """Return the experiment object associated with this visualization
+ backend."""
+ return self
+
+ @force_init_env
+ def add_config(self, config: Config, **kwargs) -> None:
+ """Record the config to disk.
+
+ Args:
+ config (Config): The Config object
+ """
+ assert isinstance(config, Config)
+ config.dump(self._config_save_file)
+
+ @force_init_env
+ def add_image(self,
+ name: str,
+ image: np.array,
+ step: int = 0,
+ **kwargs) -> None:
+ """Record the image to disk.
+
+ Args:
+ name (str): The image identifier.
+ image (np.ndarray): The image to be saved. The format
+ should be RGB. Default to None.
+ step (int): Global step value to record. Default to 0.
+ """
+ assert image.dtype == np.uint8
+ drawn_image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
+ os.makedirs(self._img_save_dir, exist_ok=True)
+ save_file_name = f'{name}_{step}.png'
+ cv2.imwrite(osp.join(self._img_save_dir, save_file_name), drawn_image)
+
+ @force_init_env
+ def add_scalar(self,
+ name: str,
+ value: Union[int, float, torch.Tensor, np.ndarray],
+ step: int = 0,
+ **kwargs) -> None:
+ """Record the scalar data to disk.
+
+ Args:
+ name (str): The scalar identifier.
+ value (int, float, torch.Tensor, np.ndarray): Value to save.
+ step (int): Global step value to record. Default to 0.
+ """
+ if isinstance(value, torch.Tensor):
+ value = value.item()
+ self._dump({name: value, 'step': step}, self._scalar_save_file, 'json')
+
+ @force_init_env
+ def add_scalars(self,
+ scalar_dict: dict,
+ step: int = 0,
+ file_path: Optional[str] = None,
+ **kwargs) -> None:
+ """Record the scalars to disk.
+
+ The scalar dict will be written to the default and
+ specified files if ``file_path`` is specified.
+
+ Args:
+ scalar_dict (dict): Key-value pair storing the tag and
+ corresponding values. The value must be dumped
+ into json format.
+ step (int): Global step value to record. Default to 0.
+ file_path (str, optional): The scalar's data will be
+ saved to the ``file_path`` file at the same time
+ if the ``file_path`` parameter is specified.
+ Default to None.
+ """
+ assert isinstance(scalar_dict, dict)
+ scalar_dict = copy.deepcopy(scalar_dict)
+ scalar_dict.setdefault('step', step)
+
+ if file_path is not None:
+ assert file_path.split('.')[-1] == 'json'
+ new_save_file_path = osp.join(
+ self._save_dir, # type: ignore
+ file_path)
+ assert new_save_file_path != self._scalar_save_file, \
+ '``file_path`` and ``scalar_save_file`` have the ' \
+ 'same name, please set ``file_path`` to another value'
+ self._dump(scalar_dict, new_save_file_path, 'json')
+ self._dump(scalar_dict, self._scalar_save_file, 'json')
+
+ def _dump(self, value_dict: dict, file_path: str,
+ file_format: str) -> None:
+ """dump dict to file.
+
+ Args:
+ value_dict (dict) : The dict data to saved.
+ file_path (str): The file path to save data.
+ file_format (str): The file format to save data.
+ """
+ with open(file_path, 'a+') as f:
+ dump(value_dict, f, file_format=file_format)
+ f.write('\n')
+
+
+@VISBACKENDS.register_module()
+class WandbVisBackend(BaseVisBackend):
+ """Wandb visualization backend class.
+
+ Examples:
+ >>> from mmengine.visualization import WandbVisBackend
+ >>> import numpy as np
+ >>> wandb_vis_backend = WandbVisBackend()
+ >>> img=np.random.randint(0, 256, size=(10, 10, 3))
+ >>> wandb_vis_backend.add_image('img', img)
+ >>> wandb_vis_backend.add_scaler('mAP', 0.6)
+ >>> wandb_vis_backend.add_scalars({'loss': [1, 2, 3],'acc': 0.8})
+ >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1])))
+ >>> wandb_vis_backend.add_config(cfg)
+
+ Args:
+ save_dir (str, optional): The root directory to save the files
+ produced by the visualizer.
+ init_kwargs (dict, optional): wandb initialization
+ input parameters. Default to None.
+ define_metric_cfg (dict, optional):
+ A dict of metrics and summary for wandb.define_metric.
+ The key is metric and the value is summary.
+ When ``define_metric_cfg={'coco/bbox_mAP': 'max'}``,
+ The maximum value of``coco/bbox_mAP`` is logged on wandb UI.
+ See
+ `wandb docs `_
+ for details.
+ Default: None
+ commit: (bool, optional) Save the metrics dict to the wandb server
+ and increment the step. If false `wandb.log` just
+ updates the current metrics dict with the row argument
+ and metrics won't be saved until `wandb.log` is called
+ with `commit=True`. Default to True.
+ log_code_name: (str, optional) The name of code artifact.
+ By default, the artifact will be named
+ source-$PROJECT_ID-$ENTRYPOINT_RELPATH. See
+ `wandb docs `_
+ for details. Defaults to None.
+ New in version 0.3.0.
+ watch_kwargs (optional, dict): Agurments for ``wandb.watch``.
+ New in version 0.4.0.
+ """
+
+ def __init__(self,
+ save_dir: str,
+ init_kwargs: Optional[dict] = None,
+ define_metric_cfg: Optional[dict] = None,
+ commit: Optional[bool] = True,
+ log_code_name: Optional[str] = None,
+ watch_kwargs: Optional[dict] = None):
+ super().__init__(save_dir)
+ self._init_kwargs = init_kwargs
+ self._define_metric_cfg = define_metric_cfg
+ self._commit = commit
+ self._log_code_name = log_code_name
+ self._watch_kwargs = watch_kwargs if watch_kwargs is not None else {}
+
+ def _init_env(self):
+ """Setup env for wandb."""
+ if not os.path.exists(self._save_dir):
+ os.makedirs(self._save_dir, exist_ok=True) # type: ignore
+ if self._init_kwargs is None:
+ self._init_kwargs = {'dir': self._save_dir}
+ else:
+ self._init_kwargs.setdefault('dir', self._save_dir)
+ try:
+ import wandb
+ except ImportError:
+ raise ImportError(
+ 'Please run "pip install wandb" to install wandb')
+
+ wandb.init(**self._init_kwargs)
+ if self._define_metric_cfg is not None:
+ for metric, summary in self._define_metric_cfg.items():
+ wandb.define_metric(metric, summary=summary)
+ self._wandb = wandb
+
+ @property # type: ignore
+ @force_init_env
+ def experiment(self):
+ """Return wandb object.
+
+ The experiment attribute can get the wandb backend, If you want to
+ write other data, such as writing a table, you can directly get the
+ wandb backend through experiment.
+ """
+ return self._wandb
+
+ @force_init_env
+ def add_config(self, config: Config, **kwargs) -> None:
+ """Record the config to wandb.
+
+ Args:
+ config (Config): The Config object
+ """
+ self._wandb.config.update(dict(config))
+ self._wandb.run.log_code(name=self._log_code_name)
+
+ @force_init_env
+ def add_graph(self, model: torch.nn.Module, data_batch: Sequence[dict],
+ **kwargs) -> None:
+ """Record the model graph.
+
+ Args:
+ model (torch.nn.Module): Model to draw.
+ data_batch (Sequence[dict]): Batch of data from dataloader.
+ """
+ self._wandb.watch(model, **self._watch_kwargs)
+
+ @force_init_env
+ def add_image(self,
+ name: str,
+ image: np.ndarray,
+ step: int = 0,
+ **kwargs) -> None:
+ """Record the image to wandb.
+
+ Args:
+ name (str): The image identifier.
+ image (np.ndarray): The image to be saved. The format
+ should be RGB.
+ step (int): Useless parameter. Wandb does not
+ need this parameter. Default to 0.
+ """
+ image = self._wandb.Image(image)
+ self._wandb.log({name: image}, commit=self._commit)
+
+ @force_init_env
+ def add_scalar(self,
+ name: str,
+ value: Union[int, float, torch.Tensor, np.ndarray],
+ step: int = 0,
+ **kwargs) -> None:
+ """Record the scalar data to wandb.
+
+ Args:
+ name (str): The scalar identifier.
+ value (int, float, torch.Tensor, np.ndarray): Value to save.
+ step (int): Useless parameter. Wandb does not
+ need this parameter. Default to 0.
+ """
+ self._wandb.log({name: value}, commit=self._commit)
+
+ @force_init_env
+ def add_scalars(self,
+ scalar_dict: dict,
+ step: int = 0,
+ file_path: Optional[str] = None,
+ **kwargs) -> None:
+ """Record the scalar's data to wandb.
+
+ Args:
+ scalar_dict (dict): Key-value pair storing the tag and
+ corresponding values.
+ step (int): Useless parameter. Wandb does not
+ need this parameter. Default to 0.
+ file_path (str, optional): Useless parameter. Just for
+ interface unification. Default to None.
+ """
+ self._wandb.log(scalar_dict, commit=self._commit)
+
+ def close(self) -> None:
+ """close an opened wandb object."""
+ if hasattr(self, '_wandb'):
+ self._wandb.join()
+
+
+@VISBACKENDS.register_module()
+class TensorboardVisBackend(BaseVisBackend):
+ """Tensorboard visualization backend class.
+
+ It can write images, config, scalars, etc. to a
+ tensorboard file.
+
+ Examples:
+ >>> from mmengine.visualization import TensorboardVisBackend
+ >>> import numpy as np
+ >>> vis_backend = TensorboardVisBackend(save_dir='temp_dir')
+ >>> img = np.random.randint(0, 256, size=(10, 10, 3))
+ >>> vis_backend.add_image('img', img)
+ >>> vis_backend.add_scaler('mAP', 0.6)
+ >>> vis_backend.add_scalars({'loss': 0.1,'acc':0.8})
+ >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1])))
+ >>> vis_backend.add_config(cfg)
+
+ Args:
+ save_dir (str): The root directory to save the files
+ produced by the backend.
+ """
+
+ def __init__(self, save_dir: str):
+ super().__init__(save_dir)
+
+ def _init_env(self):
+ """Setup env for Tensorboard."""
+ if not os.path.exists(self._save_dir):
+ os.makedirs(self._save_dir, exist_ok=True) # type: ignore
+ if TORCH_VERSION == 'parrots':
+ try:
+ from tensorboardX import SummaryWriter
+ except ImportError:
+ raise ImportError('Please install tensorboardX to use '
+ 'TensorboardLoggerHook.')
+ else:
+ try:
+ from torch.utils.tensorboard import SummaryWriter
+ except ImportError:
+ raise ImportError(
+ 'Please run "pip install future tensorboard" to install '
+ 'the dependencies to use torch.utils.tensorboard '
+ '(applicable to PyTorch 1.1 or higher)')
+ self._tensorboard = SummaryWriter(self._save_dir)
+
+ @property # type: ignore
+ @force_init_env
+ def experiment(self):
+ """Return Tensorboard object."""
+ return self._tensorboard
+
+ @force_init_env
+ def add_config(self, config: Config, **kwargs) -> None:
+ """Record the config to tensorboard.
+
+ Args:
+ config (Config): The Config object
+ """
+ self._tensorboard.add_text('config', config.pretty_text)
+
+ @force_init_env
+ def add_image(self,
+ name: str,
+ image: np.ndarray,
+ step: int = 0,
+ **kwargs) -> None:
+ """Record the image to tensorboard.
+
+ Args:
+ name (str): The image identifier.
+ image (np.ndarray): The image to be saved. The format
+ should be RGB.
+ step (int): Global step value to record. Default to 0.
+ """
+ self._tensorboard.add_image(name, image, step, dataformats='HWC')
+
+ @force_init_env
+ def add_scalar(self,
+ name: str,
+ value: Union[int, float, torch.Tensor, np.ndarray],
+ step: int = 0,
+ **kwargs) -> None:
+ """Record the scalar data to tensorboard.
+
+ Args:
+ name (str): The scalar identifier.
+ value (int, float, torch.Tensor, np.ndarray): Value to save.
+ step (int): Global step value to record. Default to 0.
+ """
+ if isinstance(value,
+ (int, float, torch.Tensor, np.ndarray, np.number)):
+ self._tensorboard.add_scalar(name, value, step)
+ else:
+ warnings.warn(f'Got {type(value)}, but numpy array, torch tensor, '
+ f'int or float are expected. skip it!')
+
+ @force_init_env
+ def add_scalars(self,
+ scalar_dict: dict,
+ step: int = 0,
+ file_path: Optional[str] = None,
+ **kwargs) -> None:
+ """Record the scalar's data to tensorboard.
+
+ Args:
+ scalar_dict (dict): Key-value pair storing the tag and
+ corresponding values.
+ step (int): Global step value to record. Default to 0.
+ file_path (str, optional): Useless parameter. Just for
+ interface unification. Default to None.
+ """
+ assert isinstance(scalar_dict, dict)
+ assert 'step' not in scalar_dict, 'Please set it directly ' \
+ 'through the step parameter'
+ for key, value in scalar_dict.items():
+ self.add_scalar(key, value, step)
+
+ def close(self):
+ """close an opened tensorboard object."""
+ if hasattr(self, '_tensorboard'):
+ self._tensorboard.close()
diff --git a/testbed/open-mmlab__mmengine/mmengine/visualization/visualizer.py b/testbed/open-mmlab__mmengine/mmengine/visualization/visualizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..79f1db51e171ab8373168db8a1667ca8edfc6081
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/mmengine/visualization/visualizer.py
@@ -0,0 +1,1131 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os.path as osp
+import warnings
+from typing import Dict, List, Optional, Sequence, Tuple, Union
+
+import cv2
+import matplotlib.pyplot as plt
+import numpy as np
+import torch
+import torch.nn.functional as F
+from matplotlib.backends.backend_agg import FigureCanvasAgg
+from matplotlib.collections import (LineCollection, PatchCollection,
+ PolyCollection)
+from matplotlib.figure import Figure
+from matplotlib.patches import Circle
+from matplotlib.pyplot import new_figure_manager
+
+from mmengine.config import Config
+from mmengine.dist import master_only
+from mmengine.registry import VISBACKENDS, VISUALIZERS
+from mmengine.structures import BaseDataElement
+from mmengine.utils import ManagerMixin
+from mmengine.visualization.utils import (check_type, check_type_and_length,
+ color_str2rgb, color_val_matplotlib,
+ convert_overlay_heatmap,
+ img_from_canvas, tensor2ndarray,
+ value2list, wait_continue)
+from mmengine.visualization.vis_backend import BaseVisBackend
+
+
+@VISUALIZERS.register_module()
+class Visualizer(ManagerMixin):
+ """MMEngine provides a Visualizer class that uses the ``Matplotlib``
+ library as the backend. It has the following functions:
+
+ - Basic drawing methods
+
+ - draw_bboxes: draw single or multiple bounding boxes
+ - draw_texts: draw single or multiple text boxes
+ - draw_points: draw single or multiple points
+ - draw_lines: draw single or multiple line segments
+ - draw_circles: draw single or multiple circles
+ - draw_polygons: draw single or multiple polygons
+ - draw_binary_masks: draw single or multiple binary masks
+ - draw_featmap: draw feature map
+
+ - Basic visualizer backend methods
+
+ - add_configs: write config to all vis storage backends
+ - add_graph: write model graph to all vis storage backends
+ - add_image: write image to all vis storage backends
+ - add_scalar: write scalar to all vis storage backends
+ - add_scalars: write scalars to all vis storage backends
+ - add_datasample: write datasample to all vis storage \
+ backends. The abstract drawing interface used by the user
+
+ - Basic info methods
+
+ - set_image: sets the original image data
+ - get_image: get the image data in Numpy format after drawing
+ - show: visualization
+ - close: close all resources that have been opened
+ - get_backend: get the specified vis backend
+
+
+ All the basic drawing methods support chain calls, which is convenient for
+ overlaydrawing and display. Each downstream algorithm library can inherit
+ ``Visualizer`` and implement the add_datasample logic. For example,
+ ``DetLocalVisualizer`` in MMDetection inherits from ``Visualizer``
+ and implements functions, such as visual detection boxes, instance masks,
+ and semantic segmentation maps in the add_datasample interface.
+
+ Args:
+ name (str): Name of the instance. Defaults to 'visualizer'.
+ image (np.ndarray, optional): the origin image to draw. The format
+ should be RGB. Defaults to None.
+ vis_backends (list, optional): Visual backend config list.
+ Default to None.
+ save_dir (str, optional): Save file dir for all storage backends.
+ If it is None, the backend storage will not save any data.
+ fig_save_cfg (dict): Keyword parameters of figure for saving.
+ Defaults to empty dict.
+ fig_show_cfg (dict): Keyword parameters of figure for showing.
+ Defaults to empty dict.
+
+ Examples:
+ >>> # Basic info methods
+ >>> vis = Visualizer()
+ >>> vis.set_image(image)
+ >>> vis.get_image()
+ >>> vis.show()
+
+ >>> # Basic drawing methods
+ >>> vis = Visualizer(image=image)
+ >>> vis.draw_bboxes(np.array([0, 0, 1, 1]), edge_colors='g')
+ >>> vis.draw_bboxes(bbox=np.array([[1, 1, 2, 2], [2, 2, 3, 3]]),
+ >>> edge_colors=['g', 'r'])
+ >>> vis.draw_lines(x_datas=np.array([1, 3]),
+ >>> y_datas=np.array([1, 3]),
+ >>> colors='r', line_widths=1)
+ >>> vis.draw_lines(x_datas=np.array([[1, 3], [2, 4]]),
+ >>> y_datas=np.array([[1, 3], [2, 4]]),
+ >>> colors=['r', 'r'], line_widths=[1, 2])
+ >>> vis.draw_texts(text='MMEngine',
+ >>> position=np.array([2, 2]),
+ >>> colors='b')
+ >>> vis.draw_texts(text=['MMEngine','OpenMMLab'],
+ >>> position=np.array([[2, 2], [5, 5]]),
+ >>> colors=['b', 'b'])
+ >>> vis.draw_circles(circle_coord=np.array([2, 2]), radius=np.array[1])
+ >>> vis.draw_circles(circle_coord=np.array([[2, 2], [3, 5]),
+ >>> radius=np.array[1, 2], colors=['g', 'r'])
+ >>> square = np.array([[0, 0], [100, 0], [100, 100], [0, 100]])
+ >>> vis.draw_polygons(polygons=square, edge_colors='g')
+ >>> squares = [np.array([[0, 0], [100, 0], [100, 100], [0, 100]]),
+ >>> np.array([[0, 0], [50, 0], [50, 50], [0, 50]])]
+ >>> vis.draw_polygons(polygons=squares, edge_colors=['g', 'r'])
+ >>> vis.draw_binary_masks(binary_mask, alpha=0.6)
+ >>> heatmap = vis.draw_featmap(featmap, img,
+ >>> channel_reduction='select_max')
+ >>> heatmap = vis.draw_featmap(featmap, img, channel_reduction=None,
+ >>> topk=8, arrangement=(4, 2))
+ >>> heatmap = vis.draw_featmap(featmap, img, channel_reduction=None,
+ >>> topk=-1)
+
+ >>> # chain calls
+ >>> vis.draw_bboxes().draw_texts().draw_circle().draw_binary_masks()
+
+ >>> # Backend related methods
+ >>> vis = Visualizer(vis_backends=[dict(type='LocalVisBackend')],
+ >>> save_dir='temp_dir')
+ >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1])))
+ >>> vis.add_config(cfg)
+ >>> image=np.random.randint(0, 256, size=(10, 10, 3)).astype(np.uint8)
+ >>> vis.add_image('image',image)
+ >>> vis.add_scaler('mAP', 0.6)
+ >>> vis.add_scalars({'loss': 0.1,'acc':0.8})
+
+ >>> # inherit
+ >>> class DetLocalVisualizer(Visualizer):
+ >>> def add_datasample(self,
+ >>> name,
+ >>> image: np.ndarray,
+ >>> gt_sample:
+ >>> Optional['BaseDataElement'] = None,
+ >>> pred_sample:
+ >>> Optional['BaseDataElement'] = None,
+ >>> draw_gt: bool = True,
+ >>> draw_pred: bool = True,
+ >>> show: bool = False,
+ >>> wait_time: int = 0,
+ >>> step: int = 0) -> None:
+ >>> pass
+ """
+
+ def __init__(
+ self,
+ name='visualizer',
+ image: Optional[np.ndarray] = None,
+ vis_backends: Optional[List[Dict]] = None,
+ save_dir: Optional[str] = None,
+ fig_save_cfg=dict(frameon=False),
+ fig_show_cfg=dict(frameon=False)
+ ) -> None:
+ super().__init__(name)
+ self._dataset_meta: Optional[dict] = None
+ self._vis_backends: Union[Dict, Dict[str, 'BaseVisBackend']] = dict()
+
+ if save_dir is None:
+ warnings.warn('`Visualizer` backend is not initialized '
+ 'because save_dir is None.')
+ elif vis_backends is not None:
+ assert len(vis_backends) > 0, 'empty list'
+ names = [
+ vis_backend.get('name', None) for vis_backend in vis_backends
+ ]
+ if None in names:
+ if len(set(names)) > 1:
+ raise RuntimeError(
+ 'If one of them has a name attribute, '
+ 'all backends must use the name attribute')
+ else:
+ type_names = [
+ vis_backend['type'] for vis_backend in vis_backends
+ ]
+ if len(set(type_names)) != len(type_names):
+ raise RuntimeError(
+ 'The same vis backend cannot exist in '
+ '`vis_backend` config. '
+ 'Please specify the name field.')
+
+ if None not in names and len(set(names)) != len(names):
+ raise RuntimeError('The name fields cannot be the same')
+
+ save_dir = osp.join(save_dir, 'vis_data')
+
+ for vis_backend in vis_backends:
+ name = vis_backend.pop('name', vis_backend['type'])
+ vis_backend.setdefault('save_dir', save_dir)
+ self._vis_backends[name] = VISBACKENDS.build(vis_backend)
+
+ self.fig_save = None
+ self.fig_save_cfg = fig_save_cfg
+ self.fig_show_cfg = fig_show_cfg
+
+ (self.fig_save_canvas, self.fig_save,
+ self.ax_save) = self._initialize_fig(fig_save_cfg)
+ self.dpi = self.fig_save.get_dpi()
+
+ if image is not None:
+ self.set_image(image)
+
+ @property # type: ignore
+ @master_only
+ def dataset_meta(self) -> Optional[dict]:
+ """Optional[dict]: Meta info of the dataset."""
+ return self._dataset_meta
+
+ @dataset_meta.setter # type: ignore
+ @master_only
+ def dataset_meta(self, dataset_meta: dict) -> None:
+ """Set the dataset meta info to the Visualizer."""
+ self._dataset_meta = dataset_meta
+
+ @master_only
+ def show(self,
+ drawn_img: Optional[np.ndarray] = None,
+ win_name: str = 'image',
+ wait_time: int = 0,
+ continue_key=' ') -> None:
+ """Show the drawn image.
+
+ Args:
+ drawn_img (np.ndarray, optional): The image to show. If drawn_img
+ is None, it will show the image got by Visualizer. Defaults
+ to None.
+ win_name (str): The image title. Defaults to 'image'.
+ wait_time (int): Delay in milliseconds. 0 is the special
+ value that means "forever". Defaults to 0.
+ continue_key (str): The key for users to continue. Defaults to
+ the space key.
+ """
+ is_inline = 'inline' in plt.get_backend()
+ img = self.get_image() if drawn_img is None else drawn_img
+ self._init_manager(win_name)
+ fig = self.manager.canvas.figure
+ # remove white edges by set subplot margin
+ fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
+ fig.clear()
+ ax = fig.add_subplot()
+ ax.axis(False)
+ ax.imshow(img)
+ self.manager.canvas.draw()
+
+ # Find a better way for inline to show the image
+ if is_inline:
+ return fig
+ wait_continue(fig, timeout=wait_time, continue_key=continue_key)
+
+ @master_only
+ def set_image(self, image: np.ndarray) -> None:
+ """Set the image to draw.
+
+ Args:
+ image (np.ndarray): The image to draw.
+ """
+ assert image is not None
+ image = image.astype('uint8')
+ self._image = image
+ self.width, self.height = image.shape[1], image.shape[0]
+ self._default_font_size = max(
+ np.sqrt(self.height * self.width) // 90, 10)
+
+ # add a small 1e-2 to avoid precision lost due to matplotlib's
+ # truncation (https://github.com/matplotlib/matplotlib/issues/15363)
+ self.fig_save.set_size_inches( # type: ignore
+ (self.width + 1e-2) / self.dpi, (self.height + 1e-2) / self.dpi)
+ # self.canvas = mpl.backends.backend_cairo.FigureCanvasCairo(fig)
+ self.ax_save.cla()
+ self.ax_save.axis(False)
+ self.ax_save.imshow(
+ image,
+ extent=(0, self.width, self.height, 0),
+ interpolation='none')
+
+ @master_only
+ def get_image(self) -> np.ndarray:
+ """Get the drawn image. The format is RGB.
+
+ Returns:
+ np.ndarray: the drawn image which channel is RGB.
+ """
+ assert self._image is not None, 'Please set image using `set_image`'
+ return img_from_canvas(self.fig_save_canvas) # type: ignore
+
+ def _initialize_fig(self, fig_cfg) -> tuple:
+ """Build figure according to fig_cfg.
+
+ Args:
+ fig_cfg (dict): The config to build figure.
+
+ Returns:
+ tuple: build canvas figure and axes.
+ """
+
+ fig = Figure(**fig_cfg)
+ ax = fig.add_subplot()
+ ax.axis(False)
+
+ # remove white edges by set subplot margin
+ fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
+ canvas = FigureCanvasAgg(fig)
+ return canvas, fig, ax
+
+ def _init_manager(self, win_name: str) -> None:
+ """Initialize the matplot manager.
+
+ Args:
+ win_name (str): The window name.
+ """
+ if getattr(self, 'manager', None) is None:
+ self.manager = new_figure_manager(
+ num=1, FigureClass=Figure, **self.fig_show_cfg)
+
+ try:
+ self.manager.set_window_title(win_name)
+ except Exception:
+ self.manager = new_figure_manager(
+ num=1, FigureClass=Figure, **self.fig_show_cfg)
+ self.manager.set_window_title(win_name)
+
+ @master_only
+ def get_backend(self, name) -> 'BaseVisBackend':
+ """get vis backend by name.
+
+ Args:
+ name (str): The name of vis backend
+
+ Returns:
+ BaseVisBackend: The vis backend.
+ """
+ return self._vis_backends.get(name) # type: ignore
+
+ def _is_posion_valid(self, position: np.ndarray) -> bool:
+ """Judge whether the position is in image.
+
+ Args:
+ position (np.ndarray): The position to judge which last dim must
+ be two and the format is [x, y].
+
+ Returns:
+ bool: Whether the position is in image.
+ """
+ flag = (position[..., 0] < self.width).all() and \
+ (position[..., 0] >= 0).all() and \
+ (position[..., 1] < self.height).all() and \
+ (position[..., 1] >= 0).all()
+ return flag
+
+ @master_only
+ def draw_points(self,
+ positions: Union[np.ndarray, torch.Tensor],
+ colors: Union[str, tuple, List[str], List[tuple]] = 'g',
+ marker: Optional[str] = None,
+ sizes: Optional[Union[np.ndarray, torch.Tensor]] = None):
+ """Draw single or multiple points.
+
+ Args:
+ positions (Union[np.ndarray, torch.Tensor]): Positions to draw.
+ colors (Union[str, tuple, List[str], List[tuple]]): The colors
+ of points. ``colors`` can have the same length with points or
+ just single value. If ``colors`` is single value, all the
+ points will have the same colors. Reference to
+ https://matplotlib.org/stable/gallery/color/named_colors.html
+ for more details. Defaults to 'g.
+ marker (str, optional): The marker style.
+ See :mod:`matplotlib.markers` for more information about
+ marker styles. Defaults to None.
+ sizes (Optional[Union[np.ndarray, torch.Tensor]]): The marker size.
+ Defaults to None.
+ """
+ check_type('positions', positions, (np.ndarray, torch.Tensor))
+ positions = tensor2ndarray(positions)
+
+ if len(positions.shape) == 1:
+ positions = positions[None]
+ assert positions.shape[-1] == 2, (
+ 'The shape of `positions` should be (N, 2), '
+ f'but got {positions.shape}')
+ colors = color_val_matplotlib(colors) # type: ignore
+ self.ax_save.scatter(
+ positions[:, 0], positions[:, 1], c=colors, s=sizes, marker=marker)
+ return self
+
+ @master_only
+ def draw_texts(
+ self,
+ texts: Union[str, List[str]],
+ positions: Union[np.ndarray, torch.Tensor],
+ font_sizes: Optional[Union[int, List[int]]] = None,
+ colors: Union[str, tuple, List[str], List[tuple]] = 'g',
+ vertical_alignments: Union[str, List[str]] = 'top',
+ horizontal_alignments: Union[str, List[str]] = 'left',
+ font_families: Union[str, List[str]] = 'sans-serif',
+ bboxes: Optional[Union[dict, List[dict]]] = None) -> 'Visualizer':
+ """Draw single or multiple text boxes.
+
+ Args:
+ texts (Union[str, List[str]]): Texts to draw.
+ positions (Union[np.ndarray, torch.Tensor]): The position to draw
+ the texts, which should have the same length with texts and
+ each dim contain x and y.
+ font_sizes (Union[int, List[int]], optional): The font size of
+ texts. ``font_sizes`` can have the same length with texts or
+ just single value. If ``font_sizes`` is single value, all the
+ texts will have the same font size. Defaults to None.
+ colors (Union[str, tuple, List[str], List[tuple]]): The colors
+ of texts. ``colors`` can have the same length with texts or
+ just single value. If ``colors`` is single value, all the
+ texts will have the same colors. Reference to
+ https://matplotlib.org/stable/gallery/color/named_colors.html
+ for more details. Defaults to 'g.
+ vertical_alignments (Union[str, List[str]]): The verticalalignment
+ of texts. verticalalignment controls whether the y positional
+ argument for the text indicates the bottom, center or top side
+ of the text bounding box.
+ ``vertical_alignments`` can have the same length with
+ texts or just single value. If ``vertical_alignments`` is
+ single value, all the texts will have the same
+ verticalalignment. verticalalignment can be 'center' or
+ 'top', 'bottom' or 'baseline'. Defaults to 'top'.
+ horizontal_alignments (Union[str, List[str]]): The
+ horizontalalignment of texts. Horizontalalignment controls
+ whether the x positional argument for the text indicates the
+ left, center or right side of the text bounding box.
+ ``horizontal_alignments`` can have
+ the same length with texts or just single value.
+ If ``horizontal_alignments`` is single value, all the texts
+ will have the same horizontalalignment. Horizontalalignment
+ can be 'center','right' or 'left'. Defaults to 'left'.
+ font_families (Union[str, List[str]]): The font family of
+ texts. ``font_families`` can have the same length with texts or
+ just single value. If ``font_families`` is single value, all
+ the texts will have the same font family.
+ font_familiy can be 'serif', 'sans-serif', 'cursive', 'fantasy'
+ or 'monospace'. Defaults to 'sans-serif'.
+ bboxes (Union[dict, List[dict]], optional): The bounding box of the
+ texts. If bboxes is None, there are no bounding box around
+ texts. ``bboxes`` can have the same length with texts or
+ just single value. If ``bboxes`` is single value, all
+ the texts will have the same bbox. Reference to
+ https://matplotlib.org/stable/api/_as_gen/matplotlib.patches.FancyBboxPatch.html#matplotlib.patches.FancyBboxPatch
+ for more details. Defaults to None.
+ """
+ check_type('texts', texts, (str, list))
+ if isinstance(texts, str):
+ texts = [texts]
+ num_text = len(texts)
+ check_type('positions', positions, (np.ndarray, torch.Tensor))
+ positions = tensor2ndarray(positions)
+ if len(positions.shape) == 1:
+ positions = positions[None]
+ assert positions.shape == (num_text, 2), (
+ '`positions` should have the shape of '
+ f'({num_text}, 2), but got {positions.shape}')
+ if not self._is_posion_valid(positions):
+ warnings.warn(
+ 'Warning: The text is out of bounds,'
+ ' the drawn text may not be in the image', UserWarning)
+ positions = positions.tolist()
+
+ if font_sizes is None:
+ font_sizes = self._default_font_size
+ check_type_and_length('font_sizes', font_sizes, (int, float, list),
+ num_text)
+ font_sizes = value2list(font_sizes, (int, float), num_text)
+
+ check_type_and_length('colors', colors, (str, tuple, list), num_text)
+ colors = value2list(colors, (str, tuple), num_text)
+ colors = color_val_matplotlib(colors) # type: ignore
+
+ check_type_and_length('vertical_alignments', vertical_alignments,
+ (str, list), num_text)
+ vertical_alignments = value2list(vertical_alignments, str, num_text)
+
+ check_type_and_length('horizontal_alignments', horizontal_alignments,
+ (str, list), num_text)
+ horizontal_alignments = value2list(horizontal_alignments, str,
+ num_text)
+
+ check_type_and_length('font_families', font_families, (str, list),
+ num_text)
+ font_families = value2list(font_families, str, num_text)
+
+ if bboxes is None:
+ bboxes = [None for _ in range(num_text)] # type: ignore
+ else:
+ check_type_and_length('bboxes', bboxes, (dict, list), num_text)
+ bboxes = value2list(bboxes, dict, num_text)
+
+ for i in range(num_text):
+ self.ax_save.text(
+ positions[i][0],
+ positions[i][1],
+ texts[i],
+ size=font_sizes[i], # type: ignore
+ bbox=bboxes[i], # type: ignore
+ verticalalignment=vertical_alignments[i],
+ horizontalalignment=horizontal_alignments[i],
+ family=font_families[i],
+ color=colors[i])
+ return self
+
+ @master_only
+ def draw_lines(
+ self,
+ x_datas: Union[np.ndarray, torch.Tensor],
+ y_datas: Union[np.ndarray, torch.Tensor],
+ colors: Union[str, tuple, List[str], List[tuple]] = 'g',
+ line_styles: Union[str, List[str]] = '-',
+ line_widths: Union[Union[int, float], List[Union[int, float]]] = 2
+ ) -> 'Visualizer':
+ """Draw single or multiple line segments.
+
+ Args:
+ x_datas (Union[np.ndarray, torch.Tensor]): The x coordinate of
+ each line' start and end points.
+ y_datas (Union[np.ndarray, torch.Tensor]): The y coordinate of
+ each line' start and end points.
+ colors (Union[str, tuple, List[str], List[tuple]]): The colors of
+ lines. ``colors`` can have the same length with lines or just
+ single value. If ``colors`` is single value, all the lines
+ will have the same colors. Reference to
+ https://matplotlib.org/stable/gallery/color/named_colors.html
+ for more details. Defaults to 'g'.
+ line_styles (Union[str, List[str]]): The linestyle
+ of lines. ``line_styles`` can have the same length with
+ texts or just single value. If ``line_styles`` is single
+ value, all the lines will have the same linestyle.
+ Reference to
+ https://matplotlib.org/stable/api/collections_api.html?highlight=collection#matplotlib.collections.AsteriskPolygonCollection.set_linestyle
+ for more details. Defaults to '-'.
+ line_widths (Union[Union[int, float], List[Union[int, float]]]):
+ The linewidth of lines. ``line_widths`` can have
+ the same length with lines or just single value.
+ If ``line_widths`` is single value, all the lines will
+ have the same linewidth. Defaults to 2.
+ """
+ check_type('x_datas', x_datas, (np.ndarray, torch.Tensor))
+ x_datas = tensor2ndarray(x_datas)
+ check_type('y_datas', y_datas, (np.ndarray, torch.Tensor))
+ y_datas = tensor2ndarray(y_datas)
+ assert x_datas.shape == y_datas.shape, (
+ '`x_datas` and `y_datas` should have the same shape')
+ assert x_datas.shape[-1] == 2, (
+ f'The shape of `x_datas` should be (N, 2), but got {x_datas.shape}'
+ )
+ if len(x_datas.shape) == 1:
+ x_datas = x_datas[None]
+ y_datas = y_datas[None]
+ colors = color_val_matplotlib(colors) # type: ignore
+ lines = np.concatenate(
+ (x_datas.reshape(-1, 2, 1), y_datas.reshape(-1, 2, 1)), axis=-1)
+ if not self._is_posion_valid(lines):
+ warnings.warn(
+ 'Warning: The line is out of bounds,'
+ ' the drawn line may not be in the image', UserWarning)
+ line_collect = LineCollection(
+ lines.tolist(),
+ colors=colors,
+ linestyles=line_styles,
+ linewidths=line_widths)
+ self.ax_save.add_collection(line_collect)
+ return self
+
+ @master_only
+ def draw_circles(
+ self,
+ center: Union[np.ndarray, torch.Tensor],
+ radius: Union[np.ndarray, torch.Tensor],
+ edge_colors: Union[str, tuple, List[str], List[tuple]] = 'g',
+ line_styles: Union[str, List[str]] = '-',
+ line_widths: Union[Union[int, float], List[Union[int, float]]] = 2,
+ face_colors: Union[str, tuple, List[str], List[tuple]] = 'none',
+ alpha: Union[float, int] = 0.8,
+ ) -> 'Visualizer':
+ """Draw single or multiple circles.
+
+ Args:
+ center (Union[np.ndarray, torch.Tensor]): The x coordinate of
+ each line' start and end points.
+ radius (Union[np.ndarray, torch.Tensor]): The y coordinate of
+ each line' start and end points.
+ edge_colors (Union[str, tuple, List[str], List[tuple]]): The
+ colors of circles. ``colors`` can have the same length with
+ lines or just single value. If ``colors`` is single value,
+ all the lines will have the same colors. Reference to
+ https://matplotlib.org/stable/gallery/color/named_colors.html
+ for more details. Defaults to 'g.
+ line_styles (Union[str, List[str]]): The linestyle
+ of lines. ``line_styles`` can have the same length with
+ texts or just single value. If ``line_styles`` is single
+ value, all the lines will have the same linestyle.
+ Reference to
+ https://matplotlib.org/stable/api/collections_api.html?highlight=collection#matplotlib.collections.AsteriskPolygonCollection.set_linestyle
+ for more details. Defaults to '-'.
+ line_widths (Union[Union[int, float], List[Union[int, float]]]):
+ The linewidth of lines. ``line_widths`` can have
+ the same length with lines or just single value.
+ If ``line_widths`` is single value, all the lines will
+ have the same linewidth. Defaults to 2.
+ face_colors (Union[str, tuple, List[str], List[tuple]]):
+ The face colors. Default to None.
+ alpha (Union[int, float]): The transparency of circles.
+ Defaults to 0.8.
+ """
+ check_type('center', center, (np.ndarray, torch.Tensor))
+ center = tensor2ndarray(center)
+ check_type('radius', radius, (np.ndarray, torch.Tensor))
+ radius = tensor2ndarray(radius)
+ if len(center.shape) == 1:
+ center = center[None]
+ assert center.shape == (radius.shape[0], 2), (
+ 'The shape of `center` should be (radius.shape, 2), '
+ f'but got {center.shape}')
+ if not (self._is_posion_valid(center -
+ np.tile(radius.reshape((-1, 1)), (1, 2)))
+ and self._is_posion_valid(
+ center + np.tile(radius.reshape((-1, 1)), (1, 2)))):
+ warnings.warn(
+ 'Warning: The circle is out of bounds,'
+ ' the drawn circle may not be in the image', UserWarning)
+
+ center = center.tolist()
+ radius = radius.tolist()
+ edge_colors = color_val_matplotlib(edge_colors) # type: ignore
+ face_colors = color_val_matplotlib(face_colors) # type: ignore
+ circles = []
+ for i in range(len(center)):
+ circles.append(Circle(tuple(center[i]), radius[i]))
+
+ if isinstance(line_widths, (int, float)):
+ line_widths = [line_widths] * len(circles)
+ line_widths = [
+ min(max(linewidth, 1), self._default_font_size / 4)
+ for linewidth in line_widths
+ ]
+ p = PatchCollection(
+ circles,
+ alpha=alpha,
+ facecolors=face_colors,
+ edgecolors=edge_colors,
+ linewidths=line_widths,
+ linestyles=line_styles)
+ self.ax_save.add_collection(p)
+ return self
+
+ @master_only
+ def draw_bboxes(
+ self,
+ bboxes: Union[np.ndarray, torch.Tensor],
+ edge_colors: Union[str, tuple, List[str], List[tuple]] = 'g',
+ line_styles: Union[str, List[str]] = '-',
+ line_widths: Union[Union[int, float], List[Union[int, float]]] = 2,
+ face_colors: Union[str, tuple, List[str], List[tuple]] = 'none',
+ alpha: Union[int, float] = 0.8,
+ ) -> 'Visualizer':
+ """Draw single or multiple bboxes.
+
+ Args:
+ bboxes (Union[np.ndarray, torch.Tensor]): The bboxes to draw with
+ the format of(x1,y1,x2,y2).
+ edge_colors (Union[str, tuple, List[str], List[tuple]]): The
+ colors of bboxes. ``colors`` can have the same length with
+ lines or just single value. If ``colors`` is single value, all
+ the lines will have the same colors. Refer to `matplotlib.
+ colors` for full list of formats that are accepted.
+ Defaults to 'g'.
+ line_styles (Union[str, List[str]]): The linestyle
+ of lines. ``line_styles`` can have the same length with
+ texts or just single value. If ``line_styles`` is single
+ value, all the lines will have the same linestyle.
+ Reference to
+ https://matplotlib.org/stable/api/collections_api.html?highlight=collection#matplotlib.collections.AsteriskPolygonCollection.set_linestyle
+ for more details. Defaults to '-'.
+ line_widths (Union[Union[int, float], List[Union[int, float]]]):
+ The linewidth of lines. ``line_widths`` can have
+ the same length with lines or just single value.
+ If ``line_widths`` is single value, all the lines will
+ have the same linewidth. Defaults to 2.
+ face_colors (Union[str, tuple, List[str], List[tuple]]):
+ The face colors. Defaults to None.
+ alpha (Union[int, float]): The transparency of bboxes.
+ Defaults to 0.8.
+ """
+ check_type('bboxes', bboxes, (np.ndarray, torch.Tensor))
+ bboxes = tensor2ndarray(bboxes)
+
+ if len(bboxes.shape) == 1:
+ bboxes = bboxes[None]
+ assert bboxes.shape[-1] == 4, (
+ f'The shape of `bboxes` should be (N, 4), but got {bboxes.shape}')
+
+ assert (bboxes[:, 0] <= bboxes[:, 2]).all() and (bboxes[:, 1] <=
+ bboxes[:, 3]).all()
+ if not self._is_posion_valid(bboxes.reshape((-1, 2, 2))):
+ warnings.warn(
+ 'Warning: The bbox is out of bounds,'
+ ' the drawn bbox may not be in the image', UserWarning)
+ poly = np.stack(
+ (bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 1],
+ bboxes[:, 2], bboxes[:, 3], bboxes[:, 0], bboxes[:, 3]),
+ axis=-1).reshape(-1, 4, 2)
+ poly = [p for p in poly]
+ return self.draw_polygons(
+ poly,
+ alpha=alpha,
+ edge_colors=edge_colors,
+ line_styles=line_styles,
+ line_widths=line_widths,
+ face_colors=face_colors)
+
+ @master_only
+ def draw_polygons(
+ self,
+ polygons: Union[Union[np.ndarray, torch.Tensor],
+ List[Union[np.ndarray, torch.Tensor]]],
+ edge_colors: Union[str, tuple, List[str], List[tuple]] = 'g',
+ line_styles: Union[str, List[str]] = '-',
+ line_widths: Union[Union[int, float], List[Union[int, float]]] = 2,
+ face_colors: Union[str, tuple, List[str], List[tuple]] = 'none',
+ alpha: Union[int, float] = 0.8,
+ ) -> 'Visualizer':
+ """Draw single or multiple bboxes.
+
+ Args:
+ polygons (Union[Union[np.ndarray, torch.Tensor],\
+ List[Union[np.ndarray, torch.Tensor]]]): The polygons to draw
+ with the format of (x1,y1,x2,y2,...,xn,yn).
+ edge_colors (Union[str, tuple, List[str], List[tuple]]): The
+ colors of polygons. ``colors`` can have the same length with
+ lines or just single value. If ``colors`` is single value,
+ all the lines will have the same colors. Refer to
+ `matplotlib.colors` for full list of formats that are accepted.
+ Defaults to 'g.
+ line_styles (Union[str, List[str]]): The linestyle
+ of lines. ``line_styles`` can have the same length with
+ texts or just single value. If ``line_styles`` is single
+ value, all the lines will have the same linestyle.
+ Reference to
+ https://matplotlib.org/stable/api/collections_api.html?highlight=collection#matplotlib.collections.AsteriskPolygonCollection.set_linestyle
+ for more details. Defaults to '-'.
+ line_widths (Union[Union[int, float], List[Union[int, float]]]):
+ The linewidth of lines. ``line_widths`` can have
+ the same length with lines or just single value.
+ If ``line_widths`` is single value, all the lines will
+ have the same linewidth. Defaults to 2.
+ face_colors (Union[str, tuple, List[str], List[tuple]]):
+ The face colors. Defaults to None.
+ alpha (Union[int, float]): The transparency of polygons.
+ Defaults to 0.8.
+ """
+ check_type('polygons', polygons, (list, np.ndarray, torch.Tensor))
+ edge_colors = color_val_matplotlib(edge_colors) # type: ignore
+ face_colors = color_val_matplotlib(face_colors) # type: ignore
+
+ if isinstance(polygons, (np.ndarray, torch.Tensor)):
+ polygons = [polygons]
+ if isinstance(polygons, list):
+ for polygon in polygons:
+ assert polygon.shape[1] == 2, (
+ 'The shape of each polygon in `polygons` should be (M, 2),'
+ f' but got {polygon.shape}')
+ polygons = [tensor2ndarray(polygon) for polygon in polygons]
+ for polygon in polygons:
+ if not self._is_posion_valid(polygon):
+ warnings.warn(
+ 'Warning: The polygon is out of bounds,'
+ ' the drawn polygon may not be in the image', UserWarning)
+ if isinstance(line_widths, (int, float)):
+ line_widths = [line_widths] * len(polygons)
+ line_widths = [
+ min(max(linewidth, 1), self._default_font_size / 4)
+ for linewidth in line_widths
+ ]
+ polygon_collection = PolyCollection(
+ polygons,
+ alpha=alpha,
+ facecolor=face_colors,
+ linestyles=line_styles,
+ edgecolors=edge_colors,
+ linewidths=line_widths)
+
+ self.ax_save.add_collection(polygon_collection)
+ return self
+
+ @master_only
+ def draw_binary_masks(
+ self,
+ binary_masks: Union[np.ndarray, torch.Tensor],
+ colors: Union[str, tuple, List[str], List[tuple]] = 'g',
+ alphas: Union[float, List[float]] = 0.8) -> 'Visualizer':
+ """Draw single or multiple binary masks.
+
+ Args:
+ binary_masks (np.ndarray, torch.Tensor): The binary_masks to draw
+ with of shape (N, H, W), where H is the image height and W is
+ the image width. Each value in the array is either a 0 or 1
+ value of uint8 type.
+ colors (np.ndarray): The colors which binary_masks will convert to.
+ ``colors`` can have the same length with binary_masks or just
+ single value. If ``colors`` is single value, all the
+ binary_masks will convert to the same colors. The colors format
+ is RGB. Defaults to np.array([0, 255, 0]).
+ alphas (Union[int, List[int]]): The transparency of masks.
+ Defaults to 0.8.
+ """
+ check_type('binary_masks', binary_masks, (np.ndarray, torch.Tensor))
+ binary_masks = tensor2ndarray(binary_masks)
+ assert binary_masks.dtype == np.bool_, (
+ 'The dtype of binary_masks should be np.bool_, '
+ f'but got {binary_masks.dtype}')
+ binary_masks = binary_masks.astype('uint8') * 255
+ img = self.get_image()
+ if binary_masks.ndim == 2:
+ binary_masks = binary_masks[None]
+ assert img.shape[:2] == binary_masks.shape[
+ 1:], '`binary_marks` must have ' \
+ 'the same shape with image'
+ binary_mask_len = binary_masks.shape[0]
+
+ check_type_and_length('colors', colors, (str, tuple, list),
+ binary_mask_len)
+ colors = value2list(colors, (str, tuple), binary_mask_len)
+ colors = [
+ color_str2rgb(color) if isinstance(color, str) else color
+ for color in colors
+ ]
+ for color in colors:
+ assert len(color) == 3
+ for channel in color:
+ assert 0 <= channel <= 255 # type: ignore
+
+ if isinstance(alphas, float):
+ alphas = [alphas] * binary_mask_len
+
+ for binary_mask, color, alpha in zip(binary_masks, colors, alphas):
+ binary_mask_complement = cv2.bitwise_not(binary_mask)
+ rgb = np.zeros_like(img)
+ rgb[...] = color
+ rgb = cv2.bitwise_and(rgb, rgb, mask=binary_mask)
+ img_complement = cv2.bitwise_and(
+ img, img, mask=binary_mask_complement)
+ rgb = rgb + img_complement
+ img = cv2.addWeighted(img, 1 - alpha, rgb, alpha, 0)
+ self.ax_save.imshow(
+ img,
+ extent=(0, self.width, self.height, 0),
+ interpolation='nearest')
+ return self
+
+ @staticmethod
+ @master_only
+ def draw_featmap(featmap: torch.Tensor,
+ overlaid_image: Optional[np.ndarray] = None,
+ channel_reduction: Optional[str] = 'squeeze_mean',
+ topk: int = 20,
+ arrangement: Tuple[int, int] = (4, 5),
+ resize_shape: Optional[tuple] = None,
+ alpha: float = 0.5) -> np.ndarray:
+ """Draw featmap.
+
+ - If `overlaid_image` is not None, the final output image will be the
+ weighted sum of img and featmap.
+
+ - If `resize_shape` is specified, `featmap` and `overlaid_image`
+ are interpolated.
+
+ - If `resize_shape` is None and `overlaid_image` is not None,
+ the feature map will be interpolated to the spatial size of the image
+ in the case where the spatial dimensions of `overlaid_image` and
+ `featmap` are different.
+
+ - If `channel_reduction` is "squeeze_mean" and "select_max",
+ it will compress featmap to single channel image and weighted
+ sum to `overlaid_image`.
+
+ - if `channel_reduction` is None
+
+ - If topk <= 0, featmap is assert to be one or three
+ channel and treated as image and will be weighted sum
+ to ``overlaid_image``.
+ - If topk > 0, it will select topk channel to show by the sum of
+ each channel. At the same time, you can specify the `arrangement`
+ to set the window layout.
+
+ Args:
+ featmap (torch.Tensor): The featmap to draw which format is
+ (C, H, W).
+ overlaid_image (np.ndarray, optional): The overlaid image.
+ Default to None.
+ channel_reduction (str, optional): Reduce multiple channels to a
+ single channel. The optional value is 'squeeze_mean'
+ or 'select_max'. Defaults to 'squeeze_mean'.
+ topk (int): If channel_reduction is not None and topk > 0,
+ it will select topk channel to show by the sum of each channel.
+ if topk <= 0, tensor_chw is assert to be one or three.
+ Defaults to 20.
+ arrangement (Tuple[int, int]): The arrangement of featmap when
+ channel_reduction is not None and topk > 0. Defaults to (4, 5).
+ resize_shape (tuple, optional): The shape to scale the feature map.
+ Default to None.
+ alpha (Union[int, List[int]]): The transparency of featmap.
+ Defaults to 0.5.
+
+ Returns:
+ np.ndarray: RGB image.
+ """
+ assert isinstance(featmap,
+ torch.Tensor), (f'`featmap` should be torch.Tensor,'
+ f' but got {type(featmap)}')
+ assert featmap.ndim == 3, f'Input dimension must be 3, ' \
+ f'but got {featmap.ndim}'
+ featmap = featmap.detach().cpu()
+
+ if overlaid_image is not None:
+ if overlaid_image.ndim == 2:
+ overlaid_image = cv2.cvtColor(overlaid_image,
+ cv2.COLOR_GRAY2RGB)
+
+ if overlaid_image.shape[:2] != featmap.shape[1:]:
+ warnings.warn(
+ f'Since the spatial dimensions of '
+ f'overlaid_image: {overlaid_image.shape[:2]} and '
+ f'featmap: {featmap.shape[1:]} are not same, '
+ f'the feature map will be interpolated. '
+ f'This may cause mismatch problems !')
+ if resize_shape is None:
+ featmap = F.interpolate(
+ featmap[None],
+ overlaid_image.shape[:2],
+ mode='bilinear',
+ align_corners=False)[0]
+
+ if resize_shape is not None:
+ featmap = F.interpolate(
+ featmap[None],
+ resize_shape,
+ mode='bilinear',
+ align_corners=False)[0]
+ if overlaid_image is not None:
+ overlaid_image = cv2.resize(overlaid_image, resize_shape[::-1])
+
+ if channel_reduction is not None:
+ assert channel_reduction in [
+ 'squeeze_mean', 'select_max'], \
+ f'Mode only support "squeeze_mean", "select_max", ' \
+ f'but got {channel_reduction}'
+ if channel_reduction == 'select_max':
+ sum_channel_featmap = torch.sum(featmap, dim=(1, 2))
+ _, indices = torch.topk(sum_channel_featmap, 1)
+ feat_map = featmap[indices]
+ else:
+ feat_map = torch.mean(featmap, dim=0)
+ return convert_overlay_heatmap(feat_map, overlaid_image, alpha)
+ elif topk <= 0:
+ featmap_channel = featmap.shape[0]
+ assert featmap_channel in [
+ 1, 3
+ ], ('The input tensor channel dimension must be 1 or 3 '
+ 'when topk is less than 1, but the channel '
+ f'dimension you input is {featmap_channel}, you can use the'
+ ' channel_reduction parameter or set topk greater than '
+ '0 to solve the error')
+ return convert_overlay_heatmap(featmap, overlaid_image, alpha)
+ else:
+ row, col = arrangement
+ channel, height, width = featmap.shape
+ assert row * col >= topk, 'The product of row and col in ' \
+ 'the `arrangement` is less than ' \
+ 'topk, please set the ' \
+ '`arrangement` correctly'
+
+ # Extract the feature map of topk
+ topk = min(channel, topk)
+ sum_channel_featmap = torch.sum(featmap, dim=(1, 2))
+ _, indices = torch.topk(sum_channel_featmap, topk)
+ topk_featmap = featmap[indices]
+
+ fig = plt.figure(frameon=False)
+ # Set the window layout
+ fig.subplots_adjust(
+ left=0, right=1, bottom=0, top=1, wspace=0, hspace=0)
+ dpi = fig.get_dpi()
+ fig.set_size_inches((width * col + 1e-2) / dpi,
+ (height * row + 1e-2) / dpi)
+ for i in range(topk):
+ axes = fig.add_subplot(row, col, i + 1)
+ axes.axis('off')
+ axes.text(2, 15, f'channel: {indices[i]}', fontsize=10)
+ axes.imshow(
+ convert_overlay_heatmap(topk_featmap[i], overlaid_image,
+ alpha))
+ image = img_from_canvas(fig.canvas)
+ plt.close(fig)
+ return image
+
+ @master_only
+ def add_config(self, config: Config, **kwargs):
+ """Record the config.
+
+ Args:
+ config (Config): The Config object.
+ """
+ for vis_backend in self._vis_backends.values():
+ vis_backend.add_config(config, **kwargs)
+
+ @master_only
+ def add_graph(self, model: torch.nn.Module, data_batch: Sequence[dict],
+ **kwargs) -> None:
+ """Record the model graph.
+
+ Args:
+ model (torch.nn.Module): Model to draw.
+ data_batch (Sequence[dict]): Batch of data from dataloader.
+ """
+ for vis_backend in self._vis_backends.values():
+ vis_backend.add_graph(model, data_batch, **kwargs)
+
+ @master_only
+ def add_image(self, name: str, image: np.ndarray, step: int = 0) -> None:
+ """Record the image.
+
+ Args:
+ name (str): The image identifier.
+ image (np.ndarray, optional): The image to be saved. The format
+ should be RGB. Default to None.
+ step (int): Global step value to record. Default to 0.
+ """
+ for vis_backend in self._vis_backends.values():
+ vis_backend.add_image(name, image, step) # type: ignore
+
+ @master_only
+ def add_scalar(self,
+ name: str,
+ value: Union[int, float],
+ step: int = 0,
+ **kwargs) -> None:
+ """Record the scalar data.
+
+ Args:
+ name (str): The scalar identifier.
+ value (float, int): Value to save.
+ step (int): Global step value to record. Default to 0.
+ """
+ for vis_backend in self._vis_backends.values():
+ vis_backend.add_scalar(name, value, step, **kwargs) # type: ignore
+
+ @master_only
+ def add_scalars(self,
+ scalar_dict: dict,
+ step: int = 0,
+ file_path: Optional[str] = None,
+ **kwargs) -> None:
+ """Record the scalars' data.
+
+ Args:
+ scalar_dict (dict): Key-value pair storing the tag and
+ corresponding values.
+ step (int): Global step value to record. Default to 0.
+ file_path (str, optional): The scalar's data will be
+ saved to the `file_path` file at the same time
+ if the `file_path` parameter is specified.
+ Default to None.
+ """
+ for vis_backend in self._vis_backends.values():
+ vis_backend.add_scalars(scalar_dict, step, file_path, **kwargs)
+
+ @master_only
+ def add_datasample(self,
+ name,
+ image: np.ndarray,
+ data_sample: Optional['BaseDataElement'] = None,
+ draw_gt: bool = True,
+ draw_pred: bool = True,
+ show: bool = False,
+ wait_time: int = 0,
+ step: int = 0) -> None:
+ """Draw datasample."""
+ pass
+
+ def close(self) -> None:
+ """close an opened object."""
+ for vis_backend in self._vis_backends.values():
+ vis_backend.close()
+
+ @classmethod
+ def get_instance(cls, name: str, **kwargs) -> 'Visualizer':
+ """Make subclass can get latest created instance by
+ ``Visualizer.get_current_instance()``.
+
+ Downstream codebase may need to get the latest created instance
+ without knowing the specific Visualizer type. For example, mmdetection
+ builds visualizer in runner and some component which cannot access
+ runner wants to get latest created visualizer. In this case,
+ the component does not know which type of visualizer has been built
+ and cannot get target instance. Therefore, :class:`Visualizer`
+ overrides the :meth:`get_instance` and its subclass will register
+ the created instance to :attr:`_instance_dict` additionally.
+ :meth:`get_current_instance` will return the latest created subclass
+ instance.
+
+ Examples:
+ >>> class DetLocalVisualizer(Visualizer):
+ >>> def __init__(self, name):
+ >>> super().__init__(name)
+ >>>
+ >>> visualizer1 = DetLocalVisualizer.get_instance('name1')
+ >>> visualizer2 = Visualizer.get_current_instance()
+ >>> visualizer3 = DetLocalVisualizer.get_current_instance()
+ >>> assert id(visualizer1) == id(visualizer2) == id(visualizer3)
+
+ Args:
+ name (str): Name of instance.
+
+ Returns:
+ object: Corresponding name instance.
+ """
+ instance = super().get_instance(name, **kwargs)
+ Visualizer._instance_dict[name] = instance
+ return instance
diff --git a/testbed/open-mmlab__mmengine/pytest.ini b/testbed/open-mmlab__mmengine/pytest.ini
new file mode 100644
index 0000000000000000000000000000000000000000..c1a82a12357bf77aa248f8af435b76ad79cae7c0
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/pytest.ini
@@ -0,0 +1,4 @@
+[pytest]
+testpaths = tests
+norecursedirs =
+ tests/data
diff --git a/testbed/open-mmlab__mmengine/requirements.txt b/testbed/open-mmlab__mmengine/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ec4ca05eb1e26fd57f55bcb2fe12e33bcd9e742b
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/requirements.txt
@@ -0,0 +1,2 @@
+-r requirements/runtime.txt
+-r requirements/tests.txt
diff --git a/testbed/open-mmlab__mmengine/requirements/docs.txt b/testbed/open-mmlab__mmengine/requirements/docs.txt
new file mode 100644
index 0000000000000000000000000000000000000000..25d3f135463e032311fcfbfe36719a792c2eac89
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/requirements/docs.txt
@@ -0,0 +1,9 @@
+docutils==0.16.0
+myst-parser
+opencv-python
+-e git+https://github.com/open-mmlab/pytorch_sphinx_theme.git#egg=pytorch_sphinx_theme
+sphinx==4.0.2
+sphinx-copybutton
+sphinx_markdown_tables
+torch
+torchvision
diff --git a/testbed/open-mmlab__mmengine/requirements/runtime.txt b/testbed/open-mmlab__mmengine/requirements/runtime.txt
new file mode 100644
index 0000000000000000000000000000000000000000..56b1fdd631192671620e39acaa3e9d853c3f82cd
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/requirements/runtime.txt
@@ -0,0 +1,7 @@
+addict
+matplotlib
+numpy
+pyyaml
+regex;sys_platform=='win32'
+termcolor
+yapf
diff --git a/testbed/open-mmlab__mmengine/requirements/tests.txt b/testbed/open-mmlab__mmengine/requirements/tests.txt
new file mode 100644
index 0000000000000000000000000000000000000000..debf7eb171feb3bee8122e778fe1342af05ca573
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/requirements/tests.txt
@@ -0,0 +1,4 @@
+coverage
+lmdb
+parameterized
+pytest
diff --git a/testbed/open-mmlab__mmengine/setup.cfg b/testbed/open-mmlab__mmengine/setup.cfg
new file mode 100644
index 0000000000000000000000000000000000000000..61a3c5faa1f60d13b321dd4126eba1b65887511b
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/setup.cfg
@@ -0,0 +1,16 @@
+[isort]
+line_length = 79
+multi_line_output = 0
+extra_standard_library = setuptools
+known_first_party = mmengine
+known_third_party = pytest,yaml
+no_lines_before = STDLIB,LOCALFOLDER
+default_section = THIRDPARTY
+
+[yapf]
+BASED_ON_STYLE = pep8
+BLANK_LINE_BEFORE_NESTED_CLASS_OR_DEF = true
+SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN = true
+
+[codespell]
+ignore-words-list = nd, ba, warmup
diff --git a/testbed/open-mmlab__mmengine/setup.py b/testbed/open-mmlab__mmengine/setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc68572a095fb65ede05ea65bd39970f793b1929
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/setup.py
@@ -0,0 +1,153 @@
+import re
+from setuptools import find_packages, setup # type: ignore
+
+from pkg_resources import DistributionNotFound, get_distribution
+
+
+def readme():
+ with open('README.md', encoding='utf-8') as f:
+ content = f.read()
+ return content
+
+
+version_file = 'mmengine/version.py'
+
+
+def choose_requirement(primary, secondary):
+ """If some version of primary requirement installed, return primary, else
+ return secondary."""
+ try:
+ name = re.split(r'[!<>=]', primary)[0]
+ get_distribution(name)
+ except DistributionNotFound:
+ return secondary
+
+ return str(primary)
+
+
+def get_version():
+ with open(version_file) as f:
+ exec(compile(f.read(), version_file, 'exec'))
+ return locals()['__version__']
+
+
+def parse_requirements(fname='requirements/runtime.txt', with_version=True):
+ """Parse the package dependencies listed in a requirements file but strips
+ specific versioning information.
+
+ Args:
+ fname (str): path to requirements file
+ with_version (bool, default=False): if True include version specs
+
+ Returns:
+ List[str]: list of requirements items
+
+ CommandLine:
+ python -c "import setup; print(setup.parse_requirements())"
+ """
+ import re
+ import sys
+ from os.path import exists
+ require_fpath = fname
+
+ def parse_line(line):
+ """Parse information from a line in a requirements text file."""
+ if line.startswith('-r '):
+ # Allow specifying requirements in other files
+ target = line.split(' ')[1]
+ for info in parse_require_file(target):
+ yield info
+ else:
+ info = {'line': line}
+ if line.startswith('-e '):
+ info['package'] = line.split('#egg=')[1]
+ else:
+ # Remove versioning from the package
+ pat = '(' + '|'.join(['>=', '==', '>']) + ')'
+ parts = re.split(pat, line, maxsplit=1)
+ parts = [p.strip() for p in parts]
+
+ info['package'] = parts[0]
+ if len(parts) > 1:
+ op, rest = parts[1:]
+ if ';' in rest:
+ # Handle platform specific dependencies
+ # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies
+ version, platform_deps = map(str.strip,
+ rest.split(';'))
+ info['platform_deps'] = platform_deps
+ else:
+ version = rest # NOQA
+ info['version'] = (op, version)
+ yield info
+
+ def parse_require_file(fpath):
+ with open(fpath) as f:
+ for line in f.readlines():
+ line = line.strip()
+ if line and not line.startswith('#'):
+ yield from parse_line(line)
+
+ def gen_packages_items():
+ if exists(require_fpath):
+ for info in parse_require_file(require_fpath):
+ parts = [info['package']]
+ if with_version and 'version' in info:
+ parts.extend(info['version'])
+ if not sys.version.startswith('3.4'):
+ # apparently package_deps are broken in 3.4
+ platform_deps = info.get('platform_deps')
+ if platform_deps is not None:
+ parts.append(';' + platform_deps)
+ item = ''.join(parts)
+ yield item
+
+ packages = list(gen_packages_items())
+ return packages
+
+
+install_requires = parse_requirements()
+try:
+ # OpenCV installed via conda.
+ import cv2 # NOQA: F401
+ major, minor, *rest = cv2.__version__.split('.')
+ if int(major) < 3:
+ raise RuntimeError(
+ f'OpenCV >=3 is required but {cv2.__version__} is installed')
+except ImportError:
+ # If first not installed install second package
+ CHOOSE_INSTALL_REQUIRES = [('opencv-python-headless>=3',
+ 'opencv-python>=3')]
+ for main, secondary in CHOOSE_INSTALL_REQUIRES:
+ install_requires.append(choose_requirement(main, secondary))
+
+setup(
+ name='mmengine',
+ version=get_version(),
+ description='Engine of OpenMMLab projects',
+ long_description=readme(),
+ long_description_content_type='text/markdown',
+ url='https://github.com/open-mmlab/mmengine',
+ author='MMEngine Authors',
+ author_email='openmmlab@gmail.com',
+ packages=find_packages(),
+ include_package_data=True,
+ classifiers=[
+ 'Development Status :: 4 - Beta',
+ 'License :: OSI Approved :: Apache Software License',
+ 'Operating System :: OS Independent',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.6',
+ 'Programming Language :: Python :: 3.7',
+ 'Programming Language :: Python :: 3.8',
+ 'Programming Language :: Python :: 3.9',
+ 'Programming Language :: Python :: 3.10',
+ 'Topic :: Utilities',
+ ],
+ python_requires='>=3.6',
+ install_requires=install_requires,
+ extras_require={
+ 'all': parse_requirements('requirements.txt'),
+ 'tests': parse_requirements('requirements/tests.txt'),
+ },
+)
diff --git a/testbed/open-mmlab__mmengine/tests/data/annotations/annotation_wrong_format.json b/testbed/open-mmlab__mmengine/tests/data/annotations/annotation_wrong_format.json
new file mode 100644
index 0000000000000000000000000000000000000000..b8dadc0d2b10b93fce9a9b562146e959667cce67
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/annotations/annotation_wrong_format.json
@@ -0,0 +1,5 @@
+[
+ {
+ "img_path": "test_img.jpg"
+ }
+]
\ No newline at end of file
diff --git a/testbed/open-mmlab__mmengine/tests/data/annotations/annotation_wrong_keys.json b/testbed/open-mmlab__mmengine/tests/data/annotations/annotation_wrong_keys.json
new file mode 100644
index 0000000000000000000000000000000000000000..31ad01a28f40bd87649417bc2fe4c6c31e8e003e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/annotations/annotation_wrong_keys.json
@@ -0,0 +1,50 @@
+{
+ "meta":
+ {
+ "dataset_type": "test_dataset",
+ "task_name": "test_task"
+ },
+ "data":
+ [
+ {
+ "img_path": "test_img.jpg",
+ "height": 604,
+ "width": 640,
+ "instances":
+ [
+ {
+ "bbox": [0, 0, 10, 20],
+ "bbox_label": 1,
+ "mask": [[0,0],[0,10],[10,20],[20,0]],
+ "extra_anns": [1,2,3]
+ },
+ {
+ "bbox": [10, 10, 110, 120],
+ "bbox_label": 2,
+ "mask": [[10,10],[10,110],[110,120],[120,10]],
+ "extra_anns": [4,5,6]
+ }
+ ]
+ },
+ {
+ "img_path": "gray.jpg",
+ "height": 288,
+ "width": 512,
+ "instances":
+ [
+ {
+ "bbox": [0, 0, 10, 20],
+ "bbox_label": 1,
+ "mask": [[0,0],[0,10],[10,20],[20,0]],
+ "extra_anns": [1,2,3]
+ },
+ {
+ "bbox": [10, 10, 110, 120],
+ "bbox_label": 2,
+ "mask": [[10,10],[10,110],[110,120],[120,10]],
+ "extra_anns": [4,5,6]
+ }
+ ]
+ }
+ ]
+ }
diff --git a/testbed/open-mmlab__mmengine/tests/data/annotations/dummy_annotation.json b/testbed/open-mmlab__mmengine/tests/data/annotations/dummy_annotation.json
new file mode 100644
index 0000000000000000000000000000000000000000..87d6f51a2abda2345f18093f0446dbb056057336
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/annotations/dummy_annotation.json
@@ -0,0 +1,71 @@
+{
+ "metainfo":
+ {
+ "dataset_type": "test_dataset",
+ "task_name": "test_task",
+ "empty_list": []
+ },
+ "data_list":
+ [
+ {
+ "img_path": "test_img.jpg",
+ "height": 604,
+ "width": 640,
+ "instances":
+ [
+ {
+ "bbox": [0, 0, 10, 20],
+ "bbox_label": 1,
+ "mask": [[0,0],[0,10],[10,20],[20,0]],
+ "extra_anns": [1,2,3]
+ },
+ {
+ "bbox": [10, 10, 110, 120],
+ "bbox_label": 2,
+ "mask": [[10,10],[10,110],[110,120],[120,10]],
+ "extra_anns": [4,5,6]
+ }
+ ]
+ },
+ {
+ "img_path": "gray.jpg",
+ "height": 288,
+ "width": 512,
+ "instances":
+ [
+ {
+ "bbox": [0, 0, 10, 20],
+ "bbox_label": 1,
+ "mask": [[0,0],[0,10],[10,20],[20,0]],
+ "extra_anns": [1,2,3]
+ },
+ {
+ "bbox": [10, 10, 110, 120],
+ "bbox_label": 2,
+ "mask": [[10,10],[10,110],[110,120],[120,10]],
+ "extra_anns": [4,5,6]
+ }
+ ]
+ },
+ {
+ "img_path": "gray.jpg",
+ "height": 512,
+ "width": 512,
+ "instances":
+ [
+ {
+ "bbox": [0, 0, 10, 20],
+ "bbox_label": 1,
+ "mask": [[0,0],[0,10],[10,20],[20,0]],
+ "extra_anns": [1,2,3]
+ },
+ {
+ "bbox": [10, 10, 110, 120],
+ "bbox_label": 2,
+ "mask": [[10,10],[10,110],[110,120],[120,10]],
+ "extra_anns": [4,5,6]
+ }
+ ]
+ }
+ ]
+ }
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/json_config/base3.json b/testbed/open-mmlab__mmengine/tests/data/config/json_config/base3.json
new file mode 100644
index 0000000000000000000000000000000000000000..3251c5d6395974fa788eb27a368b03150eabd72c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/json_config/base3.json
@@ -0,0 +1,3 @@
+{
+ "item3": true
+}
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/json_config/simple.config.json b/testbed/open-mmlab__mmengine/tests/data/config/json_config/simple.config.json
new file mode 100644
index 0000000000000000000000000000000000000000..cc317436ec91dc176eb825af2472d26a5b5cda82
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/json_config/simple.config.json
@@ -0,0 +1,8 @@
+{
+ "item1": [1, 2],
+ "item2": {
+ "a": 0
+ },
+ "item3": true,
+ "item4": "test"
+}
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/json_config/simple_config.json b/testbed/open-mmlab__mmengine/tests/data/config/json_config/simple_config.json
new file mode 100644
index 0000000000000000000000000000000000000000..cc317436ec91dc176eb825af2472d26a5b5cda82
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/json_config/simple_config.json
@@ -0,0 +1,8 @@
+{
+ "item1": [1, 2],
+ "item2": {
+ "a": 0
+ },
+ "item3": true,
+ "item4": "test"
+}
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/json_config/test_base.json b/testbed/open-mmlab__mmengine/tests/data/config/json_config/test_base.json
new file mode 100644
index 0000000000000000000000000000000000000000..dd2917b946e91179f07c737eb8ab4b50d423862f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/json_config/test_base.json
@@ -0,0 +1,13 @@
+{
+ "_base_": [
+ "../py_config/base1.py",
+ "../yaml_config/base2.yaml",
+ "./base3.json",
+ "../py_config/base4.py"
+ ],
+ "item3": false,
+ "item4": "test",
+ "item8": "{{fileBasename}}",
+ "item9": {{ _base_.item2 }},
+ "item10": {{ _base_.item7.b.c }}
+}
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/json_config/test_base_variables_nested.json b/testbed/open-mmlab__mmengine/tests/data/config/json_config/test_base_variables_nested.json
new file mode 100644
index 0000000000000000000000000000000000000000..af13a7eb997a55856231066df3e59b079ab212d0
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/json_config/test_base_variables_nested.json
@@ -0,0 +1,26 @@
+{
+ "_base_": [
+ "../py_config/test_base_variables.py"
+ ],
+ "base": "_base_.item8",
+ "item11": {{ _base_.item8 }},
+ "item12": {{ _base_.item9 }},
+ "item13": {{ _base_.item10 }},
+ "item14": {{ _base_.item1 }},
+ "item15": {
+ "a": {
+ "b": {{ _base_.item2 }}
+ },
+ "b": [
+ {{ _base_.item3 }}
+ ],
+ "c": [{{ _base_.item4 }}],
+ "d": [[
+ {
+ "e": {{ _base_.item5.a }}
+ }
+ ],
+ {{ _base_.item6 }}],
+ "e": {{ _base_.item1 }}
+ }
+}
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/json_config/test_predefined_var.json b/testbed/open-mmlab__mmengine/tests/data/config/json_config/test_predefined_var.json
new file mode 100644
index 0000000000000000000000000000000000000000..84c5e3ed33ffb4365385c4af9b83196f9d28008d
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/json_config/test_predefined_var.json
@@ -0,0 +1,3 @@
+{
+ "item1": "{{ fileDirname }}"
+}
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/json_config/test_reserved_key.json b/testbed/open-mmlab__mmengine/tests/data/config/json_config/test_reserved_key.json
new file mode 100644
index 0000000000000000000000000000000000000000..599d20a989666ecdfb3dbfe445209066b360fcd2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/json_config/test_reserved_key.json
@@ -0,0 +1,3 @@
+{
+ "filename": "reserved.py"
+}
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/base.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..2364e1d10b054e99c2e1e5780cf8d0e007d659c2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/base.py
@@ -0,0 +1,5 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+item1 = [1, 2]
+item2 = {'a': 0}
+item3 = True
+item4 = 'test'
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/base1.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/base1.py
new file mode 100644
index 0000000000000000000000000000000000000000..13db1375e71095d4295bde140bceaad9db9e1c31
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/base1.py
@@ -0,0 +1,2 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+item1 = [1, 2]
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/base4.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/base4.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb7b4365ec3674339d3de106bee06c451d4d09ee
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/base4.py
@@ -0,0 +1,4 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+item5 = dict(a=0, b=1)
+item6 = [dict(a=0), dict(b=1)]
+item7 = dict(a=[0, 1, 2], b=dict(c=[3.1, 4.2, 5.3]))
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/config.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..65c03bf884f9548e4cb5a2e04e51d127c30a272a
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/config.py
@@ -0,0 +1,5 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+test_int = 1
+test_list = [1, 2, 3]
+# include type, optimizer can be initiated by build_from_cfg
+optimizer = dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.0001)
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/simple.config.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/simple.config.py
new file mode 100644
index 0000000000000000000000000000000000000000..2364e1d10b054e99c2e1e5780cf8d0e007d659c2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/simple.config.py
@@ -0,0 +1,5 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+item1 = [1, 2]
+item2 = {'a': 0}
+item3 = True
+item4 = 'test'
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/simple_config.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/simple_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..2364e1d10b054e99c2e1e5780cf8d0e007d659c2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/simple_config.py
@@ -0,0 +1,5 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+item1 = [1, 2]
+item2 = {'a': 0}
+item3 = True
+item4 = 'test'
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_base_variables.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_base_variables.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d20d7f0250565aa0af5e1f9742ec5a6579a2639
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_base_variables.py
@@ -0,0 +1,11 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = [
+ './base1.py', '../yaml_config/base2.yaml', '../json_config/base3.json',
+ './base4.py'
+]
+
+item3 = False
+item4 = 'test'
+item8 = '{{fileBasename}}'
+item9 = {{_base_.item2}}
+item10 = {{_base_.item7.b.c}}
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_base_variables_nested.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_base_variables_nested.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea9a6004a86c15a68c9e43743376411cd07e2faf
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_base_variables_nested.py
@@ -0,0 +1,13 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = ['./test_base_variables.py']
+base = '_base_.item8'
+item11 = {{_base_.item8}}
+item12 = {{_base_.item9}}
+item13 = {{_base_.item10}}
+item14 = {{_base_.item1}}
+item15 = dict(
+ a=dict(b={{_base_.item2}}),
+ b=[{{_base_.item3}}],
+ c=[{{_base_.item4}}],
+ d=[[dict(e={{_base_.item5.a}})], {{_base_.item6}}],
+ e={{_base_.item1}})
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_code_in_config.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_code_in_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..d39c7cffe246b6c71026b71c53c9907fb01a2c00
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_code_in_config.py
@@ -0,0 +1,5 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from mmengine import Config # isort:skip
+
+cfg = Config.fromfile('tests/data/config/py_config/simple_config.py')
+item5 = cfg.item1[0] + cfg.item2.a
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_custom_import.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_custom_import.py
new file mode 100644
index 0000000000000000000000000000000000000000..d485a19005c6185d400e78f3fc588c95d8dcfd91
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_custom_import.py
@@ -0,0 +1,3 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+custom_imports = dict(
+ imports=['test_custom_import_module'], allow_failed_imports=False)
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_custom_import_module.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_custom_import_module.py
new file mode 100644
index 0000000000000000000000000000000000000000..853b31ae6bd8b2dbd239ea59d303e1d6bd61d183
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_custom_import_module.py
@@ -0,0 +1,4 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+
+os.environ['TEST_VALUE'] = 'test'
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_deprecated.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_deprecated.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c82380428f1095fce093a0ab69423d286dbbbec
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_deprecated.py
@@ -0,0 +1,5 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = './base.py'
+
+_deprecation_ = dict(
+ expected='tests/data/config/py_config/base.py', reference='')
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_deprecated_base.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_deprecated_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..828a384c8696bb1b3e9c8df5b42cc752b587c2f4
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_deprecated_base.py
@@ -0,0 +1,2 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = './test_deprecated.py'
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_dump_pickle_support.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_dump_pickle_support.py
new file mode 100644
index 0000000000000000000000000000000000000000..6050ce10b1ebb2ee743e0ca71cf588792ae814da
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_dump_pickle_support.py
@@ -0,0 +1,28 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+# config now can have imported modules and defined functions for convenience
+import os.path as osp
+
+
+def func():
+ return 'string with \tescape\\ characters\n'
+
+
+test_item1 = [1, 2]
+bool_item2 = True
+str_item3 = 'test'
+dict_item4 = dict(
+ a={
+ 'c/d': 'path/d',
+ 'f': 's3//f',
+ 6: '2333',
+ '2333': 'number'
+ },
+ b={'8': 543},
+ c={9: 678},
+ d={'a': 0},
+ f=dict(a='69'))
+dict_item5 = {'x/x': {'a.0': 233}}
+dict_list_item6 = {'x/x': [{'a.0': 1., 'b.0': 2.}, {'c/3': 3.}]}
+# Test windows path and escape.
+str_item_7 = osp.join(osp.expanduser('~'), 'folder') # with backslash in
+str_item_8 = func()
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_get_external_cfg.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_get_external_cfg.py
new file mode 100644
index 0000000000000000000000000000000000000000..7598ce0cb67cecad7e2a02c4c69596d384ca9c8d
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_get_external_cfg.py
@@ -0,0 +1,7 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = [
+ 'mmdet::_base_/models/faster-rcnn_r50_fpn.py',
+ 'mmdet::_base_/datasets/coco_detection.py',
+ 'mmdet::_base_/schedules/schedule_1x.py',
+ 'mmdet::_base_/default_runtime.py'
+]
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_get_external_cfg2.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_get_external_cfg2.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e72bdbf276823e20c259a096affd13a62fdf603
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_get_external_cfg2.py
@@ -0,0 +1,2 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = 'mmdet::faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py'
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_get_external_cfg3.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_get_external_cfg3.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ae261350a73f205f3d456e4679b11bc29e1bf89
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_get_external_cfg3.py
@@ -0,0 +1,18 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = [
+ 'mmdet::_base_/models/faster-rcnn_r50_fpn.py',
+ 'mmdet::_base_/datasets/coco_detection.py',
+ 'mmdet::_base_/schedules/schedule_1x.py',
+ 'mmdet::_base_/default_runtime.py',
+ './test_get_external_cfg_base.py'
+]
+
+custom_hooks = [dict(type='mmdet.DetVisualizationHook')]
+
+model = dict(
+ roi_head=dict(
+ bbox_head=dict(
+ loss_cls=dict(_delete_=True, type='test.ToyLoss')
+ )
+ )
+)
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_get_external_cfg_base.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_get_external_cfg_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..d680ef0a6b8d9adf8edbddd1ef54cdd0dc0370c4
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_get_external_cfg_base.py
@@ -0,0 +1,2 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+toy_model = dict(type='ToyModel')
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_delete.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_delete.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8a1eaf64c46d301f47a90d4ac907d1a0362e84e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_delete.py
@@ -0,0 +1,4 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = './base.py'
+item1 = {'a': 0, '_delete_': True}
+item2 = {'b': 0}
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_from_base_error.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_from_base_error.py
new file mode 100644
index 0000000000000000000000000000000000000000..1340e4bd27198e3d3ef82dbf516f22d8daf236f2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_from_base_error.py
@@ -0,0 +1,3 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = './base.py'
+item3 = {'a': 1}
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_from_base_single.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_from_base_single.py
new file mode 100644
index 0000000000000000000000000000000000000000..19edcf82d0c9a40c007ba6a1eca03153f7056ce0
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_from_base_single.py
@@ -0,0 +1,6 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = './base.py'
+item1 = [2, 3]
+item2 = {'a': 1}
+item3 = False
+item4 = 'test_base'
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_from_dict.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_from_dict.py
new file mode 100644
index 0000000000000000000000000000000000000000..cca07539c8942c7d0424d685d7a3c5e829f27d3a
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_from_dict.py
@@ -0,0 +1,2 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+item = [{'a': 0}, {'b': 0, 'c': 0}]
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_from_multiple_bases.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_from_multiple_bases.py
new file mode 100644
index 0000000000000000000000000000000000000000..da575c39bc507914f7a233ad2bf7aedb995b646a
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_from_multiple_bases.py
@@ -0,0 +1,9 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = [
+ './base1.py', '../yaml_config/base2.yaml', '../json_config/base3.json',
+ './base4.py'
+]
+item3 = False
+item4 = 'test'
+item_bool = True
+item_float = 1.0
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_from_multiple_error.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_from_multiple_error.py
new file mode 100644
index 0000000000000000000000000000000000000000..b38596d95393ddc0673288d86c610c26d0f6ecf5
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_from_multiple_error.py
@@ -0,0 +1,7 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = [
+ './base1.py', '../yaml_config/base2.yaml', '../json_config/base3.json',
+ 'simple_config.py'
+]
+item3 = False
+item4 = 'test'
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_intermediate_variable_base.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_intermediate_variable_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..f31a46a15de9d84191e25e8117d84a50fc967474
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_intermediate_variable_base.py
@@ -0,0 +1,8 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+item1 = [1, 2]
+item2 = {'a': 0}
+item3 = True
+item4 = 'test'
+item_cfg = {'b': 1}
+item5 = {'cfg': item_cfg}
+item6 = {'cfg': item_cfg}
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_intermediate_variable_child.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_intermediate_variable_child.py
new file mode 100644
index 0000000000000000000000000000000000000000..17325b13bc515f55c044453d3d27b4f4110d1001
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_intermediate_variable_child.py
@@ -0,0 +1,4 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = './test_merge_intermediate_variable_base.py'
+item_cfg = {'b': 2}
+item6 = {'cfg': item_cfg}
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_recursive_bases.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_recursive_bases.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d2218bab5ca7eb8c529e11e9cb0c159923b276e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_merge_recursive_bases.py
@@ -0,0 +1,3 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = './test_merge_from_base_single.py'
+item4 = 'test_recursive_bases'
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_pre_substitute_base_vars.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_pre_substitute_base_vars.py
new file mode 100644
index 0000000000000000000000000000000000000000..72d67ab404d153dea759cd0e71ad8fc28faac308
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_pre_substitute_base_vars.py
@@ -0,0 +1,11 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = ['./test_base_variables_nested.py']
+item21 = {{_base_.item11}}
+item22 = item21
+item23 = {{_base_.item10}}
+item24 = item23
+item25 = dict(
+ a=dict(b=item24),
+ b=[item24],
+ c=[[dict(e=item22)], {{_base_.item6}}],
+ e=item21)
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_predefined_var.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_predefined_var.py
new file mode 100644
index 0000000000000000000000000000000000000000..82594590cf4a73bed123e92ad8c392f3d4723148
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_predefined_var.py
@@ -0,0 +1,4 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+item1 = '{{fileBasename}}'
+item2 = '{{ fileDirname}}'
+item3 = 'abc_{{ fileBasenameNoExtension }}'
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_py_base.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_py_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..8073705726db5f0a706b21ec62201eb0c8040451
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_py_base.py
@@ -0,0 +1,11 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = [
+ './base1.py', '../yaml_config/base2.yaml', '../json_config/base3.json',
+ './base4.py'
+]
+item2 = dict(b=[5, 6])
+item3 = False
+item4 = 'test'
+_base_.item6[0] = dict(c=0)
+item8 = '{{fileBasename}}'
+item9, item10, item11 = _base_.item7['b']['c']
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_py_function_global_var.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_py_function_global_var.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a5c0953cc9fca81b518591e746c4e655d008736
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_py_function_global_var.py
@@ -0,0 +1,9 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+item1 = 1
+
+
+def get_item2():
+ return item1 + 1
+
+
+item2 = get_item2()
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_py_modify_key.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_py_modify_key.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2dbbf03b1f2ab564d363eeeb8667e33dda1e6f4
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_py_modify_key.py
@@ -0,0 +1,4 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+# Support modify value in config.
+item1 = dict()
+item1['a'] = 1
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_py_nested_path.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_py_nested_path.py
new file mode 100644
index 0000000000000000000000000000000000000000..b233616bd4879501a48d2c5ffab27e9939f09fa9
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_py_nested_path.py
@@ -0,0 +1,11 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+_base_ = ['./test_py_base.py']
+item12 = _base_.item8
+item13 = _base_.item9
+item14 = _base_.item1
+item15 = dict(
+ a=dict(b=_base_.item2),
+ b=[_base_.item3],
+ c=[_base_.item4],
+ d=[[dict(e=_base_.item5['a'])], _base_.item6],
+ e=_base_.item1)
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_reserved_key.py b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_reserved_key.py
new file mode 100644
index 0000000000000000000000000000000000000000..34d4ebe2f898a01ee8aa11a51f0383040213dc7f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/py_config/test_reserved_key.py
@@ -0,0 +1,2 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+filename = 'reserved.py'
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/base2.yaml b/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/base2.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..b73902b39a3cf65231aaa667a530c54cfa03bde2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/base2.yaml
@@ -0,0 +1 @@
+item2: {'a': 0}
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/simple.config.yaml b/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/simple.config.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..5365b7142fa06524678f3fd2502a97f4080c1d6c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/simple.config.yaml
@@ -0,0 +1,4 @@
+item1: [1, 2]
+item2: {'a': 0}
+item3: True
+item4: 'test'
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/simple_config.yaml b/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/simple_config.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..5365b7142fa06524678f3fd2502a97f4080c1d6c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/simple_config.yaml
@@ -0,0 +1,4 @@
+item1: [1, 2]
+item2: {'a': 0}
+item3: True
+item4: 'test'
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/test_base.yaml b/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/test_base.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..db16138e31cd8e9d5b681fd9191bc5ac5f04814d
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/test_base.yaml
@@ -0,0 +1,6 @@
+_base_ : ['../py_config/base1.py', './base2.yaml', '../json_config/base3.json', '../py_config/base4.py']
+item3 : False
+item4 : 'test'
+item8 : '{{fileBasename}}'
+item9 : {{ _base_.item2 }}
+item10 : {{ _base_.item7.b.c }}
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/test_base_variables_nested.yaml b/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/test_base_variables_nested.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..8b3431de1026b2e45de06141fe954bb42703a26c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/test_base_variables_nested.yaml
@@ -0,0 +1,15 @@
+_base_: ["../py_config/test_base_variables.py"]
+base: "_base_.item8"
+item11: {{ _base_.item8 }}
+item12: {{ _base_.item9 }}
+item13: {{ _base_.item10 }}
+item14: {{ _base_.item1 }}
+item15:
+ a:
+ b: {{ _base_.item2 }}
+ b: [{{ _base_.item3 }}]
+ c: [{{ _base_.item4 }}]
+ d:
+ - [e: {{ _base_.item5.a }}]
+ - {{ _base_.item6 }}
+ e: {{ _base_.item1 }}
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/test_predefined_var.yaml b/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/test_predefined_var.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..3b3e46e81a0b44a8c029e034d7008fa68fdf1c7f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/test_predefined_var.yaml
@@ -0,0 +1 @@
+item1: '{{ fileDirname }}'
diff --git a/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/test_reserved_key.yaml b/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/test_reserved_key.yaml
new file mode 100644
index 0000000000000000000000000000000000000000..456aceb160d881c6a9b8d5b0eeeb07c31bc1e625
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/config/yaml_config/test_reserved_key.yaml
@@ -0,0 +1 @@
+filename: reserved.py
diff --git a/testbed/open-mmlab__mmengine/tests/data/demo.lmdb/data.mdb b/testbed/open-mmlab__mmengine/tests/data/demo.lmdb/data.mdb
new file mode 100644
index 0000000000000000000000000000000000000000..db1f7d306cfd4255f53dca6a25411adc81cb145a
Binary files /dev/null and b/testbed/open-mmlab__mmengine/tests/data/demo.lmdb/data.mdb differ
diff --git a/testbed/open-mmlab__mmengine/tests/data/demo.lmdb/lock.mdb b/testbed/open-mmlab__mmengine/tests/data/demo.lmdb/lock.mdb
new file mode 100644
index 0000000000000000000000000000000000000000..2e0c69d48b97b0e5215261435d9e0f953b66088c
Binary files /dev/null and b/testbed/open-mmlab__mmengine/tests/data/demo.lmdb/lock.mdb differ
diff --git a/testbed/open-mmlab__mmengine/tests/data/filelist.txt b/testbed/open-mmlab__mmengine/tests/data/filelist.txt
new file mode 100644
index 0000000000000000000000000000000000000000..66117a873343d3dd52eedb6176fc9c9d69cde3b9
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/filelist.txt
@@ -0,0 +1,5 @@
+1.jpg
+2.jpg
+3.jpg
+4.jpg
+5.jpg
\ No newline at end of file
diff --git a/testbed/open-mmlab__mmengine/tests/data/imgs/gray.jpg b/testbed/open-mmlab__mmengine/tests/data/imgs/gray.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/testbed/open-mmlab__mmengine/tests/data/imgs/test_img.jpg b/testbed/open-mmlab__mmengine/tests/data/imgs/test_img.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/testbed/open-mmlab__mmengine/tests/data/mapping.txt b/testbed/open-mmlab__mmengine/tests/data/mapping.txt
new file mode 100644
index 0000000000000000000000000000000000000000..c85bdb05ffe83c501708989943673753465bdb94
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/mapping.txt
@@ -0,0 +1,3 @@
+1 cat
+2 dog cow
+3 panda
\ No newline at end of file
diff --git a/testbed/open-mmlab__mmengine/tests/data/meta/classes.txt b/testbed/open-mmlab__mmengine/tests/data/meta/classes.txt
new file mode 100644
index 0000000000000000000000000000000000000000..18a619c96eeab6fd6995ff280225eb6175171f95
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/meta/classes.txt
@@ -0,0 +1 @@
+dog
diff --git a/testbed/open-mmlab__mmengine/tests/data/scripts/hello.py b/testbed/open-mmlab__mmengine/tests/data/scripts/hello.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ed1a1e319fa36eb11ed3f0fcd365eb43a382d01
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/data/scripts/hello.py
@@ -0,0 +1,25 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+#!/usr/bin/env python
+
+import argparse
+import warnings
+
+
+def parse_args():
+ parser = argparse.ArgumentParser(description='Say hello.')
+ parser.add_argument('name', help='To whom.')
+
+ args = parser.parse_args()
+
+ return args
+
+
+def main():
+ args = parse_args()
+ print(f'hello {args.name}!')
+ if args.name == 'agent':
+ warnings.warn('I have a secret!')
+
+
+if __name__ == '__main__':
+ main()
diff --git a/testbed/open-mmlab__mmengine/tests/test_config/test_collect_meta.py b/testbed/open-mmlab__mmengine/tests/test_config/test_collect_meta.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e058f9f7bb4f6b73240d3a5a358d6181414912d
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_config/test_collect_meta.py
@@ -0,0 +1,43 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os.path
+
+import pytest
+
+from mmengine.config.utils import (_get_external_cfg_base_path,
+ _get_package_and_cfg_path)
+
+
+def test_get_external_cfg_base_path(tmp_path):
+ package_path = tmp_path
+ rel_cfg_path = os.path.join('cfg_dir', 'cfg_file')
+ with pytest.raises(FileNotFoundError):
+ _get_external_cfg_base_path(str(package_path), rel_cfg_path)
+ cfg_dir = tmp_path / '.mim' / 'configs' / 'cfg_dir'
+ cfg_dir.mkdir(parents=True, exist_ok=True)
+ f = open(cfg_dir / 'cfg_file', 'w')
+ f.close()
+ cfg_path = _get_external_cfg_base_path(str(package_path), rel_cfg_path)
+ assert cfg_path == f'{os.path.join(str(cfg_dir), "cfg_file")}'
+
+
+def test_get_external_cfg_path():
+ external_cfg_path = 'mmdet::path/cfg'
+ package, rel_cfg_path = _get_package_and_cfg_path(external_cfg_path)
+ assert package == 'mmdet'
+ assert rel_cfg_path == 'path/cfg'
+ # external config must contain `::`.
+ external_cfg_path = 'path/cfg'
+ with pytest.raises(ValueError):
+ _get_package_and_cfg_path(external_cfg_path)
+ # Use `:::` as operator will raise an error.
+ external_cfg_path = 'mmdet:::path/cfg'
+ with pytest.raises(ValueError):
+ _get_package_and_cfg_path(external_cfg_path)
+ # Use `:` as operator will raise an error.
+ external_cfg_path = 'mmdet:path/cfg'
+ with pytest.raises(ValueError):
+ _get_package_and_cfg_path(external_cfg_path)
+ # Too much `::`
+ external_cfg_path = 'mmdet::path/cfg::error'
+ with pytest.raises(ValueError):
+ _get_package_and_cfg_path(external_cfg_path)
diff --git a/testbed/open-mmlab__mmengine/tests/test_config/test_config.py b/testbed/open-mmlab__mmengine/tests/test_config/test_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..0714734fb127334d5e7dfa54d15dcb64cb4aade3
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_config/test_config.py
@@ -0,0 +1,858 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import argparse
+import copy
+import os
+import os.path as osp
+import platform
+import sys
+from importlib import import_module
+from pathlib import Path
+
+import pytest
+
+from mmengine import Config, ConfigDict, DictAction
+from mmengine.fileio import dump, load
+from mmengine.registry import MODELS, DefaultScope, Registry
+from mmengine.utils import is_installed
+
+
+class TestConfig:
+ data_path = osp.join(osp.dirname(osp.dirname(__file__)), 'data/')
+
+ @pytest.mark.parametrize('file_format', ['py', 'json', 'yaml'])
+ def test_init(self, file_format):
+ # test init Config by __init__
+ cfg = Config()
+ assert cfg.filename is None
+ assert cfg.text == ''
+ assert len(cfg) == 0
+ assert cfg._cfg_dict == {}
+
+ # test `cfg_dict` parameter
+ # `cfg_dict` is either dict or None
+ with pytest.raises(TypeError, match='cfg_dict must be a dict'):
+ Config([0, 1])
+
+ # test `filename` parameter
+ cfg_dict = dict(
+ item1=[1, 2], item2=dict(a=0), item3=True, item4='test')
+ cfg_file = osp.join(
+ self.data_path,
+ f'config/{file_format}_config/simple_config.{file_format}')
+ cfg = Config(cfg_dict, filename=cfg_file)
+ assert isinstance(cfg, Config)
+ assert cfg.filename == cfg_file
+ assert cfg.text == open(cfg_file).read()
+
+ cfg_file = osp.join(
+ self.data_path,
+ f'config/{file_format}_config/test_reserved_key.{file_format}')
+ # reserved keys cannot be set in config
+ with pytest.raises(
+ KeyError, match='filename is reserved for config '
+ 'file'):
+ Config.fromfile(cfg_file)
+
+ def test_fromfile(self):
+ # test whether import `custom_imports` from cfg_file.
+ cfg_file = osp.join(self.data_path, 'config',
+ 'py_config/test_custom_import.py')
+ sys.path.append(osp.join(self.data_path, 'config/py_config'))
+ cfg = Config.fromfile(cfg_file, import_custom_modules=True)
+ assert isinstance(cfg, Config)
+ # If import successfully, os.environ[''TEST_VALUE''] will be
+ # set to 'test'
+ assert os.environ.pop('TEST_VALUE') == 'test'
+ Config.fromfile(cfg_file, import_custom_modules=False)
+ assert 'TEST_VALUE' not in os.environ
+
+ @pytest.mark.parametrize('file_format', ['py', 'json', 'yaml'])
+ def test_fromstring(self, file_format):
+ filename = f'{file_format}_config/simple_config.{file_format}'
+ cfg_file = osp.join(self.data_path, 'config', filename)
+ file_format = osp.splitext(filename)[-1]
+ in_cfg = Config.fromfile(cfg_file)
+
+ cfg_str = open(cfg_file).read()
+ out_cfg = Config.fromstring(cfg_str, file_format)
+ assert in_cfg._cfg_dict == out_cfg._cfg_dict
+
+ # test pretty_text only supports py file format
+ # in_cfg.pretty_text is .py format, cannot be parsed to .json
+ if file_format != '.py':
+ with pytest.raises(Exception):
+ Config.fromstring(in_cfg.pretty_text, file_format)
+
+ # error format
+ with pytest.raises(IOError):
+ Config.fromstring(cfg_str, '.xml')
+
+ def test_magic_methods(self):
+ cfg_dict = dict(
+ item1=[1, 2], item2=dict(a=0), item3=True, item4='test')
+ filename = 'py_config/simple_config.py'
+ cfg_file = osp.join(self.data_path, 'config', filename)
+ cfg = Config.fromfile(cfg_file)
+ # len(cfg)
+ assert len(cfg) == 4
+ # cfg.keys()
+ assert set(cfg.keys()) == set(cfg_dict.keys())
+ assert set(cfg._cfg_dict.keys()) == set(cfg_dict.keys())
+ # cfg.values()
+ for value in cfg.values():
+ assert value in cfg_dict.values()
+ # cfg.items()
+ for name, value in cfg.items():
+ assert name in cfg_dict
+ assert value in cfg_dict.values()
+ # cfg.field
+ assert cfg.item1 == cfg_dict['item1']
+ assert cfg.item2 == cfg_dict['item2']
+ assert cfg.item2.a == 0
+ assert cfg.item3 == cfg_dict['item3']
+ assert cfg.item4 == cfg_dict['item4']
+ # accessing keys that do not exist will cause error
+ with pytest.raises(AttributeError):
+ cfg.not_exist
+ # field in cfg, cfg[field], cfg.get()
+ for name in ['item1', 'item2', 'item3', 'item4']:
+ assert name in cfg
+ assert cfg[name] == cfg_dict[name]
+ assert cfg.get(name) == cfg_dict[name]
+ assert cfg.get('not_exist') is None
+ assert cfg.get('not_exist', 0) == 0
+ # accessing keys that do not exist will cause error
+ with pytest.raises(KeyError):
+ cfg['not_exist']
+ assert 'item1' in cfg
+ assert 'not_exist' not in cfg
+ # cfg.update()
+ cfg.update(dict(item1=0))
+ assert cfg.item1 == 0
+ cfg.update(dict(item2=dict(a=1)))
+ assert cfg.item2.a == 1
+ # test __setattr__
+ cfg = Config()
+ cfg.item1 = [1, 2]
+ cfg.item2 = {'a': 0}
+ cfg['item5'] = {'a': {'b': None}}
+ assert cfg._cfg_dict['item1'] == [1, 2]
+ assert cfg.item1 == [1, 2]
+ assert cfg._cfg_dict['item2'] == {'a': 0}
+ assert cfg.item2.a == 0
+ assert cfg._cfg_dict['item5'] == {'a': {'b': None}}
+ assert cfg.item5.a.b is None
+
+ def test_merge_from_dict(self):
+ cfg_file = osp.join(self.data_path,
+ 'config/py_config/simple_config.py')
+ cfg = Config.fromfile(cfg_file)
+ input_options = {'item2.a': 1, 'item2.b': 0.1, 'item3': False}
+ cfg.merge_from_dict(input_options)
+ assert cfg.item2 == dict(a=1, b=0.1)
+ assert cfg.item3 is False
+
+ cfg_file = osp.join(self.data_path,
+ 'config/py_config/test_merge_from_dict.py')
+ cfg = Config.fromfile(cfg_file)
+
+ # Allow list keys
+ input_options = {'item.0.a': 1, 'item.1.b': 1}
+ cfg.merge_from_dict(input_options, allow_list_keys=True)
+ assert cfg.item == [{'a': 1}, {'b': 1, 'c': 0}]
+
+ # allow_list_keys is False
+ input_options = {'item.0.a': 1, 'item.1.b': 1}
+ with pytest.raises(TypeError):
+ cfg.merge_from_dict(input_options, allow_list_keys=False)
+
+ # Overflowed index number
+ input_options = {'item.2.a': 1}
+ with pytest.raises(KeyError):
+ cfg.merge_from_dict(input_options, allow_list_keys=True)
+
+ def test_auto_argparser(self):
+ # Temporarily make sys.argv only has one argument and keep backups
+ tmp = sys.argv[1:]
+ sys.argv = sys.argv[:2]
+ sys.argv[1] = osp.join(
+ self.data_path,
+ 'config/py_config/test_merge_from_multiple_bases.py')
+ parser, cfg = Config.auto_argparser()
+ args = parser.parse_args()
+ assert args.config == sys.argv[1]
+ for key in cfg._cfg_dict.keys():
+ if not isinstance(cfg[key], ConfigDict):
+ assert not getattr(args, key)
+ # TODO currently do not support nested keys, bool args will be
+ # overwritten by int
+ sys.argv.extend(tmp)
+
+ def test_dict_to_config_dict(self):
+ cfg_dict = dict(
+ a=1, b=dict(c=dict()), d=[dict(e=dict(f=(dict(g=1), [])))])
+ cfg_dict = Config._dict_to_config_dict(cfg_dict)
+ assert isinstance(cfg_dict, ConfigDict)
+ assert isinstance(cfg_dict.a, int)
+ assert isinstance(cfg_dict.b, ConfigDict)
+ assert isinstance(cfg_dict.b.c, ConfigDict)
+ assert isinstance(cfg_dict.d, list)
+ assert isinstance(cfg_dict.d[0], ConfigDict)
+ assert isinstance(cfg_dict.d[0].e, ConfigDict)
+ assert isinstance(cfg_dict.d[0].e.f, tuple)
+ assert isinstance(cfg_dict.d[0].e.f[0], ConfigDict)
+ assert isinstance(cfg_dict.d[0].e.f[1], list)
+
+ def test_dump(self, tmp_path):
+ file_path = 'config/py_config/test_merge_from_multiple_bases.py'
+ cfg_file = osp.join(self.data_path, file_path)
+ cfg = Config.fromfile(cfg_file)
+ dump_py = tmp_path / 'simple_config.py'
+
+ cfg.dump(dump_py)
+ assert cfg.dump() == cfg.pretty_text
+ assert open(dump_py).read() == cfg.pretty_text
+
+ # test dump json/yaml.
+ file_path = 'config/json_config/simple.config.json'
+ cfg_file = osp.join(self.data_path, file_path)
+ cfg = Config.fromfile(cfg_file)
+ dump_json = tmp_path / 'simple_config.json'
+ cfg.dump(dump_json)
+
+ with open(dump_json) as f:
+ assert f.read() == cfg.dump()
+
+ # test pickle
+ file_path = 'config/py_config/test_dump_pickle_support.py'
+ cfg_file = osp.join(self.data_path, file_path)
+ cfg = Config.fromfile(cfg_file)
+
+ text_cfg_filename = tmp_path / '_text_config.py'
+ cfg.dump(text_cfg_filename)
+ text_cfg = Config.fromfile(text_cfg_filename)
+ assert text_cfg.str_item_7 == osp.join(osp.expanduser('~'), 'folder')
+ assert text_cfg.str_item_8 == 'string with \tescape\\ characters\n'
+ assert text_cfg._cfg_dict == cfg._cfg_dict
+
+ cfg_file = osp.join(self.data_path,
+ 'config/py_config/test_dump_pickle_support.py')
+ cfg = Config.fromfile(cfg_file)
+
+ pkl_cfg_filename = tmp_path / '_pickle.pkl'
+ dump(cfg, pkl_cfg_filename)
+ pkl_cfg = load(pkl_cfg_filename)
+ assert pkl_cfg._cfg_dict == cfg._cfg_dict
+ # Test dump config from dict.
+ cfg_dict = dict(a=1, b=2)
+ cfg = Config(cfg_dict)
+ assert cfg.pretty_text == cfg.dump()
+ # Test dump python format config.
+ dump_file = tmp_path / 'dump_from_dict.py'
+ cfg.dump(dump_file)
+ with open(dump_file) as f:
+ assert f.read() == 'a = 1\nb = 2\n'
+ # Test dump json format config.
+ dump_file = tmp_path / 'dump_from_dict.json'
+ cfg.dump(dump_file)
+ with open(dump_file) as f:
+ assert f.read() == '{"a": 1, "b": 2}'
+ # Test dump yaml format config.
+ dump_file = tmp_path / 'dump_from_dict.yaml'
+ cfg.dump(dump_file)
+ with open(dump_file) as f:
+ assert f.read() == 'a: 1\nb: 2\n'
+
+ def test_pretty_text(self, tmp_path):
+ cfg_file = osp.join(
+ self.data_path,
+ 'config/py_config/test_merge_from_multiple_bases.py')
+ cfg = Config.fromfile(cfg_file)
+ text_cfg_filename = tmp_path / '_text_config.py'
+ with open(text_cfg_filename, 'w') as f:
+ f.write(cfg.pretty_text)
+ text_cfg = Config.fromfile(text_cfg_filename)
+ assert text_cfg._cfg_dict == cfg._cfg_dict
+
+ def test_repr(self, tmp_path):
+ cfg_file = osp.join(self.data_path,
+ 'config/py_config/simple_config.py')
+ cfg = Config.fromfile(cfg_file)
+ tmp_txt = tmp_path / 'tmp.txt'
+ with open(tmp_txt, 'w') as f:
+ print(cfg, file=f)
+ with open(tmp_txt) as f:
+ assert f.read().strip() == f'Config (path: {cfg.filename}): ' \
+ f'{cfg._cfg_dict.__repr__()}'
+
+ def test_dict_action(self):
+ parser = argparse.ArgumentParser(description='Train a detector')
+ parser.add_argument(
+ '--options', nargs='+', action=DictAction, help='custom options')
+ # Nested brackets
+ args = parser.parse_args(
+ ['--options', 'item2.a=a,b', 'item2.b=[(a,b), [1,2], false]'])
+ out_dict = {
+ 'item2.a': ['a', 'b'],
+ 'item2.b': [('a', 'b'), [1, 2], False]
+ }
+ assert args.options == out_dict
+ # Single Nested brackets
+ args = parser.parse_args(['--options', 'item2.a=[[1]]'])
+ out_dict = {'item2.a': [[1]]}
+ assert args.options == out_dict
+ # Imbalance bracket will cause error
+ with pytest.raises(AssertionError):
+ parser.parse_args(['--options', 'item2.a=[(a,b), [1,2], false'])
+ # Normal values
+ args = parser.parse_args([
+ '--options', 'item2.a=1', 'item2.b=0.1', 'item2.c=x', 'item3=false'
+ ])
+ out_dict = {
+ 'item2.a': 1,
+ 'item2.b': 0.1,
+ 'item2.c': 'x',
+ 'item3': False
+ }
+ assert args.options == out_dict
+ cfg_file = osp.join(self.data_path,
+ 'config/py_config/simple_config.py')
+ cfg = Config.fromfile(cfg_file)
+ cfg.merge_from_dict(args.options)
+ assert cfg.item2 == dict(a=1, b=0.1, c='x')
+ assert cfg.item3 is False
+
+ # test multiple options
+ args = parser.parse_args([
+ '--options', 'item1.a=1', 'item2.a=2', '--options', 'item2.a=1',
+ 'item3=false'
+ ])
+ out_dict = {'item1.a': 1, 'item2.a': 1, 'item3': False}
+ assert args.options == out_dict
+
+ def test_validate_py_syntax(self, tmp_path):
+ tmp_cfg = tmp_path / 'tmp_config.py'
+ with open(tmp_cfg, 'w') as f:
+ f.write('dict(a=1,b=2.c=3)')
+ # Incorrect point in dict will cause error
+ with pytest.raises(SyntaxError):
+ Config._validate_py_syntax(tmp_cfg)
+ with open(tmp_cfg, 'w') as f:
+ f.write('[dict(a=1, b=2, c=(1, 2)]')
+ # Imbalance bracket will cause error
+ with pytest.raises(SyntaxError):
+ Config._validate_py_syntax(tmp_cfg)
+ with open(tmp_cfg, 'w') as f:
+ f.write('dict(a=1,b=2\nc=3)')
+ # Incorrect feed line in dict will cause error
+ with pytest.raises(SyntaxError):
+ Config._validate_py_syntax(tmp_cfg)
+
+ def test_substitute_predefined_vars(self, tmp_path):
+ cfg_text = 'a={{fileDirname}}\n' \
+ 'b={{fileBasename}}\n' \
+ 'c={{fileBasenameNoExtension}}\n' \
+ 'd={{fileExtname}}\n'
+
+ cfg = tmp_path / 'tmp_cfg1.py'
+ substituted_cfg = tmp_path / 'tmp_cfg2.py'
+
+ file_dirname = osp.dirname(cfg)
+ file_basename = osp.basename(cfg)
+ file_basename_no_extension = osp.splitext(file_basename)[0]
+ file_extname = osp.splitext(cfg)[1]
+
+ expected_text = f'a={file_dirname}\n' \
+ f'b={file_basename}\n' \
+ f'c={file_basename_no_extension}\n' \
+ f'd={file_extname}\n'
+ expected_text = expected_text.replace('\\', '/')
+ with open(cfg, 'w') as f:
+ f.write(cfg_text)
+ Config._substitute_predefined_vars(cfg, substituted_cfg)
+
+ with open(substituted_cfg) as f:
+ assert f.read() == expected_text
+
+ def test_pre_substitute_base_vars(self, tmp_path):
+ cfg_path = osp.join(self.data_path, 'config',
+ 'py_config/test_pre_substitute_base_vars.py')
+ tmp_cfg = tmp_path / 'tmp_cfg.py'
+ base_var_dict = Config._pre_substitute_base_vars(cfg_path, tmp_cfg)
+ assert 'item6' in base_var_dict.values()
+ assert 'item10' in base_var_dict.values()
+ assert 'item11' in base_var_dict.values()
+ sys.path.append(str(tmp_path))
+ cfg_module_dict = import_module(tmp_cfg.name.strip('.py')).__dict__
+ assert cfg_module_dict['item22'].startswith('_item11')
+ assert cfg_module_dict['item23'].startswith('_item10')
+ assert cfg_module_dict['item25']['c'][1].startswith('_item6')
+ sys.path.pop()
+
+ cfg_path = osp.join(self.data_path, 'config',
+ 'json_config/test_base.json')
+ tmp_cfg = tmp_path / 'tmp_cfg.json'
+ Config._pre_substitute_base_vars(cfg_path, tmp_cfg)
+ cfg_module_dict = load(tmp_cfg)
+ assert cfg_module_dict['item9'].startswith('_item2')
+ assert cfg_module_dict['item10'].startswith('_item7')
+
+ cfg_path = osp.join(self.data_path, 'config',
+ 'yaml_config/test_base.yaml')
+ tmp_cfg = tmp_path / 'tmp_cfg.yaml'
+ Config._pre_substitute_base_vars(cfg_path, tmp_cfg)
+ cfg_module_dict = load(tmp_cfg)
+ assert cfg_module_dict['item9'].startswith('_item2')
+ assert cfg_module_dict['item10'].startswith('_item7')
+
+ def test_substitute_base_vars(self):
+ cfg = dict(
+ item4='_item1.12345',
+ item5=dict(item3='1', item2='_item2_.fswf'),
+ item0=('_item0_.12ed21wq', 1))
+ cfg_base = dict(item1=0, item2=[1, 2, 3], item0=(1, 2, 3))
+ base_var_dict = {
+ '_item1.12345': 'item1',
+ '_item2_.fswf': 'item2',
+ '_item0_.12ed21wq': 'item0'
+ }
+ cfg = Config._substitute_base_vars(cfg, base_var_dict, cfg_base)
+ assert cfg['item4'] == cfg_base['item1']
+ assert cfg['item5']['item2'] == cfg_base['item2']
+
+ def test_file2dict(self, tmp_path):
+
+ # test error format config
+ tmp_cfg = tmp_path / 'tmp_cfg.xml'
+ tmp_cfg.write_text('exist')
+ # invalid config format
+ with pytest.raises(IOError):
+ Config.fromfile(tmp_cfg)
+ # invalid config file path
+ with pytest.raises(FileNotFoundError):
+ Config.fromfile('no_such_file.py')
+
+ self._simple_load()
+ self._predefined_vars()
+ self._base_variables()
+ self._merge_from_base()
+ self._code_in_config()
+ self._merge_from_multiple_bases()
+ self._merge_delete()
+ self._merge_intermediate_variable()
+ self._merge_recursive_bases()
+ self._deprecation()
+
+ def test_get_cfg_path_local(self):
+ filename = 'py_config/simple_config.py'
+ filename = osp.join(self.data_path, 'config', filename)
+ cfg_name = './base.py'
+ cfg_path, scope = Config._get_cfg_path(cfg_name, filename)
+ assert scope is None
+ osp.isfile(cfg_path)
+
+ @pytest.mark.skipif(
+ not is_installed('mmdet') or not is_installed('mmcls'),
+ reason='mmdet and mmcls should be installed')
+ def test_get_cfg_path_external(self):
+ filename = 'py_config/simple_config.py'
+ filename = osp.join(self.data_path, 'config', filename)
+
+ cfg_name = 'mmdet::faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py'
+ cfg_path, scope = Config._get_cfg_path(cfg_name, filename)
+ assert scope == 'mmdet'
+ osp.isfile(cfg_path)
+
+ cfg_name = 'mmcls::cspnet/cspresnet50_8xb32_in1k.py'
+ cfg_path, scope = Config._get_cfg_path(cfg_name, filename)
+ assert scope == 'mmcls'
+ osp.isfile(cfg_path)
+
+ def _simple_load(self):
+ # test load simple config
+ for file_format in ['py', 'json', 'yaml']:
+ for name in ['simple.config', 'simple_config']:
+ filename = f'{file_format}_config/{name}.{file_format}'
+
+ cfg_file = osp.join(self.data_path, 'config', filename)
+ cfg_dict, cfg_text = Config._file2dict(cfg_file)
+ assert isinstance(cfg_text, str)
+ assert isinstance(cfg_dict, dict)
+
+ def _get_file_path(self, file_path):
+ if platform.system() == 'Windows':
+ return file_path.replace('\\', '/')
+ else:
+ return file_path
+
+ def _predefined_vars(self):
+ # test parse predefined_var in config
+ cfg_file = osp.join(self.data_path,
+ 'config/py_config/test_predefined_var.py')
+ path = osp.join(self.data_path, 'config/py_config')
+
+ path = Path(path).as_posix()
+ cfg_dict_dst = dict(
+ item1='test_predefined_var.py',
+ item2=path,
+ item3='abc_test_predefined_var')
+
+ assert Config._file2dict(cfg_file)[0]['item1'] == cfg_dict_dst['item1']
+ assert Config._file2dict(cfg_file)[0]['item2'] == cfg_dict_dst['item2']
+ assert Config._file2dict(cfg_file)[0]['item3'] == cfg_dict_dst['item3']
+
+ # test `use_predefined_variable=False`
+ cfg_dict_ori = dict(
+ item1='{{fileBasename}}',
+ item2='{{ fileDirname}}',
+ item3='abc_{{ fileBasenameNoExtension }}')
+
+ assert Config._file2dict(cfg_file,
+ False)[0]['item1'] == cfg_dict_ori['item1']
+ assert Config._file2dict(cfg_file,
+ False)[0]['item2'] == cfg_dict_ori['item2']
+ assert Config._file2dict(cfg_file,
+ False)[0]['item3'] == cfg_dict_ori['item3']
+
+ # test test_predefined_var.yaml
+ cfg_file = osp.join(self.data_path,
+ 'config/yaml_config/test_predefined_var.yaml')
+
+ # test `use_predefined_variable=False`
+ assert Config._file2dict(cfg_file,
+ False)[0]['item1'] == '{{ fileDirname }}'
+ assert Config._file2dict(cfg_file)[0]['item1'] == self._get_file_path(
+ osp.dirname(cfg_file))
+
+ # test test_predefined_var.json
+ cfg_file = osp.join(self.data_path,
+ 'config/json_config/test_predefined_var.json')
+
+ assert Config.fromfile(cfg_file, False)['item1'] == '{{ fileDirname }}'
+ assert Config.fromfile(cfg_file)['item1'] == self._get_file_path(
+ osp.dirname(cfg_file))
+
+ def _merge_from_base(self):
+ cfg_file = osp.join(self.data_path,
+ 'config/py_config/test_merge_from_base_single.py')
+ cfg_dict = Config._file2dict(cfg_file)[0]
+
+ assert cfg_dict['item1'] == [2, 3]
+ assert cfg_dict['item2']['a'] == 1
+ assert cfg_dict['item3'] is False
+ assert cfg_dict['item4'] == 'test_base'
+ # item3 is a dict in the child config but a boolean in base config
+ with pytest.raises(TypeError):
+ Config.fromfile(
+ osp.join(self.data_path,
+ 'config/py_config/test_merge_from_base_error.py'))
+
+ def _merge_from_multiple_bases(self):
+ cfg_file = osp.join(
+ self.data_path,
+ 'config/py_config/test_merge_from_multiple_bases.py')
+ cfg_dict = Config._file2dict(cfg_file)[0]
+
+ # cfg.fcfg_dictd
+ assert cfg_dict['item1'] == [1, 2]
+ assert cfg_dict['item2']['a'] == 0
+ assert cfg_dict['item3'] is False
+ assert cfg_dict['item4'] == 'test'
+ assert cfg_dict['item5'] == dict(a=0, b=1)
+ assert cfg_dict['item6'] == [dict(a=0), dict(b=1)]
+ assert cfg_dict['item7'] == dict(
+ a=[0, 1, 2], b=dict(c=[3.1, 4.2, 5.3]))
+ # Redefine key
+ with pytest.raises(KeyError):
+ Config.fromfile(
+ osp.join(self.data_path,
+ 'config/py_config/test_merge_from_multiple_error.py'))
+
+ def _base_variables(self):
+ for file in [
+ 'py_config/test_base_variables.py',
+ 'json_config/test_base.json', 'yaml_config/test_base.yaml'
+ ]:
+ cfg_file = osp.join(self.data_path, 'config', file)
+ cfg_dict = Config._file2dict(cfg_file)[0]
+
+ assert cfg_dict['item1'] == [1, 2]
+ assert cfg_dict['item2']['a'] == 0
+ assert cfg_dict['item3'] is False
+ assert cfg_dict['item4'] == 'test'
+ assert cfg_dict['item5'] == dict(a=0, b=1)
+ assert cfg_dict['item6'] == [dict(a=0), dict(b=1)]
+ assert cfg_dict['item7'] == dict(
+ a=[0, 1, 2], b=dict(c=[3.1, 4.2, 5.3]))
+ assert cfg_dict['item8'] == file.split('/')[-1]
+ assert cfg_dict['item9'] == dict(a=0)
+ assert cfg_dict['item10'] == [3.1, 4.2, 5.3]
+
+ # test nested base
+ for file in [
+ 'py_config/test_base_variables_nested.py',
+ 'json_config/test_base_variables_nested.json',
+ 'yaml_config/test_base_variables_nested.yaml'
+ ]:
+ cfg_file = osp.join(self.data_path, 'config', file)
+ cfg_dict = Config._file2dict(cfg_file)[0]
+
+ assert cfg_dict['base'] == '_base_.item8'
+ assert cfg_dict['item1'] == [1, 2]
+ assert cfg_dict['item2']['a'] == 0
+ assert cfg_dict['item3'] is False
+ assert cfg_dict['item4'] == 'test'
+ assert cfg_dict['item5'] == dict(a=0, b=1)
+ assert cfg_dict['item6'] == [dict(a=0), dict(b=1)]
+ assert cfg_dict['item7'] == dict(
+ a=[0, 1, 2], b=dict(c=[3.1, 4.2, 5.3]))
+ assert cfg_dict['item8'] == 'test_base_variables.py'
+ assert cfg_dict['item9'] == dict(a=0)
+ assert cfg_dict['item10'] == [3.1, 4.2, 5.3]
+ assert cfg_dict['item11'] == 'test_base_variables.py'
+ assert cfg_dict['item12'] == dict(a=0)
+ assert cfg_dict['item13'] == [3.1, 4.2, 5.3]
+ assert cfg_dict['item14'] == [1, 2]
+ assert cfg_dict['item15'] == dict(
+ a=dict(b=dict(a=0)),
+ b=[False],
+ c=['test'],
+ d=[[{
+ 'e': 0
+ }], [{
+ 'a': 0
+ }, {
+ 'b': 1
+ }]],
+ e=[1, 2])
+
+ # test reference assignment for py
+ cfg_file = osp.join(
+ self.data_path,
+ 'config/py_config/test_pre_substitute_base_vars.py')
+ cfg_dict = Config._file2dict(cfg_file)[0]
+
+ assert cfg_dict['item21'] == 'test_base_variables.py'
+ assert cfg_dict['item22'] == 'test_base_variables.py'
+ assert cfg_dict['item23'] == [3.1, 4.2, 5.3]
+ assert cfg_dict['item24'] == [3.1, 4.2, 5.3]
+ assert cfg_dict['item25'] == dict(
+ a=dict(b=[3.1, 4.2, 5.3]),
+ b=[[3.1, 4.2, 5.3]],
+ c=[[{
+ 'e': 'test_base_variables.py'
+ }], [{
+ 'a': 0
+ }, {
+ 'b': 1
+ }]],
+ e='test_base_variables.py')
+
+ cfg_file = osp.join(self.data_path, 'config/py_config/test_py_base.py')
+ cfg = Config.fromfile(cfg_file)
+ assert isinstance(cfg, Config)
+ assert cfg.filename == cfg_file
+ # cfg.field
+ assert cfg.item1 == [1, 2]
+ assert cfg.item2.a == 0
+ assert cfg.item2.b == [5, 6]
+ assert cfg.item3 is False
+ assert cfg.item4 == 'test'
+ assert cfg.item5 == dict(a=0, b=1)
+ assert cfg.item6 == [dict(c=0), dict(b=1)]
+ assert cfg.item7 == dict(a=[0, 1, 2], b=dict(c=[3.1, 4.2, 5.3]))
+ assert cfg.item8 == 'test_py_base.py'
+ assert cfg.item9 == 3.1
+ assert cfg.item10 == 4.2
+ assert cfg.item11 == 5.3
+
+ # test nested base
+ cfg_file = osp.join(self.data_path,
+ 'config/py_config/test_py_nested_path.py')
+ cfg = Config.fromfile(cfg_file)
+ assert isinstance(cfg, Config)
+ assert cfg.filename == cfg_file
+ # cfg.field
+ assert cfg.item1 == [1, 2]
+ assert cfg.item2.a == 0
+ assert cfg.item2.b == [5, 6]
+ assert cfg.item3 is False
+ assert cfg.item4 == 'test'
+ assert cfg.item5 == dict(a=0, b=1)
+ assert cfg.item6 == [dict(c=0), dict(b=1)]
+ assert cfg.item7 == dict(a=[0, 1, 2], b=dict(c=[3.1, 4.2, 5.3]))
+ assert cfg.item8 == 'test_py_base.py'
+ assert cfg.item9 == 3.1
+ assert cfg.item10 == 4.2
+ assert cfg.item11 == 5.3
+ assert cfg.item12 == 'test_py_base.py'
+ assert cfg.item13 == 3.1
+ assert cfg.item14 == [1, 2]
+ assert cfg.item15 == dict(
+ a=dict(b=dict(a=0, b=[5, 6])),
+ b=[False],
+ c=['test'],
+ d=[[{
+ 'e': 0
+ }], [{
+ 'c': 0
+ }, {
+ 'b': 1
+ }]],
+ e=[1, 2])
+
+ # Test use global variable in config function
+ cfg_file = osp.join(self.data_path,
+ 'config/py_config/test_py_function_global_var.py')
+ cfg = Config._file2dict(cfg_file)[0]
+ assert cfg['item1'] == 1
+ assert cfg['item2'] == 2
+
+ # Test support modifying the value of dict without defining base
+ # config.
+ cfg_file = osp.join(self.data_path,
+ 'config/py_config/test_py_modify_key.py')
+ cfg = Config._file2dict(cfg_file)[0]
+ assert cfg == dict(item1=dict(a=1))
+
+ def _merge_recursive_bases(self):
+ cfg_file = osp.join(self.data_path,
+ 'config/py_config/test_merge_recursive_bases.py')
+ cfg_dict = Config._file2dict(cfg_file)[0]
+
+ assert cfg_dict['item1'] == [2, 3]
+ assert cfg_dict['item2']['a'] == 1
+ assert cfg_dict['item3'] is False
+ assert cfg_dict['item4'] == 'test_recursive_bases'
+
+ def _merge_delete(self):
+ cfg_file = osp.join(self.data_path,
+ 'config/py_config/test_merge_delete.py')
+ cfg_dict = Config._file2dict(cfg_file)[0]
+ # cfg.field
+ assert cfg_dict['item1'] == dict(a=0)
+ assert cfg_dict['item2'] == dict(a=0, b=0)
+ assert cfg_dict['item3'] is True
+ assert cfg_dict['item4'] == 'test'
+ assert '_delete_' not in cfg_dict['item1']
+
+ assert type(cfg_dict['item1']) == ConfigDict
+ assert type(cfg_dict['item2']) == ConfigDict
+
+ def _merge_intermediate_variable(self):
+
+ cfg_file = osp.join(
+ self.data_path,
+ 'config/py_config/test_merge_intermediate_variable_child.py')
+ cfg_dict = Config._file2dict(cfg_file)[0]
+ # cfg.field
+ assert cfg_dict['item1'] == [1, 2]
+ assert cfg_dict['item2'] == dict(a=0)
+ assert cfg_dict['item3'] is True
+ assert cfg_dict['item4'] == 'test'
+ assert cfg_dict['item_cfg'] == dict(b=2)
+ assert cfg_dict['item5'] == dict(cfg=dict(b=1))
+ assert cfg_dict['item6'] == dict(cfg=dict(b=2))
+
+ def _code_in_config(self):
+ cfg_file = osp.join(self.data_path,
+ 'config/py_config/test_code_in_config.py')
+ cfg = Config.fromfile(cfg_file)
+ # cfg.field
+ assert cfg.cfg.item1 == [1, 2]
+ assert cfg.cfg.item2 == dict(a=0)
+ assert cfg.cfg.item3 is True
+ assert cfg.cfg.item4 == 'test'
+ assert cfg.item5 == 1
+
+ def _deprecation(self):
+ deprecated_cfg_files = [
+ osp.join(self.data_path, 'config', 'py_config/test_deprecated.py'),
+ osp.join(self.data_path, 'config',
+ 'py_config/test_deprecated_base.py')
+ ]
+
+ for cfg_file in deprecated_cfg_files:
+ with pytest.warns(DeprecationWarning):
+ cfg = Config.fromfile(cfg_file)
+ assert cfg.item1 == [1, 2]
+
+ def test_deepcopy(self):
+ cfg_file = osp.join(self.data_path, 'config',
+ 'py_config/test_dump_pickle_support.py')
+ cfg = Config.fromfile(cfg_file)
+ new_cfg = copy.deepcopy(cfg)
+
+ assert isinstance(new_cfg, Config)
+ assert new_cfg._cfg_dict == cfg._cfg_dict
+ assert new_cfg._cfg_dict is not cfg._cfg_dict
+ assert new_cfg._filename == cfg._filename
+ assert new_cfg._text == cfg._text
+
+ def test_copy(self):
+ cfg_file = osp.join(self.data_path, 'config',
+ 'py_config/test_dump_pickle_support.py')
+ cfg = Config.fromfile(cfg_file)
+ new_cfg = copy.copy(cfg)
+
+ assert isinstance(new_cfg, Config)
+ assert new_cfg._cfg_dict == cfg._cfg_dict
+ assert new_cfg._cfg_dict is cfg._cfg_dict
+ assert new_cfg._filename == cfg._filename
+ assert new_cfg._text == cfg._text
+
+ @pytest.mark.skipif(
+ not is_installed('mmdet'), reason='mmdet should be installed')
+ def test_get_external_cfg(self):
+ ext_cfg_path = osp.join(self.data_path,
+ 'config/py_config/test_get_external_cfg.py')
+ ext_cfg = Config.fromfile(ext_cfg_path)
+ assert ext_cfg._cfg_dict.model.neck == dict(
+ type='FPN',
+ in_channels=[256, 512, 1024, 2048],
+ out_channels=256,
+ num_outs=5,
+ )
+ assert '_scope_' in ext_cfg._cfg_dict.model
+
+ @pytest.mark.skipif(
+ not is_installed('mmdet'), reason='mmdet should be installed')
+ def test_build_external_package(self):
+ # Test load base config.
+ ext_cfg_path = osp.join(self.data_path,
+ 'config/py_config/test_get_external_cfg.py')
+ ext_cfg = Config.fromfile(ext_cfg_path)
+
+ LOCAL_MODELS = Registry('local_model', parent=MODELS, scope='test')
+ LOCAL_MODELS.build(ext_cfg.model)
+
+ # Test load non-base config
+ ext_cfg_path = osp.join(self.data_path,
+ 'config/py_config/test_get_external_cfg2.py')
+ ext_cfg = Config.fromfile(ext_cfg_path)
+ LOCAL_MODELS.build(ext_cfg.model)
+
+ # Test override base variable.
+ ext_cfg_path = osp.join(self.data_path,
+ 'config/py_config/test_get_external_cfg3.py')
+ ext_cfg = Config.fromfile(ext_cfg_path)
+
+ @LOCAL_MODELS.register_module()
+ class ToyLoss:
+ pass
+
+ @LOCAL_MODELS.register_module()
+ class ToyModel:
+ pass
+
+ DefaultScope.get_instance('test1', scope_name='test')
+ assert ext_cfg.model._scope_ == 'mmdet'
+ model = LOCAL_MODELS.build(ext_cfg.model)
+
+ # Local base config should not have scope.
+ assert '_scope_' not in ext_cfg.toy_model
+ toy_model = LOCAL_MODELS.build(ext_cfg.toy_model)
+ assert isinstance(toy_model, ToyModel)
+ assert model.backbone.style == 'pytorch'
+ assert isinstance(model.roi_head.bbox_head.loss_cls, ToyLoss)
+ DefaultScope._instance_dict.pop('test1')
diff --git a/testbed/open-mmlab__mmengine/tests/test_data/test_data_utils.py b/testbed/open-mmlab__mmengine/tests/test_data/test_data_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..76e30e8642f5b3ae7acb62b9c9768e2028c7dd39
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_data/test_data_utils.py
@@ -0,0 +1,151 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from unittest import TestCase
+
+import numpy as np
+import torch
+
+from mmengine.dataset import default_collate, pseudo_collate
+from mmengine.structures import BaseDataElement
+from mmengine.utils import is_list_of
+
+
+class TestDataUtils(TestCase):
+
+ def test_pseudo_collate(self):
+ # Test with list of dict tensor inputs.
+ input1 = torch.randn(1, 3, 5)
+ input2 = torch.randn(1, 3, 5)
+ label1 = torch.randn(1)
+ label2 = torch.randn(1)
+
+ data_batch = [
+ dict(inputs=input1, data_sample=label1),
+ dict(inputs=input2, data_sample=label2)
+ ]
+ data_batch = pseudo_collate(data_batch)
+ self.assertTrue(torch.allclose(input1, data_batch['inputs'][0]))
+ self.assertTrue(torch.allclose(input2, data_batch['inputs'][1]))
+ self.assertTrue(torch.allclose(label1, data_batch['data_sample'][0]))
+ self.assertTrue(torch.allclose(label2, data_batch['data_sample'][1]))
+
+ # Test with list of dict, and each element contains `data_sample`
+ # inputs
+ data_sample1 = BaseDataElement(label=torch.tensor(1))
+ data_sample2 = BaseDataElement(label=torch.tensor(1))
+ data = [
+ dict(inputs=input1, data_sample=data_sample1),
+ dict(inputs=input2, data_sample=data_sample2),
+ ]
+ data_batch = pseudo_collate(data)
+ batch_inputs, batch_data_sample = (data_batch['inputs'],
+ data_batch['data_sample'])
+ # check batch_inputs
+ self.assertTrue(is_list_of(batch_inputs, torch.Tensor))
+ self.assertIs(input1, batch_inputs[0])
+ self.assertIs(input2, batch_inputs[1])
+
+ # check data_sample
+ self.assertIs(batch_data_sample[0], data_sample1)
+ self.assertIs(batch_data_sample[1], data_sample2)
+
+ # Test with list of tuple, each tuple is a nested dict instance
+ data_batch = [(dict(
+ inputs=input1,
+ data_sample=data_sample1,
+ value=1,
+ name='1',
+ nested=dict(data_sample=data_sample1)),
+ dict(
+ inputs=input2,
+ data_sample=data_sample2,
+ value=2,
+ name='2',
+ nested=dict(data_sample=data_sample2))),
+ (dict(
+ inputs=input1,
+ data_sample=data_sample1,
+ value=1,
+ name='1',
+ nested=dict(data_sample=data_sample1)),
+ dict(
+ inputs=input2,
+ data_sample=data_sample2,
+ value=2,
+ name='2',
+ nested=dict(data_sample=data_sample2)))]
+ data_batch = pseudo_collate(data_batch)
+ batch_inputs_0 = data_batch[0]['inputs']
+ batch_inputs_1 = data_batch[1]['inputs']
+ batch_data_sample_0 = data_batch[0]['data_sample']
+ batch_data_sample_1 = data_batch[1]['data_sample']
+ batch_value_0 = data_batch[0]['value']
+ batch_value_1 = data_batch[1]['value']
+ batch_name_0 = data_batch[0]['name']
+ batch_name_1 = data_batch[1]['name']
+ batch_nested_0 = data_batch[0]['nested']
+ batch_nested_1 = data_batch[1]['nested']
+
+ self.assertTrue(is_list_of(batch_inputs_0, torch.Tensor))
+ self.assertTrue(is_list_of(batch_inputs_1, torch.Tensor))
+ self.assertIs(batch_inputs_0[0], input1)
+ self.assertIs(batch_inputs_0[1], input1)
+ self.assertIs(batch_inputs_1[0], input2)
+ self.assertIs(batch_inputs_1[1], input2)
+
+ self.assertIs(batch_data_sample_0[0], data_sample1)
+ self.assertIs(batch_data_sample_0[1], data_sample1)
+ self.assertIs(batch_data_sample_1[0], data_sample2)
+ self.assertIs(batch_data_sample_1[1], data_sample2)
+
+ self.assertEqual(batch_value_0, [1, 1])
+ self.assertEqual(batch_value_1, [2, 2])
+
+ self.assertEqual(batch_name_0, ['1', '1'])
+ self.assertEqual(batch_name_1, ['2', '2'])
+
+ self.assertIs(batch_nested_0['data_sample'][0], data_sample1)
+ self.assertIs(batch_nested_0['data_sample'][1], data_sample1)
+ self.assertIs(batch_nested_1['data_sample'][0], data_sample2)
+ self.assertIs(batch_nested_1['data_sample'][1], data_sample2)
+
+ def test_default_collate(self):
+ # `default_collate` has comment logic with `pseudo_collate`, therefore
+ # only test it cam stack batch tensor, convert int or float to tensor.
+ input1 = torch.randn(1, 3, 5)
+ input2 = torch.randn(1, 3, 5)
+ data_batch = [(
+ dict(inputs=input1, value=1, array=np.array(1)),
+ dict(inputs=input2, value=2, array=np.array(2)),
+ ),
+ (
+ dict(inputs=input1, value=1, array=np.array(1)),
+ dict(inputs=input2, value=2, array=np.array(2)),
+ )]
+ data_batch = default_collate(data_batch)
+ batch_inputs_0 = data_batch[0]['inputs']
+ batch_inputs_1 = data_batch[1]['inputs']
+ batch_value_0 = data_batch[0]['value']
+ batch_value_1 = data_batch[1]['value']
+ batch_array_0 = data_batch[0]['array']
+ batch_array_1 = data_batch[1]['array']
+
+ self.assertEqual(tuple(batch_inputs_0.shape), (2, 1, 3, 5))
+ self.assertEqual(tuple(batch_inputs_1.shape), (2, 1, 3, 5))
+
+ self.assertTrue(
+ torch.allclose(batch_inputs_0, torch.stack([input1, input1])))
+ self.assertTrue(
+ torch.allclose(batch_inputs_1, torch.stack([input2, input2])))
+
+ target1 = torch.stack([torch.tensor(1), torch.tensor(1)])
+ target2 = torch.stack([torch.tensor(2), torch.tensor(2)])
+
+ self.assertTrue(
+ torch.allclose(batch_value_0.to(target1.dtype), target1))
+ self.assertTrue(
+ torch.allclose(batch_value_1.to(target2.dtype), target2))
+
+ self.assertTrue(
+ torch.allclose(batch_array_0.to(target1.dtype), target1))
+ self.assertTrue(
+ torch.allclose(batch_array_1.to(target2.dtype), target2))
diff --git a/testbed/open-mmlab__mmengine/tests/test_dataset/test_base_dataset.py b/testbed/open-mmlab__mmengine/tests/test_dataset/test_base_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9a064914fa5d72c7f9bd524bc244939a6ad92f5
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_dataset/test_base_dataset.py
@@ -0,0 +1,873 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import os.path as osp
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+
+from mmengine.dataset import (BaseDataset, ClassBalancedDataset, Compose,
+ ConcatDataset, RepeatDataset, force_full_init)
+from mmengine.registry import DATASETS, TRANSFORMS
+
+
+def function_pipeline(data_info):
+ return data_info
+
+
+@TRANSFORMS.register_module()
+class CallableTransform:
+
+ def __call__(self, data_info):
+ return data_info
+
+
+@TRANSFORMS.register_module()
+class NotCallableTransform:
+ pass
+
+
+@DATASETS.register_module()
+class CustomDataset(BaseDataset):
+ pass
+
+
+class TestBaseDataset:
+
+ def setup(self):
+ self.data_info = dict(
+ filename='test_img.jpg', height=604, width=640, sample_idx=0)
+ self.imgs = torch.rand((2, 3, 32, 32))
+ self.ori_meta = BaseDataset.METAINFO
+ self.ori_parse_data_info = BaseDataset.parse_data_info
+ BaseDataset.parse_data_info = MagicMock(return_value=self.data_info)
+ self.pipeline = MagicMock(return_value=dict(imgs=self.imgs))
+
+ def teardown(self):
+ BaseDataset.METAINFO = self.ori_meta
+ BaseDataset.parse_data_info = self.ori_parse_data_info
+
+ def test_init(self):
+ # test the instantiation of self.base_dataset
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json')
+ assert dataset._fully_initialized
+ assert hasattr(dataset, 'data_list')
+ assert hasattr(dataset, 'data_address')
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path=''),
+ ann_file='annotations/dummy_annotation.json')
+ assert dataset._fully_initialized
+ assert hasattr(dataset, 'data_list')
+ assert hasattr(dataset, 'data_address')
+
+ # test the instantiation of self.base_dataset with
+ # `serialize_data=False`
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json',
+ serialize_data=False)
+ assert dataset._fully_initialized
+ assert hasattr(dataset, 'data_list')
+ assert not hasattr(dataset, 'data_address')
+ assert len(dataset) == 3
+ assert dataset.get_data_info(0) == self.data_info
+
+ # test the instantiation of self.base_dataset with lazy init
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json',
+ lazy_init=True)
+ assert not dataset._fully_initialized
+ assert not dataset.data_list
+
+ # test the instantiation of self.base_dataset if ann_file is not
+ # existed.
+ with pytest.raises(FileNotFoundError):
+ BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/not_existed_annotation.json')
+ # Use the default value of ann_file, i.e., ''
+ with pytest.raises(TypeError):
+ BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'))
+
+ # test the instantiation of self.base_dataset when the ann_file is
+ # wrong
+ with pytest.raises(ValueError):
+ BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/annotation_wrong_keys.json')
+ with pytest.raises(TypeError):
+ BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/annotation_wrong_format.json')
+ with pytest.raises(TypeError):
+ BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path=['img']),
+ ann_file='annotations/annotation_wrong_format.json')
+
+ # test the instantiation of self.base_dataset when `parse_data_info`
+ # return `list[dict]`
+ BaseDataset.parse_data_info = MagicMock(
+ return_value=[self.data_info,
+ self.data_info.copy()])
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json')
+ dataset.pipeline = self.pipeline
+ assert dataset._fully_initialized
+ assert hasattr(dataset, 'data_list')
+ assert hasattr(dataset, 'data_address')
+ assert len(dataset) == 6
+ assert dataset[0] == dict(imgs=self.imgs)
+ assert dataset.get_data_info(0) == self.data_info
+
+ # test the instantiation of self.base_dataset when `parse_data_info`
+ # return unsupported data.
+ with pytest.raises(TypeError):
+ BaseDataset.parse_data_info = MagicMock(return_value='xxx')
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json')
+ with pytest.raises(TypeError):
+ BaseDataset.parse_data_info = MagicMock(
+ return_value=[self.data_info, 'xxx'])
+ BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json')
+ # test the instantiation of self.base_dataset without `ann_file`
+ BaseDataset.parse_data_info = self.ori_parse_data_info
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='',
+ serialize_data=False,
+ lazy_init=True)
+ assert not dataset.ann_file
+
+ def test_meta(self):
+ # test dataset.metainfo with setting the metainfo from annotation file
+ # as the metainfo of self.base_dataset.
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json')
+
+ assert dataset.metainfo == dict(
+ dataset_type='test_dataset', task_name='test_task', empty_list=[])
+
+ # test dataset.metainfo with setting METAINFO in self.base_dataset
+ dataset_type = 'new_dataset'
+ BaseDataset.METAINFO = dict(
+ dataset_type=dataset_type, classes=('dog', 'cat'))
+
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json')
+ assert dataset.metainfo == dict(
+ dataset_type=dataset_type,
+ task_name='test_task',
+ classes=('dog', 'cat'),
+ empty_list=[])
+
+ # test dataset.metainfo with passing metainfo into self.base_dataset
+ metainfo = dict(classes=('dog', ), task_name='new_task')
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json',
+ metainfo=metainfo)
+ assert BaseDataset.METAINFO == dict(
+ dataset_type=dataset_type, classes=('dog', 'cat'))
+ assert dataset.metainfo == dict(
+ dataset_type=dataset_type,
+ task_name='new_task',
+ classes=('dog', ),
+ empty_list=[])
+ # reset `base_dataset.METAINFO`, the `dataset.metainfo` should not
+ # change
+ BaseDataset.METAINFO['classes'] = ('dog', 'cat', 'fish')
+ assert BaseDataset.METAINFO == dict(
+ dataset_type=dataset_type, classes=('dog', 'cat', 'fish'))
+ assert dataset.metainfo == dict(
+ dataset_type=dataset_type,
+ task_name='new_task',
+ classes=('dog', ),
+ empty_list=[])
+
+ # test dataset.metainfo with passing metainfo containing a file into
+ # self.base_dataset
+ metainfo = dict(
+ classes=osp.join(
+ osp.dirname(__file__), '../data/meta/classes.txt'))
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json',
+ metainfo=metainfo)
+ assert dataset.metainfo == dict(
+ dataset_type=dataset_type,
+ task_name='test_task',
+ classes=['dog'],
+ empty_list=[])
+
+ # test dataset.metainfo with passing unsupported metainfo into
+ # self.base_dataset
+ with pytest.raises(TypeError):
+ metainfo = 'dog'
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json',
+ metainfo=metainfo)
+
+ # test dataset.metainfo with passing metainfo into self.base_dataset
+ # and lazy_init is True
+ metainfo = dict(classes=('dog', ))
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json',
+ metainfo=metainfo,
+ lazy_init=True)
+ # 'task_name' and 'empty_list' not in dataset.metainfo
+ assert dataset.metainfo == dict(
+ dataset_type=dataset_type, classes=('dog', ))
+
+ # test whether self.base_dataset.METAINFO is changed when a customize
+ # dataset inherit self.base_dataset
+ # test reset METAINFO in ToyDataset.
+ class ToyDataset(BaseDataset):
+ METAINFO = dict(xxx='xxx')
+
+ assert ToyDataset.METAINFO == dict(xxx='xxx')
+ assert BaseDataset.METAINFO == dict(
+ dataset_type=dataset_type, classes=('dog', 'cat', 'fish'))
+
+ # test update METAINFO in ToyDataset.
+ class ToyDataset(BaseDataset):
+ METAINFO = copy.deepcopy(BaseDataset.METAINFO)
+ METAINFO['classes'] = ('bird', )
+
+ assert ToyDataset.METAINFO == dict(
+ dataset_type=dataset_type, classes=('bird', ))
+ assert BaseDataset.METAINFO == dict(
+ dataset_type=dataset_type, classes=('dog', 'cat', 'fish'))
+
+ @pytest.mark.parametrize('lazy_init', [True, False])
+ def test_length(self, lazy_init):
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json',
+ lazy_init=lazy_init)
+ if not lazy_init:
+ assert dataset._fully_initialized
+ assert hasattr(dataset, 'data_list')
+ assert len(dataset) == 3
+ else:
+ # test `__len__()` when lazy_init is True
+ assert not dataset._fully_initialized
+ assert not dataset.data_list
+ # call `full_init()` automatically
+ assert len(dataset) == 3
+ assert dataset._fully_initialized
+ assert hasattr(dataset, 'data_list')
+
+ def test_compose(self):
+ # test callable transform
+ transforms = [function_pipeline]
+ compose = Compose(transforms=transforms)
+ assert (self.imgs == compose(dict(img=self.imgs))['img']).all()
+ # test transform build from cfg_dict
+ transforms = [dict(type='CallableTransform')]
+ compose = Compose(transforms=transforms)
+ assert (self.imgs == compose(dict(img=self.imgs))['img']).all()
+ # test return None in advance
+ none_func = MagicMock(return_value=None)
+ transforms = [none_func, function_pipeline]
+ compose = Compose(transforms=transforms)
+ assert compose(dict(img=self.imgs)) is None
+ # test repr
+ repr_str = f'Compose(\n' \
+ f' {none_func}\n' \
+ f' {function_pipeline}\n' \
+ f')'
+ assert repr(compose) == repr_str
+ # non-callable transform will raise error
+ with pytest.raises(TypeError):
+ transforms = [dict(type='NotCallableTransform')]
+ Compose(transforms)
+
+ # transform must be callable or dict
+ with pytest.raises(TypeError):
+ Compose([1])
+
+ # when the input transform is None, do nothing
+ compose = Compose(None)
+ assert (compose(dict(img=self.imgs))['img'] == self.imgs).all()
+
+ compose = Compose([])
+ assert (compose(dict(img=self.imgs))['img'] == self.imgs).all()
+
+ @pytest.mark.parametrize('lazy_init', [True, False])
+ def test_getitem(self, lazy_init):
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json',
+ lazy_init=lazy_init)
+ dataset.pipeline = self.pipeline
+ if not lazy_init:
+ assert dataset._fully_initialized
+ assert hasattr(dataset, 'data_list')
+ assert dataset[0] == dict(imgs=self.imgs)
+ else:
+ # Test `__getitem__()` when lazy_init is True
+ assert not dataset._fully_initialized
+ assert not dataset.data_list
+ # Call `full_init()` automatically
+ assert dataset[0] == dict(imgs=self.imgs)
+ assert dataset._fully_initialized
+ assert hasattr(dataset, 'data_list')
+
+ # Test with test mode
+ dataset.test_mode = False
+ assert dataset[0] == dict(imgs=self.imgs)
+ # Test cannot get a valid image.
+ dataset.prepare_data = MagicMock(return_value=None)
+ with pytest.raises(Exception):
+ dataset[0]
+ # Test get valid image by `_rand_another`
+
+ def fake_prepare_data(idx):
+ if idx == 0:
+ return None
+ else:
+ return 1
+
+ dataset.prepare_data = fake_prepare_data
+ dataset[0]
+ dataset.test_mode = True
+ with pytest.raises(Exception):
+ dataset[0]
+
+ @pytest.mark.parametrize('lazy_init', [True, False])
+ def test_get_data_info(self, lazy_init):
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json',
+ lazy_init=lazy_init)
+
+ if not lazy_init:
+ assert dataset._fully_initialized
+ assert hasattr(dataset, 'data_list')
+ assert dataset.get_data_info(0) == self.data_info
+ else:
+ # test `get_data_info()` when lazy_init is True
+ assert not dataset._fully_initialized
+ assert not dataset.data_list
+ # call `full_init()` automatically
+ assert dataset.get_data_info(0) == self.data_info
+ assert dataset._fully_initialized
+ assert hasattr(dataset, 'data_list')
+ # Test parse_data_info with `data_prefix`
+ BaseDataset.parse_data_info = self.ori_parse_data_info
+ data_root = osp.join(osp.dirname(__file__), '../data/')
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json')
+ data_info = dataset.get_data_info(0)
+ assert data_info['img_path'] == osp.join(data_root, 'imgs',
+ 'test_img.jpg')
+
+ def test_force_full_init(self):
+ with pytest.raises(AttributeError):
+
+ class ClassWithoutFullInit:
+
+ @force_full_init
+ def foo(self):
+ pass
+
+ class_without_full_init = ClassWithoutFullInit()
+ class_without_full_init.foo()
+
+ def test_full_init(self):
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json',
+ lazy_init=True)
+ dataset.pipeline = self.pipeline
+ # test `full_init()` when lazy_init is True
+ assert not dataset._fully_initialized
+ assert not dataset.data_list
+ # call `full_init()` manually
+ dataset.full_init()
+ assert dataset._fully_initialized
+ assert hasattr(dataset, 'data_list')
+ assert len(dataset) == 3
+ assert dataset[0] == dict(imgs=self.imgs)
+ assert dataset.get_data_info(0) == self.data_info
+
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json',
+ lazy_init=False)
+
+ dataset.pipeline = self.pipeline
+ assert dataset._fully_initialized
+ assert hasattr(dataset, 'data_list')
+ assert len(dataset) == 3
+ assert dataset[0] == dict(imgs=self.imgs)
+ assert dataset.get_data_info(0) == self.data_info
+
+ # test the instantiation of self.base_dataset when passing indices
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path=''),
+ ann_file='annotations/dummy_annotation.json')
+ dataset_sliced = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path=''),
+ ann_file='annotations/dummy_annotation.json',
+ indices=1)
+ assert dataset_sliced[0] == dataset[0]
+ assert len(dataset_sliced) == 1
+
+ @pytest.mark.parametrize(
+ 'lazy_init, serialize_data',
+ ([True, False], [False, True], [True, True], [False, False]))
+ def test_get_subset_(self, lazy_init, serialize_data):
+ # Test positive int indices.
+ indices = 2
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path=''),
+ ann_file='annotations/dummy_annotation.json',
+ lazy_init=lazy_init,
+ serialize_data=serialize_data)
+
+ dataset_copy = copy.deepcopy(dataset)
+ dataset_copy.get_subset_(indices)
+ assert len(dataset_copy) == 2
+ for i in range(len(dataset_copy)):
+ ori_data = dataset[i]
+ assert dataset_copy[i] == ori_data
+
+ # Test negative int indices.
+ indices = -2
+ dataset_copy = copy.deepcopy(dataset)
+ dataset_copy.get_subset_(indices)
+ assert len(dataset_copy) == 2
+ for i in range(len(dataset_copy)):
+ ori_data = dataset[i + 1]
+ ori_data['sample_idx'] = i
+ assert dataset_copy[i] == ori_data
+
+ # If indices is 0, return empty dataset.
+ dataset_copy = copy.deepcopy(dataset)
+ dataset_copy.get_subset_(0)
+ assert len(dataset_copy) == 0
+
+ # Test list indices with positive element.
+ indices = [1]
+ dataset_copy = copy.deepcopy(dataset)
+ ori_data = dataset[1]
+ ori_data['sample_idx'] = 0
+ dataset_copy.get_subset_(indices)
+ assert len(dataset_copy) == 1
+ assert dataset_copy[0] == ori_data
+
+ # Test list indices with negative element.
+ indices = [-1]
+ dataset_copy = copy.deepcopy(dataset)
+ ori_data = dataset[2]
+ ori_data['sample_idx'] = 0
+ dataset_copy.get_subset_(indices)
+ assert len(dataset_copy) == 1
+ assert dataset_copy[0] == ori_data
+
+ # Test empty list.
+ indices = []
+ dataset_copy = copy.deepcopy(dataset)
+ dataset_copy.get_subset_(indices)
+ assert len(dataset_copy) == 0
+ # Test list with multiple positive indices.
+ indices = [0, 1, 2]
+ dataset_copy = copy.deepcopy(dataset)
+ dataset_copy.get_subset_(indices)
+ for i in range(len(dataset_copy)):
+ ori_data = dataset[i]
+ ori_data['sample_idx'] = i
+ assert dataset_copy[i] == ori_data
+ # Test list with multiple negative indices.
+ indices = [-1, -2, 0]
+ dataset_copy = copy.deepcopy(dataset)
+ dataset_copy.get_subset_(indices)
+ for i in range(len(dataset_copy)):
+ ori_data = dataset[len(dataset) - i - 1]
+ ori_data['sample_idx'] = i
+ assert dataset_copy[i] == ori_data
+
+ with pytest.raises(TypeError):
+ dataset.get_subset_(dict())
+
+ @pytest.mark.parametrize(
+ 'lazy_init, serialize_data',
+ ([True, False], [False, True], [True, True], [False, False]))
+ def test_get_subset(self, lazy_init, serialize_data):
+ # Test positive indices.
+ indices = 2
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path=''),
+ ann_file='annotations/dummy_annotation.json',
+ lazy_init=lazy_init,
+ serialize_data=serialize_data)
+ dataset_sliced = dataset.get_subset(indices)
+ assert len(dataset_sliced) == 2
+ assert dataset_sliced[0] == dataset[0]
+ for i in range(len(dataset_sliced)):
+ assert dataset_sliced[i] == dataset[i]
+ # Test negative indices.
+ indices = -2
+ dataset_sliced = dataset.get_subset(indices)
+ assert len(dataset_sliced) == 2
+ for i in range(len(dataset_sliced)):
+ ori_data = dataset[i + 1]
+ ori_data['sample_idx'] = i
+ assert dataset_sliced[i] == ori_data
+ # If indices is 0 or empty list, return empty dataset.
+ assert len(dataset.get_subset(0)) == 0
+ assert len(dataset.get_subset([])) == 0
+ # test list indices.
+ indices = [1]
+ dataset_sliced = dataset.get_subset(indices)
+ ori_data = dataset[1]
+ ori_data['sample_idx'] = 0
+ assert len(dataset_sliced) == 1
+ assert dataset_sliced[0] == ori_data
+ # Test list with multiple positive index.
+ indices = [0, 1, 2]
+ dataset_sliced = dataset.get_subset(indices)
+ for i in range(len(dataset_sliced)):
+ ori_data = dataset[i]
+ ori_data['sample_idx'] = i
+ assert dataset_sliced[i] == ori_data
+ # Test list with multiple negative index.
+ indices = [-1, -2, 0]
+ dataset_sliced = dataset.get_subset(indices)
+ for i in range(len(dataset_sliced)):
+ ori_data = dataset[len(dataset) - i - 1]
+ ori_data['sample_idx'] = i
+ assert dataset_sliced[i] == ori_data
+
+ def test_rand_another(self):
+ # test the instantiation of self.base_dataset when passing num_samples
+ dataset = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path=''),
+ ann_file='annotations/dummy_annotation.json',
+ indices=1)
+ assert dataset._rand_another() >= 0
+ assert dataset._rand_another() < len(dataset)
+
+
+class TestConcatDataset:
+
+ def setup(self):
+ dataset = BaseDataset
+
+ # create dataset_a
+ data_info = dict(filename='test_img.jpg', height=604, width=640)
+ dataset.parse_data_info = MagicMock(return_value=data_info)
+ imgs = torch.rand((2, 3, 32, 32))
+
+ self.dataset_a = dataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json')
+ self.dataset_a.pipeline = MagicMock(return_value=dict(imgs=imgs))
+
+ # create dataset_b
+ data_info = dict(filename='gray.jpg', height=288, width=512)
+ dataset.parse_data_info = MagicMock(return_value=data_info)
+ imgs = torch.rand((2, 3, 32, 32))
+ self.dataset_b = dataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json')
+ self.dataset_b.pipeline = MagicMock(return_value=dict(imgs=imgs))
+ # test init
+ self.cat_datasets = ConcatDataset(
+ datasets=[self.dataset_a, self.dataset_b])
+
+ def test_init(self):
+ # Test build dataset from cfg.
+ dataset_cfg_b = dict(
+ type=CustomDataset,
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json')
+ cat_datasets = ConcatDataset(datasets=[self.dataset_a, dataset_cfg_b])
+ cat_datasets.datasets[1].pipeline = self.dataset_b.pipeline
+ assert len(cat_datasets) == len(self.cat_datasets)
+ for i in range(len(cat_datasets)):
+ assert (cat_datasets.get_data_info(i) ==
+ self.cat_datasets.get_data_info(i))
+ assert (cat_datasets[i] == self.cat_datasets[i])
+
+ with pytest.raises(TypeError):
+ ConcatDataset(datasets=[0])
+
+ with pytest.raises(TypeError):
+ ConcatDataset(
+ datasets=[self.dataset_a, dataset_cfg_b], ignore_keys=1)
+
+ def test_full_init(self):
+ # test init with lazy_init=True
+ self.cat_datasets.full_init()
+ assert len(self.cat_datasets) == 6
+ self.cat_datasets.full_init()
+ self.cat_datasets._fully_initialized = False
+ self.cat_datasets[1]
+ assert len(self.cat_datasets) == 6
+
+ with pytest.raises(NotImplementedError):
+ self.cat_datasets.get_subset_(1)
+
+ with pytest.raises(NotImplementedError):
+ self.cat_datasets.get_subset(1)
+
+ dataset_b = BaseDataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json',
+ metainfo=dict(classes=('cat')))
+ # Regardless of order, different meta information without
+ # `ignore_keys` will raise error.
+ with pytest.raises(ValueError):
+ ConcatDataset(datasets=[self.dataset_a, dataset_b])
+ with pytest.raises(ValueError):
+ ConcatDataset(datasets=[dataset_b, self.dataset_a])
+ # `ignore_keys` does not contain different meta information keys will
+ # raise error.
+ with pytest.raises(ValueError):
+ ConcatDataset(
+ datasets=[self.dataset_a, dataset_b], ignore_keys=['a'])
+ # Different meta information with `ignore_keys` will not raise error.
+ cat_datasets = ConcatDataset(
+ datasets=[self.dataset_a, dataset_b], ignore_keys='classes')
+ cat_datasets.full_init()
+ assert len(cat_datasets) == 6
+ cat_datasets.full_init()
+ cat_datasets._fully_initialized = False
+ cat_datasets[1]
+ assert len(cat_datasets.metainfo) == 3
+ assert len(cat_datasets) == 6
+
+ def test_metainfo(self):
+ assert self.cat_datasets.metainfo == self.dataset_a.metainfo
+
+ def test_length(self):
+ assert len(self.cat_datasets) == (
+ len(self.dataset_a) + len(self.dataset_b))
+
+ def test_getitem(self):
+ assert (
+ self.cat_datasets[0]['imgs'] == self.dataset_a[0]['imgs']).all()
+ assert (self.cat_datasets[0]['imgs'] !=
+ self.dataset_b[0]['imgs']).all()
+
+ assert (
+ self.cat_datasets[-1]['imgs'] == self.dataset_b[-1]['imgs']).all()
+ assert (self.cat_datasets[-1]['imgs'] !=
+ self.dataset_a[-1]['imgs']).all()
+
+ def test_get_data_info(self):
+ assert self.cat_datasets.get_data_info(
+ 0) == self.dataset_a.get_data_info(0)
+ assert self.cat_datasets.get_data_info(
+ 0) != self.dataset_b.get_data_info(0)
+
+ assert self.cat_datasets.get_data_info(
+ -1) == self.dataset_b.get_data_info(-1)
+ assert self.cat_datasets.get_data_info(
+ -1) != self.dataset_a.get_data_info(-1)
+
+ def test_get_ori_dataset_idx(self):
+ assert self.cat_datasets._get_ori_dataset_idx(3) == (
+ 1, 3 - len(self.dataset_a))
+ assert self.cat_datasets._get_ori_dataset_idx(-1) == (
+ 1, len(self.dataset_b) - 1)
+ with pytest.raises(ValueError):
+ assert self.cat_datasets._get_ori_dataset_idx(-10)
+
+
+class TestRepeatDataset:
+
+ def setup(self):
+ dataset = BaseDataset
+ data_info = dict(filename='test_img.jpg', height=604, width=640)
+ dataset.parse_data_info = MagicMock(return_value=data_info)
+ imgs = torch.rand((2, 3, 32, 32))
+ self.dataset = dataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json')
+ self.dataset.pipeline = MagicMock(return_value=dict(imgs=imgs))
+
+ self.repeat_times = 5
+ # test init
+ self.repeat_datasets = RepeatDataset(
+ dataset=self.dataset, times=self.repeat_times)
+
+ def test_init(self):
+ # Test build dataset from cfg.
+ dataset_cfg = dict(
+ type=CustomDataset,
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json')
+ repeat_dataset = RepeatDataset(
+ dataset=dataset_cfg, times=self.repeat_times)
+ repeat_dataset.dataset.pipeline = self.dataset.pipeline
+ assert len(repeat_dataset) == len(self.repeat_datasets)
+ for i in range(len(repeat_dataset)):
+ assert (repeat_dataset.get_data_info(i) ==
+ self.repeat_datasets.get_data_info(i))
+ assert (repeat_dataset[i] == self.repeat_datasets[i])
+
+ with pytest.raises(TypeError):
+ RepeatDataset(dataset=[0], times=5)
+
+ def test_full_init(self):
+ self.repeat_datasets.full_init()
+ assert len(
+ self.repeat_datasets) == self.repeat_times * len(self.dataset)
+ self.repeat_datasets.full_init()
+ self.repeat_datasets._fully_initialized = False
+ self.repeat_datasets[1]
+ assert len(self.repeat_datasets) == \
+ self.repeat_times * len(self.dataset)
+
+ with pytest.raises(NotImplementedError):
+ self.repeat_datasets.get_subset_(1)
+
+ with pytest.raises(NotImplementedError):
+ self.repeat_datasets.get_subset(1)
+
+ def test_metainfo(self):
+ assert self.repeat_datasets.metainfo == self.dataset.metainfo
+
+ def test_length(self):
+ assert len(
+ self.repeat_datasets) == len(self.dataset) * self.repeat_times
+
+ def test_getitem(self):
+ for i in range(self.repeat_times):
+ assert self.repeat_datasets[len(self.dataset) *
+ i] == self.dataset[0]
+
+ def test_get_data_info(self):
+ for i in range(self.repeat_times):
+ assert self.repeat_datasets.get_data_info(
+ len(self.dataset) * i) == self.dataset.get_data_info(0)
+
+
+class TestClassBalancedDataset:
+
+ def setup(self):
+ dataset = BaseDataset
+ data_info = dict(filename='test_img.jpg', height=604, width=640)
+ dataset.parse_data_info = MagicMock(return_value=data_info)
+ imgs = torch.rand((2, 3, 32, 32))
+ dataset.get_cat_ids = MagicMock(return_value=[0])
+ self.dataset = dataset(
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json')
+ self.dataset.pipeline = MagicMock(return_value=dict(imgs=imgs))
+
+ self.repeat_indices = [0, 0, 1, 1, 1]
+ # test init
+ self.cls_banlanced_datasets = ClassBalancedDataset(
+ dataset=self.dataset, oversample_thr=1e-3)
+ self.cls_banlanced_datasets.repeat_indices = self.repeat_indices
+
+ def test_init(self):
+ # Test build dataset from cfg.
+ dataset_cfg = dict(
+ type=CustomDataset,
+ data_root=osp.join(osp.dirname(__file__), '../data/'),
+ data_prefix=dict(img_path='imgs'),
+ ann_file='annotations/dummy_annotation.json')
+ cls_banlanced_datasets = ClassBalancedDataset(
+ dataset=dataset_cfg, oversample_thr=1e-3)
+ cls_banlanced_datasets.repeat_indices = self.repeat_indices
+ cls_banlanced_datasets.dataset.pipeline = self.dataset.pipeline
+ assert len(cls_banlanced_datasets) == len(self.cls_banlanced_datasets)
+ for i in range(len(cls_banlanced_datasets)):
+ assert (cls_banlanced_datasets.get_data_info(i) ==
+ self.cls_banlanced_datasets.get_data_info(i))
+ assert (
+ cls_banlanced_datasets[i] == self.cls_banlanced_datasets[i])
+
+ with pytest.raises(TypeError):
+ ClassBalancedDataset(dataset=[0], times=5)
+
+ def test_full_init(self):
+ self.cls_banlanced_datasets.full_init()
+ self.cls_banlanced_datasets.repeat_indices = self.repeat_indices
+ assert len(self.cls_banlanced_datasets) == len(self.repeat_indices)
+ # Reinit `repeat_indices`.
+ self.cls_banlanced_datasets._fully_initialized = False
+ self.cls_banlanced_datasets.repeat_indices = self.repeat_indices
+ assert len(self.cls_banlanced_datasets) != len(self.repeat_indices)
+
+ with pytest.raises(NotImplementedError):
+ self.cls_banlanced_datasets.get_subset_(1)
+
+ with pytest.raises(NotImplementedError):
+ self.cls_banlanced_datasets.get_subset(1)
+
+ def test_metainfo(self):
+ assert self.cls_banlanced_datasets.metainfo == self.dataset.metainfo
+
+ def test_length(self):
+ assert len(self.cls_banlanced_datasets) == len(self.repeat_indices)
+
+ def test_getitem(self):
+ for i in range(len(self.repeat_indices)):
+ assert self.cls_banlanced_datasets[i] == self.dataset[
+ self.repeat_indices[i]]
+
+ def test_get_data_info(self):
+ for i in range(len(self.repeat_indices)):
+ assert self.cls_banlanced_datasets.get_data_info(
+ i) == self.dataset.get_data_info(self.repeat_indices[i])
+
+ def test_get_cat_ids(self):
+ for i in range(len(self.repeat_indices)):
+ assert self.cls_banlanced_datasets.get_cat_ids(
+ i) == self.dataset.get_cat_ids(self.repeat_indices[i])
diff --git a/testbed/open-mmlab__mmengine/tests/test_dataset/test_sampler.py b/testbed/open-mmlab__mmengine/tests/test_dataset/test_sampler.py
new file mode 100644
index 0000000000000000000000000000000000000000..31582a86796b41d089cb9120db6a1ec829a791f5
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_dataset/test_sampler.py
@@ -0,0 +1,141 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+
+from unittest import TestCase
+from unittest.mock import patch
+
+import numpy as np
+import torch
+
+from mmengine.dataset import DefaultSampler, InfiniteSampler
+
+
+class TestDefaultSampler(TestCase):
+
+ def setUp(self):
+ self.data_length = 100
+ self.dataset = list(range(self.data_length))
+
+ @patch('mmengine.dataset.sampler.get_dist_info', return_value=(0, 1))
+ def test_non_dist(self, mock):
+ sampler = DefaultSampler(self.dataset)
+ self.assertEqual(sampler.world_size, 1)
+ self.assertEqual(sampler.rank, 0)
+
+ # test round_up=True
+ sampler = DefaultSampler(self.dataset, round_up=True, shuffle=False)
+ self.assertEqual(sampler.total_size, self.data_length)
+ self.assertEqual(sampler.num_samples, self.data_length)
+ self.assertEqual(list(sampler), list(range(self.data_length)))
+
+ # test round_up=False
+ sampler = DefaultSampler(self.dataset, round_up=False, shuffle=False)
+ self.assertEqual(sampler.total_size, self.data_length)
+ self.assertEqual(sampler.num_samples, self.data_length)
+ self.assertEqual(list(sampler), list(range(self.data_length)))
+
+ @patch('mmengine.dataset.sampler.get_dist_info', return_value=(2, 3))
+ def test_dist(self, mock):
+ sampler = DefaultSampler(self.dataset)
+ self.assertEqual(sampler.world_size, 3)
+ self.assertEqual(sampler.rank, 2)
+
+ # test round_up=True
+ sampler = DefaultSampler(self.dataset, round_up=True, shuffle=False)
+ self.assertEqual(sampler.num_samples, np.ceil(self.data_length / 3))
+ self.assertEqual(sampler.total_size, sampler.num_samples * 3)
+ self.assertEqual(len(sampler), sampler.num_samples)
+ self.assertEqual(
+ list(sampler),
+ list(range(self.data_length))[2::3] + [1])
+
+ # test round_up=False
+ sampler = DefaultSampler(self.dataset, round_up=False, shuffle=False)
+ self.assertEqual(sampler.num_samples,
+ np.ceil((self.data_length - 2) / 3))
+ self.assertEqual(sampler.total_size, self.data_length)
+ self.assertEqual(len(sampler), sampler.num_samples)
+ self.assertEqual(list(sampler), list(range(self.data_length))[2::3])
+
+ @patch('mmengine.dataset.sampler.get_dist_info', return_value=(0, 1))
+ @patch('mmengine.dataset.sampler.sync_random_seed', return_value=7)
+ def test_shuffle(self, mock1, mock2):
+ # test seed=None
+ sampler = DefaultSampler(self.dataset, seed=None)
+ self.assertEqual(sampler.seed, 7)
+
+ # test random seed
+ sampler = DefaultSampler(self.dataset, shuffle=True, seed=0)
+ sampler.set_epoch(10)
+ g = torch.Generator()
+ g.manual_seed(10)
+ self.assertEqual(
+ list(sampler),
+ torch.randperm(len(self.dataset), generator=g).tolist())
+
+ sampler = DefaultSampler(self.dataset, shuffle=True, seed=42)
+ sampler.set_epoch(10)
+ g = torch.Generator()
+ g.manual_seed(42 + 10)
+ self.assertEqual(
+ list(sampler),
+ torch.randperm(len(self.dataset), generator=g).tolist())
+
+
+class TestInfiniteSampler(TestCase):
+
+ def setUp(self):
+ self.data_length = 100
+ self.dataset = list(range(self.data_length))
+
+ @patch('mmengine.dataset.sampler.get_dist_info', return_value=(0, 1))
+ def test_non_dist(self, mock):
+ sampler = InfiniteSampler(self.dataset)
+ self.assertEqual(sampler.world_size, 1)
+ self.assertEqual(sampler.rank, 0)
+
+ # test iteration
+ sampler = InfiniteSampler(self.dataset, shuffle=False)
+ self.assertEqual(len(sampler), self.data_length)
+ self.assertEqual(sampler.size, self.data_length)
+ sampler_iter = iter(sampler)
+ items = [next(sampler_iter) for _ in range(self.data_length * 2)]
+ self.assertEqual(items, list(range(self.data_length)) * 2)
+
+ @patch('mmengine.dataset.sampler.get_dist_info', return_value=(2, 3))
+ def test_dist(self, mock):
+ sampler = InfiniteSampler(self.dataset)
+ self.assertEqual(sampler.world_size, 3)
+ self.assertEqual(sampler.rank, 2)
+
+ # test iteration
+ sampler = InfiniteSampler(self.dataset, shuffle=False)
+ self.assertEqual(len(sampler), self.data_length)
+ self.assertEqual(sampler.size, self.data_length)
+ targets = (list(range(self.data_length)) * 2)[2::3]
+ sampler_iter = iter(sampler)
+ samples = [next(sampler_iter) for _ in range(len(targets))]
+ print(samples)
+ self.assertEqual(samples, targets)
+
+ @patch('mmengine.dataset.sampler.get_dist_info', return_value=(0, 1))
+ @patch('mmengine.dataset.sampler.sync_random_seed', return_value=7)
+ def test_shuffle(self, mock1, mock2):
+ # test seed=None
+ sampler = InfiniteSampler(self.dataset, seed=None)
+ self.assertEqual(sampler.seed, 7)
+
+ # test the random seed
+ sampler = InfiniteSampler(self.dataset, shuffle=True, seed=42)
+
+ sampler_iter = iter(sampler)
+ samples = [next(sampler_iter) for _ in range(self.data_length)]
+
+ g = torch.Generator()
+ g.manual_seed(42)
+ self.assertEqual(
+ samples,
+ torch.randperm(self.data_length, generator=g).tolist())
+
+ def test_set_epoch(self):
+ sampler = InfiniteSampler(self.dataset)
+ sampler.set_epoch(10)
diff --git a/testbed/open-mmlab__mmengine/tests/test_device/test_device.py b/testbed/open-mmlab__mmengine/tests/test_device/test_device.py
new file mode 100644
index 0000000000000000000000000000000000000000..19bd1f7f196090fdac485c93ca9ab16b547f6da8
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_device/test_device.py
@@ -0,0 +1,17 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from mmengine.device import (get_device, is_cuda_available, is_mlu_available,
+ is_mps_available, is_npu_available)
+
+
+def test_get_device():
+ device = get_device()
+ if is_npu_available():
+ assert device == 'npu'
+ elif is_cuda_available():
+ assert device == 'cuda'
+ elif is_mlu_available():
+ assert device == 'mlu'
+ elif is_mps_available():
+ assert device == 'mps'
+ else:
+ assert device == 'cpu'
diff --git a/testbed/open-mmlab__mmengine/tests/test_dist/test_dist.py b/testbed/open-mmlab__mmengine/tests/test_dist/test_dist.py
new file mode 100644
index 0000000000000000000000000000000000000000..d89f5eb8789bfe485f8ed1059c1067f34afa987e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_dist/test_dist.py
@@ -0,0 +1,656 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import os.path as osp
+import tempfile
+import unittest
+from itertools import product
+from unittest import TestCase
+from unittest.mock import patch
+
+import torch
+import torch.distributed as torch_dist
+
+import mmengine.dist as dist
+from mmengine.dist.dist import sync_random_seed
+from mmengine.testing._internal import MultiProcessTestCase
+from mmengine.utils import digit_version
+from mmengine.utils.dl_utils import TORCH_VERSION
+
+
+class TestDist(TestCase):
+ """Test dist module in non-distributed environment."""
+
+ def test_all_reduce(self):
+ data = torch.arange(2, dtype=torch.int64)
+ expected = torch.arange(2, dtype=torch.int64)
+ dist.all_reduce(data)
+ self.assertTrue(torch.allclose(data, expected))
+
+ def test_all_gather(self):
+ data = torch.arange(2, dtype=torch.int64)
+ expected = torch.arange(2, dtype=torch.int64)
+ output = dist.all_gather(data)
+ self.assertTrue(torch.allclose(output[0], expected))
+
+ def test_gather(self):
+ data = torch.arange(2, dtype=torch.int64)
+ expected = torch.arange(2, dtype=torch.int64)
+ output = dist.gather(data)
+ self.assertTrue(torch.allclose(output[0], expected))
+
+ def test_broadcast(self):
+ data = torch.arange(2, dtype=torch.int64)
+ expected = torch.arange(2, dtype=torch.int64)
+ dist.broadcast(data)
+ self.assertTrue(torch.allclose(data, expected))
+
+ @patch('numpy.random.randint', return_value=10)
+ def test_sync_random_seed(self, mock):
+ self.assertEqual(sync_random_seed(), 10)
+
+ def test_broadcast_object_list(self):
+ with self.assertRaises(AssertionError):
+ # input should be list of object
+ dist.broadcast_object_list('foo')
+
+ data = ['foo', 12, {1: 2}]
+ expected = ['foo', 12, {1: 2}]
+ dist.broadcast_object_list(data)
+ self.assertEqual(data, expected)
+
+ def test_all_reduce_dict(self):
+ with self.assertRaises(AssertionError):
+ # input should be dict
+ dist.all_reduce_dict('foo')
+
+ data = {
+ 'key1': torch.arange(2, dtype=torch.int64),
+ 'key2': torch.arange(3, dtype=torch.int64)
+ }
+ expected = {
+ 'key1': torch.arange(2, dtype=torch.int64),
+ 'key2': torch.arange(3, dtype=torch.int64)
+ }
+ dist.all_reduce_dict(data)
+ for key in data:
+ self.assertTrue(torch.allclose(data[key], expected[key]))
+
+ def test_all_gather_object(self):
+ data = 'foo'
+ expected = 'foo'
+ gather_objects = dist.all_gather_object(data)
+ self.assertEqual(gather_objects[0], expected)
+
+ def test_gather_object(self):
+ data = 'foo'
+ expected = 'foo'
+ gather_objects = dist.gather_object(data)
+ self.assertEqual(gather_objects[0], expected)
+
+ def test_collect_results(self):
+ data = ['foo', {1: 2}]
+ size = 2
+ expected = ['foo', {1: 2}]
+
+ # test `device=cpu`
+ output = dist.collect_results(data, size, device='cpu')
+ self.assertEqual(output, expected)
+
+ # test `device=gpu`
+ output = dist.collect_results(data, size, device='gpu')
+ self.assertEqual(output, expected)
+
+ def test_all_reduce_params(self):
+ for tensor_type, reduce_op in zip([torch.int64, torch.float32],
+ ['sum', 'mean']):
+ data = [
+ torch.tensor([0, 1], dtype=tensor_type) for _ in range(100)
+ ]
+ data_gen = (item for item in data)
+ expected = [
+ torch.tensor([0, 1], dtype=tensor_type) for _ in range(100)
+ ]
+
+ dist.all_reduce_params(data_gen, op=reduce_op)
+
+ for item1, item2 in zip(data, expected):
+ self.assertTrue(torch.allclose(item1, item2))
+
+
+class TestDistWithGLOOBackend(MultiProcessTestCase):
+
+ def _init_dist_env(self, rank, world_size):
+ """Initialize the distributed environment."""
+ os.environ['MASTER_ADDR'] = '127.0.0.1'
+ os.environ['MASTER_PORT'] = '29505'
+ os.environ['RANK'] = str(rank)
+ torch_dist.init_process_group(
+ backend='gloo', rank=rank, world_size=world_size)
+
+ def setUp(self):
+ super().setUp()
+ self._spawn_processes()
+
+ def test_all_reduce(self):
+ self._init_dist_env(self.rank, self.world_size)
+ tensor_types = [torch.int64, torch.float32, torch.int64]
+ reduce_ops = ['sum', 'mean', 'mean']
+ for tensor_type, reduce_op in zip(tensor_types, reduce_ops):
+ if dist.get_rank() == 0:
+ data = torch.tensor([1, 2], dtype=tensor_type)
+ else:
+ data = torch.tensor([3, 4], dtype=tensor_type)
+
+ if reduce_op == 'sum':
+ expected = torch.tensor([4, 6], dtype=tensor_type)
+ else:
+ expected = torch.tensor([2, 3], dtype=tensor_type)
+
+ dist.all_reduce(data, reduce_op)
+ self.assertTrue(torch.allclose(data, expected))
+
+ def test_all_gather(self):
+ self._init_dist_env(self.rank, self.world_size)
+ if dist.get_rank() == 0:
+ data = torch.tensor([0, 1])
+ else:
+ data = torch.tensor([1, 2])
+
+ expected = [torch.tensor([0, 1]), torch.tensor([1, 2])]
+
+ output = dist.all_gather(data)
+ self.assertTrue(
+ torch.allclose(output[dist.get_rank()], expected[dist.get_rank()]))
+
+ def test_gather(self):
+ self._init_dist_env(self.rank, self.world_size)
+ if dist.get_rank() == 0:
+ data = torch.tensor([0, 1])
+ else:
+ data = torch.tensor([1, 2])
+
+ output = dist.gather(data)
+
+ if dist.get_rank() == 0:
+ expected = [torch.tensor([0, 1]), torch.tensor([1, 2])]
+ for i in range(2):
+ assert torch.allclose(output[i], expected[i])
+ else:
+ assert output == []
+
+ def test_broadcast_dist(self):
+ self._init_dist_env(self.rank, self.world_size)
+ if dist.get_rank() == 0:
+ data = torch.tensor([0, 1])
+ else:
+ data = torch.tensor([1, 2])
+
+ expected = torch.tensor([0, 1])
+ dist.broadcast(data, 0)
+ assert torch.allclose(data, expected)
+
+ def test_sync_random_seed(self):
+ self._init_dist_env(self.rank, self.world_size)
+ with patch.object(
+ torch, 'tensor',
+ return_value=torch.tensor(1024)) as mock_tensor:
+ output = dist.sync_random_seed()
+ assert output == 1024
+ mock_tensor.assert_called()
+
+ def test_broadcast_object_list(self):
+ self._init_dist_env(self.rank, self.world_size)
+ if dist.get_rank() == 0:
+ data = ['foo', 12, {1: 2}]
+ else:
+ data = [None, None, None]
+
+ expected = ['foo', 12, {1: 2}]
+ dist.broadcast_object_list(data)
+ self.assertEqual(data, expected)
+
+ def test_all_reduce_dict(self):
+ self._init_dist_env(self.rank, self.world_size)
+ for tensor_type, reduce_op in zip([torch.int64, torch.float32],
+ ['sum', 'mean']):
+ if dist.get_rank() == 0:
+ data = {
+ 'key1': torch.tensor([0, 1], dtype=tensor_type),
+ 'key2': torch.tensor([1, 2], dtype=tensor_type),
+ }
+ else:
+ data = {
+ 'key1': torch.tensor([2, 3], dtype=tensor_type),
+ 'key2': torch.tensor([3, 4], dtype=tensor_type),
+ }
+
+ if reduce_op == 'sum':
+ expected = {
+ 'key1': torch.tensor([2, 4], dtype=tensor_type),
+ 'key2': torch.tensor([4, 6], dtype=tensor_type),
+ }
+ else:
+ expected = {
+ 'key1': torch.tensor([1, 2], dtype=tensor_type),
+ 'key2': torch.tensor([2, 3], dtype=tensor_type),
+ }
+
+ dist.all_reduce_dict(data, reduce_op)
+
+ for key in data:
+ assert torch.allclose(data[key], expected[key])
+
+ # `torch.cat` in torch1.5 can not concatenate different types so we
+ # fallback to convert them all to float type.
+ if digit_version(TORCH_VERSION) == digit_version('1.5.0'):
+ if dist.get_rank() == 0:
+ data = {
+ 'key1': torch.tensor([0, 1], dtype=torch.float32),
+ 'key2': torch.tensor([1, 2], dtype=torch.int32)
+ }
+ else:
+ data = {
+ 'key1': torch.tensor([2, 3], dtype=torch.float32),
+ 'key2': torch.tensor([3, 4], dtype=torch.int32),
+ }
+
+ expected = {
+ 'key1': torch.tensor([2, 4], dtype=torch.float32),
+ 'key2': torch.tensor([4, 6], dtype=torch.float32),
+ }
+
+ dist.all_reduce_dict(data, 'sum')
+
+ for key in data:
+ assert torch.allclose(data[key], expected[key])
+
+ def test_all_gather_object(self):
+ self._init_dist_env(self.rank, self.world_size)
+
+ # data is a pickable python object
+ if dist.get_rank() == 0:
+ data = 'foo'
+ else:
+ data = {1: 2}
+
+ expected = ['foo', {1: 2}]
+ output = dist.all_gather_object(data)
+
+ self.assertEqual(output, expected)
+
+ # data is a list of pickable python object
+ if dist.get_rank() == 0:
+ data = ['foo', {1: 2}]
+ else:
+ data = {2: 3}
+
+ expected = [['foo', {1: 2}], {2: 3}]
+ output = dist.all_gather_object(data)
+
+ self.assertEqual(output, expected)
+
+ def test_gather_object(self):
+ self._init_dist_env(self.rank, self.world_size)
+
+ # data is a pickable python object
+ if dist.get_rank() == 0:
+ data = 'foo'
+ else:
+ data = {1: 2}
+
+ output = dist.gather_object(data, dst=0)
+
+ if dist.get_rank() == 0:
+ self.assertEqual(output, ['foo', {1: 2}])
+ else:
+ self.assertIsNone(output)
+
+ # data is a list of pickable python object
+ if dist.get_rank() == 0:
+ data = ['foo', {1: 2}]
+ else:
+ data = {2: 3}
+
+ output = dist.gather_object(data, dst=0)
+
+ if dist.get_rank() == 0:
+ self.assertEqual(output, [['foo', {1: 2}], {2: 3}])
+ else:
+ self.assertIsNone(output)
+
+ def test_all_reduce_params(self):
+ self._init_dist_env(self.rank, self.world_size)
+
+ tensor_types = [torch.int64, torch.float32]
+ reduce_ops = ['sum', 'mean']
+ coalesces = [True, False]
+ for tensor_type, reduce_op, coalesce in zip(tensor_types, reduce_ops,
+ coalesces):
+ if dist.get_rank() == 0:
+ data = [
+ torch.tensor([0, 1], dtype=tensor_type) for _ in range(100)
+ ]
+ else:
+ data = (
+ torch.tensor([2, 3], dtype=tensor_type)
+ for _ in range(100))
+
+ data_gen = (item for item in data)
+
+ if reduce_op == 'sum':
+ expected = (
+ torch.tensor([2, 4], dtype=tensor_type)
+ for _ in range(100))
+ else:
+ expected = (
+ torch.tensor([1, 2], dtype=tensor_type)
+ for _ in range(100))
+
+ dist.all_reduce_params(data_gen, coalesce=coalesce, op=reduce_op)
+
+ for item1, item2 in zip(data, expected):
+ self.assertTrue(torch.allclose(item1, item2))
+
+
+@unittest.skipIf(
+ torch.cuda.device_count() < 2, reason='need 2 gpu to test nccl')
+class TestDistWithNCCLBackend(MultiProcessTestCase):
+
+ def _init_dist_env(self, rank, world_size):
+ """Initialize the distributed environment."""
+ os.environ['MASTER_ADDR'] = '127.0.0.1'
+ os.environ['MASTER_PORT'] = '29505'
+ os.environ['RANK'] = str(rank)
+
+ num_gpus = torch.cuda.device_count()
+ torch.cuda.set_device(rank % num_gpus)
+ torch_dist.init_process_group(
+ backend='nccl', rank=rank, world_size=world_size)
+
+ def setUp(self):
+ super().setUp()
+ self._spawn_processes()
+
+ def test_all_reduce(self):
+ self._init_dist_env(self.rank, self.world_size)
+ tensor_types = [torch.int64, torch.float32]
+ reduce_ops = ['sum', 'mean']
+ device_types = ['cpu', 'cuda']
+ for tensor_type, reduce_op, device_type in product(
+ tensor_types, reduce_ops, device_types):
+ # 'mean' op does not support torch.int64
+ if tensor_type == torch.int64 and reduce_op == 'mean':
+ continue
+
+ if dist.get_rank() == 0:
+ data = torch.tensor([1, 2], dtype=tensor_type).to(device_type)
+ else:
+ data = torch.tensor([3, 4], dtype=tensor_type).to(device_type)
+
+ if reduce_op == 'sum':
+ expected = torch.tensor([4, 6],
+ dtype=tensor_type).to(device_type)
+ else:
+ expected = torch.tensor([2, 3],
+ dtype=tensor_type).to(device_type)
+
+ dist.all_reduce(data, reduce_op)
+ self.assertTrue(torch.allclose(data, expected))
+
+ def test_all_gather(self):
+ self._init_dist_env(self.rank, self.world_size)
+ for device_type in ('cpu', 'cuda'):
+ if dist.get_rank() == 0:
+ data = torch.tensor([0, 1]).to(device_type)
+ else:
+ data = torch.tensor([1, 2]).to(device_type)
+
+ expected = [
+ torch.tensor([0, 1]).to(device_type),
+ torch.tensor([1, 2]).to(device_type)
+ ]
+
+ output = dist.all_gather(data)
+ self.assertTrue(
+ torch.allclose(output[dist.get_rank()],
+ expected[dist.get_rank()]))
+
+ def test_broadcast_dist(self):
+ self._init_dist_env(self.rank, self.world_size)
+ for device_type in ('cpu', 'cuda'):
+ if dist.get_rank() == 0:
+ data = torch.tensor([0, 1]).to(device_type)
+ else:
+ data = torch.tensor([1, 2]).to(device_type)
+
+ expected = torch.tensor([0, 1]).to(device_type)
+ dist.broadcast(data, 0)
+ assert torch.allclose(data, expected)
+
+ def test_sync_random_seed(self):
+ self._init_dist_env(self.rank, self.world_size)
+ with patch.object(
+ torch, 'tensor',
+ return_value=torch.tensor(1024)) as mock_tensor:
+ output = dist.sync_random_seed()
+ assert output == 1024
+ mock_tensor.assert_called()
+
+ def test_broadcast_object_list(self):
+ self._init_dist_env(self.rank, self.world_size)
+ if dist.get_rank() == 0:
+ data = ['foo', 12, {1: 2}]
+ else:
+ data = [None, None, None]
+
+ expected = ['foo', 12, {1: 2}]
+ dist.broadcast_object_list(data)
+ self.assertEqual(data, expected)
+
+ def test_all_reduce_dict(self):
+ self._init_dist_env(self.rank, self.world_size)
+ tensor_types = [torch.int64, torch.float32]
+ reduce_ops = ['sum', 'mean']
+ device_types = ['cpu', 'cuda']
+ for tensor_type, reduce_op, device_type in product(
+ tensor_types, reduce_ops, device_types):
+ # 'mean' op does not support torch.int64
+ if tensor_type == torch.int64 and reduce_op == 'mean':
+ continue
+
+ if dist.get_rank() == 0:
+ data = {
+ 'key1':
+ torch.tensor([0, 1], dtype=tensor_type).to(device_type),
+ 'key2':
+ torch.tensor([1, 2], dtype=tensor_type).to(device_type),
+ }
+ else:
+ data = {
+ 'key1':
+ torch.tensor([2, 3], dtype=tensor_type).to(device_type),
+ 'key2':
+ torch.tensor([3, 4], dtype=tensor_type).to(device_type),
+ }
+
+ if reduce_op == 'sum':
+ expected = {
+ 'key1':
+ torch.tensor([2, 4], dtype=tensor_type).to(device_type),
+ 'key2':
+ torch.tensor([4, 6], dtype=tensor_type).to(device_type),
+ }
+ else:
+ expected = {
+ 'key1':
+ torch.tensor([1, 2], dtype=tensor_type).to(device_type),
+ 'key2':
+ torch.tensor([2, 3], dtype=tensor_type).to(device_type),
+ }
+
+ dist.all_reduce_dict(data, reduce_op)
+
+ for key in data:
+ assert torch.allclose(data[key], expected[key])
+
+ # `torch.cat` in torch1.5 can not concatenate different types so we
+ # fallback to convert them all to float type.
+ for device_type in ('cpu', 'cuda'):
+ if digit_version(TORCH_VERSION) == digit_version('1.5.0'):
+ if dist.get_rank() == 0:
+ data = {
+ 'key1':
+ torch.tensor([0, 1],
+ dtype=torch.float32).to(device_type),
+ 'key2':
+ torch.tensor([1, 2],
+ dtype=torch.int32).to(device_type),
+ }
+ else:
+ data = {
+ 'key1':
+ torch.tensor([2, 3],
+ dtype=torch.float32).to(device_type),
+ 'key2':
+ torch.tensor([3, 4],
+ dtype=torch.int32).to(device_type),
+ }
+
+ expected = {
+ 'key1':
+ torch.tensor([2, 4], dtype=torch.float32).to(device_type),
+ 'key2':
+ torch.tensor([4, 6], dtype=torch.float32).to(device_type),
+ }
+
+ dist.all_reduce_dict(data, 'sum')
+
+ for key in data:
+ assert torch.allclose(data[key], expected[key])
+
+ def test_all_gather_object(self):
+ self._init_dist_env(self.rank, self.world_size)
+
+ # data is a pickable python object
+ if dist.get_rank() == 0:
+ data = 'foo'
+ else:
+ data = {1: 2}
+
+ expected = ['foo', {1: 2}]
+ output = dist.all_gather_object(data)
+
+ self.assertEqual(output, expected)
+
+ # data is a list of pickable python object
+ if dist.get_rank() == 0:
+ data = ['foo', {1: 2}]
+ else:
+ data = {2: 3}
+
+ expected = [['foo', {1: 2}], {2: 3}]
+ output = dist.all_gather_object(data)
+
+ self.assertEqual(output, expected)
+
+ def test_collect_results(self):
+ self._init_dist_env(self.rank, self.world_size)
+
+ # 1. test `device` and `tmpdir` parameters
+ if dist.get_rank() == 0:
+ data = ['foo', {1: 2}]
+ else:
+ data = [24, {'a': 'b'}]
+
+ size = 4
+
+ expected = ['foo', 24, {1: 2}, {'a': 'b'}]
+
+ # 1.1 test `device=cpu` and `tmpdir` is None
+ output = dist.collect_results(data, size, device='cpu')
+ if dist.get_rank() == 0:
+ self.assertEqual(output, expected)
+ else:
+ self.assertIsNone(output)
+
+ # 1.2 test `device=cpu` and `tmpdir` is not None
+ tmpdir = tempfile.mkdtemp()
+ # broadcast tmpdir to all ranks to make it consistent
+ object_list = [tmpdir]
+ dist.broadcast_object_list(object_list)
+ output = dist.collect_results(
+ data, size, device='cpu', tmpdir=object_list[0])
+ if dist.get_rank() == 0:
+ self.assertEqual(output, expected)
+ else:
+ self.assertIsNone(output)
+
+ if dist.get_rank() == 0:
+ # object_list[0] will be removed by `dist.collect_results`
+ self.assertFalse(osp.exists(object_list[0]))
+
+ # 1.3 test `device=gpu`
+ output = dist.collect_results(data, size, device='gpu')
+ if dist.get_rank() == 0:
+ self.assertEqual(output, expected)
+ else:
+ self.assertIsNone(output)
+
+ # 2. test `size` parameter
+ if dist.get_rank() == 0:
+ data = ['foo', {1: 2}]
+ else:
+ data = [24, {'a': 'b'}]
+
+ size = 3
+
+ expected = ['foo', 24, {1: 2}]
+
+ # 2.1 test `device=cpu` and `tmpdir` is None
+ output = dist.collect_results(data, size, device='cpu')
+ if dist.get_rank() == 0:
+ self.assertEqual(output, expected)
+ else:
+ self.assertIsNone(output)
+
+ # 2.2 test `device=gpu`
+ output = dist.collect_results(data, size, device='gpu')
+ if dist.get_rank() == 0:
+ self.assertEqual(output, expected)
+ else:
+ self.assertIsNone(output)
+
+ def test_all_reduce_params(self):
+ self._init_dist_env(self.rank, self.world_size)
+
+ tensor_types = [torch.int64, torch.float32]
+ reduce_ops = ['sum', 'mean']
+ coalesces = [True, False]
+ device_types = ['cpu', 'cuda']
+ for tensor_type, reduce_op, coalesce, device_type in zip(
+ tensor_types, reduce_ops, coalesces, device_types):
+ if dist.get_rank() == 0:
+ data = [
+ torch.tensor([0, 1], dtype=tensor_type).to(device_type)
+ for _ in range(100)
+ ]
+ else:
+ data = [
+ torch.tensor([2, 3], dtype=tensor_type).to(device_type)
+ for _ in range(100)
+ ]
+
+ data_gen = (item for item in data)
+ dist.all_reduce_params(data_gen, coalesce=coalesce, op=reduce_op)
+
+ if reduce_op == 'sum':
+ expected = (
+ torch.tensor([2, 4], dtype=tensor_type).to(device_type)
+ for _ in range(100))
+ else:
+ expected = (
+ torch.tensor([1, 2], dtype=tensor_type).to(device_type)
+ for _ in range(100))
+
+ for item1, item2 in zip(data_gen, expected):
+ self.assertTrue(torch.allclose(item1, item2))
diff --git a/testbed/open-mmlab__mmengine/tests/test_dist/test_utils.py b/testbed/open-mmlab__mmengine/tests/test_dist/test_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d9af72f964a7b32cdcf373d731b88f721932820a
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_dist/test_utils.py
@@ -0,0 +1,608 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import unittest
+from unittest import TestCase
+
+import numpy as np
+import torch
+import torch.distributed as torch_dist
+
+import mmengine.dist as dist
+from mmengine.testing._internal import MultiProcessTestCase
+
+
+class TestUtils(TestCase):
+
+ def test_get_backend(self):
+ self.assertIsNone(dist.get_backend())
+
+ def test_get_world_size(self):
+ self.assertEqual(dist.get_world_size(), 1)
+
+ def test_get_rank(self):
+ self.assertEqual(dist.get_rank(), 0)
+
+ def test_local_size(self):
+ self.assertEqual(dist.get_local_size(), 1)
+
+ def test_local_rank(self):
+ self.assertEqual(dist.get_local_rank(), 0)
+
+ def test_get_dist_info(self):
+ self.assertEqual(dist.get_dist_info(), (0, 1))
+
+ def test_is_main_process(self):
+ self.assertTrue(dist.is_main_process())
+
+ def test_master_only(self):
+
+ @dist.master_only
+ def fun():
+ assert dist.get_rank() == 0
+
+ fun()
+
+ def test_barrier(self):
+ dist.barrier() # nothing is done
+
+ def test_get_data_device(self):
+ # data is a Tensor
+ data = torch.tensor([0, 1])
+ self.assertEqual(dist.get_data_device(data), torch.device('cpu'))
+
+ # data is a list of Tensor
+ data = [torch.tensor([0, 1]), torch.tensor([2, 3])]
+ self.assertEqual(dist.get_data_device(data), torch.device('cpu'))
+
+ # data is a list but not all items are Tensor
+ data = [torch.tensor([0, 1]), 123]
+ with self.assertRaises(TypeError):
+ dist.get_data_device(data)
+
+ # data is a list containing Tensor and a dict
+ data = [torch.tensor([0, 1]), {'key': torch.tensor([2, 3])}]
+ self.assertEqual(dist.get_data_device(data), torch.device('cpu'))
+
+ # data is a list containing Tensor and a dict but the dict contains
+ # invalid type
+ data = [torch.tensor([0, 1]), {'key': '123'}]
+ with self.assertRaises(TypeError):
+ dist.get_data_device(data)
+
+ # data is a empty list
+ with self.assertRaises(ValueError):
+ dist.get_data_device([])
+
+ # data is a dict
+ data = {'key1': torch.tensor([0, 1]), 'key2': torch.tensor([0, 1])}
+ self.assertEqual(dist.get_data_device(data), torch.device('cpu'))
+
+ # data is a dict but not all values are Tensor
+ data = {'key1': torch.tensor([0, 1]), 'key2': 123}
+ with self.assertRaises(TypeError):
+ dist.get_data_device(data)
+
+ # data is a dict and one of values is list of Tensor
+ data = {'key1': torch.tensor([0, 1]), 'key2': [torch.tensor([0, 1])]}
+ self.assertEqual(dist.get_data_device(data), torch.device('cpu'))
+
+ # data is a dict and one of values is an invalid type
+ data = {'key1': torch.tensor([0, 1]), 'key2': ['123']}
+ with self.assertRaises(TypeError):
+ dist.get_data_device(data)
+
+ # data is a empty dict
+ with self.assertRaises(ValueError):
+ dist.get_data_device({})
+
+ # data is not a valid type
+ with self.assertRaisesRegex(
+ TypeError,
+ 'data should be a Tensor, sequence of tensor or dict'):
+ dist.get_data_device('123')
+
+ @unittest.skipIf(
+ torch.cuda.device_count() == 0, reason='at lest need 1 gpu to test')
+ def test_cast_data_device(self):
+ expected_device = torch.device('cuda', torch.cuda.current_device())
+ # data is a Tensor
+ data = torch.tensor([0, 1])
+ output = dist.cast_data_device(data, expected_device)
+ self.assertEqual(output.device, expected_device)
+
+ # data is a Tensor and out is also a Tensor
+ data = torch.tensor([0, 1])
+ out = torch.tensor([1, 2])
+ output = dist.cast_data_device(data, expected_device, out=out)
+ self.assertEqual(output.device, expected_device)
+ self.assertTrue(torch.allclose(output.cpu(), out))
+
+ # data is a list of Tensor
+ data = [torch.tensor([0, 1]), torch.tensor([2, 3])]
+ for item in dist.cast_data_device(data, expected_device):
+ self.assertEqual(item.device, expected_device)
+
+ # both data and out are list of tensor
+ data = [torch.tensor([0, 1]), torch.tensor([2, 3])]
+ out = [torch.tensor([3, 4]), torch.tensor([5, 6])]
+ output = dist.cast_data_device(data, expected_device, out=out)
+ for item1, item2 in zip(output, out):
+ self.assertEqual(item1.device, expected_device)
+ self.assertTrue(torch.allclose(item1.cpu(), item2))
+
+ # data is a list containing a Tensor and a dict
+ data = [torch.tensor([0, 1]), {'key': torch.tensor([2, 3])}]
+ output = dist.cast_data_device(data, expected_device)
+ self.assertEqual(output[0].device, expected_device)
+ self.assertEqual(output[1]['key'].device, expected_device)
+
+ # data is a list containing a Tensor and a dict, so does out
+ data = [torch.tensor([0, 1]), {'key': torch.tensor([2, 3])}]
+ out = [torch.tensor([3, 4]), {'key': torch.tensor([5, 6])}]
+ output = dist.cast_data_device(data, expected_device, out=out)
+ self.assertEqual(output[0].device, expected_device)
+ self.assertTrue(torch.allclose(output[0].cpu(), out[0]))
+ self.assertEqual(output[1]['key'].device, expected_device)
+ self.assertTrue(torch.allclose(output[1]['key'].cpu(), out[1]['key']))
+
+ # data is an empty list
+ with self.assertRaisesRegex(ValueError, 'data should not be empty'):
+ dist.cast_data_device([], expected_device)
+
+ # data is a dict
+ data = {'key1': torch.tensor([0, 1]), 'key2': torch.tensor([2, 3])}
+ output = dist.cast_data_device(data, expected_device)
+ for k, v in output.items():
+ self.assertEqual(v.device, expected_device)
+
+ # data is a dict, so does out
+ data = {'key1': torch.tensor([0, 1]), 'key2': torch.tensor([2, 3])}
+ out = {'key1': torch.tensor([3, 4]), 'key2': torch.tensor([5, 6])}
+ output = dist.cast_data_device(data, expected_device, out=out)
+ for k, v in output.items():
+ self.assertEqual(v.device, expected_device)
+ self.assertTrue(torch.allclose(v.cpu(), out[k]))
+
+ # the length of data and out should be same
+ data = {'key1': torch.tensor([0, 1]), 'key2': torch.tensor([2, 3])}
+ out = {'key1': torch.tensor([3, 4])}
+ with self.assertRaisesRegex(ValueError,
+ 'length of data and out should be same'):
+ dist.cast_data_device(data, expected_device, out=out)
+
+ # data is an empty dict
+ with self.assertRaisesRegex(ValueError, 'data should not be empty'):
+ dist.cast_data_device({}, expected_device)
+
+ # data is a dict and one of values is list
+ data = {'key1': torch.tensor([0, 1]), 'key2': [torch.tensor([2, 3])]}
+ out = {'key1': torch.tensor([3, 4]), 'key2': [torch.tensor([5, 6])]}
+ output = dist.cast_data_device(data, expected_device, out=out)
+ self.assertEqual(output['key1'].device, expected_device)
+ self.assertTrue(torch.allclose(output['key1'].cpu(), out['key1']))
+ self.assertEqual(output['key2'][0].device, expected_device)
+ self.assertTrue(
+ torch.allclose(output['key2'][0].cpu(), out['key2'][0]))
+
+ # data is not a valid type
+ with self.assertRaisesRegex(
+ TypeError, 'data should be a Tensor, list of tensor or dict'):
+ dist.cast_data_device(123, expected_device)
+
+ with self.assertRaisesRegex(
+ TypeError, 'data should be a Tensor, list of tensor or dict'):
+ dist.cast_data_device('123', expected_device)
+
+ with self.assertRaisesRegex(
+ TypeError, 'data should be a Tensor, list of tensor or dict'):
+ dist.cast_data_device(np.array([0, 1]), expected_device)
+
+ # data and out are not the same type
+ data = torch.tensor([0, 1])
+ out = '123'
+ with self.assertRaisesRegex(TypeError,
+ 'out should be the same type with data'):
+ dist.cast_data_device(data, expected_device, out=out)
+
+ data = {0, 1}
+ out = {2, 3}
+ with self.assertRaisesRegex(TypeError, 'out should not be a set'):
+ dist.cast_data_device(data, expected_device, out=out)
+
+
+class TestUtilsWithGLOOBackend(MultiProcessTestCase):
+
+ def _init_dist_env(self, rank, world_size):
+ """Initialize the distributed environment."""
+ os.environ['MASTER_ADDR'] = '127.0.0.1'
+ os.environ['MASTER_PORT'] = '29505'
+ os.environ['RANK'] = str(rank)
+
+ torch_dist.init_process_group(
+ backend='gloo', rank=rank, world_size=world_size)
+ dist.init_local_group(0, world_size)
+
+ def setUp(self):
+ super().setUp()
+ self._spawn_processes()
+
+ def test_get_backend(self):
+ self._init_dist_env(self.rank, self.world_size)
+ self.assertEqual(dist.get_backend(), torch_dist.get_backend())
+
+ def test_get_world_size(self):
+ self._init_dist_env(self.rank, self.world_size)
+ self.assertEqual(dist.get_world_size(), 2)
+
+ def test_get_rank(self):
+ self._init_dist_env(self.rank, self.world_size)
+ if torch_dist.get_rank() == 0:
+ self.assertEqual(dist.get_rank(), 0)
+ else:
+ self.assertEqual(dist.get_rank(), 1)
+
+ def test_local_size(self):
+ self._init_dist_env(self.rank, self.world_size)
+ self.assertEqual(dist.get_local_size(), 2)
+
+ def test_local_rank(self):
+ self._init_dist_env(self.rank, self.world_size)
+ self.assertEqual(
+ torch_dist.get_rank(dist.get_local_group()), dist.get_local_rank())
+
+ def test_get_dist_info(self):
+ self._init_dist_env(self.rank, self.world_size)
+ if dist.get_rank() == 0:
+ self.assertEqual(dist.get_dist_info(), (0, 2))
+ else:
+ self.assertEqual(dist.get_dist_info(), (1, 2))
+
+ def test_is_main_process(self):
+ self._init_dist_env(self.rank, self.world_size)
+ if dist.get_rank() == 0:
+ self.assertTrue(dist.is_main_process())
+ else:
+ self.assertFalse(dist.is_main_process())
+
+ def test_master_only(self):
+ self._init_dist_env(self.rank, self.world_size)
+
+ @dist.master_only
+ def fun():
+ assert dist.get_rank() == 0
+
+ fun()
+
+ def test_get_data_device(self):
+ self._init_dist_env(self.rank, self.world_size)
+
+ # data is a Tensor
+ data = torch.tensor([0, 1])
+ self.assertEqual(dist.get_data_device(data), torch.device('cpu'))
+
+ # data is a list of Tensor
+ data = [torch.tensor([0, 1]), torch.tensor([2, 3])]
+ self.assertEqual(dist.get_data_device(data), torch.device('cpu'))
+
+ # data is a list but not all items are Tensor
+ data = [torch.tensor([0, 1]), 123]
+ with self.assertRaises(TypeError):
+ dist.get_data_device(data)
+
+ # data is a list containing Tensor and a dict
+ data = [torch.tensor([0, 1]), {'key': torch.tensor([2, 3])}]
+ self.assertEqual(dist.get_data_device(data), torch.device('cpu'))
+
+ # data is a list containing Tensor and a dict but the dict contains
+ # invalid type
+ data = [torch.tensor([0, 1]), {'key': '123'}]
+ with self.assertRaises(TypeError):
+ dist.get_data_device(data)
+
+ # data is a empty list
+ with self.assertRaises(ValueError):
+ dist.get_data_device([])
+
+ # data is a dict
+ data = {'key1': torch.tensor([0, 1]), 'key2': torch.tensor([0, 1])}
+ self.assertEqual(dist.get_data_device(data), torch.device('cpu'))
+
+ # data is a dict but not all values are Tensor
+ data = {'key1': torch.tensor([0, 1]), 'key2': 123}
+ with self.assertRaises(TypeError):
+ dist.get_data_device(data)
+
+ # data is a dict and one of values is list of Tensor
+ data = {'key1': torch.tensor([0, 1]), 'key2': [torch.tensor([0, 1])]}
+ self.assertEqual(dist.get_data_device(data), torch.device('cpu'))
+
+ # data is a dict and one of values is an invalid type
+ data = {'key1': torch.tensor([0, 1]), 'key2': ['123']}
+ with self.assertRaises(TypeError):
+ dist.get_data_device(data)
+
+ # data is a empty dict
+ with self.assertRaises(ValueError):
+ dist.get_data_device({})
+
+ # data is not a valid type
+ with self.assertRaisesRegex(
+ TypeError,
+ 'data should be a Tensor, sequence of tensor or dict'):
+ dist.get_data_device('123')
+
+ def test_get_comm_device(self):
+ self._init_dist_env(self.rank, self.world_size)
+ group = dist.get_default_group()
+ assert dist.get_comm_device(group) == torch.device('cpu')
+
+
+@unittest.skipIf(
+ torch.cuda.device_count() < 2, reason='need 2 gpu to test nccl')
+class TestUtilsWithNCCLBackend(MultiProcessTestCase):
+
+ def _init_dist_env(self, rank, world_size):
+ """Initialize the distributed environment."""
+ os.environ['MASTER_ADDR'] = '127.0.0.1'
+ os.environ['MASTER_PORT'] = '29505'
+ os.environ['RANK'] = str(rank)
+
+ num_gpus = torch.cuda.device_count()
+ torch.cuda.set_device(rank % num_gpus)
+ torch_dist.init_process_group(
+ backend='nccl', rank=rank, world_size=world_size)
+ dist.init_local_group(0, world_size)
+
+ def setUp(self):
+ super().setUp()
+ self._spawn_processes()
+
+ def test_get_backend(self):
+ self._init_dist_env(self.rank, self.world_size)
+ self.assertEqual(dist.get_backend(), torch_dist.get_backend())
+
+ def test_get_world_size(self):
+ self._init_dist_env(self.rank, self.world_size)
+ self.assertEqual(dist.get_world_size(), 2)
+
+ def test_get_rank(self):
+ self._init_dist_env(self.rank, self.world_size)
+ if torch_dist.get_rank() == 0:
+ self.assertEqual(dist.get_rank(), 0)
+ else:
+ self.assertEqual(dist.get_rank(), 1)
+
+ def test_local_size(self):
+ self._init_dist_env(self.rank, self.world_size)
+ self.assertEqual(dist.get_local_size(), 2)
+
+ def test_local_rank(self):
+ self._init_dist_env(self.rank, self.world_size)
+ self.assertEqual(
+ torch_dist.get_rank(dist.get_local_group()), dist.get_local_rank())
+
+ def test_get_dist_info(self):
+ self._init_dist_env(self.rank, self.world_size)
+ if dist.get_rank() == 0:
+ self.assertEqual(dist.get_dist_info(), (0, 2))
+ else:
+ self.assertEqual(dist.get_dist_info(), (1, 2))
+
+ def test_is_main_process(self):
+ self._init_dist_env(self.rank, self.world_size)
+ if dist.get_rank() == 0:
+ self.assertTrue(dist.is_main_process())
+ else:
+ self.assertFalse(dist.is_main_process())
+
+ def test_master_only(self):
+ self._init_dist_env(self.rank, self.world_size)
+
+ @dist.master_only
+ def fun():
+ assert dist.get_rank() == 0
+
+ fun()
+
+ def test_get_data_device(self):
+ self._init_dist_env(self.rank, self.world_size)
+
+ expected_device = torch.device('cuda', torch.cuda.current_device())
+
+ # data is a Tensor
+ data = torch.tensor([0, 1]).to(expected_device)
+ self.assertEqual(dist.get_data_device(data), expected_device)
+
+ # data is a list of Tensor
+ data = [
+ torch.tensor([0, 1]).to(expected_device),
+ torch.tensor([2, 3]).to(expected_device)
+ ]
+ self.assertEqual(dist.get_data_device(data), expected_device)
+
+ # data is a list but not all items are Tensor
+ data = [torch.tensor([0, 1]).to(expected_device), 123]
+ with self.assertRaises(TypeError):
+ dist.get_data_device(data)
+
+ # data is a list of Tensor but not all items have the same device type
+ data = [torch.tensor([0, 1]), torch.tensor([2, 3]).to(expected_device)]
+ with self.assertRaises(ValueError):
+ dist.get_data_device(data)
+
+ # data is a list containing Tensor and a dict
+ data = [
+ torch.tensor([0, 1]).to(expected_device), {
+ 'key': torch.tensor([2, 3]).to(expected_device)
+ }
+ ]
+ self.assertEqual(dist.get_data_device(data), expected_device)
+
+ # data is a list containing Tensor and a dict but the dict contains
+ # invalid type
+ data = [torch.tensor([0, 1]).to(expected_device), {'key': '123'}]
+ with self.assertRaises(TypeError):
+ dist.get_data_device(data)
+
+ # data is a empty list
+ with self.assertRaises(ValueError):
+ dist.get_data_device([])
+
+ # data is a dict
+ data = {
+ 'key1': torch.tensor([0, 1]).to(expected_device),
+ 'key2': torch.tensor([0, 1]).to(expected_device)
+ }
+ self.assertEqual(dist.get_data_device(data), expected_device)
+
+ # data is a dict but not all values are Tensor
+ data = {'key1': torch.tensor([0, 1]).to(expected_device), 'key2': 123}
+ with self.assertRaises(TypeError):
+ dist.get_data_device(data)
+
+ # data is a dict but not all values have the same device type
+ data = {
+ 'key1': torch.tensor([0, 1]),
+ 'key2': torch.tensor([0, 1]).to(expected_device)
+ }
+ with self.assertRaises(ValueError):
+ dist.get_data_device(data)
+
+ # data is a dict and one of values is list of Tensor
+ data = {
+ 'key1': torch.tensor([0, 1]).to(expected_device),
+ 'key2': [torch.tensor([0, 1]).to(expected_device)]
+ }
+ self.assertEqual(dist.get_data_device(data), expected_device)
+
+ # data is a dict and one of values is an invalid type
+ data = {
+ 'key1': torch.tensor([0, 1]).to(expected_device),
+ 'key2': ['123']
+ }
+ with self.assertRaises(TypeError):
+ dist.get_data_device(data)
+
+ # data is a empty dict
+ with self.assertRaises(ValueError):
+ dist.get_data_device({})
+
+ # data is not a valid type
+ with self.assertRaisesRegex(
+ TypeError,
+ 'data should be a Tensor, sequence of tensor or dict'):
+ dist.get_data_device('123')
+
+ def test_get_comm_device(self):
+ self._init_dist_env(self.rank, self.world_size)
+ group = dist.get_default_group()
+ expected = torch.device('cuda', torch.cuda.current_device())
+ self.assertEqual(dist.get_comm_device(group), expected)
+
+ def test_cast_data_device(self):
+ self._init_dist_env(self.rank, self.world_size)
+
+ expected_device = torch.device('cuda', torch.cuda.current_device())
+ # data is a Tensor
+ data = torch.tensor([0, 1])
+ output = dist.cast_data_device(data, expected_device)
+ self.assertEqual(output.device, expected_device)
+
+ # data is a Tensor and out is also a Tensor
+ data = torch.tensor([0, 1])
+ out = torch.tensor([1, 2])
+ output = dist.cast_data_device(data, expected_device, out=out)
+ self.assertEqual(output.device, expected_device)
+ self.assertTrue(torch.allclose(output.cpu(), out))
+
+ # data is a list of Tensor
+ data = [torch.tensor([0, 1]), torch.tensor([2, 3])]
+ for item in dist.cast_data_device(data, expected_device):
+ self.assertEqual(item.device, expected_device)
+
+ # both data and out are list of tensor
+ data = [torch.tensor([0, 1]), torch.tensor([2, 3])]
+ out = [torch.tensor([3, 4]), torch.tensor([5, 6])]
+ output = dist.cast_data_device(data, expected_device, out=out)
+ for item1, item2 in zip(output, out):
+ self.assertEqual(item1.device, expected_device)
+ self.assertTrue(torch.allclose(item1.cpu(), item2))
+
+ # data is a list containing a Tensor and a dict
+ data = [torch.tensor([0, 1]), {'key': torch.tensor([2, 3])}]
+ output = dist.cast_data_device(data, expected_device)
+ self.assertEqual(output[0].device, expected_device)
+ self.assertEqual(output[1]['key'].device, expected_device)
+
+ # data is a list containing a Tensor and a dict, so does out
+ data = [torch.tensor([0, 1]), {'key': torch.tensor([2, 3])}]
+ out = [torch.tensor([3, 4]), {'key': torch.tensor([5, 6])}]
+ output = dist.cast_data_device(data, expected_device, out=out)
+ self.assertEqual(output[0].device, expected_device)
+ self.assertTrue(torch.allclose(output[0].cpu(), out[0]))
+ self.assertEqual(output[1]['key'].device, expected_device)
+ self.assertTrue(torch.allclose(output[1]['key'].cpu(), out[1]['key']))
+
+ # data is an empty list
+ with self.assertRaisesRegex(ValueError, 'data should not be empty'):
+ dist.cast_data_device([], expected_device)
+
+ # data is a dict
+ data = {'key1': torch.tensor([0, 1]), 'key2': torch.tensor([2, 3])}
+ output = dist.cast_data_device(data, expected_device)
+ for k, v in output.items():
+ self.assertEqual(v.device, expected_device)
+
+ # data is a dict, so does out
+ data = {'key1': torch.tensor([0, 1]), 'key2': torch.tensor([2, 3])}
+ out = {'key1': torch.tensor([3, 4]), 'key2': torch.tensor([5, 6])}
+ output = dist.cast_data_device(data, expected_device, out=out)
+ for k, v in output.items():
+ self.assertEqual(v.device, expected_device)
+ self.assertTrue(torch.allclose(v.cpu(), out[k]))
+
+ # the length of data and out should be same
+ data = {'key1': torch.tensor([0, 1]), 'key2': torch.tensor([2, 3])}
+ out = {'key1': torch.tensor([3, 4])}
+ with self.assertRaisesRegex(ValueError,
+ 'length of data and out should be same'):
+ dist.cast_data_device(data, expected_device, out=out)
+
+ # data is an empty dict
+ with self.assertRaisesRegex(ValueError, 'data should not be empty'):
+ dist.cast_data_device({}, expected_device)
+
+ # data is a dict and one of values is list
+ data = {'key1': torch.tensor([0, 1]), 'key2': [torch.tensor([2, 3])]}
+ out = {'key1': torch.tensor([3, 4]), 'key2': [torch.tensor([5, 6])]}
+ output = dist.cast_data_device(data, expected_device, out=out)
+ self.assertEqual(output['key1'].device, expected_device)
+ self.assertTrue(torch.allclose(output['key1'].cpu(), out['key1']))
+ self.assertEqual(output['key2'][0].device, expected_device)
+ self.assertTrue(
+ torch.allclose(output['key2'][0].cpu(), out['key2'][0]))
+
+ # data is not a valid type
+ with self.assertRaisesRegex(
+ TypeError, 'data should be a Tensor, list of tensor or dict'):
+ dist.cast_data_device(123, expected_device)
+
+ with self.assertRaisesRegex(
+ TypeError, 'data should be a Tensor, list of tensor or dict'):
+ dist.cast_data_device('123', expected_device)
+
+ with self.assertRaisesRegex(
+ TypeError, 'data should be a Tensor, list of tensor or dict'):
+ dist.cast_data_device(np.array([0, 1]), expected_device)
+
+ # data and out are not the same type
+ data = torch.tensor([0, 1])
+ out = '123'
+ with self.assertRaisesRegex(TypeError,
+ 'out should be the same type with data'):
+ dist.cast_data_device(data, expected_device, out=out)
+
+ data = {0, 1}
+ out = {2, 3}
+ with self.assertRaisesRegex(TypeError, 'out should not be a set'):
+ dist.cast_data_device(data, expected_device, out=out)
diff --git a/testbed/open-mmlab__mmengine/tests/test_evaluator/test_evaluator.py b/testbed/open-mmlab__mmengine/tests/test_evaluator/test_evaluator.py
new file mode 100644
index 0000000000000000000000000000000000000000..29dc60cfdaa36c165fa6bcb797fedbf4ff42b615
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_evaluator/test_evaluator.py
@@ -0,0 +1,283 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import math
+import unittest
+from typing import Dict, List, Optional, Sequence
+from unittest import TestCase
+
+import numpy as np
+import torch
+
+from mmengine.evaluator import BaseMetric, Evaluator, get_metric_value
+from mmengine.registry import METRICS
+from mmengine.structures import BaseDataElement
+
+
+@METRICS.register_module()
+class ToyMetric(BaseMetric):
+ """Evaluaotr that calculates the metric `accuracy` from predictions and
+ labels. Alternatively, this evaluator can return arbitrary dummy metrics
+ set in the config.
+
+ Default prefix: Toy
+
+ Metrics:
+ - accuracy (float): The classification accuracy. Only when
+ `dummy_metrics` is None.
+ - size (int): The number of test samples. Only when `dummy_metrics`
+ is None.
+
+ If `dummy_metrics` is set as a dict in the config, it will be
+ returned as the metrics and override `accuracy` and `size`.
+ """
+
+ default_prefix = 'Toy'
+
+ def __init__(self,
+ collect_device: str = 'cpu',
+ prefix: Optional[str] = None,
+ dummy_metrics: Optional[Dict] = None):
+ super().__init__(collect_device=collect_device, prefix=prefix)
+ self.dummy_metrics = dummy_metrics
+
+ def process(self, data_batch, predictions):
+ results = [{
+ 'pred': prediction['label'],
+ 'label': prediction['label']
+ } for prediction in predictions]
+ self.results.extend(results)
+
+ def compute_metrics(self, results: List):
+ if self.dummy_metrics is not None:
+ assert isinstance(self.dummy_metrics, dict)
+ return self.dummy_metrics.copy()
+
+ pred = np.array([result['pred'] for result in results])
+ label = np.array([result['label'] for result in results])
+ acc = (pred == label).sum() / pred.size
+
+ metrics = {
+ 'accuracy': acc,
+ 'size': pred.size, # To check the number of testing samples
+ }
+
+ return metrics
+
+
+@METRICS.register_module()
+class NonPrefixedMetric(BaseMetric):
+ """Evaluator with unassigned `default_prefix` to test the warning
+ information."""
+
+ def process(self, data_batch, predictions: Sequence[dict]) -> None:
+ pass
+
+ def compute_metrics(self, results: list) -> dict:
+ return dict(dummy=0.0)
+
+
+def generate_test_results(size, batch_size, pred, label):
+ num_batch = math.ceil(size / batch_size)
+ bs_residual = size % batch_size
+ for i in range(num_batch):
+ bs = bs_residual if i == num_batch - 1 else batch_size
+ data_batch = {
+ 'inputs': [np.zeros((3, 10, 10)) for _ in range(bs)],
+ 'data_sample': [BaseDataElement(label=label) for _ in range(bs)]
+ }
+ predictions = [
+ BaseDataElement(pred=pred, label=label) for _ in range(bs)
+ ]
+ yield (data_batch, predictions)
+
+
+class TestEvaluator(TestCase):
+
+ def test_single_metric(self):
+ cfg = dict(type='ToyMetric')
+ evaluator = Evaluator(cfg)
+
+ size = 10
+ batch_size = 4
+
+ for data_samples, outputs in generate_test_results(
+ size, batch_size, pred=1, label=1):
+ evaluator.process(data_samples=outputs, data_batch=data_samples)
+
+ metrics = evaluator.evaluate(size=size)
+ self.assertAlmostEqual(metrics['Toy/accuracy'], 1.0)
+ self.assertEqual(metrics['Toy/size'], size)
+
+ # Test empty results
+ cfg = dict(type='ToyMetric', dummy_metrics=dict(accuracy=1.0))
+ evaluator = Evaluator(cfg)
+ with self.assertWarnsRegex(UserWarning, 'got empty `self.results`.'):
+ evaluator.evaluate(0)
+
+ def test_composed_metrics(self):
+ cfg = [
+ dict(type='ToyMetric'),
+ dict(type='ToyMetric', dummy_metrics=dict(mAP=0.0))
+ ]
+
+ evaluator = Evaluator(cfg)
+
+ size = 10
+ batch_size = 4
+
+ for data_samples, outputs in generate_test_results(
+ size, batch_size, pred=1, label=1):
+ evaluator.process(data_samples=outputs, data_batch=data_samples)
+
+ metrics = evaluator.evaluate(size=size)
+
+ self.assertAlmostEqual(metrics['Toy/accuracy'], 1.0)
+ self.assertAlmostEqual(metrics['Toy/mAP'], 0.0)
+ self.assertEqual(metrics['Toy/size'], size)
+
+ def test_ambiguous_metric(self):
+ cfg = [
+ dict(type='ToyMetric', dummy_metrics=dict(mAP=0.0)),
+ dict(type='ToyMetric', dummy_metrics=dict(mAP=0.0))
+ ]
+
+ evaluator = Evaluator(cfg)
+
+ size = 10
+ batch_size = 4
+
+ for data_samples, outputs in generate_test_results(
+ size, batch_size, pred=1, label=1):
+ evaluator.process(data_samples=outputs, data_batch=data_samples)
+
+ with self.assertRaisesRegex(
+ ValueError,
+ 'There are multiple evaluation results with the same metric '
+ 'name'):
+ _ = evaluator.evaluate(size=size)
+
+ def test_dataset_meta(self):
+ dataset_meta = dict(classes=('cat', 'dog'))
+
+ cfg = [
+ dict(type='ToyMetric'),
+ dict(type='ToyMetric', dummy_metrics=dict(mAP=0.0))
+ ]
+
+ evaluator = Evaluator(cfg)
+ evaluator.dataset_meta = dataset_meta
+
+ self.assertDictEqual(evaluator.dataset_meta, dataset_meta)
+ for _evaluator in evaluator.metrics:
+ self.assertDictEqual(_evaluator.dataset_meta, dataset_meta)
+
+ def test_collect_device(self):
+ cfg = [
+ dict(type='ToyMetric', collect_device='cpu'),
+ dict(
+ type='ToyMetric',
+ collect_device='gpu',
+ dummy_metrics=dict(mAP=0.0))
+ ]
+
+ evaluator = Evaluator(cfg)
+ self.assertEqual(evaluator.metrics[0].collect_device, 'cpu')
+ self.assertEqual(evaluator.metrics[1].collect_device, 'gpu')
+
+ def test_prefix(self):
+ cfg = dict(type='NonPrefixedMetric')
+ with self.assertWarnsRegex(UserWarning, 'The prefix is not set'):
+ _ = Evaluator(cfg)
+
+ def test_get_metric_value(self):
+
+ metrics = {
+ 'prefix_0/metric_0': 0,
+ 'prefix_1/metric_0': 1,
+ 'prefix_1/metric_1': 2,
+ 'nonprefixed': 3,
+ }
+
+ # Test indicator with prefix
+ indicator = 'prefix_0/metric_0' # correct indicator
+ self.assertEqual(get_metric_value(indicator, metrics), 0)
+
+ indicator = 'prefix_1/metric_0' # correct indicator
+ self.assertEqual(get_metric_value(indicator, metrics), 1)
+
+ indicator = 'prefix_0/metric_1' # unmatched indicator (wrong metric)
+ with self.assertRaisesRegex(ValueError, 'can not match any metric'):
+ _ = get_metric_value(indicator, metrics)
+
+ indicator = 'prefix_2/metric' # unmatched indicator (wrong prefix)
+ with self.assertRaisesRegex(ValueError, 'can not match any metric'):
+ _ = get_metric_value(indicator, metrics)
+
+ # Test indicator without prefix
+ indicator = 'metric_1' # correct indicator (prefixed metric)
+ self.assertEqual(get_metric_value(indicator, metrics), 2)
+
+ indicator = 'nonprefixed' # correct indicator (non-prefixed metric)
+ self.assertEqual(get_metric_value(indicator, metrics), 3)
+
+ indicator = 'metric_0' # ambiguous indicator
+ with self.assertRaisesRegex(ValueError, 'matches multiple metrics'):
+ _ = get_metric_value(indicator, metrics)
+
+ indicator = 'metric_2' # unmatched indicator
+ with self.assertRaisesRegex(ValueError, 'can not match any metric'):
+ _ = get_metric_value(indicator, metrics)
+
+ def test_offline_evaluate(self):
+ cfg = dict(type='ToyMetric')
+ evaluator = Evaluator(cfg)
+
+ size = 10
+
+ all_data = [dict() for _ in range(10)]
+ all_predictions = [
+ BaseDataElement(pred=0, label=1) for _ in range(size)
+ ]
+ evaluator.offline_evaluate(all_predictions, all_data)
+
+ # Test with None data
+ all_data = None
+ evaluator.offline_evaluate(all_predictions, all_data)
+
+ # Different length of data and predictions will raise an error.
+ all_data = [dict() for _ in range(9)]
+ with self.assertRaisesRegex(
+ AssertionError,
+ 'data_samples and data should have the same length'):
+ evaluator.offline_evaluate(all_predictions, all_data)
+
+ @unittest.skipUnless(torch.cuda.is_available(), 'can only run with gpu')
+ def test_evaluate_cast_cpu(self):
+ cfg = dict(type='ToyMetric')
+ evaluator = Evaluator(cfg)
+
+ size = 10
+
+ all_data = [
+ dict(
+ inputs=torch.zeros((3, 10, 10), device='cuda'),
+ data_sample=BaseDataElement(
+ label=torch.ones((1, ), device='cuda')))
+ for _ in range(size)
+ ]
+ all_predictions = [
+ BaseDataElement(
+ pred=torch.zeros((1, ), device='cuda'),
+ label=torch.ones((1, ), device='cuda')) for _ in range(size)
+ ]
+ for data, pred in zip(all_data, all_predictions):
+ evaluator.process([pred], [data])
+
+ def test_results_device(results: List):
+ for result in results:
+ self.assertEqual(result['pred'].device, torch.device('cpu'))
+ self.assertEqual(result['label'].device, torch.device('cpu'))
+ return {}
+
+ # replace the `compute_metrics` to the test function
+ evaluator.metrics[0].compute_metrics = test_results_device
+ evaluator.evaluate(size)
diff --git a/testbed/open-mmlab__mmengine/tests/test_evaluator/test_metric.py b/testbed/open-mmlab__mmengine/tests/test_evaluator/test_metric.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb7a181d3bd92d45576c30794ca6a0117794a455
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_evaluator/test_metric.py
@@ -0,0 +1,41 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os.path as osp
+import tempfile
+from unittest import TestCase
+
+import torch
+from torch import Tensor
+
+from mmengine.evaluator import DumpResults
+from mmengine.fileio import load
+
+
+class TestDumpResults(TestCase):
+
+ def test_init(self):
+ with self.assertRaisesRegex(ValueError,
+ 'The output file must be a pkl file.'):
+ DumpResults(out_file_path='./results.json')
+
+ def test_process(self):
+ metric = DumpResults(out_file_path='./results.pkl')
+ data_samples = [dict(data=(Tensor([1, 2, 3]), Tensor([4, 5, 6])))]
+ metric.process(None, data_samples)
+ self.assertEqual(len(metric.results), 1)
+ self.assertEqual(metric.results[0]['data'][0].device,
+ torch.device('cpu'))
+
+ def test_compute_metrics(self):
+ temp_dir = tempfile.TemporaryDirectory()
+ path = osp.join(temp_dir.name, 'results.pkl')
+ metric = DumpResults(out_file_path=path)
+ data_samples = [dict(data=(Tensor([1, 2, 3]), Tensor([4, 5, 6])))]
+ metric.process(None, data_samples)
+ metric.compute_metrics(metric.results)
+ self.assertTrue(osp.isfile(path))
+
+ results = load(path)
+ self.assertEqual(len(results), 1)
+ self.assertEqual(results[0]['data'][0].device, torch.device('cpu'))
+
+ temp_dir.cleanup()
diff --git a/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_backend_utils.py b/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_backend_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..7903f5574edd990d4c8ff7593f4336c79475f936
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_backend_utils.py
@@ -0,0 +1,114 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import pytest
+
+from mmengine.fileio.backends import (BaseStorageBackend, backends,
+ prefix_to_backends, register_backend)
+
+
+def test_register_backend():
+ # 1. two ways to register backend
+ # 1.1 use it as a decorator
+ @register_backend('example')
+ class ExampleBackend(BaseStorageBackend):
+
+ def get(self, filepath):
+ return filepath
+
+ def get_text(self, filepath):
+ return filepath
+
+ assert 'example' in backends
+
+ # 1.2 use it as a normal function
+ class ExampleBackend1(BaseStorageBackend):
+
+ def get(self, filepath):
+ return filepath
+
+ def get_text(self, filepath):
+ return filepath
+
+ register_backend('example1', ExampleBackend1)
+ assert 'example1' in backends
+
+ # 2. test `name` parameter
+ # 2. name should a string
+ with pytest.raises(TypeError, match='name should be a string'):
+ register_backend(1, ExampleBackend)
+
+ register_backend('example2', ExampleBackend)
+ assert 'example2' in backends
+
+ # 3. test `backend` parameter
+ # If backend is not None, it should be a class and a subclass of
+ # BaseStorageBackend.
+ with pytest.raises(TypeError, match='backend should be a class'):
+
+ def test_backend():
+ pass
+
+ register_backend('example3', test_backend)
+
+ class ExampleBackend2:
+
+ def get(self, filepath):
+ return filepath
+
+ def get_text(self, filepath):
+ return filepath
+
+ with pytest.raises(
+ TypeError, match='not a subclass of BaseStorageBackend'):
+ register_backend('example3', ExampleBackend2)
+
+ # 4. test `force` parameter
+ # 4.1 force=False
+ with pytest.raises(ValueError, match='example is already registered'):
+ register_backend('example', ExampleBackend)
+
+ # 4.2 force=True
+ register_backend('example', ExampleBackend, force=True)
+ assert 'example' in backends
+
+ # 5. test `prefixes` parameter
+ class ExampleBackend3(BaseStorageBackend):
+
+ def get(self, filepath):
+ return filepath
+
+ def get_text(self, filepath):
+ return filepath
+
+ # 5.1 prefixes is a string
+ register_backend('example3', ExampleBackend3, prefixes='prefix1')
+ assert 'example3' in backends
+ assert 'prefix1' in prefix_to_backends
+
+ # 5.2 prefixes is a list (tuple) of strings
+ register_backend(
+ 'example4', ExampleBackend3, prefixes=['prefix2', 'prefix3'])
+ assert 'example4' in backends
+ assert 'prefix2' in prefix_to_backends
+ assert 'prefix3' in prefix_to_backends
+ assert prefix_to_backends['prefix2'] == prefix_to_backends['prefix3']
+
+ # 5.3 prefixes is an invalid type
+ with pytest.raises(AssertionError):
+ register_backend('example5', ExampleBackend3, prefixes=1)
+
+ # 5.4 prefixes is already registered
+ with pytest.raises(ValueError, match='prefix2 is already registered'):
+ register_backend('example6', ExampleBackend3, prefixes='prefix2')
+
+ class ExampleBackend4(BaseStorageBackend):
+
+ def get(self, filepath):
+ return filepath
+
+ def get_text(self, filepath):
+ return filepath
+
+ register_backend(
+ 'example6', ExampleBackend4, prefixes='prefix2', force=True)
+ assert 'example6' in backends
+ assert 'prefix2' in prefix_to_backends
diff --git a/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_base_storage_backend.py b/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_base_storage_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..6aa608851dc57bb3cb969a6625a79c1d91c8f0a7
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_base_storage_backend.py
@@ -0,0 +1,27 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import pytest
+
+from mmengine.fileio.backends import BaseStorageBackend
+
+
+def test_base_storage_backend():
+ # test inheritance
+ class ExampleBackend(BaseStorageBackend):
+ pass
+
+ with pytest.raises(
+ TypeError,
+ match="Can't instantiate abstract class ExampleBackend"):
+ ExampleBackend()
+
+ class ExampleBackend(BaseStorageBackend):
+
+ def get(self, filepath):
+ return filepath
+
+ def get_text(self, filepath):
+ return filepath
+
+ backend = ExampleBackend()
+ assert backend.get('test') == 'test'
+ assert backend.get_text('test') == 'test'
diff --git a/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_http_backend.py b/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_http_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..c69394d147352d87302dec29059492fe9b840ac3
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_http_backend.py
@@ -0,0 +1,51 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from pathlib import Path
+from unittest import TestCase
+
+import cv2
+import numpy as np
+
+from mmengine.fileio.backends import HTTPBackend
+
+
+def imfrombytes(content):
+ img_np = np.frombuffer(content, np.uint8)
+ img = cv2.imdecode(img_np, cv2.IMREAD_COLOR)
+ return img
+
+
+def imread(path):
+ with open(path, 'rb') as f:
+ content = f.read()
+ img = imfrombytes(content)
+ return img
+
+
+class TestHTTPBackend(TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ cls.img_url = (
+ 'https://download.openmmlab.com/mmengine/test-data/color.jpg')
+ cls.img_shape = (300, 400, 3)
+ cls.text_url = (
+ 'https://download.openmmlab.com/mmengine/test-data/filelist.txt')
+ cls.test_data_dir = Path(__file__).parent.parent.parent / 'data'
+ cls.text_path = cls.test_data_dir / 'filelist.txt'
+
+ def test_get(self):
+ backend = HTTPBackend()
+ img_bytes = backend.get(self.img_url)
+ img = imfrombytes(img_bytes)
+ self.assertEqual(img.shape, self.img_shape)
+
+ def test_get_text(self):
+ backend = HTTPBackend()
+ text = backend.get_text(self.text_url)
+ self.assertEqual(self.text_path.open('r').read(), text)
+
+ def test_get_local_path(self):
+ backend = HTTPBackend()
+ with backend.get_local_path(self.img_url) as filepath:
+ img = imread(filepath)
+ self.assertEqual(img.shape, self.img_shape)
diff --git a/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_lmdb_backend.py b/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_lmdb_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc2c7ded2b08ef5b6351ff661a83a283742d247d
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_lmdb_backend.py
@@ -0,0 +1,35 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from pathlib import Path
+from unittest import TestCase
+
+import cv2
+import numpy as np
+from parameterized import parameterized
+
+from mmengine.fileio.backends import LmdbBackend
+
+
+def imfrombytes(content):
+ img_np = np.frombuffer(content, np.uint8)
+ img = cv2.imdecode(img_np, cv2.IMREAD_COLOR)
+ return img
+
+
+class TestLmdbBackend(TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ cls.test_data_dir = Path(__file__).parent.parent.parent / 'data'
+ cls.lmdb_path = cls.test_data_dir / 'demo.lmdb'
+
+ @parameterized.expand([[Path], [str]])
+ def test_get(self, path_type):
+ backend = LmdbBackend(path_type(self.lmdb_path))
+ img_bytes = backend.get('baboon')
+ img = imfrombytes(img_bytes)
+ self.assertEqual(img.shape, (120, 125, 3))
+
+ def test_get_text(self):
+ backend = LmdbBackend(self.lmdb_path)
+ with self.assertRaises(NotImplementedError):
+ backend.get_text('filepath')
diff --git a/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_local_backend.py b/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_local_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..427ebf789aad3f8fc348c293be52155f6a69c79c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_local_backend.py
@@ -0,0 +1,486 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import os.path as osp
+import platform
+import tempfile
+from contextlib import contextmanager
+from pathlib import Path
+from shutil import SameFileError
+from unittest import TestCase
+from unittest.mock import patch
+
+import cv2
+import numpy as np
+from parameterized import parameterized
+
+from mmengine.fileio.backends import LocalBackend
+
+
+def imfrombytes(content):
+ img_np = np.frombuffer(content, np.uint8)
+ img = cv2.imdecode(img_np, cv2.IMREAD_COLOR)
+ return img
+
+
+@contextmanager
+def build_temporary_directory():
+ """Build a temporary directory containing many files to test
+ ``FileClient.list_dir_or_file``.
+
+ . \n
+ | -- dir1 \n
+ | -- | -- text3.txt \n
+ | -- dir2 \n
+ | -- | -- dir3 \n
+ | -- | -- | -- text4.txt \n
+ | -- | -- img.jpg \n
+ | -- text1.txt \n
+ | -- text2.txt \n
+ """
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ text1 = Path(tmp_dir) / 'text1.txt'
+ text1.open('w').write('text1')
+ text2 = Path(tmp_dir) / 'text2.txt'
+ text2.open('w').write('text2')
+ dir1 = Path(tmp_dir) / 'dir1'
+ dir1.mkdir()
+ text3 = dir1 / 'text3.txt'
+ text3.open('w').write('text3')
+ dir2 = Path(tmp_dir) / 'dir2'
+ dir2.mkdir()
+ jpg1 = dir2 / 'img.jpg'
+ jpg1.open('wb').write(b'img')
+ dir3 = dir2 / 'dir3'
+ dir3.mkdir()
+ text4 = dir3 / 'text4.txt'
+ text4.open('w').write('text4')
+ yield tmp_dir
+
+
+class TestLocalBackend(TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ cls.test_data_dir = Path(__file__).parent.parent.parent / 'data'
+ cls.img_path = cls.test_data_dir / 'color.jpg'
+ cls.img_shape = (300, 400, 3)
+ cls.text_path = cls.test_data_dir / 'filelist.txt'
+
+ def test_name(self):
+ backend = LocalBackend()
+ self.assertEqual(backend.name, 'LocalBackend')
+
+ @parameterized.expand([[Path], [str]])
+ def test_get(self, path_type):
+ backend = LocalBackend()
+ img_bytes = backend.get(path_type(self.img_path))
+ self.assertEqual(self.img_path.open('rb').read(), img_bytes)
+ img = imfrombytes(img_bytes)
+ self.assertEqual(img.shape, self.img_shape)
+
+ @parameterized.expand([[Path], [str]])
+ def test_get_text(self, path_type):
+ backend = LocalBackend()
+ text = backend.get_text(path_type(self.text_path))
+ self.assertEqual(self.text_path.open('r').read(), text)
+
+ @parameterized.expand([[Path], [str]])
+ def test_put(self, path_type):
+ backend = LocalBackend()
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ filepath = Path(tmp_dir) / 'test.jpg'
+ backend.put(b'disk', path_type(filepath))
+ self.assertEqual(backend.get(filepath), b'disk')
+
+ # If the directory does not exist, put will create a
+ # directory first
+ filepath = Path(tmp_dir) / 'not_existed_dir' / 'test.jpg'
+ backend.put(b'disk', path_type(filepath))
+ self.assertEqual(backend.get(filepath), b'disk')
+
+ @parameterized.expand([[Path], [str]])
+ def test_put_text(self, path_type):
+ backend = LocalBackend()
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ filepath = Path(tmp_dir) / 'test.txt'
+ backend.put_text('disk', path_type(filepath))
+ self.assertEqual(backend.get_text(filepath), 'disk')
+
+ # If the directory does not exist, put_text will create a
+ # directory first
+ filepath = Path(tmp_dir) / 'not_existed_dir' / 'test.txt'
+ backend.put_text('disk', path_type(filepath))
+ self.assertEqual(backend.get_text(filepath), 'disk')
+
+ @parameterized.expand([[Path], [str]])
+ def test_exists(self, path_type):
+ backend = LocalBackend()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ self.assertTrue(backend.exists(path_type(tmp_dir)))
+ filepath = Path(tmp_dir) / 'test.txt'
+ self.assertFalse(backend.exists(path_type(filepath)))
+ backend.put_text('disk', filepath)
+ self.assertTrue(backend.exists(path_type(filepath)))
+ backend.remove(filepath)
+
+ @parameterized.expand([[Path], [str]])
+ def test_isdir(self, path_type):
+ backend = LocalBackend()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ self.assertTrue(backend.isdir(path_type(tmp_dir)))
+ filepath = Path(tmp_dir) / 'test.txt'
+ backend.put_text('disk', filepath)
+ self.assertFalse(backend.isdir(path_type(filepath)))
+
+ @parameterized.expand([[Path], [str]])
+ def test_isfile(self, path_type):
+ backend = LocalBackend()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ self.assertFalse(backend.isfile(path_type(tmp_dir)))
+ filepath = Path(tmp_dir) / 'test.txt'
+ backend.put_text('disk', filepath)
+ self.assertTrue(backend.isfile(path_type(filepath)))
+
+ @parameterized.expand([[Path], [str]])
+ def test_join_path(self, path_type):
+ backend = LocalBackend()
+ filepath = backend.join_path(
+ path_type(self.test_data_dir), path_type('file'))
+ expected = osp.join(path_type(self.test_data_dir), path_type('file'))
+ self.assertEqual(filepath, expected)
+
+ filepath = backend.join_path(
+ path_type(self.test_data_dir), path_type('dir'), path_type('file'))
+ expected = osp.join(
+ path_type(self.test_data_dir), path_type('dir'), path_type('file'))
+ self.assertEqual(filepath, expected)
+
+ @parameterized.expand([[Path], [str]])
+ def test_get_local_path(self, path_type):
+ backend = LocalBackend()
+ with backend.get_local_path(path_type(self.text_path)) as filepath:
+ self.assertEqual(path_type(self.text_path), path_type(filepath))
+
+ @parameterized.expand([[Path], [str]])
+ def test_copyfile(self, path_type):
+ backend = LocalBackend()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ src = Path(tmp_dir) / 'test.txt'
+ backend.put_text('disk', src)
+ dst = Path(tmp_dir) / 'test.txt.bak'
+ self.assertEqual(
+ backend.copyfile(path_type(src), path_type(dst)),
+ path_type(dst))
+ self.assertEqual(backend.get_text(dst), 'disk')
+
+ # dst is a directory
+ dst = Path(tmp_dir) / 'dir'
+ dst.mkdir()
+ self.assertEqual(
+ backend.copyfile(path_type(src), path_type(dst)),
+ backend.join_path(path_type(dst), 'test.txt'))
+ self.assertEqual(
+ backend.get_text(backend.join_path(dst, 'test.txt')), 'disk')
+
+ # src and src should not be same file
+ with self.assertRaises(SameFileError):
+ backend.copyfile(path_type(src), path_type(src))
+
+ @parameterized.expand([[Path], [str]])
+ def test_copytree(self, path_type):
+ backend = LocalBackend()
+ with build_temporary_directory() as tmp_dir:
+ # src and dst are Path objects
+ src = Path(tmp_dir) / 'dir1'
+ dst = Path(tmp_dir) / 'dir100'
+ self.assertEqual(
+ backend.copytree(path_type(src), path_type(dst)),
+ path_type(dst))
+ self.assertTrue(backend.isdir(dst))
+ self.assertTrue(backend.isfile(dst / 'text3.txt'))
+ self.assertEqual(backend.get_text(dst / 'text3.txt'), 'text3')
+
+ # dst should not exist
+ with self.assertRaises(FileExistsError):
+ backend.copytree(
+ path_type(src), path_type(Path(tmp_dir) / 'dir2'))
+
+ @parameterized.expand([[Path], [str]])
+ def test_copyfile_from_local(self, path_type):
+ backend = LocalBackend()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ src = Path(tmp_dir) / 'test.txt'
+ backend.put_text('disk', src)
+ dst = Path(tmp_dir) / 'test.txt.bak'
+ self.assertEqual(
+ backend.copyfile(path_type(src), path_type(dst)),
+ path_type(dst))
+ self.assertEqual(backend.get_text(dst), 'disk')
+
+ dst = Path(tmp_dir) / 'dir'
+ dst.mkdir()
+ self.assertEqual(
+ backend.copyfile(path_type(src), path_type(dst)),
+ backend.join_path(path_type(dst), 'test.txt'))
+ self.assertEqual(
+ backend.get_text(backend.join_path(dst, 'test.txt')), 'disk')
+
+ # src and src should not be same file
+ with self.assertRaises(SameFileError):
+ backend.copyfile(path_type(src), path_type(src))
+
+ @parameterized.expand([[Path], [str]])
+ def test_copytree_from_local(self, path_type):
+ backend = LocalBackend()
+ with build_temporary_directory() as tmp_dir:
+ # src and dst are Path objects
+ src = Path(tmp_dir) / 'dir1'
+ dst = Path(tmp_dir) / 'dir100'
+ self.assertEqual(
+ backend.copytree(path_type(src), path_type(dst)),
+ path_type(dst))
+ self.assertTrue(backend.isdir(dst))
+ self.assertTrue(backend.isfile(dst / 'text3.txt'))
+ self.assertEqual(backend.get_text(dst / 'text3.txt'), 'text3')
+
+ # dst should not exist
+ with self.assertRaises(FileExistsError):
+ backend.copytree(
+ path_type(src), path_type(Path(tmp_dir) / 'dir2'))
+
+ @parameterized.expand([[Path], [str]])
+ def test_copyfile_to_local(self, path_type):
+ backend = LocalBackend()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ src = Path(tmp_dir) / 'test.txt'
+ backend.put_text('disk', src)
+ dst = Path(tmp_dir) / 'test.txt.bak'
+ self.assertEqual(
+ backend.copyfile(path_type(src), path_type(dst)),
+ path_type(dst))
+ self.assertEqual(backend.get_text(dst), 'disk')
+
+ dst = Path(tmp_dir) / 'dir'
+ dst.mkdir()
+ self.assertEqual(
+ backend.copyfile(path_type(src), path_type(dst)),
+ backend.join_path(path_type(dst), 'test.txt'))
+ self.assertEqual(
+ backend.get_text(backend.join_path(dst, 'test.txt')), 'disk')
+
+ # src and src should not be same file
+ with self.assertRaises(SameFileError):
+ backend.copyfile(path_type(src), path_type(src))
+
+ @parameterized.expand([[Path], [str]])
+ def test_copytree_to_local(self, path_type):
+ backend = LocalBackend()
+ with build_temporary_directory() as tmp_dir:
+ # src and dst are Path objects
+ src = Path(tmp_dir) / 'dir1'
+ dst = Path(tmp_dir) / 'dir100'
+ self.assertEqual(
+ backend.copytree(path_type(src), path_type(dst)),
+ path_type(dst))
+ self.assertTrue(backend.isdir(dst))
+ self.assertTrue(backend.isfile(dst / 'text3.txt'))
+ self.assertEqual(backend.get_text(dst / 'text3.txt'), 'text3')
+
+ # dst should not exist
+ with self.assertRaises(FileExistsError):
+ backend.copytree(
+ path_type(src), path_type(Path(tmp_dir) / 'dir2'))
+
+ @parameterized.expand([[Path], [str]])
+ def test_remove(self, path_type):
+ backend = LocalBackend()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ # filepath is a Path object
+ filepath = Path(tmp_dir) / 'test.txt'
+ backend.put_text('disk', filepath)
+ self.assertTrue(backend.exists(filepath))
+ backend.remove(path_type(filepath))
+ self.assertFalse(backend.exists(filepath))
+
+ # raise error if file does not exist
+ with self.assertRaises(FileNotFoundError):
+ filepath = Path(tmp_dir) / 'test1.txt'
+ backend.remove(path_type(filepath))
+
+ # can not remove directory
+ filepath = Path(tmp_dir) / 'dir'
+ filepath.mkdir()
+ with self.assertRaises(IsADirectoryError):
+ backend.remove(path_type(filepath))
+
+ @parameterized.expand([[Path], [str]])
+ def test_rmtree(self, path_type):
+ backend = LocalBackend()
+ with build_temporary_directory() as tmp_dir:
+ # src and dst are Path objects
+ dir_path = Path(tmp_dir) / 'dir1'
+ self.assertTrue(backend.exists(dir_path))
+ backend.rmtree(path_type(dir_path))
+ self.assertFalse(backend.exists(dir_path))
+
+ dir_path = Path(tmp_dir) / 'dir2'
+ self.assertTrue(backend.exists(dir_path))
+ backend.rmtree(path_type(dir_path))
+ self.assertFalse(backend.exists(dir_path))
+
+ @parameterized.expand([[Path], [str]])
+ def test_copy_if_symlink_fails(self, path_type):
+ backend = LocalBackend()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ # create a symlink for a file
+ src = Path(tmp_dir) / 'test.txt'
+ backend.put_text('disk', src)
+ dst = Path(tmp_dir) / 'test_link.txt'
+ res = backend.copy_if_symlink_fails(path_type(src), path_type(dst))
+ if platform.system() == 'Linux':
+ self.assertTrue(res)
+ self.assertTrue(osp.islink(dst))
+ self.assertEqual(backend.get_text(dst), 'disk')
+
+ # create a symlink for a directory
+ src = Path(tmp_dir) / 'dir'
+ src.mkdir()
+ dst = Path(tmp_dir) / 'dir_link'
+ res = backend.copy_if_symlink_fails(path_type(src), path_type(dst))
+ if platform.system() == 'Linux':
+ self.assertTrue(res)
+ self.assertTrue(osp.islink(dst))
+ self.assertTrue(backend.exists(dst))
+
+ def symlink(src, dst):
+ raise Exception
+
+ # copy files if symblink fails
+ with patch.object(os, 'symlink', side_effect=symlink):
+ src = Path(tmp_dir) / 'test.txt'
+ dst = Path(tmp_dir) / 'test_link1.txt'
+ res = backend.copy_if_symlink_fails(
+ path_type(src), path_type(dst))
+ self.assertFalse(res)
+ self.assertFalse(osp.islink(dst))
+ self.assertTrue(backend.exists(dst))
+
+ # copy directory if symblink fails
+ with patch.object(os, 'symlink', side_effect=symlink):
+ src = Path(tmp_dir) / 'dir'
+ dst = Path(tmp_dir) / 'dir_link1'
+ res = backend.copy_if_symlink_fails(
+ path_type(src), path_type(dst))
+ self.assertFalse(res)
+ self.assertFalse(osp.islink(dst))
+ self.assertTrue(backend.exists(dst))
+
+ @parameterized.expand([[Path], [str]])
+ def test_list_dir_or_file(self, path_type):
+ backend = LocalBackend()
+ with build_temporary_directory() as tmp_dir:
+ # list directories and files
+ self.assertEqual(
+ set(backend.list_dir_or_file(path_type(tmp_dir))),
+ {'dir1', 'dir2', 'text1.txt', 'text2.txt'})
+
+ # list directories and files recursively
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ path_type(tmp_dir), recursive=True)),
+ {
+ 'dir1',
+ osp.join('dir1', 'text3.txt'), 'dir2',
+ osp.join('dir2', 'dir3'),
+ osp.join('dir2', 'dir3', 'text4.txt'),
+ osp.join('dir2', 'img.jpg'), 'text1.txt', 'text2.txt'
+ })
+
+ # only list directories
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ path_type(tmp_dir), list_file=False)),
+ {'dir1', 'dir2'})
+
+ with self.assertRaisesRegex(
+ TypeError,
+ '`suffix` should be None when `list_dir` is True'):
+ backend.list_dir_or_file(
+ path_type(tmp_dir), list_file=False, suffix='.txt')
+
+ # only list directories recursively
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ path_type(tmp_dir), list_file=False, recursive=True)),
+ {'dir1', 'dir2', osp.join('dir2', 'dir3')})
+
+ # only list files
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ path_type(tmp_dir), list_dir=False)),
+ {'text1.txt', 'text2.txt'})
+
+ # only list files recursively
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ path_type(tmp_dir), list_dir=False, recursive=True)),
+ {
+ osp.join('dir1', 'text3.txt'),
+ osp.join('dir2', 'dir3', 'text4.txt'),
+ osp.join('dir2', 'img.jpg'), 'text1.txt', 'text2.txt'
+ })
+
+ # only list files ending with suffix
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ path_type(tmp_dir), list_dir=False, suffix='.txt')),
+ {'text1.txt', 'text2.txt'})
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ path_type(tmp_dir),
+ list_dir=False,
+ suffix=('.txt', '.jpg'))), {'text1.txt', 'text2.txt'})
+
+ with self.assertRaisesRegex(
+ TypeError,
+ '`suffix` must be a string or tuple of strings'):
+ backend.list_dir_or_file(
+ path_type(tmp_dir),
+ list_dir=False,
+ suffix=['.txt', '.jpg'])
+
+ # only list files ending with suffix recursively
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ path_type(tmp_dir),
+ list_dir=False,
+ suffix='.txt',
+ recursive=True)), {
+ osp.join('dir1', 'text3.txt'),
+ osp.join('dir2', 'dir3', 'text4.txt'), 'text1.txt',
+ 'text2.txt'
+ })
+
+ # only list files ending with suffix
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ path_type(tmp_dir),
+ list_dir=False,
+ suffix=('.txt', '.jpg'),
+ recursive=True)),
+ {
+ osp.join('dir1', 'text3.txt'),
+ osp.join('dir2', 'dir3', 'text4.txt'),
+ osp.join('dir2', 'img.jpg'), 'text1.txt', 'text2.txt'
+ })
diff --git a/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_memcached_backend.py b/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_memcached_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..d320fcb16be0e01d1eae1f87b1d6851fab953443
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_memcached_backend.py
@@ -0,0 +1,59 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import sys
+from pathlib import Path
+from unittest import TestCase
+from unittest.mock import MagicMock, patch
+
+import cv2
+import numpy as np
+from parameterized import parameterized
+
+from mmengine.fileio.backends import MemcachedBackend
+
+
+def imfrombytes(content):
+ img_np = np.frombuffer(content, np.uint8)
+ img = cv2.imdecode(img_np, cv2.IMREAD_COLOR)
+ return img
+
+
+sys.modules['mc'] = MagicMock()
+
+
+class MockMemcachedClient:
+
+ def __init__(self, server_list_cfg, client_cfg):
+ pass
+
+ def Get(self, filepath, buffer):
+ with open(filepath, 'rb') as f:
+ buffer.content = f.read()
+
+
+class TestMemcachedBackend(TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ cls.mc_cfg = dict(server_list_cfg='', client_cfg='', sys_path=None)
+ cls.test_data_dir = Path(__file__).parent.parent.parent / 'data'
+ cls.img_path = cls.test_data_dir / 'color.jpg'
+ cls.img_shape = (300, 400, 3)
+
+ @parameterized.expand([[Path], [str]])
+ @patch('mc.MemcachedClient.GetInstance', MockMemcachedClient)
+ @patch('mc.pyvector', MagicMock)
+ @patch('mc.ConvertBuffer', lambda x: x.content)
+ def test_get(self, path_type):
+ backend = MemcachedBackend(**self.mc_cfg)
+ img_bytes = backend.get(path_type(self.img_path))
+ self.assertEqual(self.img_path.open('rb').read(), img_bytes)
+ img = imfrombytes(img_bytes)
+ self.assertEqual(img.shape, self.img_shape)
+
+ @patch('mc.MemcachedClient.GetInstance', MockMemcachedClient)
+ @patch('mc.pyvector', MagicMock)
+ @patch('mc.ConvertBuffer', lambda x: x.content)
+ def test_get_text(self):
+ backend = MemcachedBackend(**self.mc_cfg)
+ with self.assertRaises(NotImplementedError):
+ backend.get_text('filepath')
diff --git a/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_petrel_backend.py b/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_petrel_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef2f85383c14f281064d5f791cec71dea9638601
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_fileio/test_backends/test_petrel_backend.py
@@ -0,0 +1,862 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import os.path as osp
+import sys
+import tempfile
+from contextlib import contextmanager
+from copy import deepcopy
+from pathlib import Path
+from shutil import SameFileError
+from unittest import TestCase
+from unittest.mock import MagicMock, patch
+
+from mmengine.fileio.backends import PetrelBackend
+from mmengine.utils import has_method
+
+
+@contextmanager
+def build_temporary_directory():
+ """Build a temporary directory containing many files to test
+ ``FileClient.list_dir_or_file``.
+
+ . \n
+ | -- dir1 \n
+ | -- | -- text3.txt \n
+ | -- dir2 \n
+ | -- | -- dir3 \n
+ | -- | -- | -- text4.txt \n
+ | -- | -- img.jpg \n
+ | -- text1.txt \n
+ | -- text2.txt \n
+ """
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ text1 = Path(tmp_dir) / 'text1.txt'
+ text1.open('w').write('text1')
+ text2 = Path(tmp_dir) / 'text2.txt'
+ text2.open('w').write('text2')
+ dir1 = Path(tmp_dir) / 'dir1'
+ dir1.mkdir()
+ text3 = dir1 / 'text3.txt'
+ text3.open('w').write('text3')
+ dir2 = Path(tmp_dir) / 'dir2'
+ dir2.mkdir()
+ jpg1 = dir2 / 'img.jpg'
+ jpg1.open('wb').write(b'img')
+ dir3 = dir2 / 'dir3'
+ dir3.mkdir()
+ text4 = dir3 / 'text4.txt'
+ text4.open('w').write('text4')
+ yield tmp_dir
+
+
+try:
+ # Other unit tests may mock these modules so we need to pop them first.
+ sys.modules.pop('petrel_client', None)
+ sys.modules.pop('petrel_client.client', None)
+
+ # If petrel_client is imported successfully, we can test PetrelBackend
+ # without mock.
+ import petrel_client # noqa: F401
+except ImportError:
+ sys.modules['petrel_client'] = MagicMock()
+ sys.modules['petrel_client.client'] = MagicMock()
+
+ class MockPetrelClient:
+
+ def __init__(self,
+ enable_mc=True,
+ enable_multi_cluster=False,
+ conf_path=None):
+ self.enable_mc = enable_mc
+ self.enable_multi_cluster = enable_multi_cluster
+ self.conf_path = conf_path
+
+ def Get(self, filepath):
+ with open(filepath, 'rb') as f:
+ content = f.read()
+ return content
+
+ def put(self):
+ pass
+
+ def delete(self):
+ pass
+
+ def contains(self):
+ pass
+
+ def isdir(self):
+ pass
+
+ def list(self, dir_path):
+ for entry in os.scandir(dir_path):
+ if not entry.name.startswith('.') and entry.is_file():
+ yield entry.name
+ elif osp.isdir(entry.path):
+ yield entry.name + '/'
+
+ @contextmanager
+ def delete_and_reset_method(obj, method):
+ method_obj = deepcopy(getattr(type(obj), method))
+ try:
+ delattr(type(obj), method)
+ yield
+ finally:
+ setattr(type(obj), method, method_obj)
+
+ @patch('petrel_client.client.Client', MockPetrelClient)
+ class TestPetrelBackend(TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ cls.test_data_dir = Path(__file__).parent.parent.parent / 'data'
+ cls.img_path = cls.test_data_dir / 'color.jpg'
+ cls.img_shape = (300, 400, 3)
+ cls.text_path = cls.test_data_dir / 'filelist.txt'
+ cls.petrel_dir = 'petrel://user/data'
+ cls.petrel_path = f'{cls.petrel_dir}/test.jpg'
+ cls.expected_dir = 's3://user/data'
+ cls.expected_path = f'{cls.expected_dir}/test.jpg'
+
+ def test_name(self):
+ backend = PetrelBackend()
+ self.assertEqual(backend.name, 'PetrelBackend')
+
+ def test_map_path(self):
+ backend = PetrelBackend(path_mapping=None)
+ self.assertEqual(
+ backend._map_path(self.petrel_path), self.petrel_path)
+
+ backend = PetrelBackend(
+ path_mapping={'data/': 'petrel://user/data/'})
+ self.assertEqual(
+ backend._map_path('data/test.jpg'), self.petrel_path)
+
+ def test_format_path(self):
+ backend = PetrelBackend()
+ formatted_filepath = backend._format_path(
+ 'petrel://user\\data\\test.jpg')
+ self.assertEqual(formatted_filepath, self.petrel_path)
+
+ def test_replace_prefix(self):
+ backend = PetrelBackend()
+ self.assertEqual(
+ backend._replace_prefix(self.petrel_path), self.expected_path)
+
+ def test_join_path(self):
+ backend = PetrelBackend()
+ self.assertEqual(
+ backend.join_path(self.petrel_dir, 'file'),
+ f'{self.petrel_dir}/file')
+ self.assertEqual(
+ backend.join_path(f'{self.petrel_dir}/', 'file'),
+ f'{self.petrel_dir}/file')
+ self.assertEqual(
+ backend.join_path(f'{self.petrel_dir}/', '/file'),
+ f'{self.petrel_dir}/file')
+ self.assertEqual(
+ backend.join_path(self.petrel_dir, 'dir', 'file'),
+ f'{self.petrel_dir}/dir/file')
+
+ def test_get(self):
+ backend = PetrelBackend()
+ with patch.object(
+ backend._client, 'Get',
+ return_value=b'petrel') as patched_get:
+ self.assertEqual(backend.get(self.petrel_path), b'petrel')
+ patched_get.assert_called_once_with(self.expected_path)
+
+ def test_get_text(self):
+ backend = PetrelBackend()
+ with patch.object(
+ backend._client, 'Get',
+ return_value=b'petrel') as patched_get:
+ self.assertEqual(backend.get_text(self.petrel_path), 'petrel')
+ patched_get.assert_called_once_with(self.expected_path)
+
+ def test_put(self):
+ backend = PetrelBackend()
+ with patch.object(backend._client, 'put') as patched_put:
+ backend.put(b'petrel', self.petrel_path)
+ patched_put.assert_called_once_with(self.expected_path,
+ b'petrel')
+
+ def test_put_text(self):
+ backend = PetrelBackend()
+ with patch.object(backend._client, 'put') as patched_put:
+ backend.put_text('petrel', self.petrel_path)
+ patched_put.assert_called_once_with(self.expected_path,
+ b'petrel')
+
+ def test_exists(self):
+ backend = PetrelBackend()
+ self.assertTrue(has_method(backend._client, 'contains'))
+ self.assertTrue(has_method(backend._client, 'isdir'))
+ # raise Exception if `_client.contains` and '_client.isdir' are not
+ # implemented
+ with delete_and_reset_method(backend._client, 'contains'), \
+ delete_and_reset_method(backend._client, 'isdir'):
+ self.assertFalse(has_method(backend._client, 'contains'))
+ self.assertFalse(has_method(backend._client, 'isdir'))
+ with self.assertRaises(NotImplementedError):
+ backend.exists(self.petrel_path)
+
+ with patch.object(
+ backend._client, 'contains',
+ return_value=True) as patched_contains:
+ self.assertTrue(backend.exists(self.petrel_path))
+ patched_contains.assert_called_once_with(self.expected_path)
+
+ def test_isdir(self):
+ backend = PetrelBackend()
+ self.assertTrue(has_method(backend._client, 'isdir'))
+ # raise Exception if `_client.isdir` is not implemented
+ with delete_and_reset_method(backend._client, 'isdir'):
+ self.assertFalse(has_method(backend._client, 'isdir'))
+ with self.assertRaises(NotImplementedError):
+ backend.isdir(self.petrel_path)
+
+ with patch.object(
+ backend._client, 'isdir',
+ return_value=True) as patched_contains:
+ self.assertTrue(backend.isdir(self.petrel_path))
+ patched_contains.assert_called_once_with(self.expected_path)
+
+ def test_isfile(self):
+ backend = PetrelBackend()
+ self.assertTrue(has_method(backend._client, 'contains'))
+ # raise Exception if `_client.contains` is not implemented
+ with delete_and_reset_method(backend._client, 'contains'):
+ self.assertFalse(has_method(backend._client, 'contains'))
+ with self.assertRaises(NotImplementedError):
+ backend.isfile(self.petrel_path)
+
+ with patch.object(
+ backend._client, 'contains',
+ return_value=True) as patched_contains:
+ self.assertTrue(backend.isfile(self.petrel_path))
+ patched_contains.assert_called_once_with(self.expected_path)
+
+ def test_get_local_path(self):
+ backend = PetrelBackend()
+ with patch.object(backend._client, 'Get',
+ return_value=b'petrel') as patched_get, \
+ patch.object(backend._client, 'contains',
+ return_value=True) as patch_contains:
+ with backend.get_local_path(self.petrel_path) as path:
+ self.assertTrue(osp.isfile(path))
+ self.assertEqual(Path(path).open('rb').read(), b'petrel')
+ # exist the with block and path will be released
+ self.assertFalse(osp.isfile(path))
+ patched_get.assert_called_once_with(self.expected_path)
+ patch_contains.assert_called_once_with(self.expected_path)
+
+ def test_copyfile(self):
+ backend = PetrelBackend()
+ with patch.object(backend._client, 'Get',
+ return_value=b'petrel') as patched_get, \
+ patch.object(backend._client, 'put') as patched_put, \
+ patch.object(backend._client, 'isdir', return_value=False) as \
+ patched_isdir:
+ src = self.petrel_path
+ dst = f'{self.petrel_dir}/test.bak.jpg'
+ expected_dst = f'{self.expected_dir}/test.bak.jpg'
+ self.assertEqual(backend.copyfile(src, dst), dst)
+ patched_get.assert_called_once_with(self.expected_path)
+ patched_put.assert_called_once_with(expected_dst, b'petrel')
+ patched_isdir.assert_called_once_with(expected_dst)
+
+ with patch.object(backend._client, 'Get',
+ return_value=b'petrel') as patched_get, \
+ patch.object(backend._client, 'put') as patched_put, \
+ patch.object(backend._client, 'isdir', return_value=True) as \
+ patched_isdir:
+ # dst is a directory
+ dst = f'{self.petrel_dir}/dir'
+ expected_dst = f'{self.expected_dir}/dir/test.jpg'
+ self.assertEqual(backend.copyfile(src, dst), f'{dst}/test.jpg')
+ patched_get.assert_called_once_with(self.expected_path)
+ patched_put.assert_called_once_with(expected_dst, b'petrel')
+ patched_isdir.assert_called_once_with(
+ f'{self.expected_dir}/dir')
+
+ with patch.object(backend._client, 'Get',
+ return_value=b'petrel') as patched_get, \
+ patch.object(backend._client, 'isdir', return_value=False) as \
+ patched_isdir:
+ # src and src should not be same file
+ with self.assertRaises(SameFileError):
+ backend.copyfile(src, src)
+
+ def test_copytree(self):
+ backend = PetrelBackend()
+ put_inputs = []
+ get_inputs = []
+
+ def put(obj, filepath):
+ put_inputs.append((obj, filepath))
+
+ def get(filepath):
+ get_inputs.append(filepath)
+
+ with build_temporary_directory() as tmp_dir, \
+ patch.object(backend, 'put', side_effect=put),\
+ patch.object(backend, 'get', side_effect=get),\
+ patch.object(backend, 'exists', return_value=False):
+ tmp_dir = tmp_dir.replace('\\', '/')
+ dst = f'{tmp_dir}/dir'
+ self.assertEqual(backend.copytree(tmp_dir, dst), dst)
+
+ self.assertEqual(len(put_inputs), 5)
+ self.assertEqual(len(get_inputs), 5)
+
+ # dst should not exist
+ with patch.object(backend, 'exists', return_value=True):
+ with self.assertRaises(FileExistsError):
+ backend.copytree(dst, tmp_dir)
+
+ def test_copyfile_from_local(self):
+ backend = PetrelBackend()
+ with patch.object(backend._client, 'put') as patched_put, \
+ patch.object(backend._client, 'isdir', return_value=False) \
+ as patched_isdir:
+ src = self.img_path
+ dst = f'{self.petrel_dir}/color.bak.jpg'
+ expected_dst = f'{self.expected_dir}/color.bak.jpg'
+ self.assertEqual(backend.copyfile_from_local(src, dst), dst)
+ patched_put.assert_called_once_with(expected_dst,
+ src.open('rb').read())
+ patched_isdir.assert_called_once_with(expected_dst)
+
+ with patch.object(backend._client, 'put') as patched_put, \
+ patch.object(backend._client, 'isdir', return_value=True) as \
+ patched_isdir:
+ # dst is a directory
+ src = self.img_path
+ dst = f'{self.petrel_dir}/dir'
+ expected_dst = f'{self.expected_dir}/dir/color.jpg'
+ self.assertEqual(
+ backend.copyfile_from_local(src, dst), f'{dst}/color.jpg')
+ patched_put.assert_called_once_with(expected_dst,
+ src.open('rb').read())
+ patched_isdir.assert_called_once_with(
+ f'{self.expected_dir}/dir')
+
+ def test_copytree_from_local(self):
+ backend = PetrelBackend()
+ inputs = []
+
+ def copyfile_from_local(src, dst):
+ inputs.append((src, dst))
+
+ with build_temporary_directory() as tmp_dir, \
+ patch.object(backend, 'copyfile_from_local',
+ side_effect=copyfile_from_local),\
+ patch.object(backend, 'exists', return_value=False):
+ backend.copytree_from_local(tmp_dir, self.petrel_dir)
+
+ self.assertEqual(len(inputs), 5)
+
+ # dst should not exist
+ with patch.object(backend, 'exists', return_value=True):
+ with self.assertRaises(FileExistsError):
+ backend.copytree_from_local(tmp_dir, self.petrel_dir)
+
+ def test_copyfile_to_local(self):
+ backend = PetrelBackend()
+ with patch.object(backend._client, 'Get',
+ return_value=b'petrel') as patched_get, \
+ tempfile.TemporaryDirectory() as tmp_dir:
+ src = self.petrel_path
+ dst = Path(tmp_dir) / 'test.bak.jpg'
+ self.assertEqual(backend.copyfile_to_local(src, dst), dst)
+ patched_get.assert_called_once_with(self.expected_path)
+ self.assertEqual(dst.open('rb').read(), b'petrel')
+
+ with patch.object(backend._client, 'Get',
+ return_value=b'petrel') as patched_get, \
+ tempfile.TemporaryDirectory() as tmp_dir:
+ # dst is a directory
+ src = self.petrel_path
+ dst = Path(tmp_dir) / 'dir'
+ dst.mkdir()
+ self.assertEqual(
+ backend.copyfile_to_local(src, dst), dst / 'test.jpg')
+ patched_get.assert_called_once_with(self.expected_path)
+ self.assertEqual((dst / 'test.jpg').open('rb').read(),
+ b'petrel')
+
+ def test_copytree_to_local(self):
+ backend = PetrelBackend()
+ inputs = []
+
+ def get(filepath):
+ inputs.append(filepath)
+ return b'petrel'
+
+ with build_temporary_directory() as tmp_dir, \
+ patch.object(backend, 'get', side_effect=get):
+ dst = f'{tmp_dir}/dir'
+ backend.copytree_to_local(tmp_dir, dst)
+
+ self.assertEqual(len(inputs), 5)
+
+ def test_remove(self):
+ backend = PetrelBackend()
+ self.assertTrue(has_method(backend._client, 'delete'))
+ # raise Exception if `delete` is not implemented
+ with delete_and_reset_method(backend._client, 'delete'):
+ self.assertFalse(has_method(backend._client, 'delete'))
+ with self.assertRaises(NotImplementedError):
+ backend.remove(self.petrel_path)
+
+ with patch.object(backend._client, 'delete') as patched_delete, \
+ patch.object(backend._client, 'isdir', return_value=False) \
+ as patched_isdir, \
+ patch.object(backend._client, 'contains', return_value=True) \
+ as patched_contains:
+ backend.remove(self.petrel_path)
+ patched_delete.assert_called_once_with(self.expected_path)
+ patched_isdir.assert_called_once_with(self.expected_path)
+ patched_contains.assert_called_once_with(self.expected_path)
+
+ def test_rmtree(self):
+ backend = PetrelBackend()
+ inputs = []
+
+ def remove(filepath):
+ inputs.append(filepath)
+
+ with build_temporary_directory() as tmp_dir,\
+ patch.object(backend, 'remove', side_effect=remove):
+ backend.rmtree(tmp_dir)
+
+ self.assertEqual(len(inputs), 5)
+
+ def test_copy_if_symlink_fails(self):
+ backend = PetrelBackend()
+ copyfile_inputs = []
+ copytree_inputs = []
+
+ def copyfile(src, dst):
+ copyfile_inputs.append((src, dst))
+
+ def copytree(src, dst):
+ copytree_inputs.append((src, dst))
+
+ with patch.object(backend, 'copyfile', side_effect=copyfile), \
+ patch.object(backend, 'isfile', return_value=True):
+ backend.copy_if_symlink_fails(self.petrel_path, 'path')
+
+ self.assertEqual(len(copyfile_inputs), 1)
+
+ with patch.object(backend, 'copytree', side_effect=copytree), \
+ patch.object(backend, 'isfile', return_value=False):
+ backend.copy_if_symlink_fails(self.petrel_dir, 'path')
+
+ self.assertEqual(len(copytree_inputs), 1)
+
+ def test_list_dir_or_file(self):
+ backend = PetrelBackend()
+
+ # raise Exception if `_client.list` is not implemented
+ self.assertTrue(has_method(backend._client, 'list'))
+ with delete_and_reset_method(backend._client, 'list'):
+ self.assertFalse(has_method(backend._client, 'list'))
+ with self.assertRaises(NotImplementedError):
+ list(backend.list_dir_or_file(self.petrel_dir))
+
+ with build_temporary_directory() as tmp_dir:
+ # list directories and files
+ self.assertEqual(
+ set(backend.list_dir_or_file(tmp_dir)),
+ {'dir1', 'dir2', 'text1.txt', 'text2.txt'})
+
+ # list directories and files recursively
+ self.assertEqual(
+ set(backend.list_dir_or_file(tmp_dir, recursive=True)), {
+ 'dir1', '/'.join(('dir1', 'text3.txt')), 'dir2',
+ '/'.join(('dir2', 'dir3')), '/'.join(
+ ('dir2', 'dir3', 'text4.txt')), '/'.join(
+ ('dir2', 'img.jpg')), 'text1.txt', 'text2.txt'
+ })
+
+ # only list directories
+ self.assertEqual(
+ set(backend.list_dir_or_file(tmp_dir, list_file=False)),
+ {'dir1', 'dir2'})
+ with self.assertRaisesRegex(
+ TypeError,
+ '`list_dir` should be False when `suffix` is not None'
+ ):
+ backend.list_dir_or_file(
+ tmp_dir, list_file=False, suffix='.txt')
+
+ # only list directories recursively
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ tmp_dir, list_file=False, recursive=True)),
+ {'dir1', 'dir2', '/'.join(('dir2', 'dir3'))})
+
+ # only list files
+ self.assertEqual(
+ set(backend.list_dir_or_file(tmp_dir, list_dir=False)),
+ {'text1.txt', 'text2.txt'})
+
+ # only list files recursively
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ tmp_dir, list_dir=False, recursive=True)),
+ {
+ '/'.join(('dir1', 'text3.txt')), '/'.join(
+ ('dir2', 'dir3', 'text4.txt')), '/'.join(
+ ('dir2', 'img.jpg')), 'text1.txt', 'text2.txt'
+ })
+
+ # only list files ending with suffix
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ tmp_dir, list_dir=False, suffix='.txt')),
+ {'text1.txt', 'text2.txt'})
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ tmp_dir, list_dir=False, suffix=('.txt', '.jpg'))),
+ {'text1.txt', 'text2.txt'})
+ with self.assertRaisesRegex(
+ TypeError,
+ '`suffix` must be a string or tuple of strings'):
+ backend.list_dir_or_file(
+ tmp_dir, list_dir=False, suffix=['.txt', '.jpg'])
+
+ # only list files ending with suffix recursively
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ tmp_dir,
+ list_dir=False,
+ suffix='.txt',
+ recursive=True)), {
+ '/'.join(('dir1', 'text3.txt')), '/'.join(
+ ('dir2', 'dir3', 'text4.txt')),
+ 'text1.txt', 'text2.txt'
+ })
+
+ # only list files ending with suffix
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ tmp_dir,
+ list_dir=False,
+ suffix=('.txt', '.jpg'),
+ recursive=True)),
+ {
+ '/'.join(('dir1', 'text3.txt')), '/'.join(
+ ('dir2', 'dir3', 'text4.txt')), '/'.join(
+ ('dir2', 'img.jpg')), 'text1.txt', 'text2.txt'
+ })
+
+ def test_generate_presigned_url(self):
+ pass
+
+else:
+
+ class TestPetrelBackend(TestCase): # type: ignore
+
+ @classmethod
+ def setUpClass(cls):
+ cls.test_data_dir = Path(__file__).parent.parent.parent / 'data'
+ cls.local_img_path = cls.test_data_dir / 'color.jpg'
+ cls.local_img_shape = (300, 400, 3)
+ cls.petrel_dir = 'petrel://mmengine-test/data'
+
+ def setUp(self):
+ backend = PetrelBackend()
+ backend.rmtree(self.petrel_dir)
+ with build_temporary_directory() as tmp_dir:
+ backend.copytree_from_local(tmp_dir, self.petrel_dir)
+
+ text1_path = f'{self.petrel_dir}/text1.txt'
+ text2_path = f'{self.petrel_dir}/text2.txt'
+ text3_path = f'{self.petrel_dir}/dir1/text3.txt'
+ text4_path = f'{self.petrel_dir}/dir2/dir3/text4.txt'
+ img_path = f'{self.petrel_dir}/dir2/img.jpg'
+ self.assertTrue(backend.isfile(text1_path))
+ self.assertTrue(backend.isfile(text2_path))
+ self.assertTrue(backend.isfile(text3_path))
+ self.assertTrue(backend.isfile(text4_path))
+ self.assertTrue(backend.isfile(img_path))
+
+ def test_get(self):
+ backend = PetrelBackend()
+ img_path = f'{self.petrel_dir}/dir2/img.jpg'
+ self.assertEqual(backend.get(img_path), b'img')
+
+ def test_get_text(self):
+ backend = PetrelBackend()
+ text_path = f'{self.petrel_dir}/text1.txt'
+ self.assertEqual(backend.get_text(text_path), 'text1')
+
+ def test_put(self):
+ backend = PetrelBackend()
+ img_path = f'{self.petrel_dir}/img.jpg'
+ backend.put(b'img', img_path)
+
+ def test_put_text(self):
+ backend = PetrelBackend()
+ text_path = f'{self.petrel_dir}/text5.txt'
+ backend.put_text('text5', text_path)
+
+ def test_exists(self):
+ backend = PetrelBackend()
+
+ # file and directory exist
+ dir_path = f'{self.petrel_dir}/dir2'
+ self.assertTrue(backend.exists(dir_path))
+ img_path = f'{self.petrel_dir}/dir2/img.jpg'
+ self.assertTrue(backend.exists(img_path))
+
+ # file and directory does not exist
+ not_existed_dir = f'{self.petrel_dir}/not_existed_dir'
+ self.assertFalse(backend.exists(not_existed_dir))
+ not_existed_path = f'{self.petrel_dir}/img.jpg'
+ self.assertFalse(backend.exists(not_existed_path))
+
+ def test_isdir(self):
+ backend = PetrelBackend()
+ dir_path = f'{self.petrel_dir}/dir2'
+ self.assertTrue(backend.isdir(dir_path))
+ img_path = f'{self.petrel_dir}/dir2/img.jpg'
+ self.assertFalse(backend.isdir(img_path))
+
+ def test_isfile(self):
+ backend = PetrelBackend()
+ dir_path = f'{self.petrel_dir}/dir2'
+ self.assertFalse(backend.isfile(dir_path))
+ img_path = f'{self.petrel_dir}/dir2/img.jpg'
+ self.assertTrue(backend.isfile(img_path))
+
+ def test_get_local_path(self):
+ backend = PetrelBackend()
+ img_path = f'{self.petrel_dir}/dir2/img.jpg'
+ with backend.get_local_path(img_path) as path:
+ self.assertTrue(osp.isfile(path))
+ self.assertEqual(Path(path).open('rb').read(), b'img')
+ # exist the with block and path will be released
+ self.assertFalse(osp.isfile(path))
+
+ def test_copyfile(self):
+ backend = PetrelBackend()
+
+ # dst is a file
+ src = f'{self.petrel_dir}/dir2/img.jpg'
+ dst = f'{self.petrel_dir}/img.jpg'
+ self.assertEqual(backend.copyfile(src, dst), dst)
+ self.assertTrue(backend.isfile(dst))
+
+ # dst is a directory
+ dst = f'{self.petrel_dir}/dir1'
+ expected_dst = f'{self.petrel_dir}/dir1/img.jpg'
+ self.assertEqual(backend.copyfile(src, dst), expected_dst)
+ self.assertTrue(backend.isfile(expected_dst))
+
+ # src and src should not be same file
+ with self.assertRaises(SameFileError):
+ backend.copyfile(src, src)
+
+ def test_copytree(self):
+ backend = PetrelBackend()
+ src = f'{self.petrel_dir}/dir2'
+ dst = f'{self.petrel_dir}/dir3'
+ self.assertFalse(backend.exists(dst))
+ self.assertEqual(backend.copytree(src, dst), dst)
+ self.assertEqual(
+ list(backend.list_dir_or_file(src)),
+ list(backend.list_dir_or_file(dst)))
+
+ # dst should not exist
+ with self.assertRaises(FileExistsError):
+ backend.copytree(src, dst)
+
+ def test_copyfile_from_local(self):
+ backend = PetrelBackend()
+
+ # dst is a file
+ src = self.local_img_path
+ dst = f'{self.petrel_dir}/color.jpg'
+ self.assertFalse(backend.exists(dst))
+ self.assertEqual(backend.copyfile_from_local(src, dst), dst)
+ self.assertTrue(backend.isfile(dst))
+
+ # dst is a directory
+ src = self.local_img_path
+ dst = f'{self.petrel_dir}/dir1'
+ expected_dst = f'{self.petrel_dir}/dir1/color.jpg'
+ self.assertFalse(backend.exists(expected_dst))
+ self.assertEqual(
+ backend.copyfile_from_local(src, dst), expected_dst)
+ self.assertTrue(backend.isfile(expected_dst))
+
+ def test_copytree_from_local(self):
+ backend = PetrelBackend()
+ backend.rmtree(self.petrel_dir)
+ with build_temporary_directory() as tmp_dir:
+ backend.copytree_from_local(tmp_dir, self.petrel_dir)
+ files = backend.list_dir_or_file(
+ self.petrel_dir, recursive=True)
+ self.assertEqual(len(list(files)), 8)
+
+ def test_copyfile_to_local(self):
+ backend = PetrelBackend()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ # dst is a file
+ src = f'{self.petrel_dir}/dir2/img.jpg'
+ dst = Path(tmp_dir) / 'img.jpg'
+ self.assertEqual(backend.copyfile_to_local(src, dst), dst)
+ self.assertEqual(dst.open('rb').read(), b'img')
+
+ # dst is a directory
+ dst = Path(tmp_dir) / 'dir'
+ dst.mkdir()
+ self.assertEqual(
+ backend.copyfile_to_local(src, dst), dst / 'img.jpg')
+ self.assertEqual((dst / 'img.jpg').open('rb').read(), b'img')
+
+ def test_copytree_to_local(self):
+ backend = PetrelBackend()
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ backend.copytree_to_local(self.petrel_dir, tmp_dir)
+ self.assertTrue(osp.exists(Path(tmp_dir) / 'text1.txt'))
+ self.assertTrue(osp.exists(Path(tmp_dir) / 'dir2' / 'img.jpg'))
+
+ def test_remove(self):
+ backend = PetrelBackend()
+ img_path = f'{self.petrel_dir}/dir2/img.jpg'
+ self.assertTrue(backend.isfile(img_path))
+ backend.remove(img_path)
+ self.assertFalse(backend.exists(img_path))
+
+ def test_rmtree(self):
+ backend = PetrelBackend()
+ dir_path = f'{self.petrel_dir}/dir2'
+ self.assertTrue(backend.isdir(dir_path))
+ backend.rmtree(dir_path)
+ self.assertFalse(backend.exists(dir_path))
+
+ def test_copy_if_symlink_fails(self):
+ backend = PetrelBackend()
+
+ # dst is a file
+ src = f'{self.petrel_dir}/dir2/img.jpg'
+ dst = f'{self.petrel_dir}/img.jpg'
+ self.assertFalse(backend.exists(dst))
+ self.assertFalse(backend.copy_if_symlink_fails(src, dst))
+ self.assertTrue(backend.isfile(dst))
+
+ # dst is a directory
+ src = f'{self.petrel_dir}/dir2'
+ dst = f'{self.petrel_dir}/dir'
+ self.assertFalse(backend.exists(dst))
+ self.assertFalse(backend.copy_if_symlink_fails(src, dst))
+ self.assertTrue(backend.isdir(dst))
+
+ def test_list_dir_or_file(self):
+ backend = PetrelBackend()
+
+ # list directories and files
+ self.assertEqual(
+ set(backend.list_dir_or_file(self.petrel_dir)),
+ {'dir1', 'dir2', 'text1.txt', 'text2.txt'})
+
+ # list directories and files recursively
+ self.assertEqual(
+ set(backend.list_dir_or_file(self.petrel_dir, recursive=True)),
+ {
+ 'dir1', '/'.join(('dir1', 'text3.txt')), 'dir2', '/'.join(
+ ('dir2', 'dir3')), '/'.join(
+ ('dir2', 'dir3', 'text4.txt')), '/'.join(
+ ('dir2', 'img.jpg')), 'text1.txt', 'text2.txt'
+ })
+
+ # only list directories
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(self.petrel_dir,
+ list_file=False)),
+ {'dir1', 'dir2'})
+ with self.assertRaisesRegex(
+ TypeError,
+ '`list_dir` should be False when `suffix` is not None'):
+ backend.list_dir_or_file(
+ self.petrel_dir, list_file=False, suffix='.txt')
+
+ # only list directories recursively
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ self.petrel_dir, list_file=False, recursive=True)),
+ {'dir1', 'dir2', '/'.join(('dir2', 'dir3'))})
+
+ # only list files
+ self.assertEqual(
+ set(backend.list_dir_or_file(self.petrel_dir, list_dir=False)),
+ {'text1.txt', 'text2.txt'})
+
+ # only list files recursively
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ self.petrel_dir, list_dir=False, recursive=True)),
+ {
+ '/'.join(('dir1', 'text3.txt')), '/'.join(
+ ('dir2', 'dir3', 'text4.txt')), '/'.join(
+ ('dir2', 'img.jpg')), 'text1.txt', 'text2.txt'
+ })
+
+ # only list files ending with suffix
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ self.petrel_dir, list_dir=False, suffix='.txt')),
+ {'text1.txt', 'text2.txt'})
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ self.petrel_dir,
+ list_dir=False,
+ suffix=('.txt', '.jpg'))), {'text1.txt', 'text2.txt'})
+ with self.assertRaisesRegex(
+ TypeError,
+ '`suffix` must be a string or tuple of strings'):
+ backend.list_dir_or_file(
+ self.petrel_dir, list_dir=False, suffix=['.txt', '.jpg'])
+
+ # only list files ending with suffix recursively
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ self.petrel_dir,
+ list_dir=False,
+ suffix='.txt',
+ recursive=True)), {
+ '/'.join(('dir1', 'text3.txt')), '/'.join(
+ ('dir2', 'dir3', 'text4.txt')), 'text1.txt',
+ 'text2.txt'
+ })
+
+ # only list files ending with suffix
+ self.assertEqual(
+ set(
+ backend.list_dir_or_file(
+ self.petrel_dir,
+ list_dir=False,
+ suffix=('.txt', '.jpg'),
+ recursive=True)),
+ {
+ '/'.join(('dir1', 'text3.txt')), '/'.join(
+ ('dir2', 'dir3', 'text4.txt')), '/'.join(
+ ('dir2', 'img.jpg')), 'text1.txt', 'text2.txt'
+ })
diff --git a/testbed/open-mmlab__mmengine/tests/test_fileio/test_fileclient.py b/testbed/open-mmlab__mmengine/tests/test_fileio/test_fileclient.py
new file mode 100644
index 0000000000000000000000000000000000000000..345832a026ffc502906bc540ed6df6b94ca520db
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_fileio/test_fileclient.py
@@ -0,0 +1,843 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import os.path as osp
+import sys
+import tempfile
+from contextlib import contextmanager
+from copy import deepcopy
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+import cv2
+import numpy as np
+import pytest
+
+from mmengine.fileio import BaseStorageBackend, FileClient
+from mmengine.utils import has_method
+
+sys.modules['ceph'] = MagicMock()
+sys.modules['petrel_client'] = MagicMock()
+sys.modules['petrel_client.client'] = MagicMock()
+sys.modules['mc'] = MagicMock()
+
+
+def imfrombytes(content):
+ img_np = np.frombuffer(content, np.uint8)
+ img = cv2.imdecode(img_np, cv2.IMREAD_COLOR)
+ return img
+
+
+@contextmanager
+def build_temporary_directory():
+ """Build a temporary directory containing many files to test
+ ``FileClient.list_dir_or_file``.
+
+ . \n
+ | -- dir1 \n
+ | -- | -- text3.txt \n
+ | -- dir2 \n
+ | -- | -- dir3 \n
+ | -- | -- | -- text4.txt \n
+ | -- | -- img.jpg \n
+ | -- text1.txt \n
+ | -- text2.txt \n
+ """
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ text1 = Path(tmp_dir) / 'text1.txt'
+ text1.open('w').write('text1')
+ text2 = Path(tmp_dir) / 'text2.txt'
+ text2.open('w').write('text2')
+ dir1 = Path(tmp_dir) / 'dir1'
+ dir1.mkdir()
+ text3 = dir1 / 'text3.txt'
+ text3.open('w').write('text3')
+ dir2 = Path(tmp_dir) / 'dir2'
+ dir2.mkdir()
+ jpg1 = dir2 / 'img.jpg'
+ jpg1.open('wb').write(b'img')
+ dir3 = dir2 / 'dir3'
+ dir3.mkdir()
+ text4 = dir3 / 'text4.txt'
+ text4.open('w').write('text4')
+ yield tmp_dir
+
+
+@contextmanager
+def delete_and_reset_method(obj, method):
+ method_obj = deepcopy(getattr(type(obj), method))
+ try:
+ delattr(type(obj), method)
+ yield
+ finally:
+ setattr(type(obj), method, method_obj)
+
+
+class MockS3Client:
+
+ def __init__(self, enable_mc=True):
+ self.enable_mc = enable_mc
+
+ def Get(self, filepath):
+ with open(filepath, 'rb') as f:
+ content = f.read()
+ return content
+
+
+class MockPetrelClient:
+
+ def __init__(self,
+ enable_mc=True,
+ enable_multi_cluster=False,
+ conf_path=None):
+ self.enable_mc = enable_mc
+ self.enable_multi_cluster = enable_multi_cluster
+ self.conf_path = conf_path
+
+ def Get(self, filepath):
+ with open(filepath, 'rb') as f:
+ content = f.read()
+ return content
+
+ def put(self):
+ pass
+
+ def delete(self):
+ pass
+
+ def contains(self):
+ pass
+
+ def isdir(self):
+ pass
+
+ def list(self, dir_path):
+ for entry in os.scandir(dir_path):
+ if not entry.name.startswith('.') and entry.is_file():
+ yield entry.name
+ elif osp.isdir(entry.path):
+ yield entry.name + '/'
+
+
+class MockMemcachedClient:
+
+ def __init__(self, server_list_cfg, client_cfg):
+ pass
+
+ def Get(self, filepath, buffer):
+ with open(filepath, 'rb') as f:
+ buffer.content = f.read()
+
+
+class TestFileClient:
+
+ @classmethod
+ def setup_class(cls):
+ cls.test_data_dir = Path(__file__).parent.parent / 'data'
+ cls.img_path = cls.test_data_dir / 'color.jpg'
+ cls.img_shape = (300, 400, 3)
+ cls.text_path = cls.test_data_dir / 'filelist.txt'
+
+ def test_error(self):
+ with pytest.raises(ValueError):
+ FileClient('hadoop')
+
+ def test_disk_backend(self):
+ disk_backend = FileClient('disk')
+
+ # test `name` attribute
+ assert disk_backend.name == 'HardDiskBackend'
+ # test `allow_symlink` attribute
+ assert disk_backend.allow_symlink
+ # test `get`
+ # input path is Path object
+ img_bytes = disk_backend.get(self.img_path)
+ img = imfrombytes(img_bytes)
+ assert self.img_path.open('rb').read() == img_bytes
+ assert img.shape == self.img_shape
+ # input path is str
+ img_bytes = disk_backend.get(str(self.img_path))
+ img = imfrombytes(img_bytes)
+ assert self.img_path.open('rb').read() == img_bytes
+ assert img.shape == self.img_shape
+
+ # test `get_text`
+ # input path is Path object
+ value_buf = disk_backend.get_text(self.text_path)
+ assert self.text_path.open('r').read() == value_buf
+ # input path is str
+ value_buf = disk_backend.get_text(str(self.text_path))
+ assert self.text_path.open('r').read() == value_buf
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ # test `put`
+ filepath1 = Path(tmp_dir) / 'test.jpg'
+ disk_backend.put(b'disk', filepath1)
+ assert filepath1.open('rb').read() == b'disk'
+ # test the `mkdir_or_exist` behavior in `put`
+ _filepath1 = Path(tmp_dir) / 'not_existed_dir1' / 'test.jpg'
+ disk_backend.put(b'disk', _filepath1)
+ assert _filepath1.open('rb').read() == b'disk'
+
+ # test `put_text`
+ filepath2 = Path(tmp_dir) / 'test.txt'
+ disk_backend.put_text('disk', filepath2)
+ assert filepath2.open('r').read() == 'disk'
+ # test the `mkdir_or_exist` behavior in `put_text`
+ _filepath2 = Path(tmp_dir) / 'not_existed_dir2' / 'test.txt'
+ disk_backend.put_text('disk', _filepath2)
+ assert _filepath2.open('r').read() == 'disk'
+
+ # test `isfile`
+ assert disk_backend.isfile(filepath2)
+ assert not disk_backend.isfile(Path(tmp_dir) / 'not/existed/path')
+
+ # test `remove`
+ disk_backend.remove(filepath2)
+
+ # test `exists`
+ assert not disk_backend.exists(filepath2)
+
+ # test `get_local_path`
+ # if the backend is disk, `get_local_path` just return the input
+ with disk_backend.get_local_path(filepath1) as path:
+ assert str(filepath1) == path
+ assert osp.isfile(filepath1)
+
+ # test `join_path`
+ disk_dir = '/path/of/your/directory'
+ assert disk_backend.join_path(disk_dir, 'file') == \
+ osp.join(disk_dir, 'file')
+ assert disk_backend.join_path(disk_dir, 'dir', 'file') == \
+ osp.join(disk_dir, 'dir', 'file')
+
+ # test `list_dir_or_file`
+ with build_temporary_directory() as tmp_dir:
+ # 1. list directories and files
+ assert set(disk_backend.list_dir_or_file(tmp_dir)) == {
+ 'dir1', 'dir2', 'text1.txt', 'text2.txt'
+ }
+ # 2. list directories and files recursively
+ assert set(disk_backend.list_dir_or_file(
+ tmp_dir, recursive=True)) == {
+ 'dir1',
+ osp.join('dir1', 'text3.txt'), 'dir2',
+ osp.join('dir2', 'dir3'),
+ osp.join('dir2', 'dir3', 'text4.txt'),
+ osp.join('dir2', 'img.jpg'), 'text1.txt', 'text2.txt'
+ }
+ # 3. only list directories
+ assert set(
+ disk_backend.list_dir_or_file(
+ tmp_dir, list_file=False)) == {'dir1', 'dir2'}
+ with pytest.raises(
+ TypeError,
+ match='`suffix` should be None when `list_dir` is True'):
+ # Exception is raised among the `list_dir_or_file` of client,
+ # so we need to invode the client to trigger the exception
+ disk_backend.client.list_dir_or_file(
+ tmp_dir, list_file=False, suffix='.txt')
+ # 4. only list directories recursively
+ assert set(
+ disk_backend.list_dir_or_file(
+ tmp_dir, list_file=False, recursive=True)) == {
+ 'dir1', 'dir2',
+ osp.join('dir2', 'dir3')
+ }
+ # 5. only list files
+ assert set(disk_backend.list_dir_or_file(
+ tmp_dir, list_dir=False)) == {'text1.txt', 'text2.txt'}
+ # 6. only list files recursively
+ assert set(
+ disk_backend.list_dir_or_file(
+ tmp_dir, list_dir=False, recursive=True)) == {
+ osp.join('dir1', 'text3.txt'),
+ osp.join('dir2', 'dir3', 'text4.txt'),
+ osp.join('dir2', 'img.jpg'), 'text1.txt', 'text2.txt'
+ }
+ # 7. only list files ending with suffix
+ assert set(
+ disk_backend.list_dir_or_file(
+ tmp_dir, list_dir=False,
+ suffix='.txt')) == {'text1.txt', 'text2.txt'}
+ assert set(
+ disk_backend.list_dir_or_file(
+ tmp_dir, list_dir=False,
+ suffix=('.txt', '.jpg'))) == {'text1.txt', 'text2.txt'}
+ with pytest.raises(
+ TypeError,
+ match='`suffix` must be a string or tuple of strings'):
+ disk_backend.client.list_dir_or_file(
+ tmp_dir, list_dir=False, suffix=['.txt', '.jpg'])
+ # 8. only list files ending with suffix recursively
+ assert set(
+ disk_backend.list_dir_or_file(
+ tmp_dir, list_dir=False, suffix='.txt',
+ recursive=True)) == {
+ osp.join('dir1', 'text3.txt'),
+ osp.join('dir2', 'dir3', 'text4.txt'), 'text1.txt',
+ 'text2.txt'
+ }
+ # 7. only list files ending with suffix
+ assert set(
+ disk_backend.list_dir_or_file(
+ tmp_dir,
+ list_dir=False,
+ suffix=('.txt', '.jpg'),
+ recursive=True)) == {
+ osp.join('dir1', 'text3.txt'),
+ osp.join('dir2', 'dir3', 'text4.txt'),
+ osp.join('dir2', 'img.jpg'), 'text1.txt', 'text2.txt'
+ }
+
+ @patch('petrel_client.client.Client', MockPetrelClient)
+ @pytest.mark.parametrize('backend,prefix', [('petrel', None),
+ (None, 's3')])
+ def test_petrel_backend(self, backend, prefix):
+ petrel_backend = FileClient(backend=backend, prefix=prefix)
+
+ # test `allow_symlink` attribute
+ assert not petrel_backend.allow_symlink
+
+ # input path is Path object
+ img_bytes = petrel_backend.get(self.img_path)
+ img = imfrombytes(img_bytes)
+ assert img.shape == self.img_shape
+ # input path is str
+ img_bytes = petrel_backend.get(str(self.img_path))
+ img = imfrombytes(img_bytes)
+ assert img.shape == self.img_shape
+
+ # `path_mapping` is either None or dict
+ with pytest.raises(AssertionError):
+ FileClient('petrel', path_mapping=1)
+
+ # test `_map_path`
+ petrel_dir = 's3://user/data'
+ petrel_backend = FileClient(
+ 'petrel', path_mapping={str(self.test_data_dir): petrel_dir})
+ assert petrel_backend.client._map_path(str(self.img_path)) == \
+ str(self.img_path).replace(str(self.test_data_dir), petrel_dir)
+
+ petrel_path = f'{petrel_dir}/test.jpg'
+ petrel_backend = FileClient('petrel')
+
+ # test `_format_path`
+ assert petrel_backend.client._format_path('s3://user\\data\\test.jpg')\
+ == petrel_path
+
+ # test `get`
+ with patch.object(
+ petrel_backend.client._client, 'Get',
+ return_value=b'petrel') as mock_get:
+ assert petrel_backend.get(petrel_path) == b'petrel'
+ mock_get.assert_called_once_with(petrel_path)
+
+ # test `get_text`
+ with patch.object(
+ petrel_backend.client._client, 'Get',
+ return_value=b'petrel') as mock_get:
+ assert petrel_backend.get_text(petrel_path) == 'petrel'
+ mock_get.assert_called_once_with(petrel_path)
+
+ # test `put`
+ with patch.object(petrel_backend.client._client, 'put') as mock_put:
+ petrel_backend.put(b'petrel', petrel_path)
+ mock_put.assert_called_once_with(petrel_path, b'petrel')
+
+ # test `put_text`
+ with patch.object(petrel_backend.client._client, 'put') as mock_put:
+ petrel_backend.put_text('petrel', petrel_path)
+ mock_put.assert_called_once_with(petrel_path, b'petrel')
+
+ # test `remove`
+ assert has_method(petrel_backend.client._client, 'delete')
+ # raise Exception if `delete` is not implemented
+ with delete_and_reset_method(petrel_backend.client._client, 'delete'):
+ assert not has_method(petrel_backend.client._client, 'delete')
+ with pytest.raises(NotImplementedError):
+ petrel_backend.remove(petrel_path)
+
+ with patch.object(petrel_backend.client._client,
+ 'delete') as mock_delete, \
+ patch.object(petrel_backend.client._client,
+ 'isdir', return_value=False) as mock_isdir, \
+ patch.object(petrel_backend.client._client,
+ 'contains', return_value=True) as mock_contains:
+ petrel_backend.remove(petrel_path)
+ mock_delete.assert_called_once_with(petrel_path)
+ mock_isdir.assert_called_once_with(petrel_path)
+ mock_contains.assert_called_once_with(petrel_path)
+
+ # test `exists`
+ assert has_method(petrel_backend.client._client, 'contains')
+ assert has_method(petrel_backend.client._client, 'isdir')
+ # raise Exception if `delete` is not implemented
+ with delete_and_reset_method(petrel_backend.client._client,
+ 'contains'), delete_and_reset_method(
+ petrel_backend.client._client,
+ 'isdir'):
+ assert not has_method(petrel_backend.client._client, 'contains')
+ assert not has_method(petrel_backend.client._client, 'isdir')
+ with pytest.raises(NotImplementedError):
+ petrel_backend.exists(petrel_path)
+
+ with patch.object(
+ petrel_backend.client._client, 'contains',
+ return_value=True) as mock_contains:
+ assert petrel_backend.exists(petrel_path)
+ mock_contains.assert_called_once_with(petrel_path)
+
+ # test `isdir`
+ assert has_method(petrel_backend.client._client, 'isdir')
+ with delete_and_reset_method(petrel_backend.client._client, 'isdir'):
+ assert not has_method(petrel_backend.client._client, 'isdir')
+ with pytest.raises(NotImplementedError):
+ petrel_backend.isdir(petrel_path)
+
+ with patch.object(
+ petrel_backend.client._client, 'isdir',
+ return_value=True) as mock_isdir:
+ assert petrel_backend.isdir(petrel_dir)
+ mock_isdir.assert_called_once_with(petrel_dir)
+
+ # test `isfile`
+ assert has_method(petrel_backend.client._client, 'contains')
+ with delete_and_reset_method(petrel_backend.client._client,
+ 'contains'):
+ assert not has_method(petrel_backend.client._client, 'contains')
+ with pytest.raises(NotImplementedError):
+ petrel_backend.isfile(petrel_path)
+
+ with patch.object(
+ petrel_backend.client._client, 'contains',
+ return_value=True) as mock_contains:
+ assert petrel_backend.isfile(petrel_path)
+ mock_contains.assert_called_once_with(petrel_path)
+
+ # test `join_path`
+ assert petrel_backend.join_path(petrel_dir, 'file') == \
+ f'{petrel_dir}/file'
+ assert petrel_backend.join_path(f'{petrel_dir}/', 'file') == \
+ f'{petrel_dir}/file'
+ assert petrel_backend.join_path(petrel_dir, 'dir', 'file') == \
+ f'{petrel_dir}/dir/file'
+
+ # test `get_local_path`
+ with patch.object(petrel_backend.client._client, 'Get',
+ return_value=b'petrel') as mock_get, \
+ patch.object(petrel_backend.client._client, 'contains',
+ return_value=True) as mock_contains:
+ with petrel_backend.get_local_path(petrel_path) as path:
+ assert Path(path).open('rb').read() == b'petrel'
+ # exist the with block and path will be released
+ assert not osp.isfile(path)
+ mock_get.assert_called_once_with(petrel_path)
+ mock_contains.assert_called_once_with(petrel_path)
+
+ # test `list_dir_or_file`
+ assert has_method(petrel_backend.client._client, 'list')
+ with delete_and_reset_method(petrel_backend.client._client, 'list'):
+ assert not has_method(petrel_backend.client._client, 'list')
+ with pytest.raises(NotImplementedError):
+ list(petrel_backend.list_dir_or_file(petrel_dir))
+
+ with build_temporary_directory() as tmp_dir:
+ # 1. list directories and files
+ assert set(petrel_backend.list_dir_or_file(tmp_dir)) == {
+ 'dir1', 'dir2', 'text1.txt', 'text2.txt'
+ }
+ # 2. list directories and files recursively
+ assert set(
+ petrel_backend.list_dir_or_file(tmp_dir, recursive=True)) == {
+ 'dir1', '/'.join(('dir1', 'text3.txt')), 'dir2', '/'.join(
+ ('dir2', 'dir3')), '/'.join(
+ ('dir2', 'dir3', 'text4.txt')), '/'.join(
+ ('dir2', 'img.jpg')), 'text1.txt', 'text2.txt'
+ }
+ # 3. only list directories
+ assert set(
+ petrel_backend.list_dir_or_file(
+ tmp_dir, list_file=False)) == {'dir1', 'dir2'}
+ with pytest.raises(
+ TypeError,
+ match=('`list_dir` should be False when `suffix` is not '
+ 'None')):
+ # Exception is raised among the `list_dir_or_file` of client,
+ # so we need to invode the client to trigger the exception
+ petrel_backend.client.list_dir_or_file(
+ tmp_dir, list_file=False, suffix='.txt')
+ # 4. only list directories recursively
+ assert set(
+ petrel_backend.list_dir_or_file(
+ tmp_dir, list_file=False, recursive=True)) == {
+ 'dir1', 'dir2', '/'.join(('dir2', 'dir3'))
+ }
+ # 5. only list files
+ assert set(
+ petrel_backend.list_dir_or_file(
+ tmp_dir, list_dir=False)) == {'text1.txt', 'text2.txt'}
+ # 6. only list files recursively
+ assert set(
+ petrel_backend.list_dir_or_file(
+ tmp_dir, list_dir=False, recursive=True)) == {
+ '/'.join(('dir1', 'text3.txt')), '/'.join(
+ ('dir2', 'dir3', 'text4.txt')), '/'.join(
+ ('dir2', 'img.jpg')), 'text1.txt', 'text2.txt'
+ }
+ # 7. only list files ending with suffix
+ assert set(
+ petrel_backend.list_dir_or_file(
+ tmp_dir, list_dir=False,
+ suffix='.txt')) == {'text1.txt', 'text2.txt'}
+ assert set(
+ petrel_backend.list_dir_or_file(
+ tmp_dir, list_dir=False,
+ suffix=('.txt', '.jpg'))) == {'text1.txt', 'text2.txt'}
+ with pytest.raises(
+ TypeError,
+ match='`suffix` must be a string or tuple of strings'):
+ petrel_backend.client.list_dir_or_file(
+ tmp_dir, list_dir=False, suffix=['.txt', '.jpg'])
+ # 8. only list files ending with suffix recursively
+ assert set(
+ petrel_backend.list_dir_or_file(
+ tmp_dir, list_dir=False, suffix='.txt',
+ recursive=True)) == {
+ '/'.join(('dir1', 'text3.txt')), '/'.join(
+ ('dir2', 'dir3', 'text4.txt')), 'text1.txt',
+ 'text2.txt'
+ }
+ # 7. only list files ending with suffix
+ assert set(
+ petrel_backend.list_dir_or_file(
+ tmp_dir,
+ list_dir=False,
+ suffix=('.txt', '.jpg'),
+ recursive=True)) == {
+ '/'.join(('dir1', 'text3.txt')), '/'.join(
+ ('dir2', 'dir3', 'text4.txt')), '/'.join(
+ ('dir2', 'img.jpg')), 'text1.txt', 'text2.txt'
+ }
+
+ @patch('mc.MemcachedClient.GetInstance', MockMemcachedClient)
+ @patch('mc.pyvector', MagicMock)
+ @patch('mc.ConvertBuffer', lambda x: x.content)
+ def test_memcached_backend(self):
+ mc_cfg = dict(server_list_cfg='', client_cfg='', sys_path=None)
+ mc_backend = FileClient('memcached', **mc_cfg)
+
+ # test `allow_symlink` attribute
+ assert not mc_backend.allow_symlink
+
+ # input path is Path object
+ with pytest.raises(NotImplementedError):
+ mc_backend.get_text(self.text_path)
+ # input path is str
+ with pytest.raises(NotImplementedError):
+ mc_backend.get_text(str(self.text_path))
+
+ # input path is Path object
+ img_bytes = mc_backend.get(self.img_path)
+ img = imfrombytes(img_bytes)
+ assert img.shape == self.img_shape
+ # input path is str
+ img_bytes = mc_backend.get(str(self.img_path))
+ img = imfrombytes(img_bytes)
+ assert img.shape == self.img_shape
+
+ def test_lmdb_backend(self):
+ lmdb_path = self.test_data_dir / 'demo.lmdb'
+
+ # db_path is Path object
+ lmdb_backend = FileClient('lmdb', db_path=lmdb_path)
+
+ # test `allow_symlink` attribute
+ assert not lmdb_backend.allow_symlink
+
+ with pytest.raises(NotImplementedError):
+ lmdb_backend.get_text(self.text_path)
+
+ img_bytes = lmdb_backend.get('baboon')
+ img = imfrombytes(img_bytes)
+ assert img.shape == (120, 125, 3)
+
+ # db_path is str
+ lmdb_backend = FileClient('lmdb', db_path=str(lmdb_path))
+ with pytest.raises(NotImplementedError):
+ lmdb_backend.get_text(str(self.text_path))
+ img_bytes = lmdb_backend.get('baboon')
+ img = imfrombytes(img_bytes)
+ assert img.shape == (120, 125, 3)
+
+ @pytest.mark.parametrize('backend,prefix', [('http', None),
+ (None, 'http')])
+ def test_http_backend(self, backend, prefix):
+ http_backend = FileClient(backend=backend, prefix=prefix)
+ img_url = 'https://raw.githubusercontent.com/open-mmlab/mmcv/' \
+ 'master/tests/data/color.jpg'
+ text_url = 'https://raw.githubusercontent.com/open-mmlab/mmcv/' \
+ 'master/tests/data/filelist.txt'
+
+ # test `allow_symlink` attribute
+ assert not http_backend.allow_symlink
+
+ # input is path or Path object
+ with pytest.raises(Exception):
+ http_backend.get(self.img_path)
+ with pytest.raises(Exception):
+ http_backend.get(str(self.img_path))
+ with pytest.raises(Exception):
+ http_backend.get_text(self.text_path)
+ with pytest.raises(Exception):
+ http_backend.get_text(str(self.text_path))
+
+ # input url is http image
+ img_bytes = http_backend.get(img_url)
+ img = imfrombytes(img_bytes)
+ assert img.shape == self.img_shape
+
+ # input url is http text
+ value_buf = http_backend.get_text(text_url)
+ assert self.text_path.open('r').read() == value_buf
+
+ # test `_get_local_path`
+ # exist the with block and path will be released
+ with http_backend.get_local_path(img_url) as path:
+ img_bytes = Path(path).open('rb').read()
+ img = imfrombytes(img_bytes)
+ assert img.shape == self.img_shape
+ assert not osp.isfile(path)
+
+ def test_new_magic_method(self):
+
+ class DummyBackend1(BaseStorageBackend):
+
+ def get(self, filepath):
+ return filepath
+
+ def get_text(self, filepath, encoding='utf-8'):
+ return filepath
+
+ FileClient.register_backend('dummy_backend', DummyBackend1)
+ client1 = FileClient(backend='dummy_backend')
+ client2 = FileClient(backend='dummy_backend')
+ assert client1 is client2
+
+ # if a backend is overwrote, it will disable the singleton pattern for
+ # the backend
+ class DummyBackend2(BaseStorageBackend):
+
+ def get(self, filepath):
+ pass
+
+ def get_text(self, filepath):
+ pass
+
+ FileClient.register_backend('dummy_backend', DummyBackend2, force=True)
+ client3 = FileClient(backend='dummy_backend')
+ client4 = FileClient(backend='dummy_backend')
+ assert client2 is not client3
+ assert client3 is client4
+
+ def test_parse_uri_prefix(self):
+ # input path is None
+ with pytest.raises(AssertionError):
+ FileClient.parse_uri_prefix(None)
+ # input path is list
+ with pytest.raises(AssertionError):
+ FileClient.parse_uri_prefix([])
+
+ # input path is Path object
+ assert FileClient.parse_uri_prefix(self.img_path) is None
+ # input path is str
+ assert FileClient.parse_uri_prefix(str(self.img_path)) is None
+
+ # input path starts with https
+ img_url = 'https://raw.githubusercontent.com/open-mmlab/mmcv/' \
+ 'master/tests/data/color.jpg'
+ assert FileClient.parse_uri_prefix(img_url) == 'https'
+
+ # input path starts with s3
+ img_url = 's3://your_bucket/img.png'
+ assert FileClient.parse_uri_prefix(img_url) == 's3'
+
+ # input path starts with clusterName:s3
+ img_url = 'clusterName:s3://your_bucket/img.png'
+ assert FileClient.parse_uri_prefix(img_url) == 's3'
+
+ def test_infer_client(self):
+ # HardDiskBackend
+ file_client_args = {'backend': 'disk'}
+ client = FileClient.infer_client(file_client_args)
+ assert client.name == 'HardDiskBackend'
+ client = FileClient.infer_client(uri=self.img_path)
+ assert client.name == 'HardDiskBackend'
+
+ # PetrelBackend
+ file_client_args = {'backend': 'petrel'}
+ client = FileClient.infer_client(file_client_args)
+ assert client.name == 'PetrelBackend'
+ uri = 's3://user_data'
+ client = FileClient.infer_client(uri=uri)
+ assert client.name == 'PetrelBackend'
+
+ def test_register_backend(self):
+
+ # name must be a string
+ with pytest.raises(TypeError):
+
+ class TestClass1:
+ pass
+
+ FileClient.register_backend(1, TestClass1)
+
+ # module must be a class
+ with pytest.raises(TypeError):
+ FileClient.register_backend('int', 0)
+
+ # module must be a subclass of BaseStorageBackend
+ with pytest.raises(TypeError):
+
+ class TestClass1:
+ pass
+
+ FileClient.register_backend('TestClass1', TestClass1)
+
+ class ExampleBackend(BaseStorageBackend):
+
+ def get(self, filepath):
+ return filepath
+
+ def get_text(self, filepath, encoding='utf-8'):
+ return filepath
+
+ FileClient.register_backend('example', ExampleBackend)
+ example_backend = FileClient('example')
+ assert example_backend.get(self.img_path) == self.img_path
+ assert example_backend.get_text(self.text_path) == self.text_path
+ assert 'example' in FileClient._backends
+
+ class Example2Backend(BaseStorageBackend):
+
+ def get(self, filepath):
+ return b'bytes2'
+
+ def get_text(self, filepath, encoding='utf-8'):
+ return 'text2'
+
+ # force=False
+ with pytest.raises(KeyError):
+ FileClient.register_backend('example', Example2Backend)
+
+ FileClient.register_backend('example', Example2Backend, force=True)
+ example_backend = FileClient('example')
+ assert example_backend.get(self.img_path) == b'bytes2'
+ assert example_backend.get_text(self.text_path) == 'text2'
+
+ @FileClient.register_backend(name='example3')
+ class Example3Backend(BaseStorageBackend):
+
+ def get(self, filepath):
+ return b'bytes3'
+
+ def get_text(self, filepath, encoding='utf-8'):
+ return 'text3'
+
+ example_backend = FileClient('example3')
+ assert example_backend.get(self.img_path) == b'bytes3'
+ assert example_backend.get_text(self.text_path) == 'text3'
+ assert 'example3' in FileClient._backends
+
+ # force=False
+ with pytest.raises(KeyError):
+
+ @FileClient.register_backend(name='example3')
+ class Example4Backend(BaseStorageBackend):
+
+ def get(self, filepath):
+ return b'bytes4'
+
+ def get_text(self, filepath, encoding='utf-8'):
+ return 'text4'
+
+ @FileClient.register_backend(name='example3', force=True)
+ class Example5Backend(BaseStorageBackend):
+
+ def get(self, filepath):
+ return b'bytes5'
+
+ def get_text(self, filepath, encoding='utf-8'):
+ return 'text5'
+
+ example_backend = FileClient('example3')
+ assert example_backend.get(self.img_path) == b'bytes5'
+ assert example_backend.get_text(self.text_path) == 'text5'
+
+ # prefixes is a str
+ class Example6Backend(BaseStorageBackend):
+
+ def get(self, filepath):
+ return b'bytes6'
+
+ def get_text(self, filepath, encoding='utf-8'):
+ return 'text6'
+
+ FileClient.register_backend(
+ 'example4',
+ Example6Backend,
+ force=True,
+ prefixes='example4_prefix')
+ example_backend = FileClient('example4')
+ assert example_backend.get(self.img_path) == b'bytes6'
+ assert example_backend.get_text(self.text_path) == 'text6'
+ example_backend = FileClient(prefix='example4_prefix')
+ assert example_backend.get(self.img_path) == b'bytes6'
+ assert example_backend.get_text(self.text_path) == 'text6'
+ example_backend = FileClient('example4', prefix='example4_prefix')
+ assert example_backend.get(self.img_path) == b'bytes6'
+ assert example_backend.get_text(self.text_path) == 'text6'
+
+ # prefixes is a list of str
+ class Example7Backend(BaseStorageBackend):
+
+ def get(self, filepath):
+ return b'bytes7'
+
+ def get_text(self, filepath, encoding='utf-8'):
+ return 'text7'
+
+ FileClient.register_backend(
+ 'example5',
+ Example7Backend,
+ force=True,
+ prefixes=['example5_prefix1', 'example5_prefix2'])
+ example_backend = FileClient('example5')
+ assert example_backend.get(self.img_path) == b'bytes7'
+ assert example_backend.get_text(self.text_path) == 'text7'
+ example_backend = FileClient(prefix='example5_prefix1')
+ assert example_backend.get(self.img_path) == b'bytes7'
+ assert example_backend.get_text(self.text_path) == 'text7'
+ example_backend = FileClient(prefix='example5_prefix2')
+ assert example_backend.get(self.img_path) == b'bytes7'
+ assert example_backend.get_text(self.text_path) == 'text7'
+
+ # backend has a higher priority than prefixes
+ class Example8Backend(BaseStorageBackend):
+
+ def get(self, filepath):
+ return b'bytes8'
+
+ def get_text(self, filepath, encoding='utf-8'):
+ return 'text8'
+
+ FileClient.register_backend(
+ 'example6',
+ Example8Backend,
+ force=True,
+ prefixes='example6_prefix')
+ example_backend = FileClient('example6')
+ assert example_backend.get(self.img_path) == b'bytes8'
+ assert example_backend.get_text(self.text_path) == 'text8'
+ example_backend = FileClient('example6', prefix='example4_prefix')
+ assert example_backend.get(self.img_path) == b'bytes8'
+ assert example_backend.get_text(self.text_path) == 'text8'
diff --git a/testbed/open-mmlab__mmengine/tests/test_fileio/test_fileio.py b/testbed/open-mmlab__mmengine/tests/test_fileio/test_fileio.py
new file mode 100644
index 0000000000000000000000000000000000000000..33a0956fed982656aea45cbd26cdd12676d46633
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_fileio/test_fileio.py
@@ -0,0 +1,228 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import os.path as osp
+import sys
+import tempfile
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+import mmengine
+from mmengine.fileio import HTTPBackend, PetrelBackend
+
+sys.modules['petrel_client'] = MagicMock()
+sys.modules['petrel_client.client'] = MagicMock()
+
+test_data_dir = osp.dirname(osp.dirname(__file__))
+
+
+def _test_handler(file_format, test_obj, str_checker, mode='r+'):
+ # dump to a string
+ dump_str = mmengine.dump(test_obj, file_format=file_format)
+ str_checker(dump_str)
+
+ # load/dump with filenames from disk
+ tmp_filename = osp.join(tempfile.gettempdir(), 'mmengine_test_dump')
+ mmengine.dump(test_obj, tmp_filename, file_format=file_format)
+ assert osp.isfile(tmp_filename)
+ load_obj = mmengine.load(tmp_filename, file_format=file_format)
+ assert load_obj == test_obj
+ os.remove(tmp_filename)
+
+ # load/dump with filename from petrel
+ method = 'put' if 'b' in mode else 'put_text'
+ with patch.object(PetrelBackend, method, return_value=None) as mock_method:
+ filename = 's3://path/of/your/file'
+ mmengine.dump(test_obj, filename, file_format=file_format)
+ mock_method.assert_called()
+
+ # json load/dump with a file-like object
+ with tempfile.NamedTemporaryFile(mode, delete=False) as f:
+ tmp_filename = f.name
+ mmengine.dump(test_obj, f, file_format=file_format)
+ assert osp.isfile(tmp_filename)
+ with open(tmp_filename, mode) as f:
+ load_obj = mmengine.load(f, file_format=file_format)
+ assert load_obj == test_obj
+ os.remove(tmp_filename)
+
+ # automatically inference the file format from the given filename
+ tmp_filename = osp.join(tempfile.gettempdir(),
+ 'mmengine_test_dump.' + file_format)
+ mmengine.dump(test_obj, tmp_filename)
+ assert osp.isfile(tmp_filename)
+ load_obj = mmengine.load(tmp_filename)
+ assert load_obj == test_obj
+ os.remove(tmp_filename)
+
+
+obj_for_test = [{'a': 'abc', 'b': 1}, 2, 'c']
+
+
+def test_json():
+
+ def json_checker(dump_str):
+ assert dump_str in [
+ '[{"a": "abc", "b": 1}, 2, "c"]', '[{"b": 1, "a": "abc"}, 2, "c"]'
+ ]
+
+ _test_handler('json', obj_for_test, json_checker)
+
+
+def test_yaml():
+
+ def yaml_checker(dump_str):
+ assert dump_str in [
+ '- {a: abc, b: 1}\n- 2\n- c\n', '- {b: 1, a: abc}\n- 2\n- c\n',
+ '- a: abc\n b: 1\n- 2\n- c\n', '- b: 1\n a: abc\n- 2\n- c\n'
+ ]
+
+ _test_handler('yaml', obj_for_test, yaml_checker)
+
+
+def test_pickle():
+
+ def pickle_checker(dump_str):
+ import pickle
+ assert pickle.loads(dump_str) == obj_for_test
+
+ _test_handler('pickle', obj_for_test, pickle_checker, mode='rb+')
+
+
+def test_exception():
+ test_obj = [{'a': 'abc', 'b': 1}, 2, 'c']
+
+ with pytest.raises(ValueError):
+ mmengine.dump(test_obj)
+
+ with pytest.raises(TypeError):
+ mmengine.dump(test_obj, 'tmp.txt')
+
+
+def test_register_handler():
+
+ @mmengine.register_handler('txt')
+ class TxtHandler1(mmengine.BaseFileHandler):
+
+ def load_from_fileobj(self, file):
+ return file.read()
+
+ def dump_to_fileobj(self, obj, file):
+ file.write(str(obj))
+
+ def dump_to_str(self, obj, **kwargs):
+ return str(obj)
+
+ @mmengine.register_handler(['txt1', 'txt2'])
+ class TxtHandler2(mmengine.BaseFileHandler):
+
+ def load_from_fileobj(self, file):
+ return file.read()
+
+ def dump_to_fileobj(self, obj, file):
+ file.write('\n')
+ file.write(str(obj))
+
+ def dump_to_str(self, obj, **kwargs):
+ return str(obj)
+
+ content = mmengine.load(osp.join(test_data_dir, 'data/filelist.txt'))
+ assert content == '1.jpg\n2.jpg\n3.jpg\n4.jpg\n5.jpg'
+ tmp_filename = osp.join(tempfile.gettempdir(), 'mmengine_test.txt2')
+ mmengine.dump(content, tmp_filename)
+ with open(tmp_filename) as f:
+ written = f.read()
+ os.remove(tmp_filename)
+ assert written == '\n' + content
+
+
+def test_list_from_file():
+ # get list from disk
+ filename = osp.join(test_data_dir, 'data/filelist.txt')
+ filelist = mmengine.list_from_file(filename)
+ assert filelist == ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg']
+ filelist = mmengine.list_from_file(filename, prefix='a/')
+ assert filelist == ['a/1.jpg', 'a/2.jpg', 'a/3.jpg', 'a/4.jpg', 'a/5.jpg']
+ filelist = mmengine.list_from_file(filename, offset=2)
+ assert filelist == ['3.jpg', '4.jpg', '5.jpg']
+ filelist = mmengine.list_from_file(filename, max_num=2)
+ assert filelist == ['1.jpg', '2.jpg']
+ filelist = mmengine.list_from_file(filename, offset=3, max_num=3)
+ assert filelist == ['4.jpg', '5.jpg']
+
+ # get list from http
+ filename = 'http://path/of/your/file'
+ with patch.object(
+ HTTPBackend, 'get_text', return_value='1.jpg\n2.jpg\n3.jpg'):
+ filelist = mmengine.list_from_file(
+ filename, file_client_args={'backend': 'http'})
+ assert filelist == ['1.jpg', '2.jpg', '3.jpg']
+ filelist = mmengine.list_from_file(
+ filename, file_client_args={'prefix': 'http'})
+ assert filelist == ['1.jpg', '2.jpg', '3.jpg']
+
+ filelist = mmengine.list_from_file(filename)
+ assert filelist == ['1.jpg', '2.jpg', '3.jpg']
+ filelist = mmengine.list_from_file(
+ filename, backend_args={'backend': 'http'})
+ assert filelist == ['1.jpg', '2.jpg', '3.jpg']
+
+ # get list from petrel
+ filename = 's3://path/of/your/file'
+ with patch.object(
+ PetrelBackend, 'get_text', return_value='1.jpg\n2.jpg\n3.jpg'):
+ filelist = mmengine.list_from_file(
+ filename, file_client_args={'backend': 'petrel'})
+ assert filelist == ['1.jpg', '2.jpg', '3.jpg']
+ filelist = mmengine.list_from_file(
+ filename, file_client_args={'prefix': 's3'})
+ assert filelist == ['1.jpg', '2.jpg', '3.jpg']
+ filelist = mmengine.list_from_file(filename)
+ assert filelist == ['1.jpg', '2.jpg', '3.jpg']
+ filelist = mmengine.list_from_file(
+ filename, backend_args={'backend': 'petrel'})
+ assert filelist == ['1.jpg', '2.jpg', '3.jpg']
+
+
+def test_dict_from_file():
+ # get dict from disk
+ filename = osp.join(test_data_dir, 'data/mapping.txt')
+ mapping = mmengine.dict_from_file(filename)
+ assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
+ mapping = mmengine.dict_from_file(filename, key_type=int)
+ assert mapping == {1: 'cat', 2: ['dog', 'cow'], 3: 'panda'}
+
+ # get dict from http
+ filename = 'http://path/of/your/file'
+ with patch.object(
+ HTTPBackend, 'get_text', return_value='1 cat\n2 dog cow\n3 panda'):
+ mapping = mmengine.dict_from_file(
+ filename, file_client_args={'backend': 'http'})
+ assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
+ mapping = mmengine.dict_from_file(
+ filename, file_client_args={'prefix': 'http'})
+ assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
+
+ mapping = mmengine.dict_from_file(filename)
+ assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
+ mapping = mmengine.dict_from_file(
+ filename, backend_args={'backend': 'http'})
+ assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
+
+ # get dict from petrel
+ filename = 's3://path/of/your/file'
+ with patch.object(
+ PetrelBackend, 'get_text',
+ return_value='1 cat\n2 dog cow\n3 panda'):
+ mapping = mmengine.dict_from_file(
+ filename, file_client_args={'backend': 'petrel'})
+ assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
+ mapping = mmengine.dict_from_file(
+ filename, file_client_args={'prefix': 's3'})
+ assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
+
+ mapping = mmengine.dict_from_file(filename)
+ assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
+ mapping = mmengine.dict_from_file(
+ filename, backend_args={'backend': 'petrel'})
+ assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
diff --git a/testbed/open-mmlab__mmengine/tests/test_fileio/test_io.py b/testbed/open-mmlab__mmengine/tests/test_fileio/test_io.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e8698cc68fe710deaf8ecdec78f42a9f05940ed
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_fileio/test_io.py
@@ -0,0 +1,532 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import os.path as osp
+import platform
+import sys
+import tempfile
+from contextlib import contextmanager
+from pathlib import Path
+from shutil import SameFileError
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+import mmengine.fileio as fileio
+
+sys.modules['petrel_client'] = MagicMock()
+sys.modules['petrel_client.client'] = MagicMock()
+
+test_data_dir = Path(__file__).parent.parent / 'data'
+text_path = test_data_dir / 'filelist.txt'
+img_path = test_data_dir / 'color.jpg'
+img_url = 'https://raw.githubusercontent.com/mmengine/tests/data/img.png'
+
+
+@contextmanager
+def build_temporary_directory():
+ """Build a temporary directory containing many files to test
+ ``FileClient.list_dir_or_file``.
+
+ . \n
+ | -- dir1 \n
+ | -- | -- text3.txt \n
+ | -- dir2 \n
+ | -- | -- dir3 \n
+ | -- | -- | -- text4.txt \n
+ | -- | -- img.jpg \n
+ | -- text1.txt \n
+ | -- text2.txt \n
+ """
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ text1 = Path(tmp_dir) / 'text1.txt'
+ text1.open('w').write('text1')
+ text2 = Path(tmp_dir) / 'text2.txt'
+ text2.open('w').write('text2')
+ dir1 = Path(tmp_dir) / 'dir1'
+ dir1.mkdir()
+ text3 = dir1 / 'text3.txt'
+ text3.open('w').write('text3')
+ dir2 = Path(tmp_dir) / 'dir2'
+ dir2.mkdir()
+ jpg1 = dir2 / 'img.jpg'
+ jpg1.open('wb').write(b'img')
+ dir3 = dir2 / 'dir3'
+ dir3.mkdir()
+ text4 = dir3 / 'text4.txt'
+ text4.open('w').write('text4')
+ yield tmp_dir
+
+
+def test_parse_uri_prefix():
+ # input path is None
+ with pytest.raises(AssertionError):
+ fileio.io._parse_uri_prefix(None)
+
+ # input path is list
+ with pytest.raises(AssertionError):
+ fileio.io._parse_uri_prefix([])
+
+ # input path is Path object
+ assert fileio.io._parse_uri_prefix(uri=text_path) == ''
+
+ # input path starts with https
+ assert fileio.io._parse_uri_prefix(uri=img_url) == 'https'
+
+ # input path starts with s3
+ uri = 's3://your_bucket/img.png'
+ assert fileio.io._parse_uri_prefix(uri) == 's3'
+
+ # input path starts with clusterName:s3
+ uri = 'clusterName:s3://your_bucket/img.png'
+ assert fileio.io._parse_uri_prefix(uri) == 's3'
+
+
+def test_get_file_backend():
+ # other unit tests may have added instances so clear them here.
+ fileio.io.backend_instances = {}
+
+ # uri should not be None when "backend" does not exist in backend_args
+ with pytest.raises(ValueError, match='uri should not be None'):
+ fileio.get_file_backend(None, backend_args=None)
+
+ # uri is not None
+ backend = fileio.get_file_backend(uri=text_path)
+ assert isinstance(backend, fileio.backends.LocalBackend)
+
+ uri = 'petrel://your_bucket/img.png'
+ backend = fileio.get_file_backend(uri=uri)
+ assert isinstance(backend, fileio.backends.PetrelBackend)
+
+ backend = fileio.get_file_backend(uri=img_url)
+ assert isinstance(backend, fileio.backends.HTTPBackend)
+ uri = 'http://raw.githubusercontent.com/mmengine/tests/data/img.png'
+ backend = fileio.get_file_backend(uri=uri)
+ assert isinstance(backend, fileio.backends.HTTPBackend)
+
+ # backend_args is not None and it contains a backend name
+ backend_args = {'backend': 'local'}
+ backend = fileio.get_file_backend(uri=None, backend_args=backend_args)
+ assert isinstance(backend, fileio.backends.LocalBackend)
+
+ backend_args = {'backend': 'petrel', 'enable_mc': True}
+ backend = fileio.get_file_backend(uri=None, backend_args=backend_args)
+ assert isinstance(backend, fileio.backends.PetrelBackend)
+
+ # backend name has a higher priority
+ backend_args = {'backend': 'http'}
+ backend = fileio.get_file_backend(uri=text_path, backend_args=backend_args)
+ assert isinstance(backend, fileio.backends.HTTPBackend)
+
+ # test enable_singleton parameter
+ assert len(fileio.io.backend_instances) == 0
+ backend1 = fileio.get_file_backend(uri=text_path, enable_singleton=True)
+ assert isinstance(backend1, fileio.backends.LocalBackend)
+ assert len(fileio.io.backend_instances) == 1
+ assert fileio.io.backend_instances[':{}'] is backend1
+
+ backend2 = fileio.get_file_backend(uri=text_path, enable_singleton=True)
+ assert isinstance(backend2, fileio.backends.LocalBackend)
+ assert len(fileio.io.backend_instances) == 1
+ assert backend2 is backend1
+
+ backend3 = fileio.get_file_backend(uri=text_path, enable_singleton=False)
+ assert isinstance(backend3, fileio.backends.LocalBackend)
+ assert len(fileio.io.backend_instances) == 1
+ assert backend3 is not backend2
+
+ backend_args = {'path_mapping': {'src': 'dst'}, 'enable_mc': True}
+ uri = 'petrel://your_bucket/img.png'
+ backend4 = fileio.get_file_backend(
+ uri=uri, backend_args=backend_args, enable_singleton=True)
+ assert isinstance(backend4, fileio.backends.PetrelBackend)
+ assert len(fileio.io.backend_instances) == 2
+ unique_key = 'petrel:{"path_mapping": {"src": "dst"}, "enable_mc": true}'
+ assert fileio.io.backend_instances[unique_key] is backend4
+ assert backend4 is not backend2
+
+ uri = 'petrel://your_bucket/img1.png'
+ backend5 = fileio.get_file_backend(
+ uri=uri, backend_args=backend_args, enable_singleton=True)
+ assert isinstance(backend5, fileio.backends.PetrelBackend)
+ assert len(fileio.io.backend_instances) == 2
+ assert backend5 is backend4
+ assert backend5 is not backend2
+
+ backend_args = {'path_mapping': {'src1': 'dst1'}, 'enable_mc': True}
+ backend6 = fileio.get_file_backend(
+ uri=uri, backend_args=backend_args, enable_singleton=True)
+ assert isinstance(backend6, fileio.backends.PetrelBackend)
+ assert len(fileio.io.backend_instances) == 3
+ unique_key = 'petrel:{"path_mapping": {"src1": "dst1"}, "enable_mc": true}'
+ assert fileio.io.backend_instances[unique_key] is backend6
+ assert backend6 is not backend4
+ assert backend6 is not backend5
+
+ backend7 = fileio.get_file_backend(
+ uri=uri, backend_args=backend_args, enable_singleton=False)
+ assert isinstance(backend7, fileio.backends.PetrelBackend)
+ assert len(fileio.io.backend_instances) == 3
+ assert backend7 is not backend6
+
+
+def test_get():
+ # test LocalBackend
+ filepath = Path(img_path)
+ img_bytes = fileio.get(filepath)
+ assert filepath.open('rb').read() == img_bytes
+
+
+def test_get_text():
+ # test LocalBackend
+ filepath = Path(text_path)
+ text = fileio.get_text(filepath)
+ assert filepath.open('r').read() == text
+
+
+def test_put():
+ # test LocalBackend
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ filepath = Path(tmp_dir) / 'img.png'
+ fileio.put(b'disk', filepath)
+ assert fileio.get(filepath) == b'disk'
+
+ # If the directory does not exist, put will create a
+ # directory first
+ filepath = Path(tmp_dir) / 'not_existed_dir' / 'test.jpg'
+ fileio.put(b'disk', filepath)
+ assert fileio.get(filepath) == b'disk'
+
+
+def test_put_text():
+ # test LocalBackend
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ filepath = Path(tmp_dir) / 'text.txt'
+ fileio.put_text('text', filepath)
+ assert fileio.get_text(filepath) == 'text'
+
+ # If the directory does not exist, put_text will create a
+ # directory first
+ filepath = Path(tmp_dir) / 'not_existed_dir' / 'test.txt'
+ fileio.put_text('disk', filepath)
+ assert fileio.get_text(filepath) == 'disk'
+
+
+def test_exists():
+ # test LocalBackend
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ assert fileio.exists(tmp_dir)
+ filepath = Path(tmp_dir) / 'test.txt'
+ assert not fileio.exists(filepath)
+ fileio.put_text('disk', filepath)
+ assert fileio.exists(filepath)
+
+
+def test_isdir():
+ # test LocalBackend
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ assert fileio.isdir(tmp_dir)
+ filepath = Path(tmp_dir) / 'test.txt'
+ fileio.put_text('disk', filepath)
+ assert not fileio.isdir(filepath)
+
+
+def test_isfile():
+ # test LocalBackend
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ assert not fileio.isfile(tmp_dir)
+ filepath = Path(tmp_dir) / 'test.txt'
+ fileio.put_text('disk', filepath)
+ assert fileio.isfile(filepath)
+
+
+def test_join_path():
+ # test LocalBackend
+ filepath = fileio.join_path(test_data_dir, 'file')
+ expected = osp.join(test_data_dir, 'file')
+ assert filepath == expected
+
+ filepath = fileio.join_path(test_data_dir, 'dir', 'file')
+ expected = osp.join(test_data_dir, 'dir', 'file')
+ assert filepath == expected
+
+
+def test_get_local_path():
+ # test LocalBackend
+ with fileio.get_local_path(text_path) as filepath:
+ assert str(text_path) == filepath
+
+
+def test_copyfile():
+ # test LocalBackend
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ src = Path(tmp_dir) / 'test.txt'
+ fileio.put_text('disk', src)
+ dst = Path(tmp_dir) / 'test.txt.bak'
+ assert fileio.copyfile(src, dst) == dst
+ assert fileio.get_text(dst) == 'disk'
+
+ # dst is a directory
+ dst = Path(tmp_dir) / 'dir'
+ dst.mkdir()
+ assert fileio.copyfile(src, dst) == fileio.join_path(dst, 'test.txt')
+ assert fileio.get_text(fileio.join_path(dst, 'test.txt')) == 'disk'
+
+ # src and src should not be same file
+ with pytest.raises(SameFileError):
+ fileio.copyfile(src, src)
+
+
+def test_copytree():
+ # test LocalBackend
+ with build_temporary_directory() as tmp_dir:
+ # src and dst are Path objects
+ src = Path(tmp_dir) / 'dir1'
+ dst = Path(tmp_dir) / 'dir100'
+ assert fileio.copytree(src, dst) == dst
+ assert fileio.isdir(dst)
+ assert fileio.isfile(dst / 'text3.txt')
+ assert fileio.get_text(dst / 'text3.txt') == 'text3'
+
+ # dst should not exist
+ with pytest.raises(FileExistsError):
+ fileio.copytree(src, Path(tmp_dir) / 'dir2')
+
+
+def test_copyfile_from_local():
+ # test LocalBackend
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ src = Path(tmp_dir) / 'test.txt'
+ fileio.put_text('disk', src)
+ dst = Path(tmp_dir) / 'test.txt.bak'
+ assert fileio.copyfile(src, dst) == dst
+ assert fileio.get_text(dst) == 'disk'
+
+ dst = Path(tmp_dir) / 'dir'
+ dst.mkdir()
+ assert fileio.copyfile(src, dst) == fileio.join_path(dst, 'test.txt')
+ assert fileio.get_text(fileio.join_path(dst, 'test.txt')) == 'disk'
+
+ # src and src should not be same file
+ with pytest.raises(SameFileError):
+ fileio.copyfile(src, src)
+
+
+def test_copytree_from_local():
+ # test LocalBackend
+ with build_temporary_directory() as tmp_dir:
+ # src and dst are Path objects
+ src = Path(tmp_dir) / 'dir1'
+ dst = Path(tmp_dir) / 'dir100'
+ assert fileio.copytree(src, dst) == dst
+ assert fileio.isdir(dst)
+ assert fileio.isfile(dst / 'text3.txt')
+ assert fileio.get_text(dst / 'text3.txt') == 'text3'
+
+ # dst should not exist
+ with pytest.raises(FileExistsError):
+ fileio.copytree(src, Path(tmp_dir) / 'dir2')
+
+
+def test_copyfile_to_local():
+ # test LocalBackend
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ src = Path(tmp_dir) / 'test.txt'
+ fileio.put_text('disk', src)
+ dst = Path(tmp_dir) / 'test.txt.bak'
+ assert fileio.copyfile(src, dst) == dst
+ assert fileio.get_text(dst) == 'disk'
+
+ dst = Path(tmp_dir) / 'dir'
+ dst.mkdir()
+ assert fileio.copyfile(src, dst) == fileio.join_path(dst, 'test.txt')
+ assert fileio.get_text(fileio.join_path(dst, 'test.txt')) == 'disk'
+
+ # src and src should not be same file
+ with pytest.raises(SameFileError):
+ fileio.copyfile(src, src)
+
+
+def test_copytree_to_local():
+ # test LocalBackend
+ with build_temporary_directory() as tmp_dir:
+ # src and dst are Path objects
+ src = Path(tmp_dir) / 'dir1'
+ dst = Path(tmp_dir) / 'dir100'
+ assert fileio.copytree(src, dst) == dst
+ assert fileio.isdir(dst)
+ assert fileio.isfile(dst / 'text3.txt')
+ assert fileio.get_text(dst / 'text3.txt') == 'text3'
+
+ # dst should not exist
+ with pytest.raises(FileExistsError):
+ fileio.copytree(src, Path(tmp_dir) / 'dir2')
+
+
+def test_remove():
+ # test LocalBackend
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ # filepath is a Path object
+ filepath = Path(tmp_dir) / 'test.txt'
+ fileio.put_text('disk', filepath)
+ assert fileio.exists(filepath)
+ fileio.remove(filepath)
+ assert not fileio.exists(filepath)
+
+ # raise error if file does not exist
+ with pytest.raises(FileNotFoundError):
+ filepath = Path(tmp_dir) / 'test1.txt'
+ fileio.remove(filepath)
+
+ # can not remove directory
+ filepath = Path(tmp_dir) / 'dir'
+ filepath.mkdir()
+ with pytest.raises(IsADirectoryError):
+ fileio.remove(filepath)
+
+
+def test_rmtree():
+ # test LocalBackend
+ with build_temporary_directory() as tmp_dir:
+ # src and dst are Path objects
+ dir_path = Path(tmp_dir) / 'dir1'
+ assert fileio.exists(dir_path)
+ fileio.rmtree(dir_path)
+ assert not fileio.exists(dir_path)
+
+ dir_path = Path(tmp_dir) / 'dir2'
+ assert fileio.exists(dir_path)
+ fileio.rmtree(dir_path)
+ assert not fileio.exists(dir_path)
+
+
+def test_copy_if_symlink_fails():
+ # test LocalBackend
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ # create a symlink for a file
+ src = Path(tmp_dir) / 'test.txt'
+ fileio.put_text('disk', src)
+ dst = Path(tmp_dir) / 'test_link.txt'
+ res = fileio.copy_if_symlink_fails(src, dst)
+ if platform.system() == 'Linux':
+ assert res
+ assert osp.islink(dst)
+ assert fileio.get_text(dst) == 'disk'
+
+ # create a symlink for a directory
+ src = Path(tmp_dir) / 'dir'
+ src.mkdir()
+ dst = Path(tmp_dir) / 'dir_link'
+ res = fileio.copy_if_symlink_fails(src, dst)
+ if platform.system() == 'Linux':
+ assert res
+ assert osp.islink(dst)
+ assert fileio.exists(dst)
+
+ def symlink(src, dst):
+ raise Exception
+
+ # copy files if symblink fails
+ with patch.object(os, 'symlink', side_effect=symlink):
+ src = Path(tmp_dir) / 'test.txt'
+ dst = Path(tmp_dir) / 'test_link1.txt'
+ res = fileio.copy_if_symlink_fails(src, dst)
+ assert not res
+ assert not osp.islink(dst)
+ assert fileio.exists(dst)
+
+ # copy directory if symblink fails
+ with patch.object(os, 'symlink', side_effect=symlink):
+ src = Path(tmp_dir) / 'dir'
+ dst = Path(tmp_dir) / 'dir_link1'
+ res = fileio.copy_if_symlink_fails(src, dst)
+ assert not res
+ assert not osp.islink(dst)
+ assert fileio.exists(dst)
+
+
+def test_list_dir_or_file():
+ # test LocalBackend
+ with build_temporary_directory() as tmp_dir:
+ # list directories and files
+ assert set(fileio.list_dir_or_file(tmp_dir)) == {
+ 'dir1', 'dir2', 'text1.txt', 'text2.txt'
+ }
+
+ # list directories and files recursively
+ assert set(fileio.list_dir_or_file(tmp_dir, recursive=True)) == {
+ 'dir1',
+ osp.join('dir1', 'text3.txt'), 'dir2',
+ osp.join('dir2', 'dir3'),
+ osp.join('dir2', 'dir3', 'text4.txt'),
+ osp.join('dir2', 'img.jpg'), 'text1.txt', 'text2.txt'
+ }
+
+ # only list directories
+ assert set(fileio.list_dir_or_file(
+ tmp_dir, list_file=False)) == {'dir1', 'dir2'}
+
+ with pytest.raises(
+ TypeError,
+ match='`suffix` should be None when `list_dir` is True'):
+ list(
+ fileio.list_dir_or_file(
+ tmp_dir, list_file=False, suffix='.txt'))
+
+ # only list directories recursively
+ assert set(
+ fileio.list_dir_or_file(
+ tmp_dir, list_file=False,
+ recursive=True)) == {'dir1', 'dir2',
+ osp.join('dir2', 'dir3')}
+
+ # only list files
+ assert set(fileio.list_dir_or_file(
+ tmp_dir, list_dir=False)) == {'text1.txt', 'text2.txt'}
+
+ # only list files recursively
+ assert set(
+ fileio.list_dir_or_file(tmp_dir, list_dir=False,
+ recursive=True)) == {
+ osp.join('dir1', 'text3.txt'),
+ osp.join('dir2', 'dir3', 'text4.txt'),
+ osp.join('dir2', 'img.jpg'),
+ 'text1.txt', 'text2.txt'
+ }
+
+ # only list files ending with suffix
+ assert set(
+ fileio.list_dir_or_file(
+ tmp_dir, list_dir=False,
+ suffix='.txt')) == {'text1.txt', 'text2.txt'}
+ assert set(
+ fileio.list_dir_or_file(
+ tmp_dir, list_dir=False,
+ suffix=('.txt', '.jpg'))) == {'text1.txt', 'text2.txt'}
+
+ with pytest.raises(
+ TypeError,
+ match='`suffix` must be a string or tuple of strings'):
+ list(
+ fileio.list_dir_or_file(
+ tmp_dir, list_dir=False, suffix=['.txt', '.jpg']))
+
+ # only list files ending with suffix recursively
+ assert set(
+ fileio.list_dir_or_file(
+ tmp_dir, list_dir=False, suffix='.txt', recursive=True)) == {
+ osp.join('dir1', 'text3.txt'),
+ osp.join('dir2', 'dir3', 'text4.txt'), 'text1.txt',
+ 'text2.txt'
+ }
+
+ # only list files ending with suffix
+ assert set(
+ fileio.list_dir_or_file(
+ tmp_dir,
+ list_dir=False,
+ suffix=('.txt', '.jpg'),
+ recursive=True)) == {
+ osp.join('dir1', 'text3.txt'),
+ osp.join('dir2', 'dir3', 'text4.txt'),
+ osp.join('dir2', 'img.jpg'), 'text1.txt', 'text2.txt'
+ }
diff --git a/testbed/open-mmlab__mmengine/tests/test_hooks/test_checkpoint_hook.py b/testbed/open-mmlab__mmengine/tests/test_hooks/test_checkpoint_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..8fbb1a56db89e2769cfea01401eb054a20f579f1
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_hooks/test_checkpoint_hook.py
@@ -0,0 +1,499 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import os.path as osp
+from unittest.mock import Mock
+
+import pytest
+import torch
+import torch.nn as nn
+from torch.utils.data import Dataset
+
+from mmengine.evaluator import BaseMetric
+from mmengine.fileio import FileClient, LocalBackend
+from mmengine.hooks import CheckpointHook
+from mmengine.logging import MessageHub
+from mmengine.model import BaseModel
+from mmengine.optim import OptimWrapper
+from mmengine.runner import Runner
+
+
+class ToyModel(BaseModel):
+
+ def __init__(self):
+ super().__init__()
+ self.linear = nn.Linear(2, 1)
+
+ def forward(self, inputs, data_sample, mode='tensor'):
+ labels = torch.stack(data_sample)
+ inputs = torch.stack(inputs)
+ outputs = self.linear(inputs)
+ if mode == 'tensor':
+ return outputs
+ elif mode == 'loss':
+ loss = (labels - outputs).sum()
+ outputs = dict(loss=loss)
+ return outputs
+ else:
+ return outputs
+
+
+class DummyDataset(Dataset):
+ METAINFO = dict() # type: ignore
+ data = torch.randn(12, 2)
+ label = torch.ones(12)
+
+ @property
+ def metainfo(self):
+ return self.METAINFO
+
+ def __len__(self):
+ return self.data.size(0)
+
+ def __getitem__(self, index):
+ return dict(inputs=self.data[index], data_sample=self.label[index])
+
+
+class TriangleMetric(BaseMetric):
+
+ default_prefix: str = 'test'
+
+ def __init__(self, length):
+ super().__init__()
+ self.length = length
+ self.best_idx = length // 2
+ self.cur_idx = 0
+
+ def process(self, *args, **kwargs):
+ self.results.append(0)
+
+ def compute_metrics(self, *args, **kwargs):
+ self.cur_idx += 1
+ acc = 1.0 - abs(self.cur_idx - self.best_idx) / self.length
+ return dict(acc=acc)
+
+
+class TestCheckpointHook:
+
+ def test_init(self, tmp_path):
+ # Test file_client_args and backend_args
+ with pytest.warns(
+ DeprecationWarning,
+ match='"file_client_args" will be deprecated in future'):
+ CheckpointHook(file_client_args={'backend': 'disk'})
+
+ with pytest.raises(
+ ValueError,
+ match='"file_client_args" and "backend_args" cannot be set '
+ 'at the same time'):
+ CheckpointHook(
+ file_client_args={'backend': 'disk'},
+ backend_args={'backend': 'local'})
+
+ def test_before_train(self, tmp_path):
+ runner = Mock()
+ work_dir = str(tmp_path)
+ runner.work_dir = work_dir
+
+ # file_client_args is None
+ checkpoint_hook = CheckpointHook()
+ checkpoint_hook.before_train(runner)
+ assert isinstance(checkpoint_hook.file_client, FileClient)
+ assert isinstance(checkpoint_hook.file_backend, LocalBackend)
+
+ # file_client_args is not None
+ checkpoint_hook = CheckpointHook(file_client_args={'backend': 'disk'})
+ checkpoint_hook.before_train(runner)
+ assert isinstance(checkpoint_hook.file_client, FileClient)
+ # file_backend is the alias of file_client
+ assert checkpoint_hook.file_backend is checkpoint_hook.file_client
+
+ # the out_dir of the checkpoint hook is None
+ checkpoint_hook = CheckpointHook(interval=1, by_epoch=True)
+ checkpoint_hook.before_train(runner)
+ assert checkpoint_hook.out_dir == runner.work_dir
+
+ # the out_dir of the checkpoint hook is not None
+ checkpoint_hook = CheckpointHook(
+ interval=1, by_epoch=True, out_dir='test_dir')
+ checkpoint_hook.before_train(runner)
+ assert checkpoint_hook.out_dir == osp.join(
+ 'test_dir', osp.join(osp.basename(work_dir)))
+
+ runner.message_hub = MessageHub.get_instance('test_before_train')
+ # no 'best_ckpt_path' in runtime_info
+ checkpoint_hook = CheckpointHook(interval=1, save_best=['acc', 'mIoU'])
+ checkpoint_hook.before_train(runner)
+ assert checkpoint_hook.best_ckpt_path_dict == dict(acc=None, mIoU=None)
+ assert not hasattr(checkpoint_hook, 'best_ckpt_path')
+
+ # only one 'best_ckpt_path' in runtime_info
+ runner.message_hub.update_info('best_ckpt_acc', 'best_acc')
+ checkpoint_hook.before_train(runner)
+ assert checkpoint_hook.best_ckpt_path_dict == dict(
+ acc='best_acc', mIoU=None)
+
+ # no 'best_ckpt_path' in runtime_info
+ checkpoint_hook = CheckpointHook(interval=1, save_best='acc')
+ checkpoint_hook.before_train(runner)
+ assert checkpoint_hook.best_ckpt_path is None
+ assert not hasattr(checkpoint_hook, 'best_ckpt_path_dict')
+
+ # 'best_ckpt_path' in runtime_info
+ runner.message_hub.update_info('best_ckpt', 'best_ckpt')
+ checkpoint_hook.before_train(runner)
+ assert checkpoint_hook.best_ckpt_path == 'best_ckpt'
+
+ def test_after_val_epoch(self, tmp_path):
+ runner = Mock()
+ runner.work_dir = tmp_path
+ runner.epoch = 9
+ runner.model = Mock()
+ runner.message_hub = MessageHub.get_instance('test_after_val_epoch')
+
+ with pytest.raises(ValueError):
+ # key_indicator must be valid when rule_map is None
+ CheckpointHook(interval=2, by_epoch=True, save_best='unsupport')
+
+ with pytest.raises(KeyError):
+ # rule must be in keys of rule_map
+ CheckpointHook(
+ interval=2, by_epoch=True, save_best='auto', rule='unsupport')
+
+ # if eval_res is an empty dict, print a warning information
+ with pytest.warns(UserWarning) as record_warnings:
+ eval_hook = CheckpointHook(
+ interval=2, by_epoch=True, save_best='auto')
+ eval_hook._get_metric_score(None, None)
+ # Since there will be many warnings thrown, we just need to check
+ # if the expected exceptions are thrown
+ expected_message = (
+ 'Since `eval_res` is an empty dict, the behavior to '
+ 'save the best checkpoint will be skipped in this '
+ 'evaluation.')
+ for warning in record_warnings:
+ if str(warning.message) == expected_message:
+ break
+ else:
+ assert False
+
+ # test error when number of rules and metrics are not same
+ with pytest.raises(AssertionError) as assert_error:
+ CheckpointHook(
+ interval=1,
+ save_best=['mIoU', 'acc'],
+ rule=['greater', 'greater', 'less'],
+ by_epoch=True)
+ error_message = ('Number of "rule" must be 1 or the same as number of '
+ '"save_best", but got 3.')
+ assert error_message in str(assert_error.value)
+
+ # if save_best is None,no best_ckpt meta should be stored
+ eval_hook = CheckpointHook(interval=2, by_epoch=True, save_best=None)
+ eval_hook.before_train(runner)
+ eval_hook.after_val_epoch(runner, None)
+ assert 'best_score' not in runner.message_hub.runtime_info
+ assert 'best_ckpt' not in runner.message_hub.runtime_info
+
+ # when `save_best` is set to `auto`, first metric will be used.
+ metrics = {'acc': 0.5, 'map': 0.3}
+ eval_hook = CheckpointHook(interval=2, by_epoch=True, save_best='auto')
+ eval_hook.before_train(runner)
+ eval_hook.after_val_epoch(runner, metrics)
+ best_ckpt_name = 'best_acc_epoch_9.pth'
+ best_ckpt_path = eval_hook.file_client.join_path(
+ eval_hook.out_dir, best_ckpt_name)
+ assert eval_hook.key_indicators == ['acc']
+ assert eval_hook.rules == ['greater']
+ assert 'best_score' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_score') == 0.5
+ assert 'best_ckpt' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_ckpt') == best_ckpt_path
+
+ # # when `save_best` is set to `acc`, it should update greater value
+ eval_hook = CheckpointHook(interval=2, by_epoch=True, save_best='acc')
+ eval_hook.before_train(runner)
+ metrics['acc'] = 0.8
+ eval_hook.after_val_epoch(runner, metrics)
+ assert 'best_score' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_score') == 0.8
+
+ # # when `save_best` is set to `loss`, it should update less value
+ eval_hook = CheckpointHook(interval=2, by_epoch=True, save_best='loss')
+ eval_hook.before_train(runner)
+ metrics['loss'] = 0.8
+ eval_hook.after_val_epoch(runner, metrics)
+ metrics['loss'] = 0.5
+ eval_hook.after_val_epoch(runner, metrics)
+ assert 'best_score' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_score') == 0.5
+
+ # when `rule` is set to `less`,then it should update less value
+ # no matter what `save_best` is
+ eval_hook = CheckpointHook(
+ interval=2, by_epoch=True, save_best='acc', rule='less')
+ eval_hook.before_train(runner)
+ metrics['acc'] = 0.3
+ eval_hook.after_val_epoch(runner, metrics)
+ assert 'best_score' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_score') == 0.3
+
+ # # when `rule` is set to `greater`,then it should update greater value
+ # # no matter what `save_best` is
+ eval_hook = CheckpointHook(
+ interval=2, by_epoch=True, save_best='loss', rule='greater')
+ eval_hook.before_train(runner)
+ metrics['loss'] = 1.0
+ eval_hook.after_val_epoch(runner, metrics)
+ assert 'best_score' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_score') == 1.0
+
+ # test multi `save_best` with one rule
+ eval_hook = CheckpointHook(
+ interval=2, save_best=['acc', 'mIoU'], rule='greater')
+ assert eval_hook.key_indicators == ['acc', 'mIoU']
+ assert eval_hook.rules == ['greater', 'greater']
+
+ # test multi `save_best` with multi rules
+ eval_hook = CheckpointHook(
+ interval=2, save_best=['FID', 'IS'], rule=['less', 'greater'])
+ assert eval_hook.key_indicators == ['FID', 'IS']
+ assert eval_hook.rules == ['less', 'greater']
+
+ # test multi `save_best` with default rule
+ eval_hook = CheckpointHook(interval=2, save_best=['acc', 'mIoU'])
+ assert eval_hook.key_indicators == ['acc', 'mIoU']
+ assert eval_hook.rules == ['greater', 'greater']
+ runner.message_hub = MessageHub.get_instance(
+ 'test_after_val_epoch_save_multi_best')
+ eval_hook.before_train(runner)
+ metrics = dict(acc=0.5, mIoU=0.6)
+ eval_hook.after_val_epoch(runner, metrics)
+ best_acc_name = 'best_acc_epoch_9.pth'
+ best_acc_path = eval_hook.file_client.join_path(
+ eval_hook.out_dir, best_acc_name)
+ best_mIoU_name = 'best_mIoU_epoch_9.pth'
+ best_mIoU_path = eval_hook.file_client.join_path(
+ eval_hook.out_dir, best_mIoU_name)
+ assert 'best_score_acc' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_score_acc') == 0.5
+ assert 'best_score_mIoU' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_score_mIoU') == 0.6
+ assert 'best_ckpt_acc' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_ckpt_acc') == best_acc_path
+ assert 'best_ckpt_mIoU' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_ckpt_mIoU') == best_mIoU_path
+
+ # test behavior when by_epoch is False
+ runner = Mock()
+ runner.work_dir = tmp_path
+ runner.iter = 9
+ runner.model = Mock()
+ runner.message_hub = MessageHub.get_instance(
+ 'test_after_val_epoch_by_epoch_is_false')
+
+ # check best ckpt name and best score
+ metrics = {'acc': 0.5, 'map': 0.3}
+ eval_hook = CheckpointHook(
+ interval=2, by_epoch=False, save_best='acc', rule='greater')
+ eval_hook.before_train(runner)
+ eval_hook.after_val_epoch(runner, metrics)
+ assert eval_hook.key_indicators == ['acc']
+ assert eval_hook.rules == ['greater']
+ best_ckpt_name = 'best_acc_iter_9.pth'
+ best_ckpt_path = eval_hook.file_client.join_path(
+ eval_hook.out_dir, best_ckpt_name)
+ assert 'best_ckpt' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_ckpt') == best_ckpt_path
+ assert 'best_score' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_score') == 0.5
+
+ # check best score updating
+ metrics['acc'] = 0.666
+ eval_hook.after_val_epoch(runner, metrics)
+ best_ckpt_name = 'best_acc_iter_9.pth'
+ best_ckpt_path = eval_hook.file_client.join_path(
+ eval_hook.out_dir, best_ckpt_name)
+ assert 'best_ckpt' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_ckpt') == best_ckpt_path
+ assert 'best_score' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_score') == 0.666
+ # error when 'auto' in `save_best` list
+ with pytest.raises(AssertionError):
+ CheckpointHook(interval=2, save_best=['auto', 'acc'])
+ # error when one `save_best` with multi `rule`
+ with pytest.raises(AssertionError):
+ CheckpointHook(
+ interval=2, save_best='acc', rule=['greater', 'less'])
+
+ # check best checkpoint name with `by_epoch` is False
+ eval_hook = CheckpointHook(
+ interval=2, by_epoch=False, save_best=['acc', 'mIoU'])
+ assert eval_hook.key_indicators == ['acc', 'mIoU']
+ assert eval_hook.rules == ['greater', 'greater']
+ runner.message_hub = MessageHub.get_instance(
+ 'test_after_val_epoch_save_multi_best_by_epoch_is_false')
+ eval_hook.before_train(runner)
+ metrics = dict(acc=0.5, mIoU=0.6)
+ eval_hook.after_val_epoch(runner, metrics)
+ best_acc_name = 'best_acc_iter_9.pth'
+ best_acc_path = eval_hook.file_client.join_path(
+ eval_hook.out_dir, best_acc_name)
+ best_mIoU_name = 'best_mIoU_iter_9.pth'
+ best_mIoU_path = eval_hook.file_client.join_path(
+ eval_hook.out_dir, best_mIoU_name)
+ assert 'best_score_acc' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_score_acc') == 0.5
+ assert 'best_score_mIoU' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_score_mIoU') == 0.6
+ assert 'best_ckpt_acc' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_ckpt_acc') == best_acc_path
+ assert 'best_ckpt_mIoU' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('best_ckpt_mIoU') == best_mIoU_path
+
+ # after_val_epoch should not save last_checkpoint.
+ assert not osp.isfile(osp.join(runner.work_dir, 'last_checkpoint'))
+
+ def test_after_train_epoch(self, tmp_path):
+ runner = Mock()
+ work_dir = str(tmp_path)
+ runner.work_dir = tmp_path
+ runner.epoch = 9
+ runner.model = Mock()
+ runner.message_hub = MessageHub.get_instance('test_after_train_epoch')
+
+ # by epoch is True
+ checkpoint_hook = CheckpointHook(interval=2, by_epoch=True)
+ checkpoint_hook.before_train(runner)
+ checkpoint_hook.after_train_epoch(runner)
+ assert (runner.epoch + 1) % 2 == 0
+ assert 'last_ckpt' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('last_ckpt') == \
+ osp.join(work_dir, 'epoch_10.pth')
+ last_ckpt_path = osp.join(work_dir, 'last_checkpoint')
+ assert osp.isfile(last_ckpt_path)
+ with open(last_ckpt_path) as f:
+ filepath = f.read()
+ assert filepath == osp.join(work_dir, 'epoch_10.pth')
+
+ # epoch can not be evenly divided by 2
+ runner.epoch = 10
+ checkpoint_hook.after_train_epoch(runner)
+ assert 'last_ckpt' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('last_ckpt') == \
+ osp.join(work_dir, 'epoch_10.pth')
+
+ # by epoch is False
+ runner.epoch = 9
+ runner.message_hub = MessageHub.get_instance('test_after_train_epoch1')
+ checkpoint_hook = CheckpointHook(interval=2, by_epoch=False)
+ checkpoint_hook.before_train(runner)
+ checkpoint_hook.after_train_epoch(runner)
+ assert 'last_ckpt' not in runner.message_hub.runtime_info
+
+ # # max_keep_ckpts > 0
+ runner.work_dir = work_dir
+ os.system(f'touch {work_dir}/epoch_8.pth')
+ checkpoint_hook = CheckpointHook(
+ interval=2, by_epoch=True, max_keep_ckpts=1)
+ checkpoint_hook.before_train(runner)
+ checkpoint_hook.after_train_epoch(runner)
+ assert (runner.epoch + 1) % 2 == 0
+ assert not os.path.exists(f'{work_dir}/epoch_8.pth')
+
+ # save_checkpoint of runner should be called with expected arguments
+ runner = Mock()
+ work_dir = str(tmp_path)
+ runner.work_dir = tmp_path
+ runner.epoch = 1
+ runner.message_hub = MessageHub.get_instance('test_after_train_epoch2')
+
+ checkpoint_hook = CheckpointHook(interval=2, by_epoch=True)
+ checkpoint_hook.before_train(runner)
+ checkpoint_hook.after_train_epoch(runner)
+
+ runner.save_checkpoint.assert_called_once_with(
+ runner.work_dir,
+ 'epoch_2.pth',
+ None,
+ backend_args=None,
+ by_epoch=True,
+ save_optimizer=True,
+ save_param_scheduler=True)
+
+ def test_after_train_iter(self, tmp_path):
+ work_dir = str(tmp_path)
+ runner = Mock()
+ runner.work_dir = str(work_dir)
+ runner.iter = 9
+ batch_idx = 9
+ runner.model = Mock()
+ runner.message_hub = MessageHub.get_instance('test_after_train_iter')
+
+ # by epoch is True
+ checkpoint_hook = CheckpointHook(interval=2, by_epoch=True)
+ checkpoint_hook.before_train(runner)
+ checkpoint_hook.after_train_iter(runner, batch_idx=batch_idx)
+ assert 'last_ckpt' not in runner.message_hub.runtime_info
+
+ # by epoch is False
+ checkpoint_hook = CheckpointHook(interval=2, by_epoch=False)
+ checkpoint_hook.before_train(runner)
+ checkpoint_hook.after_train_iter(runner, batch_idx=batch_idx)
+ assert (runner.iter + 1) % 2 == 0
+ assert 'last_ckpt' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('last_ckpt') == \
+ osp.join(work_dir, 'iter_10.pth')
+
+ # epoch can not be evenly divided by 2
+ runner.iter = 10
+ checkpoint_hook.after_train_epoch(runner)
+ assert 'last_ckpt' in runner.message_hub.runtime_info and \
+ runner.message_hub.get_info('last_ckpt') == \
+ osp.join(work_dir, 'iter_10.pth')
+
+ # max_keep_ckpts > 0
+ runner.iter = 9
+ runner.work_dir = work_dir
+ os.system(f'touch {osp.join(work_dir, "iter_8.pth")}')
+ checkpoint_hook = CheckpointHook(
+ interval=2, by_epoch=False, max_keep_ckpts=1)
+ checkpoint_hook.before_train(runner)
+ checkpoint_hook.after_train_iter(runner, batch_idx=batch_idx)
+ assert not os.path.exists(f'{work_dir}/iter_8.pth')
+
+ def test_with_runner(self, tmp_path):
+ max_epoch = 10
+ work_dir = osp.join(str(tmp_path), 'runner_test')
+ tmpl = '{}.pth'
+ save_interval = 2
+ checkpoint_cfg = dict(
+ type='CheckpointHook',
+ interval=save_interval,
+ filename_tmpl=tmpl,
+ by_epoch=True)
+ runner = Runner(
+ model=ToyModel(),
+ work_dir=work_dir,
+ train_dataloader=dict(
+ dataset=DummyDataset(),
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ batch_size=3,
+ num_workers=0),
+ val_dataloader=dict(
+ dataset=DummyDataset(),
+ sampler=dict(type='DefaultSampler', shuffle=False),
+ batch_size=3,
+ num_workers=0),
+ val_evaluator=dict(type=TriangleMetric, length=max_epoch),
+ optim_wrapper=OptimWrapper(
+ torch.optim.Adam(ToyModel().parameters())),
+ train_cfg=dict(
+ by_epoch=True, max_epochs=max_epoch, val_interval=1),
+ val_cfg=dict(),
+ default_hooks=dict(checkpoint=checkpoint_cfg))
+ runner.train()
+ for epoch in range(max_epoch):
+ if epoch % save_interval != 0 or epoch == 0:
+ continue
+ path = osp.join(work_dir, tmpl.format(epoch))
+ assert osp.isfile(path=path)
diff --git a/testbed/open-mmlab__mmengine/tests/test_hooks/test_ema_hook.py b/testbed/open-mmlab__mmengine/tests/test_hooks/test_ema_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd7fc91ac932b24a6b0a83c10c75c6e90b405d8f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_hooks/test_ema_hook.py
@@ -0,0 +1,306 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import logging
+import os.path as osp
+import tempfile
+from unittest import TestCase
+from unittest.mock import Mock
+
+import torch
+import torch.nn as nn
+from torch.utils.data import Dataset
+
+from mmengine.evaluator import Evaluator
+from mmengine.hooks import EMAHook
+from mmengine.logging import MMLogger
+from mmengine.model import BaseModel, ExponentialMovingAverage
+from mmengine.optim import OptimWrapper
+from mmengine.registry import DATASETS, MODEL_WRAPPERS
+from mmengine.runner import Runner
+from mmengine.testing import assert_allclose
+
+
+class ToyModel(BaseModel):
+
+ def __init__(self):
+ super().__init__()
+ self.linear = nn.Linear(2, 1)
+
+ def forward(self, inputs, data_sample, mode='tensor'):
+ labels = torch.stack(data_sample)
+ inputs = torch.stack(inputs)
+ outputs = self.linear(inputs)
+ if mode == 'tensor':
+ return outputs
+ elif mode == 'loss':
+ loss = (labels - outputs).sum()
+ outputs = dict(loss=loss)
+ return outputs
+ else:
+ return outputs
+
+
+class ToyModel1(ToyModel):
+
+ def __init__(self):
+ super().__init__()
+
+ def forward(self, *args, **kwargs):
+ return super().forward(*args, **kwargs)
+
+
+class ToyModel2(ToyModel):
+
+ def __init__(self):
+ super().__init__()
+ self.linear1 = nn.Linear(2, 1)
+
+ def forward(self, *args, **kwargs):
+ return super().forward(*args, **kwargs)
+
+
+class ToyModel3(ToyModel):
+
+ def __init__(self):
+ super().__init__()
+ self.linear = nn.Linear(2, 2)
+
+ def forward(self, *args, **kwargs):
+ return super().forward(*args, **kwargs)
+
+
+@DATASETS.register_module()
+class DummyDataset(Dataset):
+ METAINFO = dict() # type: ignore
+ data = torch.randn(12, 2)
+ label = torch.ones(12)
+
+ @property
+ def metainfo(self):
+ return self.METAINFO
+
+ def __len__(self):
+ return self.data.size(0)
+
+ def __getitem__(self, index):
+ return dict(inputs=self.data[index], data_sample=self.label[index])
+
+
+class TestEMAHook(TestCase):
+
+ def setUp(self):
+ self.temp_dir = tempfile.TemporaryDirectory()
+
+ def tearDown(self):
+ # `FileHandler` should be closed in Windows, otherwise we cannot
+ # delete the temporary directory
+ logging.shutdown()
+ MMLogger._instance_dict.clear()
+ self.temp_dir.cleanup()
+
+ def test_ema_hook(self):
+ device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
+ model = ToyModel1().to(device)
+ evaluator = Evaluator([])
+ evaluator.evaluate = Mock(return_value=dict(acc=0.5))
+ runner = Runner(
+ model=model,
+ train_dataloader=dict(
+ dataset=dict(type='DummyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ batch_size=3,
+ num_workers=0),
+ val_dataloader=dict(
+ dataset=dict(type='DummyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=False),
+ batch_size=3,
+ num_workers=0),
+ val_evaluator=evaluator,
+ work_dir=self.temp_dir.name,
+ optim_wrapper=OptimWrapper(
+ torch.optim.Adam(ToyModel().parameters())),
+ train_cfg=dict(by_epoch=True, max_epochs=2, val_interval=1),
+ val_cfg=dict(),
+ default_hooks=dict(logger=None),
+ custom_hooks=[dict(type='EMAHook', )],
+ experiment_name='test1')
+ runner.train()
+ for hook in runner.hooks:
+ if isinstance(hook, EMAHook):
+ self.assertTrue(
+ isinstance(hook.ema_model, ExponentialMovingAverage))
+
+ self.assertTrue(
+ osp.exists(osp.join(self.temp_dir.name, 'epoch_2.pth')))
+ checkpoint = torch.load(osp.join(self.temp_dir.name, 'epoch_2.pth'))
+ self.assertTrue('ema_state_dict' in checkpoint)
+ self.assertTrue(checkpoint['ema_state_dict']['steps'] == 8)
+
+ # load and testing
+ runner = Runner(
+ model=model,
+ test_dataloader=dict(
+ dataset=dict(type='DummyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ batch_size=3,
+ num_workers=0),
+ test_evaluator=evaluator,
+ test_cfg=dict(),
+ work_dir=self.temp_dir.name,
+ load_from=osp.join(self.temp_dir.name, 'epoch_2.pth'),
+ default_hooks=dict(logger=None),
+ custom_hooks=[dict(type='EMAHook')],
+ experiment_name='test2')
+ runner.test()
+
+ @MODEL_WRAPPERS.register_module()
+ class DummyWrapper(BaseModel):
+
+ def __init__(self, model):
+ super().__init__()
+ self.module = model
+
+ def forward(self, *args, **kwargs):
+ return self.module(*args, **kwargs)
+
+ # with model wrapper
+ runner = Runner(
+ model=DummyWrapper(ToyModel()),
+ test_dataloader=dict(
+ dataset=dict(type='DummyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ batch_size=3,
+ num_workers=0),
+ test_evaluator=evaluator,
+ test_cfg=dict(),
+ work_dir=self.temp_dir.name,
+ load_from=osp.join(self.temp_dir.name, 'epoch_2.pth'),
+ default_hooks=dict(logger=None),
+ custom_hooks=[dict(type='EMAHook')],
+ experiment_name='test3')
+ runner.test()
+
+ # Test load checkpoint without ema_state_dict
+ ckpt = torch.load(osp.join(self.temp_dir.name, 'epoch_2.pth'))
+ ckpt.pop('ema_state_dict')
+ torch.save(ckpt,
+ osp.join(self.temp_dir.name, 'without_ema_state_dict.pth'))
+ runner = Runner(
+ model=DummyWrapper(ToyModel()),
+ test_dataloader=dict(
+ dataset=dict(type='DummyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ batch_size=3,
+ num_workers=0),
+ test_evaluator=evaluator,
+ test_cfg=dict(),
+ work_dir=self.temp_dir.name,
+ load_from=osp.join(self.temp_dir.name,
+ 'without_ema_state_dict.pth'),
+ default_hooks=dict(logger=None),
+ custom_hooks=[dict(type='EMAHook')],
+ experiment_name='test4')
+ runner.test()
+
+ # Test does not load ckpt strict_loadly.
+ # Test load checkpoint without ema_state_dict
+ runner = Runner(
+ model=ToyModel2(),
+ test_dataloader=dict(
+ dataset=dict(type='DummyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ batch_size=3,
+ num_workers=0),
+ test_evaluator=evaluator,
+ test_cfg=dict(),
+ work_dir=self.temp_dir.name,
+ load_from=osp.join(self.temp_dir.name, 'epoch_2.pth'),
+ default_hooks=dict(logger=None),
+ custom_hooks=[dict(type='EMAHook', strict_load=False)],
+ experiment_name='test5')
+ runner.test()
+
+ # Test does not load ckpt strict_loadly.
+ # Test load checkpoint without ema_state_dict
+ # Test with different size head.
+ runner = Runner(
+ model=ToyModel3(),
+ test_dataloader=dict(
+ dataset=dict(type='DummyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ batch_size=3,
+ num_workers=0),
+ test_evaluator=evaluator,
+ test_cfg=dict(),
+ work_dir=self.temp_dir.name,
+ load_from=osp.join(self.temp_dir.name,
+ 'without_ema_state_dict.pth'),
+ default_hooks=dict(logger=None),
+ custom_hooks=[dict(type='EMAHook', strict_load=False)],
+ experiment_name='test5.1')
+ runner.test()
+
+ # Test enable ema at 5 epochs.
+ runner = Runner(
+ model=model,
+ train_dataloader=dict(
+ dataset=dict(type='DummyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ batch_size=3,
+ num_workers=0),
+ val_dataloader=dict(
+ dataset=dict(type='DummyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=False),
+ batch_size=3,
+ num_workers=0),
+ val_evaluator=evaluator,
+ work_dir=self.temp_dir.name,
+ optim_wrapper=OptimWrapper(
+ torch.optim.Adam(ToyModel().parameters())),
+ train_cfg=dict(by_epoch=True, max_epochs=10, val_interval=1),
+ val_cfg=dict(),
+ default_hooks=dict(logger=None),
+ custom_hooks=[dict(type='EMAHook', begin_epoch=5)],
+ experiment_name='test6')
+ runner.train()
+ state_dict = torch.load(
+ osp.join(self.temp_dir.name, 'epoch_4.pth'), map_location='cpu')
+ self.assertIn('ema_state_dict', state_dict)
+ for k, v in state_dict['state_dict'].items():
+ assert_allclose(v, state_dict['ema_state_dict']['module.' + k])
+ state_dict = torch.load(
+ osp.join(self.temp_dir.name, 'epoch_5.pth'), map_location='cpu')
+ self.assertIn('ema_state_dict', state_dict)
+
+ # Test enable ema at 5 iterations.
+ runner = Runner(
+ model=model,
+ train_dataloader=dict(
+ dataset=dict(type='DummyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ batch_size=3,
+ num_workers=0),
+ val_dataloader=dict(
+ dataset=dict(type='DummyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=False),
+ batch_size=3,
+ num_workers=0),
+ val_evaluator=evaluator,
+ work_dir=self.temp_dir.name,
+ optim_wrapper=OptimWrapper(
+ torch.optim.Adam(ToyModel().parameters())),
+ train_cfg=dict(by_epoch=False, max_iters=10, val_interval=1),
+ val_cfg=dict(),
+ default_hooks=dict(
+ checkpoint=dict(
+ type='CheckpointHook', interval=1, by_epoch=False)),
+ custom_hooks=[dict(type='EMAHook', begin_iter=5)],
+ experiment_name='test7')
+ runner.train()
+ state_dict = torch.load(
+ osp.join(self.temp_dir.name, 'iter_4.pth'), map_location='cpu')
+ self.assertIn('ema_state_dict', state_dict)
+ for k, v in state_dict['state_dict'].items():
+ assert_allclose(v, state_dict['ema_state_dict']['module.' + k])
+ state_dict = torch.load(
+ osp.join(self.temp_dir.name, 'iter_5.pth'), map_location='cpu')
+ self.assertIn('ema_state_dict', state_dict)
diff --git a/testbed/open-mmlab__mmengine/tests/test_hooks/test_empty_cache_hook.py b/testbed/open-mmlab__mmengine/tests/test_hooks/test_empty_cache_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..e909fc5d2d9aca2a4a69c3fb2d3b9a67c9c3bb7a
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_hooks/test_empty_cache_hook.py
@@ -0,0 +1,14 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from unittest.mock import Mock
+
+from mmengine.hooks import EmptyCacheHook
+
+
+class TestEmptyCacheHook:
+
+ def test_emtpy_cache_hook(self):
+ hook = EmptyCacheHook(True, True, True)
+ runner = Mock()
+ hook._after_iter(runner, 0)
+ hook._before_epoch(runner)
+ hook._after_epoch(runner)
diff --git a/testbed/open-mmlab__mmengine/tests/test_hooks/test_hook.py b/testbed/open-mmlab__mmengine/tests/test_hooks/test_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb2d6215a5d14aadfb63d6526bf3f2f5cc77558c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_hooks/test_hook.py
@@ -0,0 +1,194 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from unittest.mock import Mock
+
+from mmengine.hooks import Hook
+
+
+class TestHook:
+
+ def test_before_run(self):
+ hook = Hook()
+ runner = Mock()
+ hook.before_run(runner)
+
+ def test_after_run(self):
+ hook = Hook()
+ runner = Mock()
+ hook.after_run(runner)
+
+ def test_before_epoch(self):
+ hook = Hook()
+ runner = Mock()
+ hook._before_epoch(runner)
+
+ def test_after_epoch(self):
+ hook = Hook()
+ runner = Mock()
+ hook._after_epoch(runner)
+
+ def test_before_iter(self):
+ hook = Hook()
+ runner = Mock()
+ data_batch = {}
+ hook._before_iter(runner, data_batch)
+
+ def test_after_iter(self):
+ hook = Hook()
+ runner = Mock()
+ data_batch = {}
+ outputs = {}
+ hook._after_iter(runner, data_batch, outputs)
+
+ def test_before_save_checkpoint(self):
+ hook = Hook()
+ runner = Mock()
+ checkpoint = {}
+ hook.before_save_checkpoint(runner, checkpoint)
+
+ def test_after_load_checkpoint(self):
+ hook = Hook()
+ runner = Mock()
+ checkpoint = {}
+ hook.after_load_checkpoint(runner, checkpoint)
+
+ def test_before_train_epoch(self):
+ hook = Hook()
+ runner = Mock()
+ hook.before_train_epoch(runner)
+
+ def test_before_val_epoch(self):
+ hook = Hook()
+ runner = Mock()
+ hook.before_val_epoch(runner)
+
+ def test_before_test_epoch(self):
+ hook = Hook()
+ runner = Mock()
+ hook.before_test_epoch(runner)
+
+ def test_after_train_epoch(self):
+ hook = Hook()
+ runner = Mock()
+ hook.after_train_epoch(runner)
+
+ def test_after_val_epoch(self):
+ hook = Hook()
+ runner = Mock()
+ hook.after_val_epoch(runner, {})
+
+ def test_after_test_epoch(self):
+ hook = Hook()
+ runner = Mock()
+ hook.after_test_epoch(runner, {})
+
+ def test_before_train_iter(self):
+ hook = Hook()
+ runner = Mock()
+ data_batch = {}
+ hook.before_train_iter(runner, data_batch)
+
+ def test_before_val_iter(self):
+ hook = Hook()
+ runner = Mock()
+ data_batch = {}
+ hook.before_val_iter(runner, data_batch)
+
+ def test_before_test_iter(self):
+ hook = Hook()
+ runner = Mock()
+ data_batch = {}
+ hook.before_test_iter(runner, data_batch)
+
+ def test_after_train_iter(self):
+ hook = Hook()
+ runner = Mock()
+ data_batch = {}
+ outputs = {}
+ hook.after_train_iter(runner, data_batch, outputs)
+
+ def test_after_val_iter(self):
+ hook = Hook()
+ runner = Mock()
+ data_batch = {}
+ outputs = {}
+ hook.after_val_iter(runner, data_batch, outputs)
+
+ def test_after_test_iter(self):
+ hook = Hook()
+ runner = Mock()
+ data_batch = {}
+ outputs = {}
+ hook.after_test_iter(runner, data_batch, outputs)
+
+ def test_every_n_epochs(self):
+ hook = Hook()
+ runner = Mock()
+
+ for i in range(100):
+ runner.epoch = i
+ return_val = hook.every_n_epochs(runner, 3)
+ if (i + 1) % 3 == 0:
+ assert return_val
+ else:
+ assert not return_val
+
+ def test_every_n_inner_iters(self):
+ hook = Hook()
+
+ for i in range(100):
+ return_val = hook.every_n_inner_iters(i, 3)
+ if (i + 1) % 3 == 0:
+ assert return_val
+ else:
+ assert not return_val
+
+ def test_every_n_train_iters(self):
+ hook = Hook()
+ runner = Mock()
+ for i in range(100):
+ runner.iter = i
+ return_val = hook.every_n_train_iters(runner, 3)
+ if (i + 1) % 3 == 0:
+ assert return_val
+ else:
+ assert not return_val
+
+ def test_end_of_epoch(self):
+ hook = Hook()
+
+ # last inner iter
+ batch_idx = 1
+ dataloader = Mock()
+ dataloader.__len__ = Mock(return_value=2)
+ return_val = hook.end_of_epoch(dataloader, batch_idx)
+ assert return_val
+
+ # not the last inner iter
+ batch_idx = 0
+ return_val = hook.end_of_epoch(dataloader, batch_idx)
+ assert not return_val
+
+ def test_is_last_train_epoch(self):
+ hook = Hook()
+ runner = Mock()
+
+ # last epoch
+ runner.epoch = 1
+ runner.max_epochs = 2
+ return_val = hook.is_last_train_epoch(runner)
+ assert return_val
+
+ # not the last epoch
+ runner.max_epochs = 0
+ return_val = hook.is_last_train_epoch(runner)
+ assert not return_val
+
+ def test_is_last_train_iter(self):
+ hook = Hook()
+ runner = Mock()
+
+ # last iter
+ runner.iter = 1
+ runner.max_iters = 2
+ return_val = hook.is_last_train_iter(runner)
+ assert return_val
diff --git a/testbed/open-mmlab__mmengine/tests/test_hooks/test_iter_timer_hook.py b/testbed/open-mmlab__mmengine/tests/test_hooks/test_iter_timer_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..2645c9221724a31bdb8148affdabffd242d5862e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_hooks/test_iter_timer_hook.py
@@ -0,0 +1,82 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from unittest import TestCase
+from unittest.mock import MagicMock, Mock, patch
+
+from mmengine.hooks import IterTimerHook
+from mmengine.logging import MessageHub
+
+
+def time_patch():
+ if not hasattr(time_patch, 'time'):
+ time_patch.time = 0
+ else:
+ time_patch.time += 1
+ return time_patch.time
+
+
+class TestIterTimerHook(TestCase):
+
+ def setUp(self) -> None:
+ self.hook = IterTimerHook()
+
+ def test_init(self):
+ assert self.hook.time_sec_tot == 0
+ assert self.hook.start_iter == 0
+
+ def test_before_train(self):
+ runner = MagicMock()
+ runner.iter = 1
+ self.hook.before_train(runner)
+ assert self.hook.start_iter == 1
+
+ def test_before_epoch(self):
+ runner = Mock()
+ self.hook._before_epoch(runner)
+ assert isinstance(self.hook.t, float)
+
+ @patch('time.time', MagicMock(return_value=1))
+ def test_before_iter(self):
+ runner = MagicMock()
+ runner.log_buffer = dict()
+ self.hook._before_epoch(runner)
+ for mode in ('train', 'val', 'test'):
+ self.hook._before_iter(runner, batch_idx=1, mode=mode)
+ runner.message_hub.update_scalar.assert_called_with(
+ f'{mode}/data_time', 0)
+
+ @patch('time.time', time_patch)
+ def test_after_iter(self):
+ runner = MagicMock()
+ runner.log_buffer = dict()
+ runner.log_processor.window_size = 10
+ runner.max_iters = 100
+ runner.iter = 0
+ runner.test_dataloader = [0] * 20
+ runner.val_dataloader = [0] * 20
+ runner.message_hub = MessageHub.get_instance('test_iter_timer_hook')
+
+ self.hook.before_run(runner)
+ self.hook._before_epoch(runner)
+ # eta = (100 - 10) / 1
+ for _ in range(10):
+ self.hook._after_iter(runner, 1)
+ runner.iter += 1
+ assert runner.message_hub.get_info('eta') == 90
+
+ for i in range(10):
+ self.hook._after_iter(runner, batch_idx=i, mode='val')
+ assert runner.message_hub.get_info('eta') == 10
+
+ for i in range(11, 20):
+ self.hook._after_iter(runner, batch_idx=i, mode='val')
+ assert runner.message_hub.get_info('eta') == 0
+
+ self.hook.after_val_epoch(runner)
+
+ for i in range(10):
+ self.hook._after_iter(runner, batch_idx=i, mode='test')
+ assert runner.message_hub.get_info('eta') == 10
+
+ for i in range(11, 20):
+ self.hook._after_iter(runner, batch_idx=i, mode='test')
+ assert runner.message_hub.get_info('eta') == 0
diff --git a/testbed/open-mmlab__mmengine/tests/test_hooks/test_logger_hook.py b/testbed/open-mmlab__mmengine/tests/test_hooks/test_logger_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a3ddb37e8fe7f9d23fc8fd1af5687ae610cd819
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_hooks/test_logger_hook.py
@@ -0,0 +1,208 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os.path as osp
+from unittest.mock import ANY, MagicMock
+
+import pytest
+
+from mmengine.fileio.file_client import HardDiskBackend
+from mmengine.hooks import LoggerHook
+
+
+class TestLoggerHook:
+
+ def test_init(self):
+ logger_hook = LoggerHook(out_dir='tmp.txt')
+ assert logger_hook.interval == 10
+ assert logger_hook.ignore_last
+ assert logger_hook.interval_exp_name == 1000
+ assert logger_hook.out_suffix == ('.json', '.log', '.py', 'yaml')
+ assert logger_hook.keep_local
+ assert logger_hook.file_client_args is None
+ assert isinstance(logger_hook.file_client.client, HardDiskBackend)
+ # out_dir should be None or string or tuple of string.
+ with pytest.raises(TypeError):
+ LoggerHook(out_dir=1)
+
+ with pytest.raises(ValueError):
+ LoggerHook(file_client_args=dict(enable_mc=True))
+
+ # test `file_client_args` and `backend_args`
+ with pytest.warns(
+ DeprecationWarning,
+ match='"file_client_args" will be deprecated in future'):
+ logger_hook = LoggerHook(
+ out_dir='tmp.txt', file_client_args={'backend': 'disk'})
+
+ with pytest.raises(
+ ValueError,
+ match='"file_client_args" and "backend_args" cannot be '
+ 'set at the same time'):
+ logger_hook = LoggerHook(
+ out_dir='tmp.txt',
+ file_client_args={'backend': 'disk'},
+ backend_args={'backend': 'local'})
+
+ def test_before_run(self):
+ runner = MagicMock()
+ runner.iter = 10
+ runner.timestamp = '20220429'
+ runner._log_dir = f'work_dir/{runner.timestamp}'
+ runner.work_dir = 'work_dir'
+ runner.logger = MagicMock()
+ logger_hook = LoggerHook(out_dir='out_dir')
+ logger_hook.before_run(runner)
+ assert logger_hook.out_dir == osp.join('out_dir', 'work_dir')
+ assert logger_hook.json_log_path == f'{runner.timestamp}.json'
+
+ def test_after_run(self, tmp_path):
+ # Test
+ timestamp = '20220429'
+ out_dir = tmp_path / 'out_dir'
+ out_dir.mkdir()
+ work_dir = tmp_path / 'work_dir'
+ work_dir.mkdir()
+ log_dir = work_dir / timestamp
+ log_dir.mkdir()
+ log_dir_json = log_dir / 'tmp.log.json'
+ runner = MagicMock()
+ runner._log_dir = str(log_dir)
+ runner.timestamp = timestamp
+ runner.work_dir = str(work_dir)
+ # Test without out_dir.
+ logger_hook = LoggerHook()
+ logger_hook.after_run(runner)
+ # Test with out_dir and make sure json file has been moved to out_dir.
+ json_f = open(log_dir_json, 'w')
+ json_f.close()
+ logger_hook = LoggerHook(out_dir=str(out_dir), keep_local=False)
+ logger_hook.out_dir = str(out_dir)
+ logger_hook.before_run(runner)
+ logger_hook.after_run(runner)
+ # Verify that the file has been moved to `out_dir`.
+ assert not osp.exists(str(log_dir_json))
+ assert osp.exists(str(out_dir / 'work_dir' / 'tmp.log.json'))
+
+ def test_after_train_iter(self):
+ # Test LoggerHook by iter.
+ runner = MagicMock()
+ runner.log_processor.get_log_after_iter = MagicMock(
+ return_value=(dict(), 'log_str'))
+ logger_hook = LoggerHook()
+ logger_hook.after_train_iter(runner, batch_idx=5)
+ # `cur_iter=10+1`, which cannot be exact division by
+ # `logger_hook.interval`
+ runner.log_processor.get_log_after_iter.assert_not_called()
+ logger_hook.after_train_iter(runner, batch_idx=9)
+ runner.log_processor.get_log_after_iter.assert_called()
+
+ # Test LoggerHook by epoch.
+ logger_hook = LoggerHook()
+ runner = MagicMock()
+ runner.log_processor.get_log_after_iter = MagicMock(
+ return_value=(dict(), 'log_str'))
+ # Only `batch_idx` will work.
+ logger_hook.after_train_iter(runner, batch_idx=10)
+ runner.log_processor.get_log_after_iter.assert_not_called()
+ logger_hook.after_train_iter(runner, batch_idx=9)
+ runner.log_processor.get_log_after_iter.assert_called()
+
+ # Test end of the epoch.
+ runner = MagicMock()
+ runner.log_processor.get_log_after_iter = MagicMock(
+ return_value=(dict(), 'log_str'))
+ logger_hook = LoggerHook(ignore_last=False)
+ runner.train_dataloader = [0] * 5
+ logger_hook.after_train_iter(runner, batch_idx=4)
+ runner.log_processor.get_log_after_iter.assert_called()
+
+ # Test print exp_name
+ runner = MagicMock()
+ runner.log_processor.get_log_after_iter = MagicMock(
+ return_value=(dict(), 'log_str'))
+ runner.logger = MagicMock()
+ logger_hook = LoggerHook()
+ logger_hook.after_train_iter(runner, batch_idx=999)
+ runner.logger.info.assert_called()
+
+ def test_after_val_epoch(self):
+ logger_hook = LoggerHook()
+ runner = MagicMock()
+ runner.log_processor.get_log_after_epoch = MagicMock(
+ return_value=(dict(), 'string'))
+ logger_hook.after_val_epoch(runner)
+ runner.log_processor.get_log_after_epoch.assert_called()
+ runner.logger.info.assert_called()
+ runner.visualizer.add_scalars.assert_called()
+
+ # Test when `log_metric_by_epoch` is True
+ runner.log_processor.get_log_after_epoch = MagicMock(
+ return_value=({
+ 'time': 1,
+ 'datatime': 1,
+ 'acc': 0.8
+ }, 'string'))
+ logger_hook.after_val_epoch(runner)
+ args = {'step': ANY, 'file_path': ANY}
+ # expect visualizer log `time` and `metric` respectively
+ runner.visualizer.add_scalars.assert_called_with({'acc': 0.8}, **args)
+
+ # Test when `log_metric_by_epoch` is False
+ logger_hook = LoggerHook(log_metric_by_epoch=False)
+ runner.log_processor.get_log_after_epoch = MagicMock(
+ return_value=({
+ 'time': 5,
+ 'datatime': 5,
+ 'acc': 0.5
+ }, 'string'))
+ logger_hook.after_val_epoch(runner)
+ # expect visualizer log `time` and `metric` jointly
+ runner.visualizer.add_scalars.assert_called_with(
+ {
+ 'time': 5,
+ 'datatime': 5,
+ 'acc': 0.5
+ }, **args)
+
+ with pytest.raises(AssertionError):
+ runner.visualizer.add_scalars.assert_any_call(
+ {
+ 'time': 5,
+ 'datatime': 5
+ }, **args)
+ with pytest.raises(AssertionError):
+ runner.visualizer.add_scalars.assert_any_call({'acc': 0.5}, **args)
+
+ def test_after_test_epoch(self, tmp_path):
+ logger_hook = LoggerHook()
+ runner = MagicMock()
+ runner.log_dir = tmp_path
+ runner.timestamp = 'test_after_test_epoch'
+ runner.log_processor.get_log_after_epoch = MagicMock(
+ return_value=(dict(a=1, b=2), 'log_str'))
+ logger_hook.before_run(runner)
+ logger_hook.after_test_epoch(runner)
+ runner.log_processor.get_log_after_epoch.assert_called()
+ runner.logger.info.assert_called()
+ osp.isfile(osp.join(runner.log_dir, 'test_after_test_epoch.json'))
+
+ def test_after_val_iter(self):
+ logger_hook = LoggerHook()
+ runner = MagicMock()
+ runner.iter = 0
+ runner.log_processor.get_log_after_iter = MagicMock(
+ return_value=(dict(), 'log_str'))
+ logger_hook.after_val_iter(runner, 1)
+ runner.log_processor.get_log_after_iter.assert_not_called()
+ logger_hook.after_val_iter(runner, 9)
+ runner.log_processor.get_log_after_iter.assert_called()
+
+ def test_after_test_iter(self):
+ logger_hook = LoggerHook()
+ runner = MagicMock()
+ runner.iter = 0
+ runner.log_processor.get_log_after_iter = MagicMock(
+ return_value=(dict(), 'log_str'))
+ logger_hook.after_test_iter(runner, 1)
+ runner.log_processor.get_log_after_iter.assert_not_called()
+ logger_hook.after_test_iter(runner, 9)
+ runner.log_processor.get_log_after_iter.assert_called()
diff --git a/testbed/open-mmlab__mmengine/tests/test_hooks/test_naive_visualization_hook.py b/testbed/open-mmlab__mmengine/tests/test_hooks/test_naive_visualization_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e39e945274c4cfc63f204e1c9a208bdb5a11632
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_hooks/test_naive_visualization_hook.py
@@ -0,0 +1,71 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from unittest.mock import Mock
+
+import torch
+
+from mmengine.hooks import NaiveVisualizationHook
+from mmengine.structures import BaseDataElement
+
+
+class TestNaiveVisualizationHook:
+
+ def test_after_train_iter(self):
+ naive_visualization_hook = NaiveVisualizationHook()
+ runner = Mock(iter=1)
+ runner.visualizer.add_image = Mock()
+ inputs = torch.randn(1, 3, 15, 15)
+ batch_idx = 10
+ # test with normalize, resize, pad
+ gt_datasamples = BaseDataElement(
+ metainfo=dict(
+ img_norm_cfg=dict(
+ mean=(0, 0, 0), std=(0.5, 0.5, 0.5), to_bgr=True),
+ scale=(10, 10),
+ pad_shape=(15, 15, 3),
+ ori_height=5,
+ ori_width=5,
+ img_path='tmp.jpg'))
+ pred_datasamples = [BaseDataElement()]
+ data_batch = [dict(inputs=inputs, data_sample=gt_datasamples)]
+ naive_visualization_hook.after_test_iter(runner, batch_idx, data_batch,
+ pred_datasamples)
+ # test with resize, pad
+ gt_datasamples = BaseDataElement(
+ metainfo=dict(
+ scale=(10, 10),
+ pad_shape=(15, 15, 3),
+ ori_height=5,
+ ori_width=5,
+ img_path='tmp.jpg'))
+ pred_datasamples = [BaseDataElement()]
+ data_batch = [dict(inputs=inputs, data_sample=gt_datasamples)]
+ naive_visualization_hook.after_test_iter(runner, batch_idx, data_batch,
+ pred_datasamples)
+ # test with only resize
+ gt_datasamples = BaseDataElement(
+ metainfo=dict(
+ scale=(15, 15), ori_height=5, ori_width=5, img_path='tmp.jpg'))
+ pred_datasamples = [BaseDataElement()]
+ data_batch = [dict(inputs=inputs, data_sample=gt_datasamples)]
+ naive_visualization_hook.after_test_iter(runner, batch_idx, data_batch,
+ pred_datasamples)
+
+ # test with only pad
+ gt_datasamples = BaseDataElement(
+ metainfo=dict(
+ pad_shape=(15, 15, 3),
+ ori_height=5,
+ ori_width=5,
+ img_path='tmp.jpg'))
+ pred_datasamples = [BaseDataElement()]
+ data_batch = [dict(inputs=inputs, data_sample=gt_datasamples)]
+ naive_visualization_hook.after_test_iter(runner, batch_idx, data_batch,
+ pred_datasamples)
+
+ # test no transform
+ gt_datasamples = BaseDataElement(
+ metainfo=dict(ori_height=15, ori_width=15, img_path='tmp.jpg'))
+ pred_datasamples = [BaseDataElement()]
+ data_batch = [dict(inputs=inputs, data_sample=gt_datasamples)]
+ naive_visualization_hook.after_test_iter(runner, batch_idx, data_batch,
+ pred_datasamples)
diff --git a/testbed/open-mmlab__mmengine/tests/test_hooks/test_param_scheduler_hook.py b/testbed/open-mmlab__mmengine/tests/test_hooks/test_param_scheduler_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..85c7fb2297c75c5ddb6f6ca14b14f37275cb7230
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_hooks/test_param_scheduler_hook.py
@@ -0,0 +1,79 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from unittest.mock import Mock
+
+import pytest
+
+from mmengine.hooks import ParamSchedulerHook
+
+
+class TestParamSchedulerHook:
+ error_msg = ('runner.param_schedulers should be list of ParamScheduler or '
+ 'a dict containing list of ParamScheduler')
+
+ def test_after_iter(self):
+ # runner.param_schedulers should be a list or dict
+ with pytest.raises(TypeError, match=self.error_msg):
+ hook = ParamSchedulerHook()
+ runner = Mock()
+ scheduler = Mock()
+ scheduler.step = Mock()
+ scheduler.by_epoch = False
+ runner.param_schedulers = scheduler
+ hook.after_train_iter(runner, 0)
+ scheduler.step.assert_called()
+
+ # runner.param_schedulers is a list of schedulers
+ hook = ParamSchedulerHook()
+ runner = Mock()
+ scheduler = Mock()
+ scheduler.step = Mock()
+ scheduler.by_epoch = False
+ runner.param_schedulers = [scheduler]
+ hook.after_train_iter(runner, 0)
+ scheduler.step.assert_called()
+
+ # runner.param_schedulers is a dict containing list of schedulers
+ scheduler1 = Mock()
+ scheduler1.step = Mock()
+ scheduler1.by_epoch = False
+ scheduler2 = Mock()
+ scheduler2.step = Mock()
+ scheduler2.by_epoch = False
+ runner.param_schedulers = dict(key1=[scheduler1], key2=[scheduler2])
+ hook.after_train_epoch(runner)
+ hook.after_train_iter(runner, 0)
+ scheduler2.step.assert_called()
+
+ def test_after_epoch(self):
+ # runner.param_schedulers should be a list or dict
+ with pytest.raises(TypeError, match=self.error_msg):
+ hook = ParamSchedulerHook()
+ runner = Mock()
+ scheduler = Mock()
+ scheduler.step = Mock()
+ scheduler.by_epoch = True
+ runner.param_schedulers = scheduler
+ hook.after_train_iter(runner, 0)
+ scheduler.step.assert_called()
+
+ # runner.param_schedulers is a list of schedulers
+ hook = ParamSchedulerHook()
+ runner = Mock()
+ scheduler = Mock()
+ scheduler.step = Mock()
+ scheduler.by_epoch = True
+ runner.param_schedulers = [scheduler]
+ hook.after_train_epoch(runner)
+ scheduler.step.assert_called()
+
+ # runner.param_schedulers is a dict containing list of schedulers
+ scheduler1 = Mock()
+ scheduler1.step = Mock()
+ scheduler1.by_epoch = True
+ scheduler2 = Mock()
+ scheduler2.step = Mock()
+ scheduler2.by_epoch = True
+ runner.param_schedulers = dict(key1=[scheduler1], key2=[scheduler2])
+ hook.after_train_epoch(runner)
+ scheduler1.step.assert_called()
+ scheduler2.step.assert_called()
diff --git a/testbed/open-mmlab__mmengine/tests/test_hooks/test_runtime_info_hook.py b/testbed/open-mmlab__mmengine/tests/test_hooks/test_runtime_info_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b47782dd97cebda81914582d7e124977f64188c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_hooks/test_runtime_info_hook.py
@@ -0,0 +1,127 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from unittest import TestCase
+from unittest.mock import Mock
+
+import torch.nn as nn
+from torch.optim import SGD
+
+from mmengine.hooks import RuntimeInfoHook
+from mmengine.logging import MessageHub
+from mmengine.optim import OptimWrapper, OptimWrapperDict
+
+
+class TestRuntimeInfoHook(TestCase):
+
+ def test_before_train(self):
+ message_hub = MessageHub.get_instance(
+ 'runtime_info_hook_test_before_train')
+
+ class ToyDataset:
+ ...
+
+ runner = Mock()
+ runner.epoch = 7
+ runner.iter = 71
+ runner.max_epochs = 4
+ runner.max_iters = 40
+ runner.message_hub = message_hub
+ runner.train_dataloader.dataset = ToyDataset()
+ hook = RuntimeInfoHook()
+ hook.before_train(runner)
+ self.assertEqual(message_hub.get_info('epoch'), 7)
+ self.assertEqual(message_hub.get_info('iter'), 71)
+ self.assertEqual(message_hub.get_info('max_epochs'), 4)
+ self.assertEqual(message_hub.get_info('max_iters'), 40)
+ with self.assertRaisesRegex(KeyError, 'dataset_meta is not found'):
+ message_hub.get_info('dataset_meta')
+
+ class ToyDatasetWithMeta:
+ metainfo = dict()
+
+ runner.train_dataloader.dataset = ToyDatasetWithMeta()
+ hook.before_train(runner)
+ self.assertEqual(message_hub.get_info('dataset_meta'), dict())
+
+ def test_before_train_epoch(self):
+ message_hub = MessageHub.get_instance(
+ 'runtime_info_hook_test_before_train_epoch')
+ runner = Mock()
+ runner.epoch = 9
+ runner.message_hub = message_hub
+ hook = RuntimeInfoHook()
+ hook.before_train_epoch(runner)
+ self.assertEqual(message_hub.get_info('epoch'), 9)
+
+ def test_before_train_iter(self):
+ model = nn.Linear(1, 1)
+ optim1 = SGD(model.parameters(), lr=0.01)
+ optim2 = SGD(model.parameters(), lr=0.02)
+ optim_wrapper1 = OptimWrapper(optim1)
+ optim_wrapper2 = OptimWrapper(optim2)
+ optim_wrapper_dict = OptimWrapperDict(
+ key1=optim_wrapper1, key2=optim_wrapper2)
+ # single optimizer
+ message_hub = MessageHub.get_instance(
+ 'runtime_info_hook_test_before_train_iter')
+ runner = Mock()
+ runner.iter = 9
+ runner.optim_wrapper = optim_wrapper1
+ runner.message_hub = message_hub
+ hook = RuntimeInfoHook()
+ hook.before_train_iter(runner, batch_idx=2, data_batch=None)
+ self.assertEqual(message_hub.get_info('iter'), 9)
+ self.assertEqual(message_hub.get_scalar('train/lr').current(), 0.01)
+
+ with self.assertRaisesRegex(AssertionError,
+ 'runner.optim_wrapper.get_lr()'):
+ runner.optim_wrapper = Mock()
+ runner.optim_wrapper.get_lr = Mock(return_value='error type')
+ hook.before_train_iter(runner, batch_idx=2, data_batch=None)
+
+ # multiple optimizers
+ message_hub = MessageHub.get_instance(
+ 'runtime_info_hook_test_before_train_iter')
+ runner = Mock()
+ runner.iter = 9
+ optimizer1 = Mock()
+ optimizer1.param_groups = [{'lr': 0.01}]
+ optimizer2 = Mock()
+ optimizer2.param_groups = [{'lr': 0.02}]
+ runner.message_hub = message_hub
+ runner.optim_wrapper = optim_wrapper_dict
+ hook = RuntimeInfoHook()
+ hook.before_train_iter(runner, batch_idx=2, data_batch=None)
+ self.assertEqual(message_hub.get_info('iter'), 9)
+ self.assertEqual(
+ message_hub.get_scalar('train/key1.lr').current(), 0.01)
+ self.assertEqual(
+ message_hub.get_scalar('train/key2.lr').current(), 0.02)
+
+ def test_after_train_iter(self):
+ message_hub = MessageHub.get_instance(
+ 'runtime_info_hook_test_after_train_iter')
+ runner = Mock()
+ runner.message_hub = message_hub
+ hook = RuntimeInfoHook()
+ hook.after_train_iter(
+ runner, batch_idx=2, data_batch=None, outputs={'loss_cls': 1.111})
+ self.assertEqual(
+ message_hub.get_scalar('train/loss_cls').current(), 1.111)
+
+ def test_after_val_epoch(self):
+ message_hub = MessageHub.get_instance(
+ 'runtime_info_hook_test_after_val_epoch')
+ runner = Mock()
+ runner.message_hub = message_hub
+ hook = RuntimeInfoHook()
+ hook.after_val_epoch(runner, metrics={'acc': 0.8})
+ self.assertEqual(message_hub.get_scalar('val/acc').current(), 0.8)
+
+ def test_after_test_epoch(self):
+ message_hub = MessageHub.get_instance(
+ 'runtime_info_hook_test_after_test_epoch')
+ runner = Mock()
+ runner.message_hub = message_hub
+ hook = RuntimeInfoHook()
+ hook.after_test_epoch(runner, metrics={'acc': 0.8})
+ self.assertEqual(message_hub.get_scalar('test/acc').current(), 0.8)
diff --git a/testbed/open-mmlab__mmengine/tests/test_hooks/test_sampler_seed_hook.py b/testbed/open-mmlab__mmengine/tests/test_hooks/test_sampler_seed_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1bf8b543aa1a7e5bf8216a32b55692b9b4d9bb8
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_hooks/test_sampler_seed_hook.py
@@ -0,0 +1,29 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from unittest.mock import Mock
+
+from mmengine.hooks import DistSamplerSeedHook
+
+
+class TestDistSamplerSeedHook:
+
+ def test_before_epoch(self):
+
+ hook = DistSamplerSeedHook()
+ # Test dataset sampler
+ runner = Mock()
+ runner.epoch = 1
+ runner.train_loop.dataloader = Mock()
+ runner.train_loop.dataloader.sampler = Mock()
+ runner.train_loop.dataloader.sampler.set_epoch = Mock()
+ hook.before_train_epoch(runner)
+ runner.train_loop.dataloader.sampler.set_epoch.assert_called()
+ # Test batch sampler
+ runner = Mock()
+ runner.train_loop.dataloader = Mock()
+ runner.train_loop.dataloader.sampler = Mock(spec_set=True)
+ runner.train_loop.dataloader.batch_sampler = Mock()
+ runner.train_loop.dataloader.batch_sampler.sampler = Mock()
+ runner.train_loop.dataloader.batch_sampler.sampler.set_epoch = Mock()
+ hook.before_train_epoch(runner)
+ runner.train_loop.dataloader.\
+ batch_sampler.sampler.set_epoch.assert_called()
diff --git a/testbed/open-mmlab__mmengine/tests/test_hooks/test_sync_buffers_hook.py b/testbed/open-mmlab__mmengine/tests/test_hooks/test_sync_buffers_hook.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7c64287753a7f697d37332bfc22d46cc157c425
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_hooks/test_sync_buffers_hook.py
@@ -0,0 +1,13 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from unittest.mock import Mock
+
+from mmengine.hooks import SyncBuffersHook
+
+
+class TestSyncBuffersHook:
+
+ def test_sync_buffers_hook(self):
+ runner = Mock()
+ runner.model = Mock()
+ hook = SyncBuffersHook()
+ hook._after_epoch(runner)
diff --git a/testbed/open-mmlab__mmengine/tests/test_hub/test_hub.py b/testbed/open-mmlab__mmengine/tests/test_hub/test_hub.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc97bae7daa521485e5505d7f9b1a18a32d09df9
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_hub/test_hub.py
@@ -0,0 +1,52 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os.path as osp
+
+import pytest
+
+from mmengine import Config, DefaultScope
+from mmengine.hub import get_config, get_model
+from mmengine.utils import get_installed_path, is_installed
+
+data_path = osp.join(osp.dirname(osp.dirname(__file__)), 'data/')
+
+
+# mmdet has a more typical config structure, while mmpose has a complex
+# config structure
+@pytest.mark.skipif(
+ not (is_installed('mmdet') and is_installed('mmpose')),
+ reason='mmdet and mmpose should be installed')
+def test_get_config():
+ # Test load base config.
+ base_cfg = get_config('mmdet::_base_/models/faster-rcnn_r50_fpn.py')
+ package_path = get_installed_path('mmdet')
+ test_base_cfg = Config.fromfile(
+ osp.join(package_path, '.mim',
+ 'configs/_base_/models/faster-rcnn_r50_fpn.py'))
+ assert test_base_cfg._cfg_dict == base_cfg._cfg_dict
+
+ # Test load faster_rcnn config
+ cfg = get_config('mmdet::faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py')
+ test_cfg = Config.fromfile(
+ osp.join(package_path, '.mim',
+ 'configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py'))
+ assert cfg._cfg_dict == test_cfg._cfg_dict
+
+ # Test pretrained
+ cfg = get_config(
+ 'mmdet::faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py', pretrained=True)
+ assert cfg.model_path == 'https://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth' # noqa E301
+
+ # Test load mmpose
+ get_config(
+ 'mmpose::face/2d_kpt_sview_rgb_img/deeppose/wflw/res50_wflw_256x256'
+ '.py')
+
+
+@pytest.mark.skipif(
+ not is_installed('mmdet'), reason='mmdet and mmpose should be installed')
+def test_get_model():
+ # TODO compatible with downstream codebase.
+ DefaultScope.get_instance('test_get_model', scope_name='test_scope')
+ get_model('mmdet::faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py')
+ assert DefaultScope.get_current_instance().scope_name == 'test_scope'
+ DefaultScope._instance_dict.pop('test_get_model')
diff --git a/testbed/open-mmlab__mmengine/tests/test_logging/test_history_buffer.py b/testbed/open-mmlab__mmengine/tests/test_logging/test_history_buffer.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8aaca4a38632b8772fec31f64dbb2561d42edf2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_logging/test_history_buffer.py
@@ -0,0 +1,121 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import numpy as np
+import pytest
+
+from mmengine.logging import HistoryBuffer
+
+array_method = [np.array, lambda x: x]
+try:
+ import torch
+except ImportError:
+ pass
+else:
+ array_method.append(torch.tensor)
+
+
+class TestLoggerBuffer:
+
+ def test_init(self):
+ log_buffer = HistoryBuffer()
+ assert log_buffer.max_length == 1000000
+ log_history, counts = log_buffer.data
+ assert len(log_history) == 0
+ assert len(counts) == 0
+ # test the length of array exceed `max_length`
+ logs = np.random.randint(1, 10, log_buffer.max_length + 1)
+ counts = np.random.randint(1, 10, log_buffer.max_length + 1)
+ log_buffer = HistoryBuffer(logs, counts)
+ log_history, count_history = log_buffer.data
+
+ assert len(log_history) == log_buffer.max_length
+ assert len(count_history) == log_buffer.max_length
+ assert logs[1] == log_history[0]
+ assert counts[1] == count_history[0]
+
+ # The different lengths of `log_history` and `count_history` will
+ # raise error
+ with pytest.raises(AssertionError):
+ HistoryBuffer([1, 2], [1])
+
+ @pytest.mark.parametrize('array_method', array_method)
+ def test_update(self, array_method):
+ # test `update` method
+ log_buffer = HistoryBuffer()
+ log_history = array_method([1, 2, 3, 4, 5])
+ count_history = array_method([5, 5, 5, 5, 5])
+ for i in range(len(log_history)):
+ log_buffer.update(float(log_history[i]), float(count_history[i]))
+
+ recorded_history, recorded_count = log_buffer.data
+ for a, b in zip(log_history, recorded_history):
+ assert float(a) == float(b)
+ for a, b in zip(count_history, recorded_count):
+ assert float(a) == float(b)
+
+ # test the length of `array` exceed `max_length`
+ max_array = array_method([[-1] + [1] * (log_buffer.max_length - 1)])
+ max_count = array_method([[-1] + [1] * (log_buffer.max_length - 1)])
+ log_buffer = HistoryBuffer(max_array, max_count)
+ log_buffer.update(1)
+ log_history, count_history = log_buffer.data
+ assert log_history[0] == 1
+ assert count_history[0] == 1
+ assert len(log_history) == log_buffer.max_length
+ assert len(count_history) == log_buffer.max_length
+ # Update an iterable object will raise a type error, `log_val` and
+ # `count` should be single value
+ with pytest.raises(TypeError):
+ log_buffer.update(array_method([1, 2]))
+
+ @pytest.mark.parametrize('statistics_method, log_buffer_type',
+ [(np.min, 'min'), (np.max, 'max')])
+ def test_max_min(self, statistics_method, log_buffer_type):
+ log_history = np.random.randint(1, 5, 20)
+ count_history = np.ones(20)
+ log_buffer = HistoryBuffer(log_history, count_history)
+ assert statistics_method(log_history[-10:]) == \
+ getattr(log_buffer, log_buffer_type)(10)
+ assert statistics_method(log_history) == \
+ getattr(log_buffer, log_buffer_type)()
+
+ def test_mean(self):
+ log_history = np.random.randint(1, 5, 20)
+ count_history = np.ones(20)
+ log_buffer = HistoryBuffer(log_history, count_history)
+ assert np.sum(log_history[-10:]) / \
+ np.sum(count_history[-10:]) == \
+ log_buffer.mean(10)
+ assert np.sum(log_history) / \
+ np.sum(count_history) == \
+ log_buffer.mean()
+
+ def test_current(self):
+ log_history = np.random.randint(1, 5, 20)
+ count_history = np.ones(20)
+ log_buffer = HistoryBuffer(log_history, count_history)
+ assert log_history[-1] == log_buffer.current()
+ # test get empty array
+ log_buffer = HistoryBuffer()
+ with pytest.raises(ValueError):
+ log_buffer.current()
+
+ def test_statistics(self):
+ log_history = np.array([1, 2, 3, 4, 5])
+ count_history = np.array([1, 1, 1, 1, 1])
+ log_buffer = HistoryBuffer(log_history, count_history)
+ assert log_buffer.statistics('mean') == 3
+ assert log_buffer.statistics('min') == 1
+ assert log_buffer.statistics('max') == 5
+ assert log_buffer.statistics('current') == 5
+ # Access unknown method will raise an error.
+ with pytest.raises(KeyError):
+ log_buffer.statistics('unknown')
+
+ def test_register_statistics(self):
+
+ @HistoryBuffer.register_statistics
+ def custom_statistics(self):
+ return -1
+
+ log_buffer = HistoryBuffer()
+ assert log_buffer.statistics('custom_statistics') == -1
diff --git a/testbed/open-mmlab__mmengine/tests/test_logging/test_logger.py b/testbed/open-mmlab__mmengine/tests/test_logging/test_logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0734702ccb3c6e91034c3a7aa76846622bdcb7f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_logging/test_logger.py
@@ -0,0 +1,186 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import logging
+import os
+import re
+import sys
+from collections import OrderedDict
+from unittest.mock import patch
+
+import pytest
+
+from mmengine.logging import MMLogger, print_log
+
+
+class TestLogger:
+ stream_handler_regex_time = r'\d{2}/\d{2} \d{2}:\d{2}:\d{2}'
+ file_handler_regex_time = r'\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}'
+
+ @patch('mmengine.logging.logger._get_rank', lambda: 0)
+ def test_init_rank0(self, tmp_path):
+ logger = MMLogger.get_instance('rank0.pkg1', log_level='INFO')
+ assert logger.name == 'mmengine'
+ assert logger.instance_name == 'rank0.pkg1'
+ assert logger.instance_name == 'rank0.pkg1'
+ # Logger get from `MMLogger.get_instance` does not inherit from
+ # `logging.root`
+ assert logger.parent is None
+ assert len(logger.handlers) == 1
+ assert isinstance(logger.handlers[0], logging.StreamHandler)
+ assert logger.level == logging.NOTSET
+ assert logger.handlers[0].level == logging.INFO
+ # If `rank=0`, the `log_level` of stream_handler and file_handler
+ # depends on the given arguments.
+ tmp_file = tmp_path / 'tmp_file.log'
+ logger = MMLogger.get_instance(
+ 'rank0.pkg2', log_level='INFO', log_file=str(tmp_file))
+ assert isinstance(logger, logging.Logger)
+ assert len(logger.handlers) == 2
+ assert isinstance(logger.handlers[0], logging.StreamHandler)
+ assert isinstance(logger.handlers[1], logging.FileHandler)
+ logger_pkg3 = MMLogger.get_instance('rank0.pkg2')
+ assert id(logger_pkg3) == id(logger)
+ logger = MMLogger.get_instance(
+ 'rank0.pkg3', logger_name='logger_test', log_level='INFO')
+ assert logger.name == 'logger_test'
+ assert logger.instance_name == 'rank0.pkg3'
+ # `FileHandler` should be closed in Windows, otherwise we cannot
+ # delete the temporary directory
+ logging.shutdown()
+ MMLogger._instance_dict.clear()
+
+ @patch('mmengine.logging.logger._get_rank', lambda: 1)
+ def test_init_rank1(self, tmp_path):
+ # If `rank!=1`, the `loglevel` of file_handler is `logging.ERROR`.
+ tmp_file = tmp_path / 'tmp_file.log'
+ log_path = tmp_path / 'tmp_file_rank1.log'
+ logger = MMLogger.get_instance(
+ 'rank1.pkg2', log_level='INFO', log_file=str(tmp_file))
+ assert len(logger.handlers) == 1
+ logger = MMLogger.get_instance(
+ 'rank1.pkg3',
+ log_level='INFO',
+ log_file=str(tmp_file),
+ distributed=True)
+ assert logger.handlers[0].level == logging.ERROR
+ assert logger.handlers[1].level == logging.INFO
+ assert len(logger.handlers) == 2
+ assert os.path.exists(log_path)
+ # `FileHandler` should be closed in Windows, otherwise we cannot
+ # delete the temporary directory
+ logging.shutdown()
+ MMLogger._instance_dict.clear()
+
+ @pytest.mark.parametrize('log_level',
+ [logging.WARNING, logging.INFO, logging.DEBUG])
+ def test_handler(self, capsys, tmp_path, log_level):
+ # test stream handler can output correct format logs
+ instance_name = f'test_stream_{str(log_level)}'
+ logger = MMLogger.get_instance(instance_name, log_level=log_level)
+ logger.log(level=log_level, msg='welcome')
+ out, _ = capsys.readouterr()
+ # Skip match colored INFO
+ loglevl_name = logging._levelToName[log_level]
+ match = re.fullmatch(
+ self.stream_handler_regex_time + f' - mmengine - '
+ f'(.*){loglevl_name}(.*) - welcome\n', out)
+ assert match is not None
+
+ # test file_handler output plain text without color.
+ tmp_file = tmp_path / 'tmp_file.log'
+ instance_name = f'test_file_{log_level}'
+ logger = MMLogger.get_instance(
+ instance_name, log_level=log_level, log_file=tmp_file)
+ logger.log(level=log_level, msg='welcome')
+ with open(tmp_path / 'tmp_file.log') as f:
+ log_text = f.read()
+ match = re.fullmatch(
+ self.file_handler_regex_time +
+ f' - mmengine - {loglevl_name} - '
+ f'welcome\n', log_text)
+ assert match is not None
+ # `FileHandler` should be closed in Windows, otherwise we cannot
+ # delete the temporary directory
+ logging.shutdown()
+ MMLogger._instance_dict.clear()
+
+ def test_error_format(self, capsys):
+ # test error level log can output file path, function name and
+ # line number
+ logger = MMLogger.get_instance('test_error', log_level='INFO')
+ logger.error('welcome')
+ lineno = sys._getframe().f_lineno - 1
+ # replace \ for windows:
+ # origin: c:\\a\\b\\c.py
+ # replaced: c:\\\\a\\\\b\\\\c.py for re.match.
+ file_path = __file__.replace('\\', '\\\\')
+ function_name = sys._getframe().f_code.co_name
+ pattern = self.stream_handler_regex_time + \
+ r' - mmengine - (.*)ERROR(.*) - ' \
+ f'{file_path} - {function_name} - ' \
+ f'{lineno} - welcome\n'
+ out, _ = capsys.readouterr()
+ match = re.fullmatch(pattern, out)
+ assert match is not None
+
+ def test_print_log(self, capsys, tmp_path):
+ # caplog cannot record MMLogger's logs.
+ # Test simple print.
+ print_log('welcome', logger=None)
+ out, _ = capsys.readouterr()
+ assert out == 'welcome\n'
+ # Test silent logger and skip print.
+ print_log('welcome', logger='silent')
+ out, _ = capsys.readouterr()
+ assert out == ''
+ logger = MMLogger.get_instance('test_print_log')
+ # Test using specified logger
+ print_log('welcome', logger=logger)
+ out, _ = capsys.readouterr()
+ match = re.fullmatch(
+ self.stream_handler_regex_time + ' - mmengine - (.*)INFO(.*) - '
+ 'welcome\n', out)
+ assert match is not None
+ # Test access logger by name.
+ print_log('welcome', logger='test_print_log')
+ out, _ = capsys.readouterr()
+ match = re.fullmatch(
+ self.stream_handler_regex_time + ' - mmengine - (.*)INFO(.*) - '
+ 'welcome\n', out)
+ assert match is not None
+ # Test access the latest created logger.
+ print_log('welcome', logger='current')
+ out, _ = capsys.readouterr()
+ match = re.fullmatch(
+ self.stream_handler_regex_time + ' - mmengine - (.*)INFO(.*) - '
+ 'welcome\n', out)
+ assert match is not None
+ # Test invalid logger type.
+ with pytest.raises(TypeError):
+ print_log('welcome', logger=dict)
+ with pytest.raises(ValueError):
+ print_log('welcome', logger='unknown')
+
+ def test_get_instance(self):
+ # Test get root mmengine logger.
+ MMLogger._instance_dict = OrderedDict()
+ root_logger = MMLogger.get_current_instance()
+ mmdet_logger = MMLogger.get_instance('mmdet')
+ assert root_logger.name == mmdet_logger.name
+ assert id(root_logger) != id(mmdet_logger)
+ assert id(MMLogger.get_instance('mmengine')) == id(root_logger)
+ # Test original `get_current_instance` function.
+ MMLogger.get_instance('mmdet')
+ assert MMLogger.get_current_instance().instance_name == 'mmdet'
+
+ def test_set_level(self, capsys):
+ logger = MMLogger.get_instance('test_set_level')
+ logger.info('hello')
+ out, _ = capsys.readouterr()
+ assert 'INFO' in out
+ logger.setLevel('WARNING')
+ logger.info('hello')
+ out, _ = capsys.readouterr()
+ assert not out
+ logger.warning('hello')
+ out, _ = capsys.readouterr()
+ assert 'WARNING' in out
diff --git a/testbed/open-mmlab__mmengine/tests/test_logging/test_message_hub.py b/testbed/open-mmlab__mmengine/tests/test_logging/test_message_hub.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6061f82e82ab77f9a8da7b974551baf9bd2aaaa
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_logging/test_message_hub.py
@@ -0,0 +1,200 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import pickle
+from collections import OrderedDict
+
+import numpy as np
+import pytest
+
+from mmengine.logging import HistoryBuffer, MessageHub
+from mmengine.utils import is_installed
+
+
+class NoDeepCopy:
+
+ def __deepcopy__(self, memodict={}):
+ raise NotImplementedError
+
+
+class TestMessageHub:
+
+ def test_init(self):
+ message_hub = MessageHub('name')
+ assert message_hub.instance_name == 'name'
+ assert len(message_hub.log_scalars) == 0
+ assert len(message_hub.log_scalars) == 0
+ # The type of log_scalars's value must be `HistoryBuffer`.
+ with pytest.raises(AssertionError):
+ MessageHub('hello', log_scalars=OrderedDict(a=1))
+ # `Resumed_keys`
+ with pytest.raises(AssertionError):
+ MessageHub(
+ 'hello',
+ runtime_info=OrderedDict(iter=1),
+ resumed_keys=OrderedDict(iters=False))
+
+ def test_update_scalar(self):
+ message_hub = MessageHub.get_instance('mmengine')
+ # test create target `HistoryBuffer` by name
+ message_hub.update_scalar('name', 1)
+ log_buffer = message_hub.log_scalars['name']
+ assert (log_buffer._log_history == np.array([1])).all()
+ # test update target `HistoryBuffer` by name
+ message_hub.update_scalar('name', 1)
+ assert (log_buffer._log_history == np.array([1, 1])).all()
+ # unmatched string will raise a key error
+
+ def test_update_info(self):
+ message_hub = MessageHub.get_instance('mmengine')
+ # test runtime value can be overwritten.
+ message_hub.update_info('key', 2)
+ assert message_hub.runtime_info['key'] == 2
+ message_hub.update_info('key', 1)
+ assert message_hub.runtime_info['key'] == 1
+
+ def test_update_infos(self):
+ message_hub = MessageHub.get_instance('mmengine')
+ # test runtime value can be overwritten.
+ message_hub.update_info_dict({'a': 2, 'b': 3})
+ assert message_hub.runtime_info['a'] == 2
+ assert message_hub.runtime_info['b'] == 3
+ assert message_hub._resumed_keys['a']
+ assert message_hub._resumed_keys['b']
+
+ def test_get_scalar(self):
+ message_hub = MessageHub.get_instance('mmengine')
+ # Get undefined key will raise error
+ with pytest.raises(KeyError):
+ message_hub.get_scalar('unknown')
+ # test get log_buffer as wished
+ log_history = np.array([1, 2, 3, 4, 5])
+ count = np.array([1, 1, 1, 1, 1])
+ for i in range(len(log_history)):
+ message_hub.update_scalar('test_value', float(log_history[i]),
+ int(count[i]))
+ recorded_history, recorded_count = \
+ message_hub.get_scalar('test_value').data
+ assert (log_history == recorded_history).all()
+ assert (recorded_count == count).all()
+
+ def test_get_runtime(self):
+ message_hub = MessageHub.get_instance('mmengine')
+ with pytest.raises(KeyError):
+ message_hub.get_info('unknown')
+ recorded_dict = dict(a=1, b=2)
+ message_hub.update_info('test_value', recorded_dict)
+ assert message_hub.get_info('test_value') == recorded_dict
+
+ @pytest.mark.skipif(not is_installed('torch'), reason='requires torch')
+ def test_get_scalars(self):
+ import torch
+ message_hub = MessageHub.get_instance('mmengine')
+ log_dict = dict(
+ loss=1,
+ loss_cls=torch.tensor(2),
+ loss_bbox=np.array(3),
+ loss_iou=dict(value=1, count=2))
+ message_hub.update_scalars(log_dict)
+ loss = message_hub.get_scalar('loss')
+ loss_cls = message_hub.get_scalar('loss_cls')
+ loss_bbox = message_hub.get_scalar('loss_bbox')
+ loss_iou = message_hub.get_scalar('loss_iou')
+ assert loss.current() == 1
+ assert loss_cls.current() == 2
+ assert loss_bbox.current() == 3
+ assert loss_iou.mean() == 0.5
+
+ with pytest.raises(AssertionError):
+ loss_dict = dict(error_type=[])
+ message_hub.update_scalars(loss_dict)
+
+ with pytest.raises(AssertionError):
+ loss_dict = dict(error_type=dict(count=1))
+ message_hub.update_scalars(loss_dict)
+
+ def test_state_dict(self):
+ message_hub = MessageHub.get_instance('test_state_dict')
+ # update log_scalars.
+ message_hub.update_scalar('loss', 0.1)
+ message_hub.update_scalar('lr', 0.1, resumed=False)
+ # update runtime information
+ message_hub.update_info('iter', 1, resumed=True)
+ message_hub.update_info('tensor', [1, 2, 3], resumed=False)
+ no_copy = NoDeepCopy()
+ message_hub.update_info('no_copy', no_copy, resumed=True)
+ state_dict = message_hub.state_dict()
+
+ assert state_dict['log_scalars']['loss'].data == (np.array([0.1]),
+ np.array([1]))
+ assert 'lr' not in state_dict['log_scalars']
+ assert state_dict['runtime_info']['iter'] == 1
+ assert 'tensor' not in state_dict['runtime_info']
+ assert state_dict['runtime_info']['no_copy'] is no_copy
+
+ def test_load_state_dict(self, capsys):
+ message_hub1 = MessageHub.get_instance('test_load_state_dict1')
+ # update log_scalars.
+ message_hub1.update_scalar('loss', 0.1)
+ message_hub1.update_scalar('lr', 0.1, resumed=False)
+ # update runtime information
+ message_hub1.update_info('iter', 1, resumed=True)
+ message_hub1.update_info('tensor', [1, 2, 3], resumed=False)
+ state_dict = message_hub1.state_dict()
+
+ # Resume from state_dict
+ message_hub2 = MessageHub.get_instance('test_load_state_dict2')
+ message_hub2.load_state_dict(state_dict)
+ assert message_hub2.get_scalar('loss').data == (np.array([0.1]),
+ np.array([1]))
+ assert message_hub2.get_info('iter') == 1
+
+ # Test resume from `MessageHub` instance.
+ message_hub3 = MessageHub.get_instance('test_load_state_dict3')
+ message_hub3.load_state_dict(state_dict)
+ assert message_hub3.get_scalar('loss').data == (np.array([0.1]),
+ np.array([1]))
+ assert message_hub3.get_info('iter') == 1
+
+ # Test resume custom state_dict
+ state_dict = OrderedDict()
+ state_dict['log_scalars'] = dict(a=1, b=HistoryBuffer())
+ state_dict['runtime_info'] = dict(c=1, d=NoDeepCopy(), e=1)
+ state_dict['resumed_keys'] = dict(
+ a=True, b=True, c=True, e=False, f=True)
+
+ message_hub4 = MessageHub.get_instance('test_load_state_dict4')
+ message_hub4.load_state_dict(state_dict)
+ assert 'a' not in message_hub4.log_scalars and 'b' in \
+ message_hub4.log_scalars
+ assert 'c' in message_hub4.runtime_info and \
+ state_dict['runtime_info']['d'] is \
+ message_hub4.runtime_info['d']
+ assert message_hub4._resumed_keys == OrderedDict(
+ b=True, c=True, e=False)
+
+ def test_getstate(self):
+ message_hub = MessageHub.get_instance('name')
+ # update log_scalars.
+ message_hub.update_scalar('loss', 0.1)
+ message_hub.update_scalar('lr', 0.1, resumed=False)
+ # update runtime information
+ message_hub.update_info('iter', 1, resumed=True)
+ message_hub.update_info('tensor', [1, 2, 3], resumed=False)
+ obj = pickle.dumps(message_hub)
+ instance = pickle.loads(obj)
+
+ with pytest.raises(KeyError):
+ instance.get_info('feat')
+ with pytest.raises(KeyError):
+ instance.get_info('lr')
+
+ instance.get_info('iter')
+ instance.get_scalar('loss')
+
+ def test_get_instance(self):
+ # Test get root mmengine message hub.
+ MessageHub._instance_dict = OrderedDict()
+ message_hub = MessageHub.get_current_instance()
+ assert id(MessageHub.get_instance('mmengine')) == id(message_hub)
+ # Test original `get_current_instance` function.
+ MessageHub.get_instance('mmdet')
+ assert MessageHub.get_current_instance().instance_name == 'mmdet'
diff --git a/testbed/open-mmlab__mmengine/tests/test_model/test_averaged_model.py b/testbed/open-mmlab__mmengine/tests/test_model/test_averaged_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..efbe3349c0cf81e997db8762615717beba7ffd54
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_model/test_averaged_model.py
@@ -0,0 +1,262 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import itertools
+from unittest import TestCase
+
+import torch
+
+from mmengine.model import (ExponentialMovingAverage, MomentumAnnealingEMA,
+ StochasticWeightAverage)
+from mmengine.testing import assert_allclose
+
+
+class TestAveragedModel(TestCase):
+ """Test the AveragedModel class.
+
+ Some test cases are referenced from https://github.com/pytorch/pytorch/blob/master/test/test_optim.py
+ """ # noqa: E501
+
+ def _test_swa_model(self, net_device, avg_device):
+ model = torch.nn.Sequential(
+ torch.nn.Conv2d(1, 5, kernel_size=3),
+ torch.nn.Linear(5, 10)).to(net_device)
+
+ averaged_model = StochasticWeightAverage(model, device=avg_device)
+ averaged_params = [
+ torch.zeros_like(param) for param in model.parameters()
+ ]
+ n_updates = 2
+ for i in range(n_updates):
+ for p, p_avg in zip(model.parameters(), averaged_params):
+ p.detach().add_(torch.randn_like(p))
+ p_avg += p.detach() / n_updates
+ averaged_model.update_parameters(model)
+
+ for p_avg, p_swa in zip(averaged_params, averaged_model.parameters()):
+ # Check that AveragedModel is on the correct device
+ self.assertTrue(p_swa.device == avg_device)
+ self.assertTrue(p.device == net_device)
+ assert_allclose(p_avg, p_swa.to(p_avg.device))
+ self.assertTrue(averaged_model.steps.device == avg_device)
+
+ def test_averaged_model_all_devices(self):
+ cpu = torch.device('cpu')
+ self._test_swa_model(cpu, cpu)
+ if torch.cuda.is_available():
+ cuda = torch.device(0)
+ self._test_swa_model(cuda, cpu)
+ self._test_swa_model(cpu, cuda)
+ self._test_swa_model(cuda, cuda)
+
+ def test_swa_mixed_device(self):
+ if not torch.cuda.is_available():
+ return
+ model = torch.nn.Sequential(
+ torch.nn.Conv2d(1, 5, kernel_size=3), torch.nn.Linear(5, 10))
+ model[0].cuda()
+ model[1].cpu()
+ averaged_model = StochasticWeightAverage(model)
+ averaged_params = [
+ torch.zeros_like(param) for param in model.parameters()
+ ]
+ n_updates = 10
+ for i in range(n_updates):
+ for p, p_avg in zip(model.parameters(), averaged_params):
+ p.detach().add_(torch.randn_like(p))
+ p_avg += p.detach() / n_updates
+ averaged_model.update_parameters(model)
+
+ for p_avg, p_swa in zip(averaged_params, averaged_model.parameters()):
+ assert_allclose(p_avg, p_swa)
+ # Check that AveragedModel is on the correct device
+ self.assertTrue(p_avg.device == p_swa.device)
+
+ def test_swa_state_dict(self):
+ model = torch.nn.Sequential(
+ torch.nn.Conv2d(1, 5, kernel_size=3), torch.nn.Linear(5, 10))
+ averaged_model = StochasticWeightAverage(model)
+ averaged_model2 = StochasticWeightAverage(model)
+ n_updates = 10
+ for i in range(n_updates):
+ for p in model.parameters():
+ p.detach().add_(torch.randn_like(p))
+ averaged_model.update_parameters(model)
+ averaged_model2.load_state_dict(averaged_model.state_dict())
+ for p_swa, p_swa2 in zip(averaged_model.parameters(),
+ averaged_model2.parameters()):
+ assert_allclose(p_swa, p_swa2)
+ self.assertTrue(averaged_model.steps == averaged_model2.steps)
+
+ def test_ema(self):
+ # test invalid momentum
+ with self.assertRaisesRegex(AssertionError,
+ 'momentum must be in range'):
+ model = torch.nn.Sequential(
+ torch.nn.Conv2d(1, 5, kernel_size=3), torch.nn.Linear(5, 10))
+ ExponentialMovingAverage(model, momentum=3)
+
+ with self.assertWarnsRegex(
+ Warning,
+ 'The value of momentum in EMA is usually a small number'):
+ model = torch.nn.Sequential(
+ torch.nn.Conv2d(1, 5, kernel_size=3), torch.nn.Linear(5, 10))
+ ExponentialMovingAverage(model, momentum=0.9)
+ # test EMA
+ model = torch.nn.Sequential(
+ torch.nn.Conv2d(1, 5, kernel_size=3), torch.nn.Linear(5, 10))
+ momentum = 0.1
+
+ ema_model = ExponentialMovingAverage(model, momentum=momentum)
+ averaged_params = [
+ torch.zeros_like(param) for param in model.parameters()
+ ]
+ n_updates = 10
+ for i in range(n_updates):
+ updated_averaged_params = []
+ for p, p_avg in zip(model.parameters(), averaged_params):
+ p.detach().add_(torch.randn_like(p))
+ if i == 0:
+ updated_averaged_params.append(p.clone())
+ else:
+ updated_averaged_params.append(
+ (p_avg * (1 - momentum) + p * momentum).clone())
+ ema_model.update_parameters(model)
+ averaged_params = updated_averaged_params
+
+ for p_target, p_ema in zip(averaged_params, ema_model.parameters()):
+ assert_allclose(p_target, p_ema)
+
+ def test_ema_update_buffers(self):
+ # Test EMA and update_buffers as True.
+ model = torch.nn.Sequential(
+ torch.nn.Conv2d(1, 5, kernel_size=3),
+ torch.nn.BatchNorm2d(5, momentum=0.3), torch.nn.Linear(5, 10))
+ momentum = 0.1
+
+ ema_model = ExponentialMovingAverage(
+ model, momentum=momentum, update_buffers=True)
+ averaged_params = [
+ torch.zeros_like(param)
+ for param in itertools.chain(model.parameters(), model.buffers())
+ if param.size() != torch.Size([])
+ ]
+ n_updates = 10
+ for i in range(n_updates):
+ updated_averaged_params = []
+ params = [
+ param for param in itertools.chain(model.parameters(),
+ model.buffers())
+ if param.size() != torch.Size([])
+ ]
+ for p, p_avg in zip(params, averaged_params):
+ p.detach().add_(torch.randn_like(p))
+ if i == 0:
+ updated_averaged_params.append(p.clone())
+ else:
+ updated_averaged_params.append(
+ (p_avg * (1 - momentum) + p * momentum).clone())
+ ema_model.update_parameters(model)
+ averaged_params = updated_averaged_params
+
+ ema_params = [
+ param for param in itertools.chain(ema_model.module.parameters(),
+ ema_model.module.buffers())
+ if param.size() != torch.Size([])
+ ]
+ for p_target, p_ema in zip(averaged_params, ema_params):
+ assert_allclose(p_target, p_ema)
+
+ def test_momentum_annealing_ema(self):
+ model = torch.nn.Sequential(
+ torch.nn.Conv2d(1, 5, kernel_size=3),
+ torch.nn.BatchNorm2d(5, momentum=0.3), torch.nn.Linear(5, 10))
+ # Test invalid gamma
+ with self.assertRaisesRegex(AssertionError,
+ 'gamma must be greater than 0'):
+ MomentumAnnealingEMA(model, gamma=-1)
+
+ # Test EMA with momentum annealing.
+ momentum = 0.1
+ gamma = 4
+
+ ema_model = MomentumAnnealingEMA(
+ model, gamma=gamma, momentum=momentum, update_buffers=True)
+ averaged_params = [
+ torch.zeros_like(param)
+ for param in itertools.chain(model.parameters(), model.buffers())
+ if param.size() != torch.Size([])
+ ]
+ n_updates = 10
+ for i in range(n_updates):
+ updated_averaged_params = []
+ params = [
+ param for param in itertools.chain(model.parameters(),
+ model.buffers())
+ if param.size() != torch.Size([])
+ ]
+ for p, p_avg in zip(params, averaged_params):
+ p.add(torch.randn_like(p))
+ if i == 0:
+ updated_averaged_params.append(p.clone())
+ else:
+ m = max(momentum, gamma / (gamma + i))
+ updated_averaged_params.append(
+ (p_avg * (1 - m) + p * m).clone())
+ ema_model.update_parameters(model)
+ averaged_params = updated_averaged_params
+
+ ema_params = [
+ param for param in itertools.chain(ema_model.module.parameters(),
+ ema_model.module.buffers())
+ if param.size() != torch.Size([])
+ ]
+ for p_target, p_ema in zip(averaged_params, ema_params):
+ assert_allclose(p_target, p_ema)
+
+ def test_momentum_annealing_ema_with_interval(self):
+ # Test EMA with momentum annealing and interval
+ model = torch.nn.Sequential(
+ torch.nn.Conv2d(1, 5, kernel_size=3),
+ torch.nn.BatchNorm2d(5, momentum=0.3), torch.nn.Linear(5, 10))
+ momentum = 0.1
+ gamma = 4
+ interval = 3
+
+ ema_model = MomentumAnnealingEMA(
+ model,
+ gamma=gamma,
+ momentum=momentum,
+ interval=interval,
+ update_buffers=True)
+ averaged_params = [
+ torch.zeros_like(param)
+ for param in itertools.chain(model.parameters(), model.buffers())
+ if param.size() != torch.Size([])
+ ]
+ n_updates = 10
+ for i in range(n_updates):
+ updated_averaged_params = []
+ params = [
+ param for param in itertools.chain(model.parameters(),
+ model.buffers())
+ if param.size() != torch.Size([])
+ ]
+ for p, p_avg in zip(params, averaged_params):
+ p.add(torch.randn_like(p))
+ if i == 0:
+ updated_averaged_params.append(p.clone())
+ elif i % interval == 0:
+ m = max(momentum, gamma / (gamma + i))
+ updated_averaged_params.append(
+ (p_avg * (1 - m) + p * m).clone())
+ else:
+ updated_averaged_params.append(p_avg.clone())
+ ema_model.update_parameters(model)
+ averaged_params = updated_averaged_params
+
+ ema_params = [
+ param for param in itertools.chain(ema_model.module.parameters(),
+ ema_model.module.buffers())
+ if param.size() != torch.Size([])
+ ]
+ for p_target, p_ema in zip(averaged_params, ema_params):
+ assert_allclose(p_target, p_ema)
diff --git a/testbed/open-mmlab__mmengine/tests/test_model/test_base_model/test_base_model.py b/testbed/open-mmlab__mmengine/tests/test_model/test_base_model/test_base_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..21356af771f81d571b802c760c7d2e444e624c91
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_model/test_base_model/test_base_model.py
@@ -0,0 +1,203 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import itertools
+import unittest
+from unittest import TestCase
+
+import torch
+import torch.nn as nn
+from parameterized import parameterized
+from torch.optim import SGD
+
+from mmengine.model import BaseDataPreprocessor, BaseModel
+from mmengine.optim import OptimWrapper
+from mmengine.registry import MODELS
+from mmengine.testing import assert_allclose
+
+dtypes_to_test = [torch.float16, torch.float32, torch.float64, torch.half]
+
+cpu_devices = ['cpu', torch.device('cpu')]
+cuda_devices = ['cuda', 0, torch.device('cuda')]
+devices_to_test = cpu_devices
+if torch.cuda.is_available():
+ devices_to_test += cuda_devices
+
+
+def list_product(*args):
+ return list(itertools.product(*args))
+
+
+@MODELS.register_module()
+class CustomDataPreprocessor(BaseDataPreprocessor):
+
+ def forward(self, data, training=False):
+ if training:
+ return 1
+ else:
+ return 2
+
+
+class ToyModel(BaseModel):
+
+ def __init__(self, data_preprocessor=None):
+ super().__init__(data_preprocessor=data_preprocessor, init_cfg=None)
+ self.conv = nn.Conv2d(3, 1, 1)
+
+ def forward(self, inputs, data_sample=None, mode='tensor'):
+ if mode == 'loss':
+ out = self.conv(inputs)
+ return dict(loss=out)
+ elif mode == 'predict':
+ out = self.conv(inputs)
+ return out
+ elif mode == 'tensor':
+ out = self.conv(inputs)
+ return out
+
+
+class NestedModel(BaseModel):
+
+ def __init__(self):
+ super().__init__()
+ self.toy_model = ToyModel()
+
+ def forward(self):
+ pass
+
+
+class TestBaseModel(TestCase):
+
+ def test_init(self):
+ # initiate model without `data_preprocessor`
+ model = ToyModel()
+ self.assertIsInstance(model.data_preprocessor, BaseDataPreprocessor)
+ data_preprocessor = dict(type='CustomDataPreprocessor')
+ model = ToyModel(data_preprocessor=data_preprocessor)
+ self.assertIsInstance(model.data_preprocessor, CustomDataPreprocessor)
+ self.assertEqual(model.data_preprocessor(1, training=True), 1)
+ self.assertEqual(model.data_preprocessor(1, training=False), 2)
+
+ # initiate model with built `data_preprocessor`.
+ data_preprocessor = CustomDataPreprocessor()
+ model = ToyModel(data_preprocessor=data_preprocessor)
+ self.assertIs(model.data_preprocessor, data_preprocessor)
+
+ # initiate model with error type `data_preprocessor`.
+ with self.assertRaisesRegex(TypeError, 'data_preprocessor should be'):
+ ToyModel(data_preprocessor=[data_preprocessor])
+
+ def test_parse_losses(self):
+ model = ToyModel()
+ loss_cls = torch.tensor(1, dtype=torch.float32)
+ loss_list = [
+ torch.tensor(2, dtype=torch.float32),
+ torch.tensor(3, dtype=torch.float32)
+ ]
+ losses = dict(loss_cls=loss_cls, loss_list=loss_list)
+ target_parsed_losses = torch.tensor(6, dtype=torch.float32)
+ targe_log_vars = dict(
+ loss=torch.tensor(6, dtype=torch.float32),
+ loss_cls=torch.tensor(1, dtype=torch.float32),
+ loss_list=torch.tensor(5, dtype=torch.float32))
+ parse_losses, log_vars = model.parse_losses(losses)
+ assert_allclose(parse_losses, target_parsed_losses)
+ for key in log_vars:
+ self.assertIn(key, targe_log_vars)
+ assert_allclose(log_vars[key], targe_log_vars[key])
+
+ with self.assertRaises(TypeError):
+ losses['error_key'] = dict()
+ model.parse_losses(losses)
+
+ def test_train_step(self):
+ model = ToyModel()
+ optimizer = SGD(model.parameters(), lr=0.1)
+ optim_wrapper = OptimWrapper(optimizer)
+ inputs = torch.randn(1, 3, 1, 1)
+ data = dict(inputs=inputs, data_sample=None)
+ # initiate grad.
+ # model.conv.weight.grad = torch.randn(1, 3, 1, 1)
+ log_vars = model.train_step(data, optim_wrapper)
+ self.assertIsNotNone(model.conv.weight.grad)
+ self.assertIsInstance(log_vars['loss'], torch.Tensor)
+
+ def test_val_step(self):
+ inputs = torch.randn(1, 3, 1, 1)
+ data = dict(inputs=inputs, data_sample=None)
+ model = ToyModel()
+ out = model.val_step(data)
+ self.assertIsInstance(out, torch.Tensor)
+
+ def test_test_step(self):
+ inputs = torch.randn(1, 3, 1, 1)
+ data = dict(inputs=inputs, data_sample=None)
+ model = ToyModel()
+ out = model.val_step(data)
+ self.assertIsInstance(out, torch.Tensor)
+
+ @unittest.skipIf(not torch.cuda.is_available(), 'cuda should be available')
+ def test_cuda(self):
+ inputs = torch.randn(1, 3, 1, 1).cuda()
+ data = dict(inputs=inputs, data_sample=None)
+ model = ToyModel().cuda()
+ out = model.val_step(data)
+ self.assertEqual(out.device.type, 'cuda')
+
+ model = NestedModel()
+ self.assertEqual(model.data_preprocessor._device, torch.device('cpu'))
+ self.assertEqual(model.toy_model.data_preprocessor._device,
+ torch.device('cpu'))
+ model.cuda()
+ self.assertEqual(model.data_preprocessor._device, torch.device('cuda'))
+ self.assertEqual(model.toy_model.data_preprocessor._device,
+ torch.device('cuda'))
+
+ @unittest.skipIf(not torch.cuda.is_available(), 'cuda should be available')
+ def test_to(self):
+ inputs = torch.randn(1, 3, 1, 1).to('cuda:0')
+ data = dict(inputs=inputs, data_sample=None)
+ model = ToyModel().to(torch.cuda.current_device())
+ out = model.val_step(data)
+ self.assertEqual(out.device.type, 'cuda')
+
+ model = NestedModel()
+ self.assertEqual(model.data_preprocessor._device, torch.device('cpu'))
+ self.assertEqual(model.toy_model.data_preprocessor._device,
+ torch.device('cpu'))
+ model.to('cuda')
+ self.assertEqual(model.data_preprocessor._device, torch.device('cuda'))
+ self.assertEqual(model.toy_model.data_preprocessor._device,
+ torch.device('cuda'))
+
+ model.to()
+ self.assertEqual(model.data_preprocessor._device, torch.device('cuda'))
+ self.assertEqual(model.toy_model.data_preprocessor._device,
+ torch.device('cuda'))
+
+ @parameterized.expand(list_product(devices_to_test))
+ def test_to_device(self, device):
+ model = ToyModel().to(device)
+ self.assertTrue(
+ all(p.device.type == torch.device(device).type
+ for p in model.parameters())
+ and model.data_preprocessor._device == torch.device(device))
+
+ @parameterized.expand(list_product(dtypes_to_test))
+ def test_to_dtype(self, dtype):
+ model = ToyModel().to(dtype)
+ self.assertTrue(all(p.dtype == dtype for p in model.parameters()))
+
+ @parameterized.expand(
+ list_product(devices_to_test, dtypes_to_test,
+ ['args', 'kwargs', 'hybrid']))
+ def test_to_device_and_dtype(self, device, dtype, mode):
+ if mode == 'args':
+ model = ToyModel().to(device, dtype)
+ elif mode == 'kwargs':
+ model = ToyModel().to(device=device, dtype=dtype)
+ elif mode == 'hybrid':
+ model = ToyModel().to(device, dtype=dtype)
+ self.assertTrue(
+ all(p.dtype == dtype for p in model.parameters())
+ and model.data_preprocessor._device == torch.device(device)
+ and all(p.device.type == torch.device(device).type
+ for p in model.parameters()))
diff --git a/testbed/open-mmlab__mmengine/tests/test_model/test_base_model/test_data_preprocessor.py b/testbed/open-mmlab__mmengine/tests/test_model/test_base_model/test_data_preprocessor.py
new file mode 100644
index 0000000000000000000000000000000000000000..377cb1753b7a5869d4636886203b513c56d9bc5c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_model/test_base_model/test_data_preprocessor.py
@@ -0,0 +1,252 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from unittest import TestCase
+
+import torch
+import torch.nn.functional as F
+
+from mmengine.model import BaseDataPreprocessor, ImgDataPreprocessor
+from mmengine.structures import InstanceData
+from mmengine.testing import assert_allclose
+
+
+class TestBaseDataPreprocessor(TestCase):
+
+ def test_init(self):
+ base_data_preprocessor = BaseDataPreprocessor()
+ self.assertEqual(base_data_preprocessor._device.type, 'cpu')
+ self.assertEqual(base_data_preprocessor._non_blocking, False)
+
+ base_data_preprocessor = BaseDataPreprocessor(True)
+ self.assertEqual(base_data_preprocessor._device.type, 'cpu')
+ self.assertEqual(base_data_preprocessor._non_blocking, True)
+
+ def test_forward(self):
+ # Test cpu forward with list of data samples.
+ base_data_preprocessor = BaseDataPreprocessor()
+ input1 = torch.randn(1, 3, 5)
+ input2 = torch.randn(1, 3, 5)
+ label1 = torch.randn(1)
+ label2 = torch.randn(1)
+
+ # Test with dict of batch inputs and batch data samples
+ data = dict(inputs=[input1, input2], data_sample=[label1, label2])
+ output = base_data_preprocessor(data)
+ batch_inputs, batch_labels = output['inputs'], output['data_sample']
+ self.assertTrue(torch.is_floating_point(batch_inputs[0]))
+ self.assertEqual(batch_inputs[0].shape, (1, 3, 5))
+
+ assert_allclose(input1, batch_inputs[0])
+ assert_allclose(input2, batch_inputs[1])
+ assert_allclose(label1, batch_labels[0])
+ assert_allclose(label2, batch_labels[1])
+
+ # Test with tuple of batch inputs and batch data samples
+ data = (torch.stack([input1, input2]), (label1, label2))
+ batch_inputs, batch_labels = base_data_preprocessor(data)
+ self.assertTrue(torch.is_floating_point(batch_inputs))
+ self.assertEqual(batch_inputs[0].shape, (1, 3, 5))
+ self.assertEqual(batch_inputs[1].shape, (1, 3, 5))
+ self.assertTrue(torch.is_floating_point(batch_inputs[0]))
+
+ # Test cuda forward
+ if torch.cuda.is_available():
+ # Test with list of data samples.
+ data = dict(inputs=[input1, input2], data_sample=[label1, label2])
+ base_data_preprocessor = base_data_preprocessor.cuda()
+ output = base_data_preprocessor(data)
+ batch_inputs, batch_labels = output['inputs'], output[
+ 'data_sample']
+ self.assertTrue(torch.is_floating_point(batch_inputs[0]))
+ self.assertEqual(batch_inputs[0].device.type, 'cuda')
+
+ # Fallback to test with cpu.
+ base_data_preprocessor = base_data_preprocessor.cpu()
+ output = base_data_preprocessor(data)
+ batch_inputs, batch_labels = output['inputs'], output[
+ 'data_sample']
+ self.assertTrue(torch.is_floating_point(batch_inputs[0]))
+ self.assertEqual(batch_inputs[0].device.type, 'cpu')
+
+ # Test `base_data_preprocessor` can be moved to cuda again.
+ base_data_preprocessor = base_data_preprocessor.to('cuda:0')
+ output = base_data_preprocessor(data)
+ batch_inputs, batch_labels = output['inputs'], output[
+ 'data_sample']
+ self.assertTrue(torch.is_floating_point(batch_inputs[0]))
+ self.assertEqual(batch_inputs[0].device.type, 'cuda')
+
+ # device of `base_data_preprocessor` is cuda, output should be
+ # cuda tensor.
+ self.assertEqual(batch_inputs[0].device.type, 'cuda')
+ self.assertEqual(batch_labels[0].device.type, 'cuda')
+
+ # Test forward with string value
+ data = dict(string='abc')
+ base_data_preprocessor(data)
+
+ with self.assertRaisesRegex(TypeError,
+ '`BaseDataPreprocessor.cast_data`:'):
+ data = dict(string=object())
+ base_data_preprocessor(data)
+
+
+class TestImgDataPreprocessor(TestBaseDataPreprocessor):
+
+ def test_init(self):
+ # Initiate processor without arguments
+ data_processor = ImgDataPreprocessor()
+ self.assertFalse(data_processor._channel_conversion)
+ self.assertFalse(hasattr(data_processor, 'mean'))
+ self.assertFalse(hasattr(data_processor, 'std'))
+ self.assertEqual(data_processor.pad_size_divisor, 1)
+ assert_allclose(data_processor.pad_value, torch.tensor(0))
+
+ # Initiate model with bgr2rgb, mean, std .etc..
+ data_processor = ImgDataPreprocessor(
+ bgr_to_rgb=True,
+ mean=[0, 0, 0],
+ std=[255, 255, 255],
+ pad_size_divisor=16,
+ pad_value=10)
+ self.assertTrue(data_processor._enable_normalize)
+ self.assertTrue(data_processor._channel_conversion, True)
+ assert_allclose(data_processor.mean,
+ torch.tensor([0, 0, 0]).view(-1, 1, 1))
+ assert_allclose(data_processor.std,
+ torch.tensor([255, 255, 255]).view(-1, 1, 1))
+ assert_allclose(data_processor.pad_value, torch.tensor(10))
+ self.assertEqual(data_processor.pad_size_divisor, 16)
+
+ with self.assertRaisesRegex(AssertionError, '`mean` should have'):
+ ImgDataPreprocessor(mean=(1, 2), std=(1, 2, 3))
+
+ with self.assertRaisesRegex(AssertionError, '`std` should have'):
+ ImgDataPreprocessor(mean=(1, 2, 3), std=(1, 2))
+
+ with self.assertRaisesRegex(AssertionError, '`bgr2rgb` and `rgb2bgr`'):
+ ImgDataPreprocessor(bgr_to_rgb=True, rgb_to_bgr=True)
+
+ with self.assertRaisesRegex(AssertionError, 'mean and std should be'):
+ ImgDataPreprocessor(
+ bgr_to_rgb=True,
+ mean=None,
+ std=[255, 255, 255],
+ pad_size_divisor=16,
+ pad_value=10)
+
+ data_processor = ImgDataPreprocessor(
+ bgr_to_rgb=True, pad_size_divisor=16, pad_value=10)
+ self.assertFalse(data_processor._enable_normalize)
+
+ def test_forward(self):
+ # Test `pad_value`, `to_rgb`, `pad_size_divisor`.
+ data_preprocessor = ImgDataPreprocessor(
+ mean=[127.5],
+ std=[1, 2, 3],
+ pad_size_divisor=16,
+ pad_value=10,
+ rgb_to_bgr=True,
+ )
+ inputs1 = torch.randn(3, 10, 10)
+ inputs2 = torch.randn(3, 15, 15)
+ data_sample1 = InstanceData(bboxes=torch.randn(5, 4))
+ data_sample2 = InstanceData(bboxes=torch.randn(5, 4))
+
+ data = dict(
+ inputs=[inputs1.clone(), inputs2.clone()],
+ data_sample=[data_sample1.clone(),
+ data_sample2.clone()])
+
+ std = torch.tensor([1, 2, 3]).view(-1, 1, 1)
+ target_inputs1 = (inputs1.clone()[[2, 1, 0], ...] - 127.5) / std
+ target_inputs2 = (inputs2.clone()[[2, 1, 0], ...] - 127.5) / std
+
+ target_inputs1 = F.pad(target_inputs1, (0, 6, 0, 6), value=10)
+ target_inputs2 = F.pad(target_inputs2, (0, 1, 0, 1), value=10)
+
+ target_inputs = [target_inputs1, target_inputs2]
+ output = data_preprocessor(data, True)
+ inputs, data_samples = output['inputs'], output['data_sample']
+ self.assertTrue(torch.is_floating_point(inputs))
+
+ target_data_samples = [data_sample1, data_sample2]
+ for input_, data_sample, target_input, target_data_sample in zip(
+ inputs, data_samples, target_inputs, target_data_samples):
+ assert_allclose(input_, target_input)
+ assert_allclose(data_sample.bboxes, target_data_sample.bboxes)
+
+ # Test image without normalization.
+ data_preprocessor = ImgDataPreprocessor(
+ pad_size_divisor=16,
+ pad_value=10,
+ rgb_to_bgr=True,
+ )
+ target_inputs1 = (inputs1.clone()[[2, 1, 0], ...])
+ target_inputs2 = (inputs2.clone()[[2, 1, 0], ...])
+ target_inputs1 = F.pad(target_inputs1, (0, 6, 0, 6), value=10)
+ target_inputs2 = F.pad(target_inputs2, (0, 1, 0, 1), value=10)
+
+ target_inputs = [target_inputs1, target_inputs2]
+ output = data_preprocessor(data, True)
+ inputs, data_samples = output['inputs'], output['data_sample']
+ self.assertTrue(torch.is_floating_point(inputs))
+
+ target_data_samples = [data_sample1, data_sample2]
+ for input_, data_sample, target_input, target_data_sample in zip(
+ inputs, data_samples, target_inputs, target_data_samples):
+ assert_allclose(input_, target_input)
+ assert_allclose(data_sample.bboxes, target_data_sample.bboxes)
+
+ # Test gray image with 3 dim mean will raise error
+ data_preprocessor = ImgDataPreprocessor(
+ mean=(127.5, 127.5, 127.5), std=(127.5, 127.5, 127.5))
+ data = dict(
+ inputs=[torch.ones(10, 10), torch.ones(10, 10)], data_sample=None)
+ with self.assertRaisesRegex(AssertionError,
+ 'If the mean has 3 values'):
+ data_preprocessor(data)
+
+ data = dict(
+ inputs=[torch.ones(10, 10), torch.ones(10, 10)], data_sample=None)
+ with self.assertRaisesRegex(AssertionError,
+ 'If the mean has 3 values'):
+ data_preprocessor(data)
+
+ # Test stacked batch inputs and batch data samples
+ data_preprocessor = ImgDataPreprocessor(
+ mean=(127.5, 127.5, 127.5),
+ std=(127.5, 127.5, 127.5),
+ rgb_to_bgr=True,
+ pad_size_divisor=16)
+ _batch_inputs = torch.randn(2, 3, 10, 10)
+ _batch_labels = [torch.randn(1), torch.randn(1)]
+ data = dict(inputs=_batch_inputs, data_sample=_batch_labels)
+ output = data_preprocessor(data)
+ inputs, data_samples = output['inputs'], output['data_sample']
+ target_batch_inputs = _batch_inputs[:, [2, 1, 0], ...]
+ target_batch_inputs = (target_batch_inputs - 127.5) / 127.5
+ target_batch_inputs = F.pad(target_batch_inputs, (0, 6, 0, 6), value=0)
+ self.assertEqual(inputs.shape, torch.Size([2, 3, 16, 16]))
+ self.assertTrue(torch.is_floating_point(inputs))
+ assert_allclose(target_batch_inputs, inputs)
+
+ # Test batch inputs without convert channel order and pad
+ data_preprocessor = ImgDataPreprocessor(
+ mean=(127.5, 127.5, 127.5), std=(127.5, 127.5, 127.5))
+ _batch_inputs = torch.randn(2, 3, 10, 10)
+ _batch_labels = [torch.randn(1), torch.randn(1)]
+ data = dict(inputs=_batch_inputs, data_sample=_batch_labels)
+ output = data_preprocessor(data)
+ inputs, data_samples = output['inputs'], output['data_sample']
+ target_batch_inputs = (_batch_inputs - 127.5) / 127.5
+ self.assertEqual(inputs.shape, torch.Size([2, 3, 10, 10]))
+ self.assertTrue(torch.is_floating_point(inputs))
+ assert_allclose(target_batch_inputs, inputs)
+
+ # Test empty `data_sample`
+ data = dict(
+ inputs=[inputs1.clone(), inputs2.clone()], data_sample=None)
+ output = data_preprocessor(data, True)
+ inputs, data_samples = output['inputs'], output['data_sample']
+ self.assertIsNone(data_samples)
+ self.assertTrue(torch.is_floating_point(inputs))
diff --git a/testbed/open-mmlab__mmengine/tests/test_model/test_base_module.py b/testbed/open-mmlab__mmengine/tests/test_model/test_base_module.py
new file mode 100644
index 0000000000000000000000000000000000000000..25d43c2bdd95f05c5d78b14bc7de215c501bf685
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_model/test_base_module.py
@@ -0,0 +1,369 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import logging
+from unittest import TestCase
+
+import torch
+from torch import nn
+
+from mmengine.logging.logger import MMLogger
+from mmengine.model import BaseModule, ModuleDict, ModuleList, Sequential
+from mmengine.registry import Registry, build_from_cfg
+
+COMPONENTS = Registry('component')
+FOOMODELS = Registry('model')
+
+Logger = MMLogger.get_current_instance()
+
+
+@COMPONENTS.register_module()
+class FooConv1d(BaseModule):
+
+ def __init__(self, init_cfg=None):
+ super().__init__(init_cfg)
+ self.conv1d = nn.Conv1d(4, 1, 4)
+
+ def forward(self, x):
+ return self.conv1d(x)
+
+
+@COMPONENTS.register_module()
+class FooConv2d(BaseModule):
+
+ def __init__(self, init_cfg=None):
+ super().__init__(init_cfg)
+ self.conv2d = nn.Conv2d(3, 1, 3)
+
+ def forward(self, x):
+ return self.conv2d(x)
+
+
+@COMPONENTS.register_module()
+class FooLinear(BaseModule):
+
+ def __init__(self, init_cfg=None):
+ super().__init__(init_cfg)
+ self.linear = nn.Linear(3, 4)
+
+ def forward(self, x):
+ return self.linear(x)
+
+
+@COMPONENTS.register_module()
+class FooLinearConv1d(BaseModule):
+
+ def __init__(self, linear=None, conv1d=None, init_cfg=None):
+ super().__init__(init_cfg)
+ if linear is not None:
+ self.linear = build_from_cfg(linear, COMPONENTS)
+ if conv1d is not None:
+ self.conv1d = build_from_cfg(conv1d, COMPONENTS)
+
+ def forward(self, x):
+ x = self.linear(x)
+ return self.conv1d(x)
+
+
+@FOOMODELS.register_module()
+class FooModel(BaseModule):
+
+ def __init__(self,
+ component1=None,
+ component2=None,
+ component3=None,
+ component4=None,
+ init_cfg=None) -> None:
+ super().__init__(init_cfg)
+ if component1 is not None:
+ self.component1 = build_from_cfg(component1, COMPONENTS)
+ if component2 is not None:
+ self.component2 = build_from_cfg(component2, COMPONENTS)
+ if component3 is not None:
+ self.component3 = build_from_cfg(component3, COMPONENTS)
+ if component4 is not None:
+ self.component4 = build_from_cfg(component4, COMPONENTS)
+
+ # its type is not BaseModule, it can be initialized
+ # with "override" key.
+ self.reg = nn.Linear(3, 4)
+
+
+class TestBaseModule(TestCase):
+
+ def setUp(self) -> None:
+ self.BaseModule = BaseModule()
+ self.model_cfg = dict(
+ type='FooModel',
+ init_cfg=[
+ dict(type='Constant', val=1, bias=2, layer='Linear'),
+ dict(type='Constant', val=3, bias=4, layer='Conv1d'),
+ dict(type='Constant', val=5, bias=6, layer='Conv2d')
+ ],
+ component1=dict(type='FooConv1d'),
+ component2=dict(type='FooConv2d'),
+ component3=dict(type='FooLinear'),
+ component4=dict(
+ type='FooLinearConv1d',
+ linear=dict(type='FooLinear'),
+ conv1d=dict(type='FooConv1d')))
+
+ self.model = build_from_cfg(self.model_cfg, FOOMODELS)
+ self.logger = MMLogger.get_instance(self._testMethodName)
+
+ def tearDown(self) -> None:
+ logging.shutdown()
+ MMLogger._instance_dict.clear()
+ return super().tearDown()
+
+ def test_is_init(self):
+ assert self.BaseModule.is_init is False
+
+ def test_init_weights(self):
+ """
+ Config
+ model (FooModel, Linear: weight=1, bias=2, Conv1d: weight=3, bias=4,
+ Conv2d: weight=5, bias=6)
+ ├──component1 (FooConv1d)
+ ├──component2 (FooConv2d)
+ ├──component3 (FooLinear)
+ ├──component4 (FooLinearConv1d)
+ ├──linear (FooLinear)
+ ├──conv1d (FooConv1d)
+ ├──reg (nn.Linear)
+ Parameters after initialization
+ model (FooModel)
+ ├──component1 (FooConv1d, weight=3, bias=4)
+ ├──component2 (FooConv2d, weight=5, bias=6)
+ ├──component3 (FooLinear, weight=1, bias=2)
+ ├──component4 (FooLinearConv1d)
+ ├──linear (FooLinear, weight=1, bias=2)
+ ├──conv1d (FooConv1d, weight=3, bias=4)
+ ├──reg (nn.Linear, weight=1, bias=2)
+ """
+
+ self.model.init_weights()
+
+ assert torch.equal(
+ self.model.component1.conv1d.weight,
+ torch.full(self.model.component1.conv1d.weight.shape, 3.0))
+ assert torch.equal(
+ self.model.component1.conv1d.bias,
+ torch.full(self.model.component1.conv1d.bias.shape, 4.0))
+ assert torch.equal(
+ self.model.component2.conv2d.weight,
+ torch.full(self.model.component2.conv2d.weight.shape, 5.0))
+ assert torch.equal(
+ self.model.component2.conv2d.bias,
+ torch.full(self.model.component2.conv2d.bias.shape, 6.0))
+ assert torch.equal(
+ self.model.component3.linear.weight,
+ torch.full(self.model.component3.linear.weight.shape, 1.0))
+ assert torch.equal(
+ self.model.component3.linear.bias,
+ torch.full(self.model.component3.linear.bias.shape, 2.0))
+ assert torch.equal(
+ self.model.component4.linear.linear.weight,
+ torch.full(self.model.component4.linear.linear.weight.shape, 1.0))
+ assert torch.equal(
+ self.model.component4.linear.linear.bias,
+ torch.full(self.model.component4.linear.linear.bias.shape, 2.0))
+ assert torch.equal(
+ self.model.component4.conv1d.conv1d.weight,
+ torch.full(self.model.component4.conv1d.conv1d.weight.shape, 3.0))
+ assert torch.equal(
+ self.model.component4.conv1d.conv1d.bias,
+ torch.full(self.model.component4.conv1d.conv1d.bias.shape, 4.0))
+ assert torch.equal(self.model.reg.weight,
+ torch.full(self.model.reg.weight.shape, 1.0))
+ assert torch.equal(self.model.reg.bias,
+ torch.full(self.model.reg.bias.shape, 2.0))
+
+ def test_dump_init_info(self):
+ import os
+ import shutil
+ dump_dir = 'tests/test_model/test_dump_info'
+ if not (os.path.exists(dump_dir) and os.path.isdir(dump_dir)):
+ os.makedirs(dump_dir)
+ for filename in os.listdir(dump_dir):
+ file_path = os.path.join(dump_dir, filename)
+ if os.path.isfile(file_path) or os.path.islink(file_path):
+ os.unlink(file_path)
+ elif os.path.isdir(file_path):
+ shutil.rmtree(file_path)
+
+ MMLogger.get_instance('logger1') # add logger without FileHandler
+ model1 = build_from_cfg(self.model_cfg, FOOMODELS)
+ model1.init_weights()
+ assert len(os.listdir(dump_dir)) == 0
+ log_path = os.path.join(dump_dir, 'out.log')
+ MMLogger.get_instance(
+ 'logger2', log_file=log_path) # add logger with FileHandler
+ model2 = build_from_cfg(self.model_cfg, FOOMODELS)
+ model2.init_weights()
+ assert len(os.listdir(dump_dir)) == 1
+ assert os.stat(log_path).st_size != 0
+ # `FileHandler` should be closed in Windows, otherwise we cannot
+ # delete the temporary directory
+ logging.shutdown()
+ MMLogger._instance_dict.clear()
+ shutil.rmtree(dump_dir)
+
+
+class TestModuleList(TestCase):
+
+ def test_modulelist_weight_init(self):
+ models_cfg = [
+ dict(
+ type='FooConv1d',
+ init_cfg=dict(
+ type='Constant', layer='Conv1d', val=0., bias=1.)),
+ dict(
+ type='FooConv2d',
+ init_cfg=dict(
+ type='Constant', layer='Conv2d', val=2., bias=3.)),
+ ]
+ layers = [build_from_cfg(cfg, COMPONENTS) for cfg in models_cfg]
+ modellist = ModuleList(layers)
+ modellist.init_weights()
+ self.assertTrue(
+ torch.equal(modellist[0].conv1d.weight,
+ torch.full(modellist[0].conv1d.weight.shape, 0.)))
+ self.assertTrue(
+ torch.equal(modellist[0].conv1d.bias,
+ torch.full(modellist[0].conv1d.bias.shape, 1.)))
+ self.assertTrue(
+ torch.equal(modellist[1].conv2d.weight,
+ torch.full(modellist[1].conv2d.weight.shape, 2.)))
+ self.assertTrue(
+ torch.equal(modellist[1].conv2d.bias,
+ torch.full(modellist[1].conv2d.bias.shape, 3.)))
+ # inner init_cfg has higher priority
+ layers = [build_from_cfg(cfg, COMPONENTS) for cfg in models_cfg]
+ modellist = ModuleList(
+ layers,
+ init_cfg=dict(
+ type='Constant', layer=['Conv1d', 'Conv2d'], val=4., bias=5.))
+ modellist.init_weights()
+ self.assertTrue(
+ torch.equal(modellist[0].conv1d.weight,
+ torch.full(modellist[0].conv1d.weight.shape, 0.)))
+ self.assertTrue(
+ torch.equal(modellist[0].conv1d.bias,
+ torch.full(modellist[0].conv1d.bias.shape, 1.)))
+ self.assertTrue(
+ torch.equal(modellist[1].conv2d.weight,
+ torch.full(modellist[1].conv2d.weight.shape, 2.)))
+ self.assertTrue(
+ torch.equal(modellist[1].conv2d.bias,
+ torch.full(modellist[1].conv2d.bias.shape, 3.)))
+
+
+class TestModuleDict(TestCase):
+
+ def test_moduledict_weight_init(self):
+ models_cfg = dict(
+ foo_conv_1d=dict(
+ type='FooConv1d',
+ init_cfg=dict(
+ type='Constant', layer='Conv1d', val=0., bias=1.)),
+ foo_conv_2d=dict(
+ type='FooConv2d',
+ init_cfg=dict(
+ type='Constant', layer='Conv2d', val=2., bias=3.)),
+ )
+ layers = {
+ name: build_from_cfg(cfg, COMPONENTS)
+ for name, cfg in models_cfg.items()
+ }
+ modeldict = ModuleDict(layers)
+ modeldict.init_weights()
+ self.assertTrue(
+ torch.equal(
+ modeldict['foo_conv_1d'].conv1d.weight,
+ torch.full(modeldict['foo_conv_1d'].conv1d.weight.shape, 0.)))
+ self.assertTrue(
+ torch.equal(
+ modeldict['foo_conv_1d'].conv1d.bias,
+ torch.full(modeldict['foo_conv_1d'].conv1d.bias.shape, 1.)))
+ self.assertTrue(
+ torch.equal(
+ modeldict['foo_conv_2d'].conv2d.weight,
+ torch.full(modeldict['foo_conv_2d'].conv2d.weight.shape, 2.)))
+ self.assertTrue(
+ torch.equal(
+ modeldict['foo_conv_2d'].conv2d.bias,
+ torch.full(modeldict['foo_conv_2d'].conv2d.bias.shape, 3.)))
+ # inner init_cfg has higher priority
+ layers = {
+ name: build_from_cfg(cfg, COMPONENTS)
+ for name, cfg in models_cfg.items()
+ }
+ modeldict = ModuleDict(
+ layers,
+ init_cfg=dict(
+ type='Constant', layer=['Conv1d', 'Conv2d'], val=4., bias=5.))
+ modeldict.init_weights()
+ self.assertTrue(
+ torch.equal(
+ modeldict['foo_conv_1d'].conv1d.weight,
+ torch.full(modeldict['foo_conv_1d'].conv1d.weight.shape, 0.)))
+ self.assertTrue(
+ torch.equal(
+ modeldict['foo_conv_1d'].conv1d.bias,
+ torch.full(modeldict['foo_conv_1d'].conv1d.bias.shape, 1.)))
+ self.assertTrue(
+ torch.equal(
+ modeldict['foo_conv_2d'].conv2d.weight,
+ torch.full(modeldict['foo_conv_2d'].conv2d.weight.shape, 2.)))
+ self.assertTrue(
+ torch.equal(
+ modeldict['foo_conv_2d'].conv2d.bias,
+ torch.full(modeldict['foo_conv_2d'].conv2d.bias.shape, 3.)))
+
+
+class TestSequential(TestCase):
+
+ def test_sequential_model_weight_init(self):
+ seq_model_cfg = [
+ dict(
+ type='FooConv1d',
+ init_cfg=dict(
+ type='Constant', layer='Conv1d', val=0., bias=1.)),
+ dict(
+ type='FooConv2d',
+ init_cfg=dict(
+ type='Constant', layer='Conv2d', val=2., bias=3.)),
+ ]
+ layers = [build_from_cfg(cfg, COMPONENTS) for cfg in seq_model_cfg]
+ seq_model = Sequential(*layers)
+ seq_model.init_weights()
+ self.assertTrue(
+ torch.equal(seq_model[0].conv1d.weight,
+ torch.full(seq_model[0].conv1d.weight.shape, 0.)))
+ self.assertTrue(
+ torch.equal(seq_model[0].conv1d.bias,
+ torch.full(seq_model[0].conv1d.bias.shape, 1.)))
+ self.assertTrue(
+ torch.equal(seq_model[1].conv2d.weight,
+ torch.full(seq_model[1].conv2d.weight.shape, 2.)))
+ self.assertTrue(
+ torch.equal(seq_model[1].conv2d.bias,
+ torch.full(seq_model[1].conv2d.bias.shape, 3.)))
+ # inner init_cfg has higher priority
+ layers = [build_from_cfg(cfg, COMPONENTS) for cfg in seq_model_cfg]
+ seq_model = Sequential(
+ *layers,
+ init_cfg=dict(
+ type='Constant', layer=['Conv1d', 'Conv2d'], val=4., bias=5.))
+ seq_model.init_weights()
+ self.assertTrue(
+ torch.equal(seq_model[0].conv1d.weight,
+ torch.full(seq_model[0].conv1d.weight.shape, 0.)))
+ self.assertTrue(
+ torch.equal(seq_model[0].conv1d.bias,
+ torch.full(seq_model[0].conv1d.bias.shape, 1.)))
+ self.assertTrue(
+ torch.equal(seq_model[1].conv2d.weight,
+ torch.full(seq_model[1].conv2d.weight.shape, 2.)))
+ self.assertTrue(
+ torch.equal(seq_model[1].conv2d.bias,
+ torch.full(seq_model[1].conv2d.bias.shape, 3.)))
diff --git a/testbed/open-mmlab__mmengine/tests/test_model/test_model_utils.py b/testbed/open-mmlab__mmengine/tests/test_model/test_model_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a8d0001bd0bfb021538ea0fb5be82c6b44ce070
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_model/test_model_utils.py
@@ -0,0 +1,120 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+
+import pytest
+import torch
+import torch.nn as nn
+from torch.distributed import destroy_process_group, init_process_group
+from torch.nn.parallel import DataParallel, DistributedDataParallel
+
+from mmengine.model import (MMDistributedDataParallel,
+ MMSeparateDistributedDataParallel,
+ convert_sync_batchnorm, is_model_wrapper,
+ revert_sync_batchnorm)
+from mmengine.registry import MODEL_WRAPPERS, Registry
+from mmengine.utils import is_installed
+
+
+class ToyModule(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.layer1 = nn.Linear(1, 1)
+
+ def add_module(self, name, module):
+ raise ValueError()
+
+
+@pytest.mark.skipif(
+ torch.__version__ == 'parrots', reason='not supported in parrots now')
+def test_revert_syncbn():
+ # conv = ConvModule(3, 8, 2, norm_cfg=dict(type='SyncBN'))
+ conv = nn.Sequential(nn.Conv2d(3, 8, 2), nn.SyncBatchNorm(8))
+ x = torch.randn(1, 3, 10, 10)
+ # Expect a ValueError prompting that SyncBN is not supported on CPU
+ with pytest.raises(ValueError):
+ y = conv(x)
+ conv = revert_sync_batchnorm(conv)
+ y = conv(x)
+ assert y.shape == (1, 8, 9, 9)
+
+ # TODO, capsys provided by `pytest` cannot capture the error log produced
+ # by MMLogger. Test the error log after refactoring the unit test with
+ # `unittest`
+ conv = nn.Sequential(ToyModule(), nn.SyncBatchNorm(8))
+ revert_sync_batchnorm(conv)
+
+
+@pytest.mark.skipif(
+ torch.__version__ == 'parrots', reason='not supported in parrots now')
+def test_convert_syncbn():
+ # conv = ConvModule(3, 8, 2, norm_cfg=dict(type='SyncBN'))
+ conv = nn.Sequential(nn.Conv2d(3, 8, 2), nn.BatchNorm2d(8))
+ x = torch.randn(1, 3, 10, 10)
+ y = conv(x)
+ assert y.shape == (1, 8, 9, 9)
+
+ # Test convert to mmcv SyncBatchNorm
+ if is_installed('mmcv'):
+ # MMCV SyncBatchNorm is only supported on distributed training.
+ # torch 1.6 will throw an AssertionError, and higher version will
+ # throw an RuntimeError
+ with pytest.raises((RuntimeError, AssertionError)):
+ convert_sync_batchnorm(conv, implementation='mmcv')
+
+ # Test convert BN to Pytorch SyncBatchNorm
+ # Expect a ValueError prompting that SyncBN is not supported on CPU
+ converted_conv = convert_sync_batchnorm(conv)
+ assert isinstance(converted_conv[1], torch.nn.SyncBatchNorm)
+ with pytest.raises(ValueError):
+ converted_conv(x)
+
+
+def test_is_model_wrapper():
+ # Test basic module wrapper.
+ os.environ['MASTER_ADDR'] = '127.0.0.1'
+ os.environ['MASTER_PORT'] = '29510'
+ os.environ['RANK'] = str(0)
+ init_process_group(backend='gloo', rank=0, world_size=1)
+ model = nn.Linear(1, 1)
+
+ for wrapper in [
+ DistributedDataParallel, MMDistributedDataParallel,
+ MMSeparateDistributedDataParallel, DataParallel
+ ]:
+ wrapper_model = wrapper(model)
+ assert is_model_wrapper(wrapper_model)
+
+ # Test `is_model_wrapper` can check model wrapper registered in custom
+ # registry.
+ CHILD_REGISTRY = Registry('test_is_model_wrapper', parent=MODEL_WRAPPERS)
+
+ class CustomModelWrapper(nn.Module):
+
+ def __init__(self, model):
+ super().__init__()
+ self.module = model
+
+ pass
+
+ CHILD_REGISTRY.register_module(module=CustomModelWrapper, force=True)
+
+ for wrapper in [
+ DistributedDataParallel, MMDistributedDataParallel,
+ MMSeparateDistributedDataParallel, DataParallel, CustomModelWrapper
+ ]:
+ wrapper_model = wrapper(model)
+ assert is_model_wrapper(wrapper_model)
+
+ # Test `is_model_wrapper` will not check model wrapper in parent
+ # registry from a child registry.
+ for wrapper in [
+ DistributedDataParallel, MMDistributedDataParallel,
+ MMSeparateDistributedDataParallel, DataParallel
+ ]:
+ wrapper_model = wrapper(model)
+ assert not is_model_wrapper(wrapper_model, registry=CHILD_REGISTRY)
+
+ wrapper_model = CustomModelWrapper(model)
+ assert is_model_wrapper(wrapper_model, registry=CHILD_REGISTRY)
+ destroy_process_group()
diff --git a/testbed/open-mmlab__mmengine/tests/test_model/test_wrappers/test_model_wrapper.py b/testbed/open-mmlab__mmengine/tests/test_model/test_wrappers/test_model_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..999f1fedf5d3c6a127d35780bc20a11e38a010d2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_model/test_wrappers/test_model_wrapper.py
@@ -0,0 +1,271 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import unittest
+from unittest.mock import MagicMock
+
+import torch
+import torch.distributed as torch_dist
+import torch.nn as nn
+from torch.optim import SGD
+
+from mmengine.dist import all_gather
+from mmengine.model import (BaseDataPreprocessor, BaseModel,
+ ExponentialMovingAverage,
+ MMDistributedDataParallel,
+ MMSeparateDistributedDataParallel)
+from mmengine.optim import AmpOptimWrapper, OptimWrapper, OptimWrapperDict
+from mmengine.testing import assert_allclose
+from mmengine.testing._internal import MultiProcessTestCase
+from mmengine.utils.dl_utils import TORCH_VERSION
+from mmengine.utils.version_utils import digit_version
+
+if digit_version(TORCH_VERSION) >= digit_version('1.11.0'):
+ from mmengine.model import MMFullyShardedDataParallel # noqa: F401
+
+
+class ToyDataPreprocessor(BaseDataPreprocessor):
+
+ def forward(self, data: dict, training: bool = False):
+ self.called = True
+ return super().forward(data, training)
+
+
+class ToyModel(BaseModel):
+
+ def __init__(self):
+ super().__init__(data_preprocessor=ToyDataPreprocessor())
+ self.conv1 = nn.Conv2d(3, 1, 1)
+ self.conv2 = nn.Conv2d(1, 1, 1)
+
+ def forward(self, inputs, data_sample=None, mode='tensor'):
+ x = self.conv1(inputs)
+ x = self.conv2(x)
+ if mode == 'loss':
+ return dict(loss=x)
+ elif mode == 'predict':
+ return x
+ else:
+ return x
+
+
+class ComplexModel(BaseModel):
+
+ def __init__(self):
+ super().__init__()
+ self.conv1 = nn.Conv2d(3, 1, 1)
+ self.conv2 = nn.Conv2d(3, 1, 1)
+
+ def train_step(self, data, optim_wrapper):
+ inputs = self.data_preprocessor(data)['inputs']
+ loss1 = self.conv1(inputs)
+ optim_wrapper['optim_wrapper1'].update_params(loss1)
+ loss2 = self.conv2(inputs)
+ optim_wrapper['optim_wrapper2'].update_params(loss2)
+ return dict(loss1=loss1, loss2=loss2)
+
+ def val_step(self, data):
+ return 1
+
+ def test_step(self, data):
+ return 2
+
+ def forward(self):
+ pass
+
+
+class TestDistributedDataParallel(MultiProcessTestCase):
+
+ def setUp(self) -> None:
+ super().setUp()
+ self._spawn_processes()
+
+ @unittest.skipIf(
+ not torch.cuda.is_available(), reason='cuda should be available')
+ def test_train_step(self):
+ self._init_dist_env(self.rank, self.world_size)
+ # Mixed precision training and gradient asynchronous should be valid at
+ # the same time
+ model = ToyModel().cuda()
+ ddp_model = MMDistributedDataParallel(module=model)
+ optimizer = SGD(ddp_model.parameters(), lr=0)
+ optim_wrapper = AmpOptimWrapper(
+ optimizer=optimizer, accumulative_counts=3)
+ inputs = torch.randn(1, 3, 1, 1).cuda() * self.rank * 255
+ data = dict(inputs=inputs, data_sample=None)
+ res = ddp_model.train_step(data, optim_wrapper=optim_wrapper)['loss']
+ self.assertIs(res.dtype, torch.float16)
+ grad = ddp_model.module.conv1.weight.grad
+ all_grads = all_gather(grad)
+ with self.assertRaises(AssertionError):
+ assert_allclose(all_grads[0], all_grads[1])
+
+ # Gradient accumulation
+ ddp_model.train_step(data, optim_wrapper=optim_wrapper)
+
+ # Test update params and clean grads.
+ ddp_model.train_step(data, optim_wrapper=optim_wrapper)
+ grad = ddp_model.module.conv1.weight.grad
+ all_grads = all_gather(grad)
+ assert_allclose(all_grads[0], torch.zeros_like(all_grads[0]))
+ assert_allclose(all_grads[1], torch.zeros_like(all_grads[0]))
+
+ # Test enable detect_anomalous_params.
+ ddp_model = MMDistributedDataParallel(
+ module=model, detect_anomalous_params=True)
+ optimizer = SGD(ddp_model.parameters(), lr=0)
+ optim_wrapper = AmpOptimWrapper(
+ optimizer=optimizer, accumulative_counts=3)
+ inputs = torch.randn(1, 3, 1, 1).cuda() * self.rank * 255
+ data = dict(inputs=inputs, data_sample=None)
+ res = ddp_model.train_step(data, optim_wrapper=optim_wrapper)['loss']
+
+ def test_val_step(self):
+ self._init_dist_env(self.rank, self.world_size)
+ model = ToyModel()
+ ddp_model = MMDistributedDataParallel(module=model)
+ inputs = torch.randn(1, 3, 1, 1) * self.rank * 255
+ data = dict(inputs=inputs, data_sample=None)
+ # Test get predictions.
+ predictions = ddp_model.val_step(data)
+ self.assertIsInstance(predictions, torch.Tensor)
+ self.assertTrue(model.data_preprocessor.called)
+
+ def test_test_step(self):
+ self._init_dist_env(self.rank, self.world_size)
+ model = ToyModel()
+ ddp_model = MMDistributedDataParallel(module=model)
+ inputs = torch.randn(1, 3, 1, 1) * self.rank * 255
+ data = dict(inputs=inputs, data_sample=None)
+ predictions = ddp_model.test_step(data)
+ self.assertIsInstance(predictions, torch.Tensor)
+ self.assertTrue(model.data_preprocessor.called)
+
+ def _init_dist_env(self, rank, world_size):
+ """Initialize the distributed environment."""
+ os.environ['MASTER_ADDR'] = '127.0.0.1'
+ os.environ['MASTER_PORT'] = '29510'
+ os.environ['RANK'] = str(rank)
+ torch_dist.init_process_group(
+ backend='gloo', rank=rank, world_size=world_size)
+
+
+@unittest.skipIf(
+ not torch.cuda.is_available(), reason='cuda should be available')
+class TestMMSeparateDistributedDataParallel(TestDistributedDataParallel):
+
+ def test_init(self):
+ self._init_dist_env(self.rank, self.world_size)
+ model = ComplexModel()
+ model.ema = ExponentialMovingAverage(nn.Conv2d(1, 1, 1))
+ model.act = nn.ReLU()
+ ddp_model = MMSeparateDistributedDataParallel(model.cuda())
+ self.assertIsInstance(ddp_model.module.ema, ExponentialMovingAverage)
+ self.assertIsInstance(ddp_model.module.conv1,
+ MMDistributedDataParallel)
+ self.assertIsInstance(ddp_model.module.act, nn.ReLU)
+
+ def test_train_step(self):
+ self._init_dist_env(self.rank, self.world_size)
+ # Test `optim_wrapper` is a dict. In this case,
+ # There will be two independently updated `DistributedDataParallel`
+ # submodules.
+ model = ComplexModel()
+ ddp_model = MMSeparateDistributedDataParallel(model.cuda())
+ optimizer1 = SGD(model.conv1.parameters(), lr=0.1)
+ optimizer2 = SGD(model.conv1.parameters(), lr=0.2)
+ optim_wrapper1 = OptimWrapper(optimizer1, 1)
+ optim_wrapper2 = OptimWrapper(optimizer2, 1)
+ optim_wrapper_dict = OptimWrapperDict(
+ optim_wrapper1=optim_wrapper1, optim_wrapper2=optim_wrapper2)
+ inputs = torch.randn(1, 3, 1, 1).cuda() * self.rank * 255
+ data = dict(inputs=inputs, data_sample=None)
+ # Automatically sync grads of `optim_wrapper1` since
+ # `cumulative_iters` = 1
+ ddp_model.train()
+ self.assertTrue(ddp_model.training)
+ ddp_model.train_step(data, optim_wrapper=optim_wrapper_dict)
+
+ def test_val_step(self):
+ self._init_dist_env(self.rank, self.world_size)
+ model = ComplexModel()
+ ddp_model = MMSeparateDistributedDataParallel(model)
+ data = torch.randn(1, 3, 1, 1)
+ # Test get predictions.
+ ddp_model.eval()
+ self.assertFalse(ddp_model.training)
+ predictions = ddp_model.val_step(data)
+ self.assertEqual(predictions, 1)
+
+ def test_test_step(self):
+ self._init_dist_env(self.rank, self.world_size)
+ model = ComplexModel()
+ ddp_model = MMSeparateDistributedDataParallel(model)
+ data = torch.randn(1, 3, 1, 1)
+ # Test get predictions.
+ ddp_model.eval()
+ self.assertFalse(ddp_model.training)
+ predictions = ddp_model.test_step(data)
+ self.assertEqual(predictions, 2)
+
+ def _init_dist_env(self, rank, world_size):
+ """Initialize the distributed environment."""
+ os.environ['MASTER_ADDR'] = '127.0.0.1'
+ os.environ['MASTER_PORT'] = '29515'
+ os.environ['RANK'] = str(rank)
+ torch_dist.init_process_group(
+ backend='gloo', rank=rank, world_size=world_size)
+
+
+@unittest.skipIf(
+ torch.cuda.device_count() < 2, reason='need 2 gpu to test fsdp')
+@unittest.skipIf(
+ digit_version(TORCH_VERSION) < digit_version('1.11.0'),
+ reason='fsdp needs Pytorch 1.11 or higher')
+class TestMMFullyShardedDataParallel(MultiProcessTestCase):
+
+ def _init_dist_env(self, rank, world_size):
+ """Initialize the distributed environment."""
+ os.environ['MASTER_ADDR'] = '127.0.0.1'
+ os.environ['MASTER_PORT'] = '29520'
+ os.environ['RANK'] = str(rank)
+
+ num_gpus = torch.cuda.device_count()
+ torch.cuda.set_device(rank % num_gpus)
+ torch_dist.init_process_group(
+ backend='nccl', rank=rank, world_size=world_size)
+
+ def setUp(self) -> None:
+ super().setUp()
+ self._spawn_processes()
+
+ def test_train_step(self):
+ self._init_dist_env(self.rank, self.world_size)
+ # Test `optim_wrapper` is a instance of `OptimWrapper`
+ model = ToyModel()
+ fsdp_model = MMFullyShardedDataParallel(module=model.cuda())
+ optimizer = SGD(fsdp_model.parameters(), lr=0)
+ optim_wrapper = OptimWrapper(optimizer, accumulative_iters=1)
+ inputs = torch.randn(1, 3, 1, 1) * self.rank * 255
+ data = dict(inputs=[inputs], data_sample=MagicMock())
+ fsdp_model.train()
+ self.assertTrue(fsdp_model.training)
+ fsdp_model.train_step(data, optim_wrapper=optim_wrapper)
+
+ def test_val_step(self):
+ self._init_dist_env(self.rank, self.world_size)
+ model = ToyModel()
+ fsdp_model = MMFullyShardedDataParallel(module=model.cuda())
+ inputs = torch.randn(1, 3, 1, 1) * self.rank * 255
+ data = dict(inputs=[inputs], data_sample=MagicMock())
+ # Test get predictions.
+ predictions = fsdp_model.val_step(data)
+ self.assertIsInstance(predictions, torch.Tensor)
+
+ def test_test_step(self):
+ self._init_dist_env(self.rank, self.world_size)
+ model = ToyModel()
+ fsdp_model = MMFullyShardedDataParallel(module=model.cuda())
+ inputs = torch.randn(1, 3, 1, 1) * self.rank * 255
+ data = dict(inputs=inputs, data_sample=MagicMock())
+ predictions = fsdp_model.test_step(data)
+ self.assertIsInstance(predictions, torch.Tensor)
diff --git a/testbed/open-mmlab__mmengine/tests/test_model/test_wrappers/test_test_aug_time.py b/testbed/open-mmlab__mmengine/tests/test_model/test_wrappers/test_test_aug_time.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7bb808d166ec434bc669d29bc79595873930197
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_model/test_wrappers/test_test_aug_time.py
@@ -0,0 +1,55 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from unittest import TestCase
+
+from torch.utils.data import DataLoader
+
+from mmengine.model import BaseModel, BaseTTAModel
+from mmengine.registry import MODELS
+
+
+class ToyTestTimeAugModel(BaseTTAModel):
+
+ def merge_preds(self, data_samples_list):
+ result = [sum(x) for x in data_samples_list]
+ return result
+
+
+@MODELS.register_module()
+class TTAToyModel(BaseModel):
+
+ def forward(self, inputs, data_samples, mode='tensor'):
+ return data_samples
+
+
+class TestBaseTTAModel(TestCase):
+
+ def setUp(self) -> None:
+ dict_dataset = [
+ dict(inputs=[1, 2], data_samples=[3, 4]) for _ in range(10)
+ ]
+ tuple_dataset = [([1, 2], [3, 4]) for _ in range(10)]
+ self.model = TTAToyModel()
+ self.dict_dataloader = DataLoader(dict_dataset, batch_size=2)
+ self.tuple_dataloader = DataLoader(tuple_dataset, batch_size=2)
+
+ def test_test_step(self):
+ tta_model = ToyTestTimeAugModel(self.model)
+
+ # Test dict dataset
+
+ for data in self.dict_dataloader:
+ # Test step will call forward.
+ result = tta_model.test_step(data)
+ self.assertEqual(result, [7, 7])
+
+ for data in self.tuple_dataloader:
+ result = tta_model.test_step(data)
+ self.assertEqual(result, [7, 7])
+
+ def test_init(self):
+ tta_model = ToyTestTimeAugModel(self.model)
+ self.assertIs(tta_model.module, self.model)
+ # Test build from cfg.
+ model = dict(type='TTAToyModel')
+ tta_model = ToyTestTimeAugModel(model)
+ self.assertIsInstance(tta_model.module, TTAToyModel)
diff --git a/testbed/open-mmlab__mmengine/tests/test_optim/test_optimizer/test_optimizer.py b/testbed/open-mmlab__mmengine/tests/test_optim/test_optimizer/test_optimizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..d896d05dbc8b150866ff7996b553da0efaea6060
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_optim/test_optimizer/test_optimizer.py
@@ -0,0 +1,821 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import sys
+import unittest
+from unittest import TestCase
+from unittest.mock import MagicMock
+
+import torch
+import torch.nn as nn
+from torch.distributed.rpc import is_available
+
+from mmengine.dist import get_rank
+from mmengine.optim import (OPTIM_WRAPPER_CONSTRUCTORS, OPTIMIZERS,
+ DefaultOptimWrapperConstructor, OptimWrapper,
+ build_optim_wrapper)
+from mmengine.optim.optimizer.builder import TORCH_OPTIMIZERS
+from mmengine.registry import build_from_cfg
+from mmengine.testing._internal import MultiProcessTestCase
+from mmengine.utils.dl_utils import TORCH_VERSION, mmcv_full_available
+from mmengine.utils.version_utils import digit_version
+
+MMCV_FULL_AVAILABLE = mmcv_full_available()
+if not MMCV_FULL_AVAILABLE:
+ sys.modules['mmcv.ops'] = MagicMock(
+ DeformConv2d=dict, ModulatedDeformConv2d=dict)
+
+
+class ExampleModel(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.param1 = nn.Parameter(torch.ones(1))
+ self.conv1 = nn.Conv2d(3, 4, kernel_size=1, bias=False)
+ self.conv2 = nn.Conv2d(4, 2, kernel_size=1)
+ self.bn = nn.BatchNorm2d(2)
+ self.sub = SubModel()
+ if MMCV_FULL_AVAILABLE:
+ from mmcv.ops import DeformConv2dPack
+ self.dcn = DeformConv2dPack(
+ 3, 4, kernel_size=3, deformable_groups=1)
+
+
+class ExampleDuplicateModel(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.param1 = nn.Parameter(torch.ones(1))
+ self.conv1 = nn.Sequential(nn.Conv2d(3, 4, kernel_size=1, bias=False))
+ self.conv2 = nn.Sequential(nn.Conv2d(4, 2, kernel_size=1))
+ self.bn = nn.BatchNorm2d(2)
+ self.sub = SubModel()
+ self.conv3 = nn.Sequential(nn.Conv2d(3, 4, kernel_size=1, bias=False))
+ self.conv3[0] = self.conv1[0]
+ if MMCV_FULL_AVAILABLE:
+ from mmcv.ops import DeformConv2dPack
+ self.dcn = DeformConv2dPack(
+ 3, 4, kernel_size=3, deformable_groups=1)
+
+ def forward(self, x):
+ return x
+
+
+class SubModel(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.conv1 = nn.Conv2d(2, 2, kernel_size=1, groups=2)
+ self.gn = nn.GroupNorm(2, 2)
+ self.param1 = nn.Parameter(torch.ones(1))
+
+ def forward(self, x):
+ return x
+
+
+class PseudoDataParallel(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.module = ExampleModel()
+
+ def forward(self, x):
+ return x
+
+
+class TestBuilder(TestCase):
+
+ def setUp(self):
+ self.model = ExampleModel()
+ self.base_lr = 0.01
+ self.momentum = 0.0001
+ self.base_wd = 0.9
+
+ def _check_default_optimizer(self, optimizer, model, prefix=''):
+ assert isinstance(optimizer, torch.optim.SGD)
+ assert optimizer.defaults['lr'] == self.base_lr
+ assert optimizer.defaults['momentum'] == self.momentum
+ assert optimizer.defaults['weight_decay'] == self.base_wd
+ param_groups = optimizer.param_groups[0]
+ if MMCV_FULL_AVAILABLE:
+ param_names = [
+ 'param1', 'conv1.weight', 'conv2.weight', 'conv2.bias',
+ 'bn.weight', 'bn.bias', 'sub.param1', 'sub.conv1.weight',
+ 'sub.conv1.bias', 'sub.gn.weight', 'sub.gn.bias', 'dcn.weight',
+ 'dcn.conv_offset.weight', 'dcn.conv_offset.bias'
+ ]
+ else:
+ param_names = [
+ 'param1', 'conv1.weight', 'conv2.weight', 'conv2.bias',
+ 'bn.weight', 'bn.bias', 'sub.param1', 'sub.conv1.weight',
+ 'sub.conv1.bias', 'sub.gn.weight', 'sub.gn.bias'
+ ]
+ param_dict = dict(model.named_parameters())
+ assert len(param_groups['params']) == len(param_names)
+ for i in range(len(param_groups['params'])):
+ assert torch.equal(param_groups['params'][i],
+ param_dict[prefix + param_names[i]])
+
+ def _check_sgd_optimizer(self,
+ optimizer,
+ model,
+ prefix='',
+ bias_lr_mult=1,
+ bias_decay_mult=1,
+ norm_decay_mult=1,
+ dwconv_decay_mult=1,
+ dcn_offset_lr_mult=1,
+ flat_decay_mult=1,
+ bypass_duplicate=False):
+ param_groups = optimizer.param_groups
+ assert isinstance(optimizer, torch.optim.SGD)
+ assert optimizer.defaults['lr'] == self.base_lr
+ assert optimizer.defaults['momentum'] == self.momentum
+ assert optimizer.defaults['weight_decay'] == self.base_wd
+ model_parameters = list(model.parameters())
+ assert len(param_groups) == len(model_parameters)
+ for i, param in enumerate(model_parameters):
+ param_group = param_groups[i]
+ assert torch.equal(param_group['params'][0], param)
+ assert param_group['momentum'] == self.momentum
+
+ # param1
+ param1 = param_groups[0]
+ assert param1['lr'] == self.base_lr
+ assert param1['weight_decay'] == self.base_wd * flat_decay_mult
+ # conv1.weight
+ conv1_weight = param_groups[1]
+ assert conv1_weight['lr'] == self.base_lr
+ assert conv1_weight['weight_decay'] == self.base_wd
+ # conv2.weight
+ conv2_weight = param_groups[2]
+ assert conv2_weight['lr'] == self.base_lr
+ assert conv2_weight['weight_decay'] == self.base_wd
+ # conv2.bias
+ conv2_bias = param_groups[3]
+ assert conv2_bias['lr'] == self.base_lr * bias_lr_mult
+ assert conv2_bias['weight_decay'] == self.base_wd * bias_decay_mult
+ # bn.weight
+ bn_weight = param_groups[4]
+ assert bn_weight['lr'] == self.base_lr
+ assert bn_weight['weight_decay'] == self.base_wd * norm_decay_mult
+ # bn.bias
+ bn_bias = param_groups[5]
+ assert bn_bias['lr'] == self.base_lr
+ assert bn_bias['weight_decay'] == self.base_wd * norm_decay_mult
+ # sub.param1
+ sub_param1 = param_groups[6]
+ assert sub_param1['lr'] == self.base_lr
+ assert sub_param1['weight_decay'] == self.base_wd * flat_decay_mult
+ # sub.conv1.weight
+ sub_conv1_weight = param_groups[7]
+ assert sub_conv1_weight['lr'] == self.base_lr
+ assert sub_conv1_weight[
+ 'weight_decay'] == self.base_wd * dwconv_decay_mult
+ # sub.conv1.bias
+ sub_conv1_bias = param_groups[8]
+ assert sub_conv1_bias['lr'] == self.base_lr * bias_lr_mult
+ assert sub_conv1_bias['weight_decay'] == self.base_wd * bias_decay_mult
+ # sub.gn.weight
+ sub_gn_weight = param_groups[9]
+ assert sub_gn_weight['lr'] == self.base_lr
+ assert sub_gn_weight['weight_decay'] == self.base_wd * norm_decay_mult
+ # sub.gn.bias
+ sub_gn_bias = param_groups[10]
+ assert sub_gn_bias['lr'] == self.base_lr
+ assert sub_gn_bias['weight_decay'] == self.base_wd * norm_decay_mult
+
+ # test dcn which requires cuda is available and
+ # mmcv-full has been installed
+ if torch.cuda.is_available() and MMCV_FULL_AVAILABLE:
+ dcn_conv_weight = param_groups[11]
+ assert dcn_conv_weight['lr'] == self.base_lr
+ assert dcn_conv_weight['weight_decay'] == self.base_wd
+
+ dcn_offset_weight = param_groups[12]
+ assert dcn_offset_weight['lr'] == self.base_lr * dcn_offset_lr_mult
+ assert dcn_offset_weight['weight_decay'] == self.base_wd
+
+ dcn_offset_bias = param_groups[13]
+ assert dcn_offset_bias['lr'] == self.base_lr * dcn_offset_lr_mult
+ assert dcn_offset_bias['weight_decay'] == self.base_wd
+
+ def test_torch_optimizers(self):
+ torch_optimizers = [
+ 'ASGD', 'Adadelta', 'Adagrad', 'Adam', 'AdamW', 'Adamax', 'LBFGS',
+ 'Optimizer', 'RMSprop', 'Rprop', 'SGD', 'SparseAdam'
+ ]
+ assert set(torch_optimizers).issubset(set(TORCH_OPTIMIZERS))
+
+ def test_build_optimizer(self):
+ # test build function without ``constructor`` and ``paramwise_cfg``
+ optim_wrapper_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(
+ type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+ optim_wrapper = build_optim_wrapper(self.model, optim_wrapper_cfg)
+ self._check_default_optimizer(optim_wrapper.optimizer, self.model)
+
+ # test build optimizer without type in optim_wrapper_cfg
+ optim_wrapper_cfg = dict(
+ optimizer=dict(
+ type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+ optim_wrapper = build_optim_wrapper(self.model, optim_wrapper_cfg)
+ self.assertIsInstance(optim_wrapper, OptimWrapper)
+ self._check_default_optimizer(optim_wrapper.optimizer, self.model)
+
+ # test build function with invalid ``constructor``
+ with self.assertRaises(KeyError):
+ optim_wrapper_cfg['constructor'] = 'INVALID_CONSTRUCTOR'
+ build_optim_wrapper(self.model, optim_wrapper_cfg)
+
+ # test build function with invalid ``paramwise_cfg``
+ with self.assertRaises(KeyError):
+ optim_wrapper_cfg['paramwise_cfg'] = dict(invalid_mult=1)
+ build_optim_wrapper(self.model, optim_wrapper_cfg)
+
+ optim_wrapper_cfg.pop('optimizer')
+ optim_wrapper_cfg.pop('constructor')
+ optim_wrapper_cfg.pop('paramwise_cfg')
+ self.assertRaisesRegex(
+ AssertionError, '`optim_wrapper_cfg` must contain',
+ lambda: build_optim_wrapper(self.model, optim_wrapper_cfg))
+
+ def test_build_default_optimizer_constructor(self):
+ optim_wrapper = dict(
+ type='OptimWrapper',
+ optimizer=dict(
+ type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+ paramwise_cfg = dict(
+ bias_lr_mult=2,
+ bias_decay_mult=0.5,
+ norm_decay_mult=0,
+ dwconv_decay_mult=0.1,
+ dcn_offset_lr_mult=0.1,
+ flat_decay_mult=0.3)
+ optim_constructor_cfg = dict(
+ type='DefaultOptimWrapperConstructor',
+ optim_wrapper_cfg=optim_wrapper,
+ paramwise_cfg=paramwise_cfg)
+ optim_constructor = OPTIM_WRAPPER_CONSTRUCTORS.build(
+ optim_constructor_cfg)
+ optim_wrapper = optim_constructor(self.model)
+ self._check_sgd_optimizer(optim_wrapper.optimizer, self.model,
+ **paramwise_cfg)
+
+ def test_build_custom_optimizer_constructor(self):
+ optim_wrapper_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(
+ type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+
+ @OPTIM_WRAPPER_CONSTRUCTORS.register_module()
+ class MyOptimizerConstructor(DefaultOptimWrapperConstructor):
+
+ def __call__(self, model):
+ if hasattr(model, 'module'):
+ model = model.module
+
+ conv1_lr_mult = self.paramwise_cfg.get('conv1_lr_mult', 1.)
+ params = []
+
+ for name, param in model.named_parameters():
+ param_group = {'params': [param]}
+ if name.startswith('conv1') and param.requires_grad:
+ param_group['lr'] = self.base_lr * conv1_lr_mult
+ params.append(param_group)
+ self.optimizer_cfg['params'] = params
+
+ return build_from_cfg(self.optimizer_cfg, OPTIMIZERS)
+
+ paramwise_cfg = dict(conv1_lr_mult=5)
+ optim_constructor_cfg = dict(
+ type='MyOptimizerConstructor',
+ optim_wrapper_cfg=optim_wrapper_cfg,
+ paramwise_cfg=paramwise_cfg)
+ optim_constructor = OPTIM_WRAPPER_CONSTRUCTORS.build(
+ optim_constructor_cfg)
+ optimizer = optim_constructor(self.model)
+
+ param_groups = optimizer.param_groups
+ assert isinstance(optimizer, torch.optim.SGD)
+ assert optimizer.defaults['lr'] == self.base_lr
+ assert optimizer.defaults['momentum'] == self.momentum
+ assert optimizer.defaults['weight_decay'] == self.base_wd
+ for i, param in enumerate(self.model.parameters()):
+ param_group = param_groups[i]
+ assert torch.equal(param_group['params'][0], param)
+ assert param_group['momentum'] == self.momentum
+ # conv1.weight
+ assert param_groups[1][
+ 'lr'] == self.base_lr * paramwise_cfg['conv1_lr_mult']
+ assert param_groups[1]['weight_decay'] == self.base_wd
+
+ def test_default_optimizer_constructor(self):
+ with self.assertRaises(TypeError):
+ # optimizer_cfg must be a dict
+ optimizer_cfg = []
+ optim_constructor = DefaultOptimWrapperConstructor(optimizer_cfg)
+ optim_constructor(self.model)
+
+ with self.assertRaises(TypeError):
+ # paramwise_cfg must be a dict or None
+ optim_wrapper_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(lr=0.0001, weight_decay=None))
+ paramwise_cfg = ['error']
+ optim_constructor = DefaultOptimWrapperConstructor(
+ optim_wrapper_cfg, paramwise_cfg)
+ optim_constructor(self.model)
+
+ with self.assertRaises(ValueError):
+ # bias_decay_mult/norm_decay_mult is specified but weight_decay
+ # is None
+ optim_wrapper_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(lr=0.0001, weight_decay=None))
+ paramwise_cfg = dict(bias_decay_mult=1, norm_decay_mult=1)
+ optim_constructor = DefaultOptimWrapperConstructor(
+ optim_wrapper_cfg, paramwise_cfg)
+ optim_constructor(self.model)
+
+ # basic config with ExampleModel
+ optimizer_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(
+ type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+ optim_constructor = DefaultOptimWrapperConstructor(optimizer_cfg)
+ optim_wrapper = optim_constructor(self.model)
+ self._check_default_optimizer(optim_wrapper.optimizer, self.model)
+
+ def test_default_optimizer_constructor_with_model_wrapper(self):
+ # basic config with pseudo data parallel
+ model = PseudoDataParallel()
+ optim_wrapper_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(
+ type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+ paramwise_cfg = None
+ optim_constructor = DefaultOptimWrapperConstructor(optim_wrapper_cfg)
+ optim_wrapper = optim_constructor(model)
+ self._check_default_optimizer(
+ optim_wrapper.optimizer, model, prefix='module.')
+
+ # paramwise_cfg with pseudo data parallel
+ model = PseudoDataParallel()
+ optim_wrapper_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(
+ type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+ paramwise_cfg = dict(
+ bias_lr_mult=2,
+ bias_decay_mult=0.5,
+ norm_decay_mult=0,
+ dwconv_decay_mult=0.1,
+ dcn_offset_lr_mult=0.1,
+ flat_decay_mult=0.3)
+ optim_constructor = DefaultOptimWrapperConstructor(
+ optim_wrapper_cfg, paramwise_cfg)
+ optim_wrapper = optim_constructor(model)
+ self._check_sgd_optimizer(
+ optim_wrapper.optimizer, model, prefix='module.', **paramwise_cfg)
+
+ # basic config with DataParallel
+ if torch.cuda.is_available():
+ model = torch.nn.DataParallel(ExampleModel())
+ optim_wrapper_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(
+ type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+ paramwise_cfg = None
+ optim_constructor = DefaultOptimWrapperConstructor(
+ optim_wrapper_cfg)
+ optim_wrapper = optim_constructor(model)
+ self._check_default_optimizer(
+ optim_wrapper.optimizer, model, prefix='module.')
+
+ # paramwise_cfg with DataParallel
+ if torch.cuda.is_available():
+ model = torch.nn.DataParallel(self.model)
+ optim_wrapper_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(
+ type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+ paramwise_cfg = dict(
+ bias_lr_mult=2,
+ bias_decay_mult=0.5,
+ norm_decay_mult=0,
+ dwconv_decay_mult=0.1,
+ dcn_offset_lr_mult=0.1,
+ flat_decay_mult=0.3)
+ optim_constructor = DefaultOptimWrapperConstructor(
+ optim_wrapper_cfg, paramwise_cfg)
+ optim_wrapper = optim_constructor(model)
+ self._check_sgd_optimizer(
+ optim_wrapper.optimizer,
+ model,
+ prefix='module.',
+ **paramwise_cfg)
+
+ def test_default_optimizer_constructor_with_empty_paramwise_cfg(self):
+ # Empty paramwise_cfg with ExampleModel
+ optim_wrapper_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(
+ type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+ paramwise_cfg = dict()
+ optim_constructor = DefaultOptimWrapperConstructor(
+ optim_wrapper_cfg, paramwise_cfg)
+ optim_wrapper = optim_constructor(self.model)
+ self._check_default_optimizer(optim_wrapper.optimizer, self.model)
+
+ # Empty paramwise_cfg with ExampleModel and no grad
+ model = ExampleModel()
+ for param in model.parameters():
+ param.requires_grad = False
+ optim_wrapper_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(
+ type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+ paramwise_cfg = dict()
+ optim_constructor = DefaultOptimWrapperConstructor(optim_wrapper_cfg)
+ optim_wrapper = optim_constructor(model)
+ self._check_default_optimizer(optim_wrapper.optimizer, model)
+
+ def test_default_optimizer_constructor_with_paramwise_cfg(self):
+ # paramwise_cfg with ExampleModel
+ optim_wrapper_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(
+ type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+ paramwise_cfg = dict(
+ bias_lr_mult=2,
+ bias_decay_mult=0.5,
+ norm_decay_mult=0,
+ dwconv_decay_mult=0.1,
+ dcn_offset_lr_mult=0.1,
+ flat_decay_mult=0.3)
+ optim_constructor = DefaultOptimWrapperConstructor(
+ optim_wrapper_cfg, paramwise_cfg)
+ optim_wrapper = optim_constructor(self.model)
+ self._check_sgd_optimizer(optim_wrapper.optimizer, self.model,
+ **paramwise_cfg)
+
+ def test_default_optimizer_constructor_no_grad(self):
+ # paramwise_cfg with ExampleModel and no grad
+ optim_wrapper_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(
+ type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+ paramwise_cfg = dict(
+ bias_lr_mult=2,
+ bias_decay_mult=0.5,
+ norm_decay_mult=0,
+ dwconv_decay_mult=0.1,
+ dcn_offset_lr_mult=0.1)
+
+ for param in self.model.parameters():
+ param.requires_grad = False
+ optim_constructor = DefaultOptimWrapperConstructor(
+ optim_wrapper_cfg, paramwise_cfg)
+ optim_wrapper = optim_constructor(self.model)
+ optimizer = optim_wrapper.optimizer
+ param_groups = optimizer.param_groups
+ assert isinstance(optim_wrapper.optimizer, torch.optim.SGD)
+ assert optimizer.defaults['lr'] == self.base_lr
+ assert optimizer.defaults['momentum'] == self.momentum
+ assert optimizer.defaults['weight_decay'] == self.base_wd
+ for i, (name, param) in enumerate(self.model.named_parameters()):
+ param_group = param_groups[i]
+ assert torch.equal(param_group['params'][0], param)
+ assert param_group['momentum'] == self.momentum
+ assert param_group['lr'] == self.base_lr
+ assert param_group['weight_decay'] == self.base_wd
+
+ def test_default_optimizer_constructor_bypass_duplicate(self):
+ # paramwise_cfg with bypass_duplicate option
+ model = ExampleDuplicateModel()
+ optim_wrapper_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(
+ type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+ paramwise_cfg = dict(
+ bias_lr_mult=2,
+ bias_decay_mult=0.5,
+ norm_decay_mult=0,
+ dwconv_decay_mult=0.1)
+
+ with self.assertRaisesRegex(
+ ValueError,
+ 'some parameters appear in more than one parameter group'):
+ optim_constructor = DefaultOptimWrapperConstructor(
+ optim_wrapper_cfg, paramwise_cfg)
+ optim_constructor(model)
+
+ paramwise_cfg = dict(
+ bias_lr_mult=2,
+ bias_decay_mult=0.5,
+ norm_decay_mult=0,
+ dwconv_decay_mult=0.1,
+ dcn_offset_lr_mult=0.1,
+ flat_decay_mult=0.3,
+ bypass_duplicate=True)
+ optim_constructor = DefaultOptimWrapperConstructor(
+ optim_wrapper_cfg, paramwise_cfg)
+
+ self.assertWarnsRegex(
+ Warning,
+ 'conv3.0 is duplicate. It is skipped since bypass_duplicate=True',
+ lambda: optim_constructor(model))
+ optim_wrapper = optim_constructor(model)
+ model_parameters = list(model.parameters())
+ num_params = 14 if MMCV_FULL_AVAILABLE else 11
+ assert len(optim_wrapper.optimizer.param_groups) == len(
+ model_parameters) == num_params
+ self._check_sgd_optimizer(optim_wrapper.optimizer, model,
+ **paramwise_cfg)
+
+ def test_default_optimizer_constructor_custom_key(self):
+ # test DefaultOptimWrapperConstructor with custom_keys and
+ # ExampleModel
+ optim_wrapper_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(
+ type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+ paramwise_cfg = dict(
+ custom_keys={
+ 'param1': dict(lr_mult=10),
+ 'sub': dict(lr_mult=0.1, decay_mult=0),
+ 'sub.gn': dict(lr_mult=0.01),
+ 'non_exist_key': dict(lr_mult=0.0)
+ },
+ norm_decay_mult=0.5)
+
+ with self.assertRaises(TypeError):
+ # custom_keys should be a dict
+ paramwise_cfg_ = dict(custom_keys=[0.1, 0.0001])
+ optim_constructor = DefaultOptimWrapperConstructor(
+ optim_wrapper_cfg, paramwise_cfg_)
+ optimizer = optim_constructor(self.model)
+
+ with self.assertRaises(ValueError):
+ # if 'decay_mult' is specified in custom_keys, weight_decay
+ # should be specified
+ optim_wrapper_cfg_ = dict(
+ type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01))
+ paramwise_cfg_ = dict(
+ custom_keys={'.backbone': dict(decay_mult=0.5)})
+ optim_constructor = DefaultOptimWrapperConstructor(
+ optim_wrapper_cfg_, paramwise_cfg_)
+ optim_constructor(self.model)
+
+ optim_constructor = DefaultOptimWrapperConstructor(
+ optim_wrapper_cfg, paramwise_cfg)
+ optimizer = optim_constructor(self.model).optimizer
+ # check optimizer type and default config
+ assert isinstance(optimizer, torch.optim.SGD)
+ assert optimizer.defaults['lr'] == self.base_lr
+ assert optimizer.defaults['momentum'] == self.momentum
+ assert optimizer.defaults['weight_decay'] == self.base_wd
+
+ # check params groups
+ param_groups = optimizer.param_groups
+
+ groups = []
+ group_settings = []
+ # group 1, matches of 'param1'
+ # 'param1' is the longest match for 'sub.param1'
+ groups.append(['param1', 'sub.param1'])
+ group_settings.append({
+ 'lr': self.base_lr * 10,
+ 'momentum': self.momentum,
+ 'weight_decay': self.base_wd,
+ })
+ # group 2, matches of 'sub.gn'
+ groups.append(['sub.gn.weight', 'sub.gn.bias'])
+ group_settings.append({
+ 'lr': self.base_lr * 0.01,
+ 'momentum': self.momentum,
+ 'weight_decay': self.base_wd,
+ })
+ # group 3, matches of 'sub'
+ groups.append(['sub.conv1.weight', 'sub.conv1.bias'])
+ group_settings.append({
+ 'lr': self.base_lr * 0.1,
+ 'momentum': self.momentum,
+ 'weight_decay': 0,
+ })
+ # group 4, bn is configured by 'norm_decay_mult'
+ groups.append(['bn.weight', 'bn.bias'])
+ group_settings.append({
+ 'lr': self.base_lr,
+ 'momentum': self.momentum,
+ 'weight_decay': self.base_wd * 0.5,
+ })
+ # group 5, default group
+ groups.append(['conv1.weight', 'conv2.weight', 'conv2.bias'])
+ group_settings.append({
+ 'lr': self.base_lr,
+ 'momentum': self.momentum,
+ 'weight_decay': self.base_wd
+ })
+
+ num_params = 14 if MMCV_FULL_AVAILABLE else 11
+ assert len(param_groups) == num_params
+ for i, (name, param) in enumerate(self.model.named_parameters()):
+ assert torch.equal(param_groups[i]['params'][0], param)
+ for group, settings in zip(groups, group_settings):
+ if name in group:
+ for setting in settings:
+ assert param_groups[i][setting] == settings[
+ setting], f'{name} {setting}'
+
+ # test DefaultOptimWrapperConstructor with custom_keys and
+ # ExampleModel 2
+ optim_wrapper_cfg = dict(
+ type='OptimWrapper',
+ optimizer=dict(
+ type='SGD', lr=self.base_lr, momentum=self.momentum))
+ paramwise_cfg = dict(custom_keys={'param1': dict(lr_mult=10)})
+
+ optim_constructor = DefaultOptimWrapperConstructor(
+ optim_wrapper_cfg, paramwise_cfg)
+ optimizer = optim_constructor(self.model).optimizer
+ # check optimizer type and default config
+ assert isinstance(optimizer, torch.optim.SGD)
+ assert optimizer.defaults['lr'] == self.base_lr
+ assert optimizer.defaults['momentum'] == self.momentum
+ assert optimizer.defaults['weight_decay'] == 0
+
+ # check params groups
+ param_groups = optimizer.param_groups
+
+ groups = []
+ group_settings = []
+ # group 1, matches of 'param1'
+ groups.append(['param1', 'sub.param1'])
+ group_settings.append({
+ 'lr': self.base_lr * 10,
+ 'momentum': self.momentum,
+ 'weight_decay': 0,
+ })
+ # group 2, default group
+ groups.append([
+ 'sub.conv1.weight', 'sub.conv1.bias', 'sub.gn.weight',
+ 'sub.gn.bias', 'conv1.weight', 'conv2.weight', 'conv2.bias',
+ 'bn.weight', 'bn.bias'
+ ])
+ group_settings.append({
+ 'lr': self.base_lr,
+ 'momentum': self.momentum,
+ 'weight_decay': 0
+ })
+
+ num_params = 14 if MMCV_FULL_AVAILABLE else 11
+ assert len(param_groups) == num_params
+ for i, (name, param) in enumerate(self.model.named_parameters()):
+ assert torch.equal(param_groups[i]['params'][0], param)
+ for group, settings in zip(groups, group_settings):
+ if name in group:
+ for setting in settings:
+ assert param_groups[i][setting] == settings[
+ setting], f'{name} {setting}'
+
+
+@unittest.skipIf(
+ (digit_version(TORCH_VERSION) < digit_version('1.8.0'))
+ or not is_available(),
+ reason='ZeRO requires pytorch>=1.8 with torch.distributed.rpc available.')
+class TestZeroOptimizer(MultiProcessTestCase):
+
+ def setUp(self) -> None:
+ super().setUp()
+ self._spawn_processes()
+
+ def _check_default_optimizer(self, optimizer, model):
+ self.assertIsInstance(optimizer.optim, torch.optim.SGD)
+ self.assertEqual(optimizer.defaults['lr'], self.base_lr)
+ self.assertEqual(optimizer.defaults['momentum'], self.momentum)
+ self.assertEqual(optimizer.defaults['weight_decay'], self.base_wd)
+ param_groups = optimizer.param_groups
+ params_set = set(model.parameters())
+ self.assertEqual(
+ sum(len(param_group['params']) for param_group in param_groups),
+ len(params_set))
+ self.assertTrue(
+ all(param in params_set for param_group in param_groups
+ for param in param_group['params']))
+ state_dict = optimizer.state_dict()
+ if get_rank() == 0:
+ self.assertEqual(
+ sum(len(pg['params']) for pg in state_dict['param_groups']),
+ len(params_set))
+ else:
+ self.assertEqual(state_dict, {})
+
+ def test_zero_redundancy_optimizer(self):
+ self._init_dist_env(self.rank, self.world_size)
+ model = ExampleModel()
+ self.base_lr = 0.01
+ self.momentum = 0.0001
+ self.base_wd = 0.9
+
+ # test build function
+ optim_wrapper_cfg = dict(
+ optimizer=dict(
+ type='ZeroRedundancyOptimizer',
+ optimizer_type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+ optim_wrapper = build_optim_wrapper(model, optim_wrapper_cfg)
+ self._check_default_optimizer(optim_wrapper.optimizer, model)
+
+ # test build optimizer without ``optimizer_type``
+ with self.assertRaises(TypeError):
+ optim_wrapper_cfg = dict(
+ optimizer=dict(
+ type='ZeroRedundancyOptimizer',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum))
+ optim_wrapper = build_optim_wrapper(model, optim_wrapper_cfg)
+
+ @unittest.skipIf(
+ digit_version(TORCH_VERSION) < digit_version('1.12.0'),
+ reason='ZeRO started to support param groups since pytorch 1.12.0')
+ def test_zero_redundancy_optimizer_with_paramwise_cfg(self):
+ self._init_dist_env(self.rank, self.world_size)
+ model = ExampleModel()
+ self.base_lr = 0.01
+ self.momentum = 0.0001
+ self.base_wd = 0.9
+
+ # test build function
+ paramwise_cfg = dict(
+ custom_keys={
+ 'conv1': dict(lr_mult=0.0, decay_mult=0.0),
+ 'conv2': dict(lr_mult=1.0, decay_mult=2.0)
+ })
+ optim_wrapper_cfg = dict(
+ optimizer=dict(
+ type='ZeroRedundancyOptimizer',
+ optimizer_type='SGD',
+ lr=self.base_lr,
+ weight_decay=self.base_wd,
+ momentum=self.momentum),
+ paramwise_cfg=paramwise_cfg)
+ optim_wrapper = build_optim_wrapper(model, optim_wrapper_cfg)
+ self._check_default_optimizer(optim_wrapper.optimizer, model)
+
+ def _init_dist_env(self, rank, world_size):
+ """Initialize the distributed environment."""
+ os.environ['MASTER_ADDR'] = '127.0.0.1'
+ os.environ['MASTER_PORT'] = '29510'
+ os.environ['RANK'] = str(rank)
+ torch.distributed.init_process_group(
+ backend='gloo', rank=rank, world_size=world_size)
diff --git a/testbed/open-mmlab__mmengine/tests/test_optim/test_optimizer/test_optimizer_wrapper.py b/testbed/open-mmlab__mmengine/tests/test_optim/test_optimizer/test_optimizer_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..35984ce37fb6085702801d8f282272063b0bfd52
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_optim/test_optimizer/test_optimizer_wrapper.py
@@ -0,0 +1,402 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import unittest
+from unittest import TestCase
+from unittest.mock import MagicMock
+
+import pytest
+import torch
+import torch.distributed as torch_dist
+import torch.nn as nn
+from torch.cuda.amp import GradScaler
+from torch.nn.parallel.distributed import DistributedDataParallel
+from torch.optim import SGD, Adam, Optimizer
+
+from mmengine.dist import all_gather
+from mmengine.logging import MessageHub, MMLogger
+from mmengine.optim import AmpOptimWrapper, OptimWrapper
+from mmengine.testing import assert_allclose
+from mmengine.testing._internal import MultiProcessTestCase
+from mmengine.utils import digit_version
+from mmengine.utils.dl_utils import TORCH_VERSION
+
+
+class ToyModel(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.conv1 = nn.Conv2d(1, 1, 1)
+ self.conv2 = nn.Conv2d(1, 1, 1)
+ self.conv3 = nn.Conv2d(1, 1, 1)
+
+ def forward(self, x):
+ x = self.conv1(x)
+ x = self.conv2(x)
+ return x
+
+
+class ToyModel2(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.conv = nn.Conv2d(1, 1, 1)
+
+ def forward(self, x):
+ x = self.conv(x)
+ return x
+
+
+class TestOptimWrapper(MultiProcessTestCase):
+ # Test `OptimWrapper.optim_context` will block the gradient
+ # synchronization when using gradient accumulation strategy in distributed
+ # data parallel training.
+ def setUp(self) -> None:
+ super().setUp()
+ self._spawn_processes()
+
+ def run_test(self, test_name: str, parent_pipe) -> None:
+ self.model = ToyModel()
+ self.optimizer = SGD(self.model.parameters(), lr=0.1)
+ self.logger = MMLogger.get_instance('test_optim_wrapper')
+ self.message_hub = MessageHub.get_instance('test_optim_wrapper_init')
+ super().run_test(test_name, parent_pipe)
+
+ def test_init(self):
+ optim_wrapper = OptimWrapper(self.optimizer)
+ self.assertIs(optim_wrapper.optimizer, self.optimizer)
+ self.assertIsNone(optim_wrapper.clip_grad_kwargs)
+ self.assertEqual(optim_wrapper._accumulative_counts, 1)
+ self.assertIs(optim_wrapper.message_hub, self.message_hub)
+ self.assertEqual(optim_wrapper._inner_count, 0)
+ self.assertEqual(optim_wrapper._max_counts, -1)
+ self.assertEqual(optim_wrapper._remainder_counts, -1)
+
+ with self.assertRaisesRegex(AssertionError,
+ 'If `clip_grad` is not None'):
+ OptimWrapper(self.optimizer, clip_grad=[])
+
+ def test_update_params(self):
+ # Test update params every iteration.
+ optim_wrapper = OptimWrapper(self.optimizer, accumulative_counts=1)
+ self._mock_method(optim_wrapper)
+ loss = torch.tensor(1.)
+ optim_wrapper.update_params(loss)
+ self.assertEqual(optim_wrapper.scaled_loss, torch.tensor(1.))
+ optim_wrapper.step.assert_called_with()
+ optim_wrapper.zero_grad.assert_called_with()
+
+ # Test gradient accumulation.
+ optim_wrapper = OptimWrapper(self.optimizer, accumulative_counts=3)
+ self._mock_method(optim_wrapper)
+ # `iter=0`, accumulate gradient and do not update params.
+ loss = torch.tensor(1.)
+ optim_wrapper.update_params(loss)
+ self.assertEqual(optim_wrapper.scaled_loss, torch.tensor(1.) / 3.)
+ optim_wrapper.step.assert_not_called()
+ optim_wrapper.zero_grad.assert_not_called()
+
+ # gradient accumulate
+ optim_wrapper.update_params(loss)
+ self.assertEqual(optim_wrapper._inner_count, 2.)
+
+ # `iter=2`, update params.
+ optim_wrapper.update_params(loss)
+ optim_wrapper.step.assert_called()
+ optim_wrapper.zero_grad.assert_called()
+ self._mock_method(optim_wrapper)
+
+ # Test end of training without calling `initialize_iter_status`
+ optim_wrapper._inner_count = 99
+ optim_wrapper.update_params(loss)
+ optim_wrapper.step.assert_not_called()
+ optim_wrapper.zero_grad.assert_not_called()
+ self.assertEqual(optim_wrapper.scaled_loss, torch.tensor(1.) / 3.)
+ self._mock_method(optim_wrapper)
+
+ # After calling `initialize_iter_status`, params will be updated at the
+ # last iteration, and the `loss_scaler` will be adjusted.
+ optim_wrapper.initialize_count_status(self.model, 99, 100)
+ optim_wrapper.update_params(loss)
+ optim_wrapper.step.assert_called()
+ optim_wrapper.zero_grad.assert_called()
+ self.assertEqual(optim_wrapper.scaled_loss, torch.tensor(1.))
+ self._mock_method(optim_wrapper)
+
+ # optim_wrapper.step should not be called at iteration 97 98, and the
+ # loss factor should be 3 at iteration 99.
+ optim_wrapper.initialize_count_status(self.model, 96, 100)
+ for _ in range(2):
+ optim_wrapper.update_params(loss)
+ optim_wrapper.step.assert_not_called()
+ optim_wrapper.zero_grad.assert_not_called()
+ self.assertEqual(optim_wrapper.scaled_loss, torch.tensor(1.) / 3)
+
+ def test_initialize_iter_status(self):
+ optim_wrapper = OptimWrapper(self.optimizer, accumulative_counts=3)
+ optim_wrapper.initialize_count_status(self.model, 0, 100)
+ self.assertEqual(optim_wrapper._remainder_counts, 1)
+
+ # Indivisible cur_iter will output warning.
+ optim_wrapper = OptimWrapper(self.optimizer, accumulative_counts=3)
+ with self.assertLogs(self.logger) as cm:
+ optim_wrapper.initialize_count_status(self.model, 2, 100)
+ self.assertEqual(len(cm.output), 1)
+ self.assertRegex(cm.records[0].msg, 'Resumed iteration number')
+
+ # Model with batch norm will output warning.
+ optim_wrapper = OptimWrapper(self.optimizer, accumulative_counts=3)
+ model = nn.BatchNorm2d(1)
+ with self.assertLogs(self.logger) as cm:
+ optim_wrapper.initialize_count_status(model, 0, 99)
+ self.assertEqual(len(cm.output), 1)
+ self.assertRegex(cm.records[0].msg, 'Gradient accumulative')
+
+ def test_ger_lr(self):
+ model = ToyModel()
+ optim = SGD(model.parameters(), lr=0.1)
+ optim_wrapper = OptimWrapper(optim)
+ self.assertEqual(optim_wrapper.get_lr(), dict(lr=[0.1]))
+
+ def test_get_momentum(self):
+ # Get momentum from SGD
+ model = ToyModel()
+ optim = SGD(model.parameters(), lr=0., momentum=0.8)
+ optim_wrapper = OptimWrapper(optim)
+ self.assertEqual(optim_wrapper.get_momentum(), dict(momentum=[0.8]))
+ # Get momentum from Adam
+ optim = Adam(model.parameters(), lr=0., betas=(0.9, 0.9))
+ optim_wrapper = OptimWrapper(optim)
+ self.assertEqual(optim_wrapper.get_momentum(), dict(momentum=[0.9]))
+
+ def test_backward(self):
+ loss = MagicMock()
+ optim_wrapper = OptimWrapper(self.optimizer)
+ optim_wrapper.backward(loss)
+ loss.backward.assert_called()
+
+ def test_zero_grad(self):
+ optimizer = MagicMock(spec=Optimizer)
+ optim_wrapper = OptimWrapper(optimizer)
+ optim_wrapper.zero_grad()
+ optimizer.zero_grad.assert_called()
+
+ def test_step(self):
+ optimizer = MagicMock(spec=Optimizer)
+ optim_wrapper = OptimWrapper(optimizer)
+ optim_wrapper.step()
+ optimizer.step.assert_called()
+
+ # TODO: This unit test could cause CI to fail with some probability, which
+ # is caused by MultiProcessTestCase. This problem should be solved
+ # in the future).
+ @pytest.mark.skipif(True, reason='Solved in the future')
+ def test_clip_grads(self):
+ # Test `clip_grad` with `clip_norm_`
+ optim_wrapper = OptimWrapper(
+ self.optimizer, clip_grad=dict(max_norm=35))
+ loss = self.model(torch.Tensor(1, 1, 1, 1))
+ loss.backward()
+ optim_wrapper._clip_grad()
+ log_scalars = self.message_hub.log_scalars
+ self.assertIn('train/grad_norm', log_scalars)
+ self.message_hub._log_scalars.clear()
+
+ # Test `clip_grad` with `clip_value_`
+ optim_wrapper = OptimWrapper(
+ self.optimizer, clip_grad=dict(type='value', clip_value=0.5))
+ loss = self.model(torch.Tensor(1, 1, 1, 1))
+ loss.backward()
+ optim_wrapper._clip_grad()
+ self.assertNotIn('train/grad_norm', log_scalars)
+
+ def test_state_dict(self):
+ optim_wrapper = OptimWrapper(self.optimizer)
+ self.assertEqual(optim_wrapper.state_dict(),
+ self.optimizer.state_dict())
+
+ def test_load_state_dict(self):
+ optim_wrapper = OptimWrapper(self.optimizer)
+ model = ToyModel()
+ optimizer = SGD(model.parameters(), lr=0.1)
+ optim_wrapper.load_state_dict(optimizer.state_dict())
+
+ self.assertEqual(optim_wrapper.state_dict(), optimizer.state_dict())
+
+ def test_param_groups(self):
+ optim_wrapper = OptimWrapper(self.optimizer)
+ self.assertEqual(optim_wrapper.param_groups,
+ self.optimizer.param_groups)
+
+ def test_optim_context(self):
+ self._init_dist_env(self.rank, self.world_size)
+ model = ToyModel2()
+ ddp_model = DistributedDataParallel(model)
+ optimizer = SGD(ddp_model.parameters(), lr=0.01)
+ optim_wrapper = OptimWrapper(optimizer, accumulative_counts=1)
+ optim_wrapper.zero_grad()
+
+ # Automatically sync grads if `accumulative_counts` = 1
+ optim_wrapper.initialize_count_status(model, 0, 100)
+ inputs = torch.randn(1, 1, 1, 1) * self.rank
+ ddp_model(inputs).sum().backward()
+ grad = model.conv.weight.grad
+ all_grads = all_gather(grad)
+ assert_allclose(all_grads[0], all_grads[1])
+
+ # Do not sync grads when `optim_wrapper.cur_iter` cannot be
+ # divided by `optim_wrapper._accumulative_counts`
+ optim_wrapper = OptimWrapper(optimizer, accumulative_counts=3)
+ optim_wrapper.initialize_count_status(model, 0, 100)
+ with optim_wrapper.optim_context(ddp_model):
+ loss = ddp_model(inputs).sum()
+ loss.backward()
+ all_grads = all_gather(model.conv.weight.grad)
+ with self.assertRaises(AssertionError):
+ assert_allclose(all_grads[0], all_grads[1])
+
+ # sync grads if `cur_iter == 2`
+ optim_wrapper.initialize_count_status(model, 2, 100)
+ with optim_wrapper.optim_context(ddp_model):
+ loss = ddp_model(inputs).sum()
+ loss.backward()
+ all_grads = all_gather(model.conv.weight.grad)
+ assert_allclose(all_grads[0], all_grads[1])
+
+ def _init_dist_env(self, rank, world_size):
+ """Initialize the distributed environment."""
+ os.environ['MASTER_ADDR'] = '127.0.0.1'
+ os.environ['MASTER_PORT'] = '29515'
+ os.environ['RANK'] = str(rank)
+ torch_dist.init_process_group(
+ backend='gloo', rank=rank, world_size=world_size)
+
+ # TODO Test the real interface after add testing tool function which can
+ # test the function or method is read called.
+ def _mock_method(self, optim_wrapper):
+
+ def mock_methd(loss):
+ optim_wrapper._inner_count += 1
+ optim_wrapper.scaled_loss = loss
+
+ optim_wrapper.backward = mock_methd
+ optim_wrapper.step = MagicMock()
+ optim_wrapper.zero_grad = MagicMock()
+
+
+class TestAmpOptimWrapper(TestCase):
+
+ def setUp(self) -> None:
+ self.model = ToyModel()
+ self.optimizer = SGD(self.model.parameters(), lr=0.1)
+
+ @unittest.skipIf(
+ not torch.cuda.is_available()
+ and (digit_version(TORCH_VERSION) >= digit_version('1.6.0')),
+ reason='`torch.cuda.amp` is only available when pytorch-gpu version '
+ '>= 1.6')
+ def test_init(self):
+ # Test with default arguments.
+ amp_optim_wrapper = AmpOptimWrapper(optimizer=self.optimizer)
+ self.assertIsInstance(amp_optim_wrapper.loss_scaler, GradScaler)
+
+ # Test with dynamic.
+ amp_optim_wrapper = AmpOptimWrapper(
+ 'dynamic', optimizer=self.optimizer)
+ self.assertIsNone(amp_optim_wrapper._scale_update_param)
+ self.assertIsInstance(amp_optim_wrapper.loss_scaler, GradScaler)
+
+ # Test with dict loss_scale.
+ amp_optim_wrapper = AmpOptimWrapper(
+ dict(init_scale=1, growth_factor=2), optimizer=self.optimizer)
+ self.assertIsInstance(amp_optim_wrapper.loss_scaler, GradScaler)
+ self.assertIsNone(amp_optim_wrapper._scale_update_param)
+ with self.assertRaisesRegex(TypeError,
+ 'loss_scale must be of type float'):
+ AmpOptimWrapper(optimizer=self.optimizer, loss_scale='unknown')
+
+ @unittest.skipIf(
+ not torch.cuda.is_available()
+ and (digit_version(TORCH_VERSION) >= digit_version('1.6.0')),
+ reason='`torch.cuda.amp` is only available when pytorch-gpu version '
+ '>= 1.6')
+ def test_step(self):
+ optimizer = MagicMock(spec=Optimizer)
+ amp_optim_wrapper = AmpOptimWrapper(optimizer=optimizer)
+ amp_optim_wrapper.loss_scaler = MagicMock()
+ amp_optim_wrapper.step()
+ amp_optim_wrapper.loss_scaler.step.assert_called_with(
+ amp_optim_wrapper.optimizer)
+ amp_optim_wrapper.loss_scaler.update.assert_called_with(
+ amp_optim_wrapper._scale_update_param)
+
+ @unittest.skipIf(
+ not torch.cuda.is_available()
+ and (digit_version(TORCH_VERSION) >= digit_version('1.6.0')),
+ reason='`torch.cuda.amp` is only available when pytorch-gpu version '
+ '>= 1.6')
+ def test_backward(self):
+ amp_optim_wrapper = AmpOptimWrapper(optimizer=self.optimizer)
+ loss_scaler = MagicMock()
+ scale_return = MagicMock()
+ scale_fn = MagicMock(return_value=scale_return)
+ loss_scaler.scale = scale_fn
+ amp_optim_wrapper.loss_scaler = loss_scaler
+
+ amp_optim_wrapper.backward(1)
+ loss_scaler.scale.assert_called_with(1)
+ scale_return.backward.assert_called_with()
+
+ @unittest.skipIf(
+ not torch.cuda.is_available()
+ and (digit_version(TORCH_VERSION) >= digit_version('1.6.0')),
+ reason='`torch.cuda.amp` is only available when pytorch-gpu version '
+ '>= 1.6')
+ def test_state_dict(self):
+ self.model = self.model.cuda()
+ amp_optim_wrapper = AmpOptimWrapper(optimizer=self.optimizer)
+ loss = self.model(torch.Tensor(1, 1, 1, 1).cuda())
+ amp_optim_wrapper.update_params(loss)
+ state_dict = amp_optim_wrapper.state_dict()
+ scalar_state_dict = state_dict.pop('loss_scaler')
+ optim_state_dict = state_dict
+
+ self.assertDictEqual(optim_state_dict,
+ amp_optim_wrapper.optimizer.state_dict())
+ self.assertDictEqual(scalar_state_dict,
+ amp_optim_wrapper.loss_scaler.state_dict())
+
+ @unittest.skipIf(
+ not torch.cuda.is_available()
+ and (digit_version(TORCH_VERSION) >= digit_version('1.6.0')),
+ reason='`torch.cuda.amp` is only available when pytorch-gpu version '
+ '>= 1.6')
+ def test_load_state_dict(self):
+ amp_optim_wrapper = AmpOptimWrapper(optimizer=self.optimizer)
+ self.model = self.model.cuda()
+ # Test load from optimizer
+ optimizer = SGD(self.model.parameters(), lr=0.1)
+ amp_optim_wrapper.load_state_dict(optimizer.state_dict())
+
+ self.assertDictEqual(optimizer.state_dict(),
+ amp_optim_wrapper.optimizer.state_dict())
+ # Test load from optim_wrapper
+ amp_optim_wrapper = AmpOptimWrapper(optimizer=self.optimizer)
+ amp_optim_wrapper_ = AmpOptimWrapper(
+ optimizer=SGD(self.model.parameters(), lr=0.1))
+ amp_optim_wrapper_.load_state_dict(amp_optim_wrapper.state_dict())
+ self.assertDictEqual(amp_optim_wrapper.optimizer.state_dict(),
+ amp_optim_wrapper_.optimizer.state_dict())
+ self.assertDictEqual(amp_optim_wrapper.loss_scaler.state_dict(),
+ amp_optim_wrapper_.loss_scaler.state_dict())
+
+ @unittest.skipIf(
+ not torch.cuda.is_available()
+ and (digit_version(TORCH_VERSION) >= digit_version('1.6.0')),
+ reason='`torch.cuda.amp` is only available when pytorch-gpu version '
+ '>= 1.6')
+ def test_optim_context(self):
+ amp_optim_wrapper = AmpOptimWrapper(optimizer=self.optimizer)
+ with amp_optim_wrapper.optim_context(self.model):
+ x = torch.randn(1, 1, 1, 1).cuda()
+ y = nn.Conv2d(1, 1, 1).cuda()(x)
+ self.assertEqual(y.dtype, torch.float16)
diff --git a/testbed/open-mmlab__mmengine/tests/test_optim/test_optimizer/test_optimizer_wrapper_dict.py b/testbed/open-mmlab__mmengine/tests/test_optim/test_optimizer/test_optimizer_wrapper_dict.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5dd2c42679e9a8e43ca4aea7a7405708246e557
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_optim/test_optimizer/test_optimizer_wrapper_dict.py
@@ -0,0 +1,153 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from unittest import TestCase
+
+import torch
+import torch.nn as nn
+from torch.optim import SGD
+
+from mmengine.optim import OptimWrapper, OptimWrapperDict
+
+
+class TestOptimWrapperDict(TestCase):
+
+ def setUp(self) -> None:
+ self.model1 = nn.Linear(1, 1)
+ self.model2 = nn.Linear(1, 1)
+ self.optim1 = SGD(self.model1.parameters(), lr=0.1, momentum=0.8)
+ self.optim2 = SGD(self.model2.parameters(), lr=0.2, momentum=0.9)
+ self.optim_wrapper1 = OptimWrapper(self.optim1)
+ self.optim_wrapper2 = OptimWrapper(self.optim2)
+ self.optimizers_wrappers = dict(
+ optim1=self.optim_wrapper1, optim2=self.optim_wrapper2)
+
+ def test_init(self):
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ self.assertEqual(optim_wrapper_dict.optim_wrappers,
+ self.optimizers_wrappers)
+ with self.assertRaisesRegex(AssertionError,
+ '`OptimWrapperDict` only accept'):
+ OptimWrapperDict(**dict(optim1=self.optim1, optim2=self.optim2))
+
+ def test_update_params(self):
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ with self.assertRaisesRegex(NotImplementedError,
+ '`update_params` should be called'):
+ optim_wrapper_dict.update_params(1)
+
+ def test_backward(self):
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ with self.assertRaisesRegex(NotImplementedError,
+ '`backward` should be called'):
+ optim_wrapper_dict.backward(1)
+
+ def test_step(self):
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ with self.assertRaisesRegex(NotImplementedError,
+ '`step` should be called'):
+ optim_wrapper_dict.step()
+
+ def test_zero_grad(self):
+ # Test clear all grad
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ self.model1(torch.randn(1, 1)).sum().backward()
+ self.model2(torch.randn(1, 1)).sum().backward()
+ self.assertTrue((self.model1.weight.grad != 0).any())
+ self.assertTrue((self.model2.weight.grad != 0).any())
+ optim_wrapper_dict.zero_grad()
+ self.assertTrue((self.model1.weight.grad == 0).all())
+ self.assertTrue((self.model2.weight.grad == 0).all())
+
+ def test_optim_context(self):
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ with self.assertRaisesRegex(NotImplementedError,
+ '`optim_context` should be called'):
+ with optim_wrapper_dict.optim_context(self.model1):
+ yield
+
+ def test_initialize_count_status(self):
+ # Test `initialize_count_status` can be called.
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ optim_wrapper_dict.initialize_count_status(self.model1, 1, 1)
+
+ def test_param_groups(self):
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ self.assertEqual(optim_wrapper_dict.param_groups['optim1'],
+ self.optim1.param_groups)
+ self.assertEqual(optim_wrapper_dict.param_groups['optim2'],
+ self.optim2.param_groups)
+
+ def test_get_lr(self):
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ lr = optim_wrapper_dict.get_lr()
+ self.assertEqual(lr['optim1.lr'], [0.1])
+ self.assertEqual(lr['optim2.lr'], [0.2])
+
+ def test_get_momentum(self):
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ momentum = optim_wrapper_dict.get_momentum()
+ self.assertEqual(momentum['optim1.momentum'], [0.8])
+ self.assertEqual(momentum['optim2.momentum'], [0.9])
+
+ def test_state_dict(self):
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ state_dict = optim_wrapper_dict.state_dict()
+ self.assertEqual(state_dict['optim1'],
+ self.optim_wrapper1.state_dict())
+ self.assertEqual(state_dict['optim2'],
+ self.optim_wrapper2.state_dict())
+
+ def test_load_state_dict(self):
+ # Test OptimWrapperDict can load from saved state dict.
+ model1 = nn.Linear(1, 1)
+ model2 = nn.Linear(1, 1)
+ optim1 = SGD(model1.parameters(), lr=0.1)
+ optim2 = SGD(model2.parameters(), lr=0.1)
+ optim_wrapper_load1 = OptimWrapper(optim1)
+ optim_wrapper_load2 = OptimWrapper(optim2)
+
+ optim_wrapper_dict_save = OptimWrapperDict(**self.optimizers_wrappers)
+ optim_wrapper_dict_load = OptimWrapperDict(
+ optim1=optim_wrapper_load1, optim2=optim_wrapper_load2)
+ state_dict = optim_wrapper_dict_save.state_dict()
+ optim_wrapper_dict_load.load_state_dict(state_dict)
+
+ self.assertDictEqual(optim_wrapper_dict_load.state_dict(),
+ optim_wrapper_dict_save.state_dict())
+
+ def test_items(self):
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ self.assertListEqual(
+ list(optim_wrapper_dict.items()),
+ list(self.optimizers_wrappers.items()))
+
+ def test_values(self):
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ self.assertListEqual(
+ list(optim_wrapper_dict.values()),
+ list(self.optimizers_wrappers.values()))
+
+ def test_keys(self):
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ self.assertListEqual(
+ list(optim_wrapper_dict.keys()),
+ list(self.optimizers_wrappers.keys()))
+
+ def test_getitem(self):
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ self.assertIs(self.optimizers_wrappers['optim1'],
+ optim_wrapper_dict['optim1'])
+ self.assertIs(self.optimizers_wrappers['optim2'],
+ optim_wrapper_dict['optim2'])
+
+ def test_len(self):
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ self.assertEqual(len(optim_wrapper_dict), 2)
+
+ def test_contain(self):
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ self.assertIn('optim1', optim_wrapper_dict)
+
+ def test_repr(self):
+ optim_wrapper_dict = OptimWrapperDict(**self.optimizers_wrappers)
+ desc = repr(optim_wrapper_dict)
+ self.assertRegex(desc, 'name: optim1')
diff --git a/testbed/open-mmlab__mmengine/tests/test_optim/test_scheduler/test_lr_scheduler.py b/testbed/open-mmlab__mmengine/tests/test_optim/test_scheduler/test_lr_scheduler.py
new file mode 100644
index 0000000000000000000000000000000000000000..bd537b8680e2d0e4a8f72ddfc43f680cd5dbc0e1
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_optim/test_scheduler/test_lr_scheduler.py
@@ -0,0 +1,678 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import math
+from unittest import TestCase
+
+import torch
+import torch.nn.functional as F
+import torch.optim as optim
+
+from mmengine.optim.scheduler import (ConstantLR, CosineAnnealingLR,
+ CosineRestartLR, ExponentialLR, LinearLR,
+ MultiStepLR, OneCycleLR, PolyLR, StepLR,
+ _ParamScheduler)
+from mmengine.testing import assert_allclose
+
+
+class ToyModel(torch.nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.conv1 = torch.nn.Conv2d(1, 1, 1)
+ self.conv2 = torch.nn.Conv2d(1, 1, 1)
+
+ def forward(self, x):
+ return self.conv2(F.relu(self.conv1(x)))
+
+
+class TestLRScheduler(TestCase):
+
+ def setUp(self):
+ """Setup the model and optimizer which are used in every test method.
+
+ TestCase calls functions in this order: setUp() -> testMethod() ->
+ tearDown() -> cleanUp()
+ """
+ self.model = ToyModel()
+ lr = 0.05
+ self.layer2_mult = 10
+ self.optimizer = optim.SGD([{
+ 'params': self.model.conv1.parameters()
+ }, {
+ 'params': self.model.conv2.parameters(),
+ 'lr': lr * self.layer2_mult,
+ }],
+ lr=lr,
+ momentum=0.01,
+ weight_decay=5e-4)
+
+ def test_base_scheduler_step(self):
+ with self.assertRaises(NotImplementedError):
+ _ParamScheduler(self.optimizer, param_name='lr')
+
+ def test_invalid_optimizer(self):
+ with self.assertRaisesRegex(TypeError, 'should be an Optimizer'):
+ StepLR('invalid_optimizer', step_size=1)
+
+ def test_overwrite_optimzer_step(self):
+ # raise warning if the counter in optimizer.step() is overwritten
+ scheduler = ExponentialLR(self.optimizer, gamma=0.9)
+
+ def overwrite_fun():
+ pass
+
+ self.optimizer.step = overwrite_fun
+ self.optimizer.step()
+ self.assertWarnsRegex(UserWarning, r'how-to-adjust-learning-rate',
+ scheduler.step)
+
+ def test_resume(self):
+ # test invalid case: optimizer and scheduler are not both resumed
+ with self.assertRaisesRegex(KeyError,
+ "param 'initial_lr' is not specified"):
+ StepLR(self.optimizer, gamma=0.1, step_size=3, last_step=10)
+
+ # test manually resume with ``last_step`` instead of load_state_dict
+ epochs = 10
+ targets = [0.05 * (0.9**x) for x in range(epochs)]
+ scheduler = ExponentialLR(self.optimizer, gamma=0.9)
+
+ results = []
+ for epoch in range(5):
+ results.append(self.optimizer.param_groups[0]['lr'])
+ # The order should be
+ # train_epoch() -> save_checkpoint() -> scheduler.step().
+ # Break at here to simulate the checkpoint is saved before
+ # the scheduler.step().
+ if epoch == 4:
+ break
+ scheduler.step()
+ scheduler2 = ExponentialLR(self.optimizer, gamma=0.9, last_step=4)
+ for epoch in range(6):
+ results.append(self.optimizer.param_groups[0]['lr'])
+ scheduler2.step()
+
+ for epoch in range(epochs):
+ assert_allclose(
+ targets[epoch],
+ results[epoch],
+ msg='lr is wrong in epoch {}: expected {}, got {}'.format(
+ epoch, targets[epoch], results[epoch]),
+ atol=1e-5,
+ rtol=0)
+
+ def test_scheduler_before_optim_warning(self):
+ """warns if scheduler is used before optimizer."""
+
+ def call_sch_before_optim():
+ scheduler = StepLR(self.optimizer, gamma=0.1, step_size=3)
+ scheduler.step()
+ self.optimizer.step()
+
+ # check warning doc link
+ self.assertWarnsRegex(UserWarning, r'how-to-adjust-learning-rate',
+ call_sch_before_optim)
+
+ # check warning when resume
+ for i, group in enumerate(self.optimizer.param_groups):
+ group['initial_lr'] = 0.01
+
+ def call_sch_before_optim_resume():
+ scheduler = StepLR(
+ self.optimizer, gamma=0.1, step_size=3, last_step=10)
+ scheduler.step()
+ self.optimizer.step()
+
+ # check warning doc link
+ self.assertWarnsRegex(UserWarning, r'how-to-adjust-learning-rate',
+ call_sch_before_optim_resume)
+
+ def test_get_last_value(self):
+ epochs = 10
+ single_targets = [0.05] * 3 + [0.005] * 3 + [0.0005] * 3 + [0.00005]
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = StepLR(self.optimizer, 3, gamma=0.1)
+ for epoch in range(epochs):
+ result = scheduler.get_last_value()
+ self.optimizer.step()
+ scheduler.step()
+ target = [t[epoch] for t in targets]
+ for t, r in zip(target, result):
+ assert_allclose(
+ target,
+ result,
+ msg='LR is wrong in epoch {}: expected {}, got {}'.format(
+ epoch, t, r),
+ atol=1e-5,
+ rtol=0)
+
+ def test_scheduler_step_count(self):
+ iteration = 10
+ scheduler = StepLR(self.optimizer, gamma=0.1, step_size=3)
+ self.assertEqual(scheduler.last_step, 0)
+ target = [i + 1 for i in range(iteration)]
+ step_counts = []
+ for i in range(iteration):
+ self.optimizer.step()
+ scheduler.step()
+ step_counts.append(scheduler.last_step)
+ self.assertEqual(step_counts, target)
+
+ def test_effective_interval(self):
+ # check invalid begin end
+ with self.assertRaisesRegex(ValueError,
+ 'end should be larger than begin'):
+ StepLR(self.optimizer, gamma=0.1, step_size=3, begin=10, end=5)
+
+ # lr = 0.05 if epoch == 0
+ # lr = 0.025 if epoch == 1
+ # lr = 0.03125 if epoch == 2
+ # lr = 0.0375 if epoch == 3
+ # lr = 0.04375 if epoch == 4
+ # lr = 0.005 if epoch > 4
+ begin = 1
+ epochs = 10
+ start_factor = 1.0 / 2
+ iters = 4
+ interpolation = [
+ start_factor + i * (1 - start_factor) / iters for i in range(iters)
+ ]
+ single_targets = [0.05] * begin + [x * 0.05
+ for x in interpolation] + [0.05] * (
+ epochs - iters - begin)
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = LinearLR(
+ self.optimizer,
+ start_factor=start_factor,
+ begin=begin,
+ end=begin + iters + 1)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ def _test_scheduler_value(self,
+ schedulers,
+ targets,
+ epochs=10,
+ param_name='lr'):
+ if isinstance(schedulers, _ParamScheduler):
+ schedulers = [schedulers]
+ for epoch in range(epochs):
+ for param_group, target in zip(self.optimizer.param_groups,
+ targets):
+ assert_allclose(
+ target[epoch],
+ param_group[param_name],
+ msg='{} is wrong in epoch {}: expected {}, got {}'.format(
+ param_name, epoch, target[epoch],
+ param_group[param_name]),
+ atol=1e-5,
+ rtol=0)
+ [scheduler.step() for scheduler in schedulers]
+
+ def test_step_scheduler(self):
+ # lr = 0.05 if epoch < 3
+ # lr = 0.005 if 3 <= epoch < 6
+ # lr = 0.0005 if 6 <= epoch < 9
+ # lr = 0.00005 if epoch >=9
+ epochs = 10
+ single_targets = [0.05] * 3 + [0.005] * 3 + [0.0005] * 3 + [0.00005
+ ] * 3
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = StepLR(
+ self.optimizer, gamma=0.1, step_size=3, verbose=True)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ def test_multi_step_scheduler(self):
+ # lr = 0.05 if epoch < 2
+ # lr = 0.005 if 2 <= epoch < 5
+ # lr = 0.0005 if 5 <= epoch < 9
+ # lr = 0.00005 if epoch >= 9
+ epochs = 10
+ single_targets = [0.05] * 2 + [0.005] * 3 + [0.0005] * 4 + [0.00005
+ ] * 3
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = MultiStepLR(
+ self.optimizer, gamma=0.1, milestones=[2, 5, 9])
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ def test_constant_scheduler(self):
+ # factor should between 0~1
+ with self.assertRaises(ValueError):
+ ConstantLR(self.optimizer, factor=99)
+
+ # lr = 0.025 if epoch < 5
+ # lr = 0.005 if 5 <= epoch
+ epochs = 10
+ single_targets = [0.025] * 4 + [0.05] * 6
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = ConstantLR(self.optimizer, factor=1.0 / 2, end=5)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ def test_linear_scheduler(self):
+ with self.assertRaises(ValueError):
+ LinearLR(self.optimizer, start_factor=10, end=900)
+ with self.assertRaises(ValueError):
+ LinearLR(self.optimizer, start_factor=-1, end=900)
+ with self.assertRaises(ValueError):
+ LinearLR(self.optimizer, end_factor=1.001, end=900)
+ with self.assertRaises(ValueError):
+ LinearLR(self.optimizer, end_factor=-0.00001, end=900)
+ # lr = 0.025 if epoch == 0
+ # lr = 0.03125 if epoch == 1
+ # lr = 0.0375 if epoch == 2
+ # lr = 0.04375 if epoch == 3
+ # lr = 0.005 if epoch >= 4
+ epochs = 10
+ start_factor = 1.0 / 2
+ iters = 4
+ interpolation = [
+ start_factor + i * (1 - start_factor) / iters for i in range(iters)
+ ]
+ single_targets = [x * 0.05 for x in interpolation] + [0.05] * (
+ epochs - iters)
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = LinearLR(
+ self.optimizer, start_factor=start_factor, end=iters + 1)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ def test_exp_scheduler(self):
+ epochs = 10
+ single_targets = [0.05 * (0.9**x) for x in range(epochs)]
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = ExponentialLR(self.optimizer, gamma=0.9)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ def test_cos_anneal_scheduler(self):
+ epochs = 12
+ t = 10
+ eta_min = 1e-10
+ single_targets = [
+ eta_min + (0.05 - eta_min) * (1 + math.cos(math.pi * x / t)) / 2
+ for x in range(epochs)
+ ]
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = CosineAnnealingLR(self.optimizer, T_max=t, eta_min=eta_min)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ # Test default `T_max`
+ scheduler = CosineAnnealingLR(
+ self.optimizer, begin=5, end=100, eta_min=eta_min)
+ self.assertEqual(scheduler.T_max, 100 - 5)
+
+ def test_poly_scheduler(self):
+ epochs = 10
+ power = 0.9
+ min_lr = 0.001
+ iters = 4
+ targets_layer1 = [
+ min_lr + (0.05 - min_lr) * (1 - i / iters)**power
+ for i in range(iters)
+ ] + [min_lr] * (
+ epochs - iters)
+ targets_layer2 = [
+ min_lr + (0.05 * self.layer2_mult - min_lr) *
+ (1 - i / iters)**power for i in range(iters)
+ ] + [min_lr] * (
+ epochs - iters)
+ targets = [targets_layer1, targets_layer2]
+ scheduler = PolyLR(
+ self.optimizer, power=power, eta_min=min_lr, end=iters + 1)
+ self._test_scheduler_value(scheduler, targets, epochs=10)
+
+ def test_cosine_restart_scheduler(self):
+ with self.assertRaises(AssertionError):
+ CosineRestartLR(
+ self.optimizer,
+ periods=[4, 5],
+ restart_weights=[1, 0.5],
+ eta_min=0,
+ eta_min_ratio=0.1)
+ with self.assertRaises(AssertionError):
+ CosineRestartLR(
+ self.optimizer,
+ periods=[4, 5],
+ restart_weights=[1, 0.5, 0.0],
+ eta_min=0)
+ single_targets = [
+ 0.05, 0.0426776, 0.025, 0.00732233, 0.025, 0.022612712, 0.01636271,
+ 0.0086372, 0.0023872, 0.0023872
+ ]
+ targets = [
+ single_targets, [t * self.layer2_mult for t in single_targets]
+ ]
+ scheduler = CosineRestartLR(
+ self.optimizer,
+ periods=[4, 5],
+ restart_weights=[1, 0.5],
+ eta_min=0)
+ self._test_scheduler_value(scheduler, targets, epochs=10)
+
+ def _check_scheduler_state_dict(self, construct, construct2, epochs=10):
+ scheduler = construct()
+ for _ in range(epochs):
+ scheduler.optimizer.step()
+ scheduler.step()
+ scheduler_copy = construct2()
+ scheduler_copy.load_state_dict(scheduler.state_dict())
+ for key in scheduler.__dict__.keys():
+ if key != 'optimizer':
+ self.assertEqual(scheduler.__dict__[key],
+ scheduler_copy.__dict__[key])
+ self.assertEqual(scheduler.get_last_value(),
+ scheduler_copy.get_last_value())
+
+ def test_step_scheduler_state_dict(self):
+ self._check_scheduler_state_dict(
+ lambda: StepLR(self.optimizer, gamma=0.1, step_size=3),
+ lambda: StepLR(self.optimizer, gamma=0.01 / 2, step_size=1))
+
+ def test_multi_step_scheduler_state_dict(self):
+ self._check_scheduler_state_dict(
+ lambda: MultiStepLR(
+ self.optimizer, gamma=0.1, milestones=[2, 5, 9]),
+ lambda: MultiStepLR(
+ self.optimizer, gamma=0.01, milestones=[1, 4, 6]))
+
+ def test_exp_scheduler_state_dict(self):
+ self._check_scheduler_state_dict(
+ lambda: ExponentialLR(self.optimizer, gamma=0.1),
+ lambda: ExponentialLR(self.optimizer, gamma=0.01))
+
+ def test_cosine_scheduler_state_dict(self):
+ epochs = 10
+ eta_min = 1e-10
+ self._check_scheduler_state_dict(
+ lambda: CosineAnnealingLR(
+ self.optimizer, T_max=epochs, eta_min=eta_min),
+ lambda: CosineAnnealingLR(
+ self.optimizer, T_max=epochs // 2, eta_min=eta_min / 2),
+ epochs=epochs)
+
+ def test_linear_scheduler_state_dict(self):
+ epochs = 10
+ self._check_scheduler_state_dict(
+ lambda: LinearLR(self.optimizer, start_factor=1 / 3),
+ lambda: LinearLR(self.optimizer, start_factor=0, end_factor=0.3),
+ epochs=epochs)
+
+ def test_poly_scheduler_state_dict(self):
+ self._check_scheduler_state_dict(
+ lambda: PolyLR(self.optimizer, power=0.5, eta_min=0.001),
+ lambda: PolyLR(self.optimizer, power=0.8, eta_min=0.002),
+ epochs=10)
+
+ def test_cosine_restart_scheduler_state_dict(self):
+ self._check_scheduler_state_dict(
+ lambda: CosineRestartLR(
+ self.optimizer,
+ periods=[4, 5],
+ restart_weights=[1, 0.5],
+ eta_min=0),
+ lambda: CosineRestartLR(
+ self.optimizer,
+ periods=[4, 6],
+ restart_weights=[1, 0.5],
+ eta_min=0),
+ epochs=10)
+
+ def test_step_scheduler_convert_iterbased(self):
+ # invalid epoch_length
+ with self.assertRaises(AssertionError):
+ scheduler = StepLR.build_iter_from_epoch(
+ self.optimizer, gamma=0.1, step_size=2, epoch_length=-1)
+
+ # lr = 0.05 if epoch < 2
+ # lr = 0.005 if 2 <= epoch < 4
+ epochs = 4
+ epoch_length = 7
+ single_targets = [0.05] * 2 * epoch_length + [0.005] * 2 * epoch_length
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = StepLR.build_iter_from_epoch(
+ self.optimizer, gamma=0.1, step_size=2, epoch_length=epoch_length)
+ self._test_scheduler_value(
+ scheduler, targets, epochs * epoch_length, param_name='lr')
+
+ def test_multi_step_scheduler_convert_iterbased(self):
+ # lr = 0.05 if epoch < 2
+ # lr = 0.005 if 2 <= epoch < 5
+ # lr = 0.0005 if 5 <= epoch < 9
+ # lr = 0.00005 if epoch >= 9
+ epochs = 10
+ epoch_length = 7
+ single_targets = [0.05
+ ] * 2 * epoch_length + [0.005] * 3 * epoch_length + [
+ 0.0005
+ ] * 4 * epoch_length + [0.00005] * 3 * epoch_length
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = MultiStepLR.build_iter_from_epoch(
+ self.optimizer,
+ gamma=0.1,
+ milestones=[2, 5, 9],
+ epoch_length=epoch_length)
+ self._test_scheduler_value(scheduler, targets, epochs * epoch_length)
+
+ def test_constant_scheduler_convert_iterbased(self):
+ # lr = 0.025 if epoch < 5
+ # lr = 0.005 if 5 <= epoch
+ epochs = 10
+ epoch_length = 7
+ single_targets = [0.025] * (5 * epoch_length -
+ 1) + [0.05] * (5 * epoch_length + 1)
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = ConstantLR.build_iter_from_epoch(
+ self.optimizer, factor=1.0 / 2, end=5, epoch_length=epoch_length)
+ self._test_scheduler_value(scheduler, targets, epochs * epoch_length)
+
+ def test_linear_scheduler_convert_iterbased(self):
+ epochs = 10
+ start_factor = 1.0 / 2
+ end = 5
+ epoch_length = 11
+
+ iters = end * epoch_length - 1
+ interpolation = [
+ start_factor + i * (1 - start_factor) / iters for i in range(iters)
+ ]
+ single_targets = [x * 0.05 for x in interpolation] + [0.05] * (
+ epochs * epoch_length - iters)
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = LinearLR.build_iter_from_epoch(
+ self.optimizer,
+ start_factor=start_factor,
+ end=end,
+ epoch_length=epoch_length)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ def test_exp_scheduler_convert_iterbased(self):
+ epochs = 10
+ epoch_length = 7
+
+ single_targets = [
+ 0.05 * (0.9**x) for x in range(epochs * epoch_length)
+ ]
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = ExponentialLR.build_iter_from_epoch(
+ self.optimizer, gamma=0.9, epoch_length=epoch_length)
+ self._test_scheduler_value(scheduler, targets, epochs * epoch_length)
+
+ def test_cos_anneal_scheduler_convert_iterbased(self):
+ epochs = 12
+ t = 10
+ eta_min = 1e-10
+ epoch_length = 11
+ single_targets = [
+ eta_min + (0.05 - eta_min) *
+ (1 + math.cos(math.pi * x / t / epoch_length)) / 2
+ for x in range(epochs * epoch_length)
+ ]
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = CosineAnnealingLR.build_iter_from_epoch(
+ self.optimizer,
+ T_max=t,
+ eta_min=eta_min,
+ epoch_length=epoch_length)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ def test_poly_scheduler_convert_iterbased(self):
+ epochs = 10
+ power = 0.9
+ min_lr = 0.001
+ end = 5
+ epoch_length = 11
+
+ iters = end * epoch_length - 1
+ targets_layer1 = [
+ min_lr + (0.05 - min_lr) * (1 - i / iters)**power
+ for i in range(iters)
+ ] + [min_lr] * (
+ epochs - iters)
+ targets_layer2 = [
+ min_lr + (0.05 * self.layer2_mult - min_lr) *
+ (1 - i / iters)**power for i in range(iters)
+ ] + [min_lr] * (
+ epochs - iters)
+ targets = [targets_layer1, targets_layer2]
+ scheduler = PolyLR.build_iter_from_epoch(
+ self.optimizer,
+ power=power,
+ eta_min=min_lr,
+ end=end,
+ epoch_length=epoch_length)
+ self._test_scheduler_value(scheduler, targets, epochs=10)
+
+ def test_multi_scheduler_without_overlap_linear_multi_step(self):
+ # use Linear in the first 5 epochs and then use MultiStep
+ epochs = 12
+ single_targets = [0.025, 0.03125, 0.0375, 0.04375
+ ] + [0.05] * 4 + [0.005] * 3 + [0.0005] * 1
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler1 = LinearLR(
+ self.optimizer, start_factor=1 / 2, begin=0, end=5)
+ scheduler2 = MultiStepLR(
+ self.optimizer, gamma=0.1, milestones=[3, 6], begin=5, end=12)
+ self._test_scheduler_value([scheduler1, scheduler2], targets, epochs)
+
+ def test_multi_scheduler_without_overlap_exp_cosine(self):
+ # in the first 5 epochs use Exp and then use Cosine
+ epochs = 10
+ single_targets1 = [0.05 * (0.9**x) for x in range(5)]
+ scheduler1 = ExponentialLR(self.optimizer, gamma=0.9, begin=0, end=5)
+
+ eta_min = 1e-10
+ single_targets2 = [
+ eta_min + (single_targets1[-1] - eta_min) *
+ (1 + math.cos(math.pi * x / 5)) / 2 for x in range(5)
+ ]
+ single_targets = single_targets1 + single_targets2
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler2 = CosineAnnealingLR(
+ self.optimizer, T_max=5, eta_min=eta_min, begin=5, end=10)
+
+ self._test_scheduler_value([scheduler1, scheduler2], targets, epochs)
+
+ def test_multi_scheduler_with_overlap(self):
+ # use Exp in the first 5 epochs and then use Cosine
+ epochs = 10
+ single_targets = [0.025, 0.03125, 0.0375, 0.004375
+ ] + [0.005] * 2 + [0.0005] * 3 + [0.00005] * 1
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler1 = LinearLR(
+ self.optimizer, start_factor=1 / 2, begin=0, end=5)
+ scheduler2 = MultiStepLR(
+ self.optimizer, gamma=0.1, milestones=[3, 6, 9])
+ self._test_scheduler_value([scheduler1, scheduler2], targets, epochs)
+
+ def test_multi_scheduler_with_gap(self):
+ # use Exp in the first 5 epochs and the last 5 epochs use Cosine
+ # no scheduler in the middle 5 epochs
+ epochs = 15
+ single_targets1 = [0.05 * (0.9**x) for x in range(5)]
+ scheduler1 = ExponentialLR(self.optimizer, gamma=0.9, begin=0, end=5)
+
+ eta_min = 1e-10
+ single_targets2 = [
+ eta_min + (single_targets1[-1] - eta_min) *
+ (1 + math.cos(math.pi * x / 5)) / 2 for x in range(5)
+ ]
+ single_targets = single_targets1 + [single_targets1[-1]
+ ] * 5 + single_targets2
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler2 = CosineAnnealingLR(
+ self.optimizer, T_max=5, eta_min=eta_min, begin=10, end=15)
+
+ self._test_scheduler_value([scheduler1, scheduler2], targets, epochs)
+
+ def test_onecycle_lr(self):
+ # test linear annealing
+ target = [1., 13., 25., 21.5, 18., 14.5, 11., 7.5, 4., 0.5]
+ scheduler = OneCycleLR(
+ self.optimizer,
+ eta_max=25,
+ final_div_factor=2,
+ total_steps=10,
+ anneal_strategy='linear')
+ self._test_scheduler_value(scheduler, [target], 10)
+ # test linear annealing three phase
+ target = [1., 9., 17., 25., 17., 9., 1., 0.75, 0.5, 0.25]
+ scheduler = OneCycleLR(
+ self.optimizer,
+ eta_max=25,
+ div_factor=25,
+ total_steps=10,
+ anneal_strategy='linear',
+ pct_start=0.4,
+ final_div_factor=4,
+ three_phase=True)
+ self._test_scheduler_value(scheduler, [target], 10)
+
+ # test cosine annealing
+ def annealing_cos(start, end, pct):
+ cos_out = math.cos(math.pi * pct) + 1
+ return end + (start - end) / 2.0 * cos_out
+
+ target = [
+ 1., 13., 25.,
+ annealing_cos(25, 0.5, 1 / 7.0),
+ annealing_cos(25, 0.5, 2 / 7.0),
+ annealing_cos(25, 0.5, 3 / 7.0),
+ annealing_cos(25, 0.5, 4 / 7.0),
+ annealing_cos(25, 0.5, 5 / 7.0),
+ annealing_cos(25, 0.5, 6 / 7.0), 0.5
+ ]
+ scheduler = OneCycleLR(
+ self.optimizer, eta_max=25, final_div_factor=2, total_steps=10)
+ self._test_scheduler_value(scheduler, [target], 10)
diff --git a/testbed/open-mmlab__mmengine/tests/test_optim/test_scheduler/test_momentum_scheduler.py b/testbed/open-mmlab__mmengine/tests/test_optim/test_scheduler/test_momentum_scheduler.py
new file mode 100644
index 0000000000000000000000000000000000000000..d98f2fe424a2f915eb9c200b6b0d423e67bab15c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_optim/test_scheduler/test_momentum_scheduler.py
@@ -0,0 +1,583 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import math
+from unittest import TestCase
+
+import torch
+import torch.nn.functional as F
+import torch.optim as optim
+
+from mmengine.optim.scheduler import (ConstantMomentum,
+ CosineAnnealingMomentum,
+ CosineRestartMomentum,
+ ExponentialMomentum, LinearMomentum,
+ MultiStepMomentum, PolyMomentum,
+ StepMomentum, _ParamScheduler)
+from mmengine.testing import assert_allclose
+
+
+class ToyModel(torch.nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.conv1 = torch.nn.Conv2d(1, 1, 1)
+ self.conv2 = torch.nn.Conv2d(1, 1, 1)
+
+ def forward(self, x):
+ return self.conv2(F.relu(self.conv1(x)))
+
+
+class TestMomentumScheduler(TestCase):
+
+ def setUp(self):
+ """Setup the model and optimizer which are used in every test method.
+
+ TestCase calls functions in this order: setUp() -> testMethod() ->
+ tearDown() -> cleanUp()
+ """
+ self.model = ToyModel()
+ momentum = 0.05
+ self.layer2_mult = 10
+ self.optimizer = optim.SGD([{
+ 'params': self.model.conv1.parameters()
+ }, {
+ 'params': self.model.conv2.parameters(),
+ 'momentum': momentum * self.layer2_mult
+ }],
+ lr=0.01,
+ momentum=momentum,
+ weight_decay=5e-4)
+ self.optimizer_with_betas = optim.Adam(
+ [{
+ 'params': self.model.conv1.parameters()
+ }, {
+ 'params': self.model.conv2.parameters(),
+ 'betas': (momentum * self.layer2_mult, 0.999)
+ }],
+ lr=0.01,
+ betas=(momentum, 0.999),
+ weight_decay=5e-4)
+
+ def test_invalid_optimizer(self):
+ with self.assertRaisesRegex(
+ ValueError,
+ 'optimizer must support momentum when using momentum scheduler'
+ ):
+ optimizer = optim.ASGD(
+ self.model.parameters(),
+ lr=0.01,
+ )
+ StepMomentum(optimizer, step_size=1)
+
+ def test_overwrite_optimzer_step(self):
+ # raise warning if the counter in optimizer.step() is overwritten
+ scheduler = ExponentialMomentum(self.optimizer, gamma=0.9)
+
+ def overwrite_fun():
+ pass
+
+ self.optimizer.step = overwrite_fun
+ self.optimizer.step()
+ self.assertWarnsRegex(UserWarning, r'how-to-adjust-learning-rate',
+ scheduler.step)
+
+ def test_resume(self):
+ # test invalid case: optimizer and scheduler are not both resumed
+ with self.assertRaisesRegex(
+ KeyError, "param 'initial_momentum' is not specified"):
+ StepMomentum(self.optimizer, gamma=0.1, step_size=3, last_step=10)
+
+ # test manually resume with ``last_step`` instead of load_state_dict
+ epochs = 10
+ targets = [0.05 * (0.9**x) for x in range(epochs)]
+ scheduler = ExponentialMomentum(self.optimizer, gamma=0.9)
+
+ results = []
+ for epoch in range(5):
+ results.append(self.optimizer.param_groups[0]['momentum'])
+ # The order should be
+ # train_epoch() -> save_checkpoint() -> scheduler.step().
+ # Break at here to simulate the checkpoint is saved before
+ # the scheduler.step().
+ if epoch == 4:
+ break
+ scheduler.step()
+ scheduler2 = ExponentialMomentum(
+ self.optimizer, gamma=0.9, last_step=4)
+ for epoch in range(6):
+ results.append(self.optimizer.param_groups[0]['momentum'])
+ scheduler2.step()
+
+ for epoch in range(epochs):
+ assert_allclose(
+ targets[epoch],
+ results[epoch],
+ msg='momentum is wrong in epoch {}: expected {}, got {}'.
+ format(epoch, targets[epoch], results[epoch]),
+ atol=1e-5,
+ rtol=0)
+
+ def test_scheduler_before_optim_warning(self):
+ """warns if scheduler is used before optimizer."""
+
+ def call_sch_before_optim():
+ scheduler = StepMomentum(self.optimizer, gamma=0.1, step_size=3)
+ scheduler.step()
+ self.optimizer.step()
+
+ # check warning doc link
+ self.assertWarnsRegex(UserWarning, r'how-to-adjust-learning-rate',
+ call_sch_before_optim)
+
+ # check warning when resume
+ for i, group in enumerate(self.optimizer.param_groups):
+ group['initial_momentum'] = 0.01
+
+ def call_sch_before_optim_resume():
+ scheduler = StepMomentum(
+ self.optimizer, gamma=0.1, step_size=3, last_step=10)
+ scheduler.step()
+ self.optimizer.step()
+
+ # check warning doc link
+ self.assertWarnsRegex(UserWarning, r'how-to-adjust-learning-rate',
+ call_sch_before_optim_resume)
+
+ def test_get_last_value(self):
+ epochs = 10
+ single_targets = [0.05] * 3 + [0.005] * 3 + [0.0005] * 3 + [0.00005]
+ targets = [
+ single_targets, [t * self.layer2_mult for t in single_targets]
+ ]
+ scheduler = StepMomentum(self.optimizer, 3, gamma=0.1)
+ for epoch in range(epochs):
+ result = scheduler.get_last_value()
+ self.optimizer.step()
+ scheduler.step()
+ target = [t[epoch] for t in targets]
+ for t, r in zip(target, result):
+ assert_allclose(
+ target,
+ result,
+ msg='momentum is wrong in epoch {}: expected {}, got {}'.
+ format(epoch, t, r),
+ atol=1e-5,
+ rtol=0)
+
+ def test_scheduler_step_count(self):
+ iteration = 10
+ scheduler = StepMomentum(self.optimizer, gamma=0.1, step_size=3)
+ self.assertEqual(scheduler.last_step, 0)
+ target = [i + 1 for i in range(iteration)]
+ step_counts = []
+ for i in range(iteration):
+ self.optimizer.step()
+ scheduler.step()
+ step_counts.append(scheduler.last_step)
+ self.assertEqual(step_counts, target)
+
+ def test_effective_interval(self):
+ # check invalid begin end
+ with self.assertRaisesRegex(ValueError,
+ 'end should be larger than begin'):
+ StepMomentum(
+ self.optimizer, gamma=0.1, step_size=3, begin=10, end=5)
+
+ # momentum = 0.05 if epoch == 0
+ # momentum = 0.025 if epoch == 1
+ # momentum = 0.03125 if epoch == 2
+ # momentum = 0.0375 if epoch == 3
+ # momentum = 0.04375 if epoch == 4
+ # momentum = 0.005 if epoch > 4
+ begin = 1
+ epochs = 10
+ start_factor = 1.0 / 2
+ iters = 4
+ interpolation = [
+ start_factor + i * (1 - start_factor) / iters for i in range(iters)
+ ]
+ single_targets = [0.05] * begin + [x * 0.05
+ for x in interpolation] + [0.05] * (
+ epochs - iters - begin)
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = LinearMomentum(
+ self.optimizer,
+ start_factor=start_factor,
+ begin=begin,
+ end=begin + iters + 1)
+ self._test_scheduler_value(self.optimizer, scheduler, targets, epochs)
+
+ def _test_scheduler_value(self,
+ optimizer,
+ schedulers,
+ targets,
+ epochs=10,
+ param_name='momentum'):
+ if isinstance(schedulers, _ParamScheduler):
+ schedulers = [schedulers]
+ for epoch in range(epochs):
+ for param_group, target in zip(optimizer.param_groups, targets):
+ assert_allclose(
+ target[epoch],
+ param_group[param_name],
+ msg='{} is wrong in epoch {}: expected {}, got {}'.format(
+ param_name, epoch, target[epoch],
+ param_group[param_name]),
+ atol=1e-5,
+ rtol=0)
+ if 'betas' in optimizer.defaults:
+ assert_allclose(
+ target[epoch],
+ param_group['betas'][0],
+ msg='{} is wrong in epoch {}: expected {}, got {}'.
+ format('betas_0', epoch, target[epoch],
+ param_group['betas'][0]),
+ atol=1e-5,
+ rtol=0)
+ [scheduler.step() for scheduler in schedulers]
+
+ def test_step_scheduler(self):
+ # momentum = 0.05 if epoch < 3
+ # momentum = 0.005 if 3 <= epoch < 6
+ # momentum = 0.0005 if 6 <= epoch < 9
+ # momentum = 0.00005 if epoch >=9
+ epochs = 10
+ single_targets = [0.05] * 3 + [0.005] * 3 + [0.0005] * 3 + [0.00005
+ ] * 3
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = StepMomentum(
+ self.optimizer, gamma=0.1, step_size=3, verbose=True)
+ self._test_scheduler_value(self.optimizer, scheduler, targets, epochs)
+
+ scheduler = StepMomentum(
+ self.optimizer_with_betas, gamma=0.1, step_size=3, verbose=True)
+ self._test_scheduler_value(self.optimizer_with_betas, scheduler,
+ targets, epochs)
+
+ def test_multi_step_scheduler(self):
+ # momentum = 0.05 if epoch < 2
+ # momentum = 0.005 if 2 <= epoch < 5
+ # momentum = 0.0005 if 5 <= epoch < 9
+ # momentum = 0.00005 if epoch >= 9
+ epochs = 10
+ single_targets = [0.05] * 2 + [0.005] * 3 + [0.0005] * 4 + [0.00005
+ ] * 3
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = MultiStepMomentum(
+ self.optimizer, gamma=0.1, milestones=[2, 5, 9])
+ self._test_scheduler_value(self.optimizer, scheduler, targets, epochs)
+
+ scheduler = MultiStepMomentum(
+ self.optimizer_with_betas, gamma=0.1, milestones=[2, 5, 9])
+ self._test_scheduler_value(self.optimizer_with_betas, scheduler,
+ targets, epochs)
+
+ def test_constant_scheduler(self):
+ # factor should between 0~1
+ with self.assertRaises(ValueError):
+ ConstantMomentum(self.optimizer, factor=99)
+
+ # momentum = 0.025 if epoch < 5
+ # momentum = 0.005 if 5 <= epoch
+ epochs = 10
+ single_targets = [0.025] * 4 + [0.05] * 6
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = ConstantMomentum(self.optimizer, factor=1.0 / 2, end=5)
+ self._test_scheduler_value(self.optimizer, scheduler, targets, epochs)
+
+ scheduler = ConstantMomentum(
+ self.optimizer_with_betas, factor=1.0 / 2, end=5)
+ self._test_scheduler_value(self.optimizer_with_betas, scheduler,
+ targets, epochs)
+
+ def test_linear_scheduler(self):
+ with self.assertRaises(ValueError):
+ LinearMomentum(self.optimizer, start_factor=10, end=900)
+ with self.assertRaises(ValueError):
+ LinearMomentum(self.optimizer, start_factor=-1, end=900)
+ with self.assertRaises(ValueError):
+ LinearMomentum(self.optimizer, end_factor=1.001, end=900)
+ with self.assertRaises(ValueError):
+ LinearMomentum(self.optimizer, end_factor=-0.00001, end=900)
+ # momentum = 0.025 if epoch == 0
+ # momentum = 0.03125 if epoch == 1
+ # momentum = 0.0375 if epoch == 2
+ # momentum = 0.04375 if epoch == 3
+ # momentum = 0.005 if epoch >= 4
+ epochs = 10
+ start_factor = 1.0 / 2
+ iters = 4
+ interpolation = [
+ start_factor + i * (1 - start_factor) / iters for i in range(iters)
+ ]
+ single_targets = [x * 0.05 for x in interpolation] + [0.05] * (
+ epochs - iters)
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = LinearMomentum(
+ self.optimizer, start_factor=start_factor, end=iters + 1)
+ self._test_scheduler_value(self.optimizer, scheduler, targets, epochs)
+
+ scheduler = LinearMomentum(
+ self.optimizer_with_betas,
+ start_factor=start_factor,
+ end=iters + 1)
+ self._test_scheduler_value(self.optimizer_with_betas, scheduler,
+ targets, epochs)
+
+ def test_exp_scheduler(self):
+ epochs = 10
+ single_targets = [0.05 * (0.9**x) for x in range(epochs)]
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = ExponentialMomentum(self.optimizer, gamma=0.9)
+ self._test_scheduler_value(self.optimizer, scheduler, targets, epochs)
+
+ scheduler = ExponentialMomentum(self.optimizer_with_betas, gamma=0.9)
+ self._test_scheduler_value(self.optimizer_with_betas, scheduler,
+ targets, epochs)
+
+ def test_cos_anneal_scheduler(self):
+ epochs = 12
+ t = 10
+ eta_min = 1e-10
+ single_targets = [
+ eta_min + (0.05 - eta_min) * (1 + math.cos(math.pi * x / t)) / 2
+ for x in range(epochs)
+ ]
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = CosineAnnealingMomentum(
+ self.optimizer, T_max=t, eta_min=eta_min)
+ self._test_scheduler_value(self.optimizer, scheduler, targets, epochs)
+
+ scheduler = CosineAnnealingMomentum(
+ self.optimizer_with_betas, T_max=t, eta_min=eta_min)
+ self._test_scheduler_value(self.optimizer_with_betas, scheduler,
+ targets, epochs)
+
+ # Test default `T_max`
+ scheduler = CosineAnnealingMomentum(
+ self.optimizer, begin=5, end=100, eta_min=eta_min)
+ self.assertEqual(scheduler.T_max, 100 - 5)
+
+ def test_poly_scheduler(self):
+ epochs = 10
+ power = 0.9
+ min_lr = 0.001
+ iters = 4
+ layer1_targets = [
+ min_lr + (0.05 - min_lr) * (1 - i / iters)**power
+ for i in range(iters)
+ ] + [min_lr] * (
+ epochs - iters)
+ layer2_targets = [
+ min_lr + (0.05 * self.layer2_mult - min_lr) *
+ (1 - i / iters)**power for i in range(iters)
+ ] + [min_lr] * (
+ epochs - iters)
+ targets = [layer1_targets, layer2_targets]
+ scheduler = PolyMomentum(
+ self.optimizer, power=power, eta_min=min_lr, end=iters + 1)
+ self._test_scheduler_value(
+ self.optimizer, scheduler, targets, epochs=10)
+
+ scheduler = PolyMomentum(
+ self.optimizer_with_betas,
+ power=power,
+ eta_min=min_lr,
+ end=iters + 1)
+ self._test_scheduler_value(
+ self.optimizer_with_betas, scheduler, targets, epochs=10)
+
+ def test_cosine_restart_scheduler(self):
+ with self.assertRaises(AssertionError):
+ CosineRestartMomentum(
+ self.optimizer,
+ periods=[4, 5],
+ restart_weights=[1, 0.5],
+ eta_min=0,
+ eta_min_ratio=0.1)
+ with self.assertRaises(AssertionError):
+ CosineRestartMomentum(
+ self.optimizer,
+ periods=[4, 5],
+ restart_weights=[1, 0.5, 0.0],
+ eta_min=0)
+ single_targets = [
+ 0.05, 0.0426776, 0.025, 0.00732233, 0.025, 0.022612712, 0.01636271,
+ 0.0086372, 0.0023872, 0.0023872
+ ]
+ targets = [
+ single_targets, [t * self.layer2_mult for t in single_targets]
+ ]
+ scheduler = CosineRestartMomentum(
+ self.optimizer,
+ periods=[4, 5],
+ restart_weights=[1, 0.5],
+ eta_min=0)
+ self._test_scheduler_value(
+ self.optimizer, scheduler, targets, epochs=10)
+
+ scheduler = CosineRestartMomentum(
+ self.optimizer_with_betas,
+ periods=[4, 5],
+ restart_weights=[1, 0.5],
+ eta_min=0)
+ self._test_scheduler_value(
+ self.optimizer_with_betas, scheduler, targets, epochs=10)
+
+ def _check_scheduler_state_dict(self, construct, construct2, epochs=10):
+ scheduler = construct()
+ for _ in range(epochs):
+ scheduler.optimizer.step()
+ scheduler.step()
+ scheduler_copy = construct2()
+ scheduler_copy.load_state_dict(scheduler.state_dict())
+ for key in scheduler.__dict__.keys():
+ if key != 'optimizer':
+ self.assertEqual(scheduler.__dict__[key],
+ scheduler_copy.__dict__[key])
+ self.assertEqual(scheduler.get_last_value(),
+ scheduler_copy.get_last_value())
+
+ def test_step_scheduler_state_dict(self):
+ self._check_scheduler_state_dict(
+ lambda: StepMomentum(self.optimizer, gamma=0.1, step_size=3),
+ lambda: StepMomentum(self.optimizer, gamma=0.01 / 2, step_size=1))
+
+ def test_multi_step_scheduler_state_dict(self):
+ self._check_scheduler_state_dict(
+ lambda: MultiStepMomentum(
+ self.optimizer, gamma=0.1, milestones=[2, 5, 9]),
+ lambda: MultiStepMomentum(
+ self.optimizer, gamma=0.01, milestones=[1, 4, 6]))
+
+ def test_exp_scheduler_state_dict(self):
+ self._check_scheduler_state_dict(
+ lambda: ExponentialMomentum(self.optimizer, gamma=0.1),
+ lambda: ExponentialMomentum(self.optimizer, gamma=0.01))
+
+ def test_cosine_scheduler_state_dict(self):
+ epochs = 10
+ eta_min = 1e-10
+ self._check_scheduler_state_dict(
+ lambda: CosineAnnealingMomentum(
+ self.optimizer, T_max=epochs, eta_min=eta_min),
+ lambda: CosineAnnealingMomentum(
+ self.optimizer, T_max=epochs // 2, eta_min=eta_min / 2),
+ epochs=epochs)
+
+ def test_linear_scheduler_state_dict(self):
+ epochs = 10
+ self._check_scheduler_state_dict(
+ lambda: LinearMomentum(self.optimizer, start_factor=1 / 3),
+ lambda: LinearMomentum(
+ self.optimizer, start_factor=0, end_factor=0.3),
+ epochs=epochs)
+
+ def test_poly_scheduler_state_dict(self):
+ self._check_scheduler_state_dict(
+ lambda: PolyMomentum(self.optimizer, power=0.5, eta_min=0.001),
+ lambda: PolyMomentum(self.optimizer, power=0.8, eta_min=0.002),
+ epochs=10)
+
+ def test_cosine_restart_scheduler_state_dict(self):
+ self._check_scheduler_state_dict(
+ lambda: CosineRestartMomentum(
+ self.optimizer,
+ periods=[4, 5],
+ restart_weights=[1, 0.5],
+ eta_min=0),
+ lambda: CosineRestartMomentum(
+ self.optimizer,
+ periods=[4, 6],
+ restart_weights=[1, 0.5],
+ eta_min=0),
+ epochs=10)
+
+ def test_multi_scheduler_without_overlap_linear_multi_step(self):
+ # use Linear in the first 5 epochs and then use MultiStep
+ epochs = 12
+ single_targets = [0.025, 0.03125, 0.0375, 0.04375
+ ] + [0.05] * 4 + [0.005] * 3 + [0.0005] * 1
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler1 = LinearMomentum(
+ self.optimizer, start_factor=1 / 2, begin=0, end=5)
+ scheduler2 = MultiStepMomentum(
+ self.optimizer, gamma=0.1, milestones=[3, 6], begin=5, end=12)
+ self._test_scheduler_value(self.optimizer, [scheduler1, scheduler2],
+ targets, epochs)
+
+ def test_multi_scheduler_without_overlap_exp_cosine(self):
+ # use Exp in the first 5 epochs and then use Cosine
+ epochs = 10
+ single_targets1 = [0.05 * (0.9**x) for x in range(5)]
+ scheduler1 = ExponentialMomentum(
+ self.optimizer, gamma=0.9, begin=0, end=5)
+
+ eta_min = 1e-10
+ single_targets2 = [
+ eta_min + (single_targets1[-1] - eta_min) *
+ (1 + math.cos(math.pi * x / 5)) / 2 for x in range(5)
+ ]
+ single_targets = single_targets1 + single_targets2
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler2 = CosineAnnealingMomentum(
+ self.optimizer, T_max=5, eta_min=eta_min, begin=5, end=10)
+
+ self._test_scheduler_value(self.optimizer, [scheduler1, scheduler2],
+ targets, epochs)
+
+ def test_multi_scheduler_with_overlap(self):
+ # use Linear at first 5 epochs together with MultiStep
+ epochs = 10
+ single_targets = [0.025, 0.03125, 0.0375, 0.004375
+ ] + [0.005] * 2 + [0.0005] * 3 + [0.00005] * 1
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler1 = LinearMomentum(
+ self.optimizer, start_factor=1 / 2, begin=0, end=5)
+ scheduler2 = MultiStepMomentum(
+ self.optimizer, gamma=0.1, milestones=[3, 6, 9])
+ self._test_scheduler_value(self.optimizer, [scheduler1, scheduler2],
+ targets, epochs)
+
+ def test_multi_scheduler_with_gap(self):
+ # use Exp in the first 5 epochs and the last 5 epochs use Cosine
+ # no scheduler in the middle 5 epochs
+ epochs = 15
+ single_targets1 = [0.05 * (0.9**x) for x in range(5)]
+ scheduler1 = ExponentialMomentum(
+ self.optimizer, gamma=0.9, begin=0, end=5)
+
+ eta_min = 1e-10
+ single_targets2 = [
+ eta_min + (single_targets1[-1] - eta_min) *
+ (1 + math.cos(math.pi * x / 5)) / 2 for x in range(5)
+ ]
+ single_targets = single_targets1 + [single_targets1[-1]
+ ] * 5 + single_targets2
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler2 = CosineAnnealingMomentum(
+ self.optimizer, T_max=5, eta_min=eta_min, begin=10, end=15)
+
+ self._test_scheduler_value(self.optimizer, [scheduler1, scheduler2],
+ targets, epochs)
diff --git a/testbed/open-mmlab__mmengine/tests/test_optim/test_scheduler/test_param_scheduler.py b/testbed/open-mmlab__mmengine/tests/test_optim/test_scheduler/test_param_scheduler.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce86195b944fc9c696bdb30c596d718915ee5180
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_optim/test_scheduler/test_param_scheduler.py
@@ -0,0 +1,857 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import math
+import os.path as osp
+import tempfile
+from unittest import TestCase
+
+import torch
+import torch.nn.functional as F
+import torch.optim as optim
+
+from mmengine.optim import OptimWrapper
+# yapf: disable
+from mmengine.optim.scheduler import (ConstantParamScheduler,
+ CosineAnnealingParamScheduler,
+ CosineRestartParamScheduler,
+ ExponentialParamScheduler,
+ LinearParamScheduler,
+ MultiStepParamScheduler,
+ OneCycleParamScheduler,
+ PolyParamScheduler, StepParamScheduler,
+ _ParamScheduler)
+# yapf: enable
+from mmengine.testing import assert_allclose
+
+
+class ToyModel(torch.nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.conv1 = torch.nn.Conv2d(1, 1, 1)
+ self.conv2 = torch.nn.Conv2d(1, 1, 1)
+
+ def forward(self, x):
+ return self.conv2(F.relu(self.conv1(x)))
+
+
+class TestParameterScheduler(TestCase):
+
+ def setUp(self):
+ """Setup the model and optimizer which are used in every test method.
+
+ TestCase calls functions in this order: setUp() -> testMethod() ->
+ tearDown() -> cleanUp()
+ """
+ self.model = ToyModel()
+ self.layer2_mult = 10
+ lr = 0.05
+ momentum = 0.01
+ weight_decay = 5e-4
+ self.optimizer = optim.SGD(
+ [{
+ 'params': self.model.conv1.parameters()
+ }, {
+ 'params': self.model.conv2.parameters(),
+ 'lr': lr * self.layer2_mult,
+ 'momentum': momentum * self.layer2_mult,
+ 'weight_decay': weight_decay * self.layer2_mult
+ }],
+ lr=lr,
+ momentum=momentum,
+ weight_decay=weight_decay)
+ self.temp_dir = tempfile.TemporaryDirectory()
+
+ def test_base_scheduler_step(self):
+ with self.assertRaises(NotImplementedError):
+ _ParamScheduler(self.optimizer, param_name='lr')
+
+ def test_invalid_optimizer(self):
+ with self.assertRaisesRegex(TypeError, 'should be an Optimizer'):
+ StepParamScheduler(
+ 'invalid_optimizer', step_size=1, param_name='lr')
+
+ def test_overwrite_optimzer_step(self):
+ # raise warning if the counter in optimizer.step() is overwritten
+ scheduler = ExponentialParamScheduler(
+ self.optimizer, param_name='lr', gamma=0.9)
+
+ def overwrite_fun():
+ pass
+
+ self.optimizer.step = overwrite_fun
+ self.optimizer.step()
+ self.assertWarnsRegex(UserWarning, r'how-to-adjust-learning-rate',
+ scheduler.step)
+
+ def test_resume(self):
+ # test invalid case: optimizer and scheduler are not both resumed
+ with self.assertRaisesRegex(KeyError,
+ "param 'initial_lr' is not specified"):
+ StepParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ gamma=0.1,
+ step_size=3,
+ last_step=10)
+
+ # test manually resume with ``last_step`` instead of load_state_dict
+ epochs = 10
+ targets = [0.05 * (0.9**x) for x in range(epochs)]
+ scheduler = ExponentialParamScheduler(
+ self.optimizer, param_name='lr', gamma=0.9)
+
+ results = []
+ for epoch in range(5):
+ results.append(self.optimizer.param_groups[0]['lr'])
+ # The order should be
+ # train_epoch() -> save_checkpoint() -> scheduler.step().
+ # Break at here to simulate the checkpoint is saved before
+ # the scheduler.step().
+ if epoch == 4:
+ break
+ scheduler.step()
+ scheduler2 = ExponentialParamScheduler(
+ self.optimizer, param_name='lr', gamma=0.9, last_step=4)
+ for epoch in range(6):
+ results.append(self.optimizer.param_groups[0]['lr'])
+ scheduler2.step()
+
+ for epoch in range(epochs):
+ assert_allclose(
+ targets[epoch],
+ results[epoch],
+ msg='lr is wrong in epoch {}: expected {}, got {}'.format(
+ epoch, targets[epoch], results[epoch]),
+ atol=1e-5,
+ rtol=0)
+
+ def test_scheduler_before_optim_warning(self):
+ """warns if scheduler is used before optimizer."""
+
+ def call_sch_before_optim():
+ scheduler = StepParamScheduler(
+ self.optimizer, param_name='lr', gamma=0.1, step_size=3)
+ scheduler.step()
+ self.optimizer.step()
+
+ # check warning doc link
+ self.assertWarnsRegex(UserWarning, r'how-to-adjust-learning-rate',
+ call_sch_before_optim)
+
+ # check warning when resume
+ for i, group in enumerate(self.optimizer.param_groups):
+ group['initial_lr'] = 0.01
+
+ def call_sch_before_optim_resume():
+ scheduler = StepParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ gamma=0.1,
+ step_size=3,
+ last_step=10)
+ scheduler.step()
+ self.optimizer.step()
+
+ # check warning doc link
+ self.assertWarnsRegex(UserWarning, r'how-to-adjust-learning-rate',
+ call_sch_before_optim_resume)
+
+ def test_get_last_value(self):
+ epochs = 10
+ single_targets = [0.05] * 3 + [0.005] * 3 + [0.0005] * 3 + [0.00005]
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = StepParamScheduler(
+ self.optimizer, param_name='lr', step_size=3, gamma=0.1)
+ for epoch in range(epochs):
+ result = scheduler.get_last_value()
+ self.optimizer.step()
+ scheduler.step()
+ target = [t[epoch] for t in targets]
+ for t, r in zip(target, result):
+ assert_allclose(
+ target,
+ result,
+ msg='LR is wrong in epoch {}: expected {}, got {}'.format(
+ epoch, t, r),
+ atol=1e-5,
+ rtol=0)
+
+ def test_scheduler_step_count(self):
+ iteration = 10
+ scheduler = StepParamScheduler(
+ self.optimizer, param_name='lr', gamma=0.1, step_size=3)
+ self.assertEqual(scheduler.last_step, 0)
+ target = [i + 1 for i in range(iteration)]
+ step_counts = []
+ for i in range(iteration):
+ self.optimizer.step()
+ scheduler.step()
+ step_counts.append(scheduler.last_step)
+ self.assertEqual(step_counts, target)
+
+ def test_effective_interval(self):
+ # check invalid begin end
+ with self.assertRaisesRegex(ValueError,
+ 'end should be larger than begin'):
+ StepParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ gamma=0.1,
+ step_size=3,
+ begin=10,
+ end=5)
+
+ # lr = 0.05 if epoch == 0
+ # lr = 0.025 if epoch == 1
+ # lr = 0.03125 if epoch == 2
+ # lr = 0.0375 if epoch == 3
+ # lr = 0.04375 if epoch == 4
+ # lr = 0.005 if epoch > 4
+ begin = 1
+ epochs = 10
+ start_factor = 1.0 / 2
+ iters = 4
+ interpolation = [
+ start_factor + i * (1 - start_factor) / iters for i in range(iters)
+ ]
+ single_targets = [0.05] * begin + [x * 0.05
+ for x in interpolation] + [0.05] * (
+ epochs - iters - begin)
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = LinearParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ start_factor=start_factor,
+ begin=begin,
+ end=begin + iters + 1)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ def test_param_name(self):
+ with self.assertRaises(KeyError):
+ StepParamScheduler(
+ self.optimizer, param_name='invalid_name', step_size=10)
+
+ def _test_scheduler_value(self,
+ schedulers,
+ targets,
+ epochs=10,
+ param_name='lr'):
+ if isinstance(schedulers, _ParamScheduler):
+ schedulers = [schedulers]
+ for epoch in range(epochs):
+ for param_group, target in zip(self.optimizer.param_groups,
+ targets):
+ assert_allclose(
+ target[epoch],
+ param_group[param_name],
+ msg='{} is wrong in epoch {}: expected {}, got {}'.format(
+ param_name, epoch, target[epoch],
+ param_group[param_name]),
+ atol=1e-5,
+ rtol=0)
+ [scheduler.step() for scheduler in schedulers]
+
+ def test_step_scheduler(self):
+ # lr = 0.05 if epoch < 3
+ # lr = 0.005 if 3 <= epoch < 6
+ # lr = 0.0005 if 6 <= epoch < 9
+ # lr = 0.00005 if epoch >=9
+ epochs = 10
+ single_targets = [0.05] * 3 + [0.005] * 3 + [0.0005] * 3 + [0.00005
+ ] * 3
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = StepParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ gamma=0.1,
+ step_size=3,
+ verbose=True)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ # momentum = 0.01 if epoch < 2
+ # momentum = 0.001 if 2 <= epoch < 4
+ epochs = 4
+ single_targets = [0.01] * 2 + [0.001] * 2
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = StepParamScheduler(
+ self.optimizer, param_name='momentum', gamma=0.1, step_size=2)
+ self._test_scheduler_value(
+ scheduler, targets, epochs, param_name='momentum')
+
+ def test_multi_step_scheduler(self):
+ # lr = 0.05 if epoch < 2
+ # lr = 0.005 if 2 <= epoch < 5
+ # lr = 0.0005 if 5 <= epoch < 9
+ # lr = 0.00005 if epoch >= 9
+ epochs = 10
+ single_targets = [0.05] * 2 + [0.005] * 3 + [0.0005] * 4 + [0.00005
+ ] * 3
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = MultiStepParamScheduler(
+ self.optimizer, param_name='lr', gamma=0.1, milestones=[2, 5, 9])
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ def test_constant_scheduler(self):
+ # factor should between 0~1
+ with self.assertRaises(ValueError):
+ ConstantParamScheduler(self.optimizer, param_name='lr', factor=99)
+
+ # lr = 0.025 if epoch < 5
+ # lr = 0.005 if 5 <= epoch
+ epochs = 10
+ single_targets = [0.025] * 4 + [0.05] * 6
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = ConstantParamScheduler(
+ self.optimizer, param_name='lr', factor=1.0 / 2, end=5)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ def test_linear_scheduler(self):
+ with self.assertRaises(ValueError):
+ LinearParamScheduler(
+ self.optimizer, param_name='lr', start_factor=10, end=900)
+ with self.assertRaises(ValueError):
+ LinearParamScheduler(
+ self.optimizer, param_name='lr', start_factor=-1, end=900)
+ with self.assertRaises(ValueError):
+ LinearParamScheduler(
+ self.optimizer, param_name='lr', end_factor=1.001, end=900)
+ with self.assertRaises(ValueError):
+ LinearParamScheduler(
+ self.optimizer, param_name='lr', end_factor=-0.00001, end=900)
+ # lr = 0.025 if epoch == 0
+ # lr = 0.03125 if epoch == 1
+ # lr = 0.0375 if epoch == 2
+ # lr = 0.04375 if epoch == 3
+ # lr = 0.005 if epoch >= 4
+ epochs = 10
+ start_factor = 1.0 / 2
+ iters = 4
+ interpolation = [
+ start_factor + i * (1 - start_factor) / iters for i in range(iters)
+ ]
+ single_targets = [x * 0.05 for x in interpolation] + [0.05] * (
+ epochs - iters)
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = LinearParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ start_factor=start_factor,
+ end=iters + 1)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ def test_exp_scheduler(self):
+ epochs = 10
+ single_targets = [0.05 * (0.9**x) for x in range(epochs)]
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = ExponentialParamScheduler(
+ self.optimizer, param_name='lr', gamma=0.9)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ def test_cos_anneal_scheduler(self):
+ with self.assertRaises(AssertionError):
+ CosineAnnealingParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ T_max=10,
+ eta_min=0,
+ eta_min_ratio=0.1)
+ epochs = 12
+ t = 10
+ eta_min = 5e-3
+ targets1 = [
+ eta_min + (0.05 - eta_min) * (1 + math.cos(math.pi * x / t)) / 2
+ for x in range(epochs)
+ ]
+ targets2 = [
+ eta_min + (0.5 - eta_min) * (1 + math.cos(math.pi * x / t)) / 2
+ for x in range(epochs)
+ ]
+ targets = [targets1, targets2]
+ scheduler = CosineAnnealingParamScheduler(
+ self.optimizer, param_name='lr', T_max=t, eta_min=eta_min)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ # Test `eta_min_ratio`
+ self.setUp()
+ eta_min_ratio = 1e-3
+ targets1 = [
+ 0.05 * eta_min_ratio + (0.05 - 0.05 * eta_min_ratio) *
+ (1 + math.cos(math.pi * x / t)) / 2 for x in range(epochs)
+ ]
+ targets2 = [
+ 0.5 * eta_min_ratio + (0.5 - 0.5 * eta_min_ratio) *
+ (1 + math.cos(math.pi * x / t)) / 2 for x in range(epochs)
+ ]
+ targets = [targets1, targets2]
+ scheduler = CosineAnnealingParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ T_max=t,
+ eta_min_ratio=eta_min_ratio)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ # Test default `T_max`
+ scheduler = CosineAnnealingParamScheduler(
+ self.optimizer, param_name='lr', begin=5, end=100, eta_min=eta_min)
+ self.assertEqual(scheduler.T_max, 100 - 5)
+
+ def test_poly_scheduler(self):
+ epochs = 10
+ power = 0.9
+ min_lr = 0.001
+ iters = 4
+ targets_layer1 = [
+ min_lr + (0.05 - min_lr) * (1 - i / iters)**power
+ for i in range(iters)
+ ] + [min_lr] * (
+ epochs - iters)
+ targets_layer2 = [
+ min_lr + (0.05 * self.layer2_mult - min_lr) *
+ (1 - i / iters)**power for i in range(iters)
+ ] + [min_lr] * (
+ epochs - iters)
+ targets = [targets_layer1, targets_layer2]
+ scheduler = PolyParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ power=power,
+ eta_min=min_lr,
+ end=iters + 1)
+ self._test_scheduler_value(scheduler, targets, epochs=10)
+
+ def test_cosine_restart_scheduler(self):
+ with self.assertRaises(AssertionError):
+ CosineRestartParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ periods=[4, 5],
+ restart_weights=[1, 0.5],
+ eta_min=0,
+ eta_min_ratio=0.1)
+ with self.assertRaises(AssertionError):
+ CosineRestartParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ periods=[4, 5],
+ restart_weights=[1, 0.5, 0.0],
+ eta_min=0)
+ single_targets = [
+ 0.05, 0.0426776, 0.025, 0.00732233, 0.025, 0.022612712, 0.01636271,
+ 0.0086372, 0.0023872, 0.0023872
+ ]
+ targets = [
+ single_targets, [t * self.layer2_mult for t in single_targets]
+ ]
+
+ # Test with non-zero eta-min.
+ scheduler = CosineRestartParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ periods=[4, 5],
+ restart_weights=[1, 0.5],
+ eta_min=0)
+ self._test_scheduler_value(scheduler, targets, epochs=10)
+
+ epochs = 10
+ t = 10
+ eta_min = 5e-3
+ targets1 = [
+ eta_min + (0.05 - eta_min) * (1 + math.cos(math.pi * x / t)) / 2
+ for x in range(epochs)
+ ]
+ targets2 = [
+ eta_min + (0.5 - eta_min) * (1 + math.cos(math.pi * x / t)) / 2
+ for x in range(epochs)
+ ]
+ targets = [targets1, targets2]
+ scheduler = CosineRestartParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ periods=[t],
+ restart_weights=[1],
+ eta_min=eta_min)
+ self._test_scheduler_value(scheduler, targets, epochs=10)
+
+ def _check_scheduler_state_dict(self, construct, construct2, epochs=10):
+ scheduler = construct()
+ for _ in range(epochs):
+ scheduler.optimizer.step()
+ scheduler.step()
+ scheduler_copy = construct2()
+ torch.save(scheduler.state_dict(),
+ osp.join(self.temp_dir.name, 'tmp.pth'))
+ state_dict = torch.load(osp.join(self.temp_dir.name, 'tmp.pth'))
+ scheduler_copy.load_state_dict(state_dict)
+ for key in scheduler.__dict__.keys():
+ if key != 'optimizer':
+ self.assertEqual(scheduler.__dict__[key],
+ scheduler_copy.__dict__[key])
+ self.assertEqual(scheduler.get_last_value(),
+ scheduler_copy.get_last_value())
+
+ def test_step_scheduler_state_dict(self):
+ self._check_scheduler_state_dict(
+ lambda: StepParamScheduler(
+ self.optimizer, param_name='lr', gamma=0.1, step_size=3),
+ lambda: StepParamScheduler(
+ self.optimizer, param_name='lr', gamma=0.01 / 2, step_size=1))
+
+ def test_multi_step_scheduler_state_dict(self):
+ self._check_scheduler_state_dict(
+ lambda: MultiStepParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ gamma=0.1,
+ milestones=[2, 5, 9]), lambda: MultiStepParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ gamma=0.01,
+ milestones=[1, 4, 6]))
+
+ def test_exp_scheduler_state_dict(self):
+ self._check_scheduler_state_dict(
+ lambda: ExponentialParamScheduler(
+ self.optimizer, param_name='lr', gamma=0.1),
+ lambda: ExponentialParamScheduler(
+ self.optimizer, param_name='lr', gamma=0.01))
+
+ def test_cosine_scheduler_state_dict(self):
+ epochs = 10
+ eta_min = 1e-10
+ self._check_scheduler_state_dict(
+ lambda: CosineAnnealingParamScheduler(
+ self.optimizer, param_name='lr', T_max=epochs, eta_min=eta_min
+ ),
+ lambda: CosineAnnealingParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ T_max=epochs // 2,
+ eta_min=eta_min / 2),
+ epochs=epochs)
+
+ def test_linear_scheduler_state_dict(self):
+ epochs = 10
+ self._check_scheduler_state_dict(
+ lambda: LinearParamScheduler(
+ self.optimizer, param_name='lr', start_factor=1 / 3),
+ lambda: LinearParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ start_factor=0,
+ end_factor=0.3),
+ epochs=epochs)
+
+ def test_poly_scheduler_state_dict(self):
+ self._check_scheduler_state_dict(
+ lambda: PolyParamScheduler(
+ self.optimizer, param_name='lr', power=0.5, eta_min=0.001),
+ lambda: PolyParamScheduler(
+ self.optimizer, param_name='lr', power=0.8, eta_min=0.002),
+ epochs=10)
+
+ def test_cosine_restart_scheduler_state_dict(self):
+ self._check_scheduler_state_dict(
+ lambda: CosineRestartParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ periods=[4, 5],
+ restart_weights=[1, 0.5],
+ eta_min=0),
+ lambda: CosineRestartParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ periods=[4, 6],
+ restart_weights=[1, 0.5],
+ eta_min=0),
+ epochs=10)
+
+ def test_step_scheduler_convert_iterbased(self):
+ # invalid epoch_length
+ with self.assertRaises(AssertionError):
+ scheduler = StepParamScheduler.build_iter_from_epoch(
+ self.optimizer,
+ param_name='momentum',
+ gamma=0.1,
+ step_size=2,
+ epoch_length=-1)
+
+ # momentum = 0.01 if epoch < 2
+ # momentum = 0.001 if 2 <= epoch < 4
+ epochs = 4
+ epoch_length = 7
+ single_targets = [0.01] * 2 * epoch_length + [0.001] * 2 * epoch_length
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = StepParamScheduler.build_iter_from_epoch(
+ self.optimizer,
+ param_name='momentum',
+ gamma=0.1,
+ step_size=2,
+ epoch_length=epoch_length)
+ self._test_scheduler_value(
+ scheduler, targets, epochs * epoch_length, param_name='momentum')
+
+ def test_multi_step_scheduler_convert_iterbased(self):
+ # lr = 0.05 if epoch < 2
+ # lr = 0.005 if 2 <= epoch < 5
+ # lr = 0.0005 if 5 <= epoch < 9
+ # lr = 0.00005 if epoch >= 9
+ epochs = 10
+ epoch_length = 7
+ single_targets = [0.05
+ ] * 2 * epoch_length + [0.005] * 3 * epoch_length + [
+ 0.0005
+ ] * 4 * epoch_length + [0.00005] * 3 * epoch_length
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = MultiStepParamScheduler.build_iter_from_epoch(
+ self.optimizer,
+ param_name='lr',
+ gamma=0.1,
+ milestones=[2, 5, 9],
+ epoch_length=epoch_length)
+ self._test_scheduler_value(scheduler, targets, epochs * epoch_length)
+
+ def test_constant_scheduler_convert_iterbased(self):
+ # lr = 0.025 if epoch < 5
+ # lr = 0.005 if 5 <= epoch
+ epochs = 10
+ epoch_length = 7
+ single_targets = [0.025] * (5 * epoch_length -
+ 1) + [0.05] * (5 * epoch_length + 1)
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = ConstantParamScheduler.build_iter_from_epoch(
+ self.optimizer,
+ param_name='lr',
+ factor=1.0 / 2,
+ end=5,
+ epoch_length=epoch_length)
+ self._test_scheduler_value(scheduler, targets, epochs * epoch_length)
+
+ def test_linear_scheduler_convert_iterbased(self):
+ epochs = 10
+ start_factor = 1.0 / 2
+ end = 5
+ epoch_length = 11
+
+ iters = end * epoch_length - 1
+ interpolation = [
+ start_factor + i * (1 - start_factor) / iters for i in range(iters)
+ ]
+ single_targets = [x * 0.05 for x in interpolation] + [0.05] * (
+ epochs * epoch_length - iters)
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = LinearParamScheduler.build_iter_from_epoch(
+ self.optimizer,
+ param_name='lr',
+ start_factor=start_factor,
+ end=end,
+ epoch_length=epoch_length)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ def test_exp_scheduler_convert_iterbased(self):
+ epochs = 10
+ epoch_length = 7
+
+ single_targets = [
+ 0.05 * (0.9**x) for x in range(epochs * epoch_length)
+ ]
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = ExponentialParamScheduler.build_iter_from_epoch(
+ self.optimizer,
+ param_name='lr',
+ gamma=0.9,
+ epoch_length=epoch_length)
+ self._test_scheduler_value(scheduler, targets, epochs * epoch_length)
+
+ def test_cos_anneal_scheduler_convert_iterbased(self):
+ epochs = 12
+ t = 10
+ eta_min = 1e-10
+ epoch_length = 11
+ single_targets = [
+ eta_min + (0.05 - eta_min) *
+ (1 + math.cos(math.pi * x / t / epoch_length)) / 2
+ for x in range(epochs * epoch_length)
+ ]
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler = CosineAnnealingParamScheduler.build_iter_from_epoch(
+ self.optimizer,
+ param_name='lr',
+ T_max=t,
+ eta_min=eta_min,
+ epoch_length=epoch_length)
+ self._test_scheduler_value(scheduler, targets, epochs)
+
+ def test_poly_scheduler_convert_iterbased(self):
+ epochs = 10
+ power = 0.9
+ min_lr = 0.001
+ end = 5
+ epoch_length = 11
+
+ iters = end * epoch_length - 1
+ targets_layer1 = [
+ min_lr + (0.05 - min_lr) * (1 - i / iters)**power
+ for i in range(iters)
+ ] + [min_lr] * (
+ epochs - iters)
+ targets_layer2 = [
+ min_lr + (0.05 * self.layer2_mult - min_lr) *
+ (1 - i / iters)**power for i in range(iters)
+ ] + [min_lr] * (
+ epochs - iters)
+ targets = [targets_layer1, targets_layer2]
+ scheduler = PolyParamScheduler.build_iter_from_epoch(
+ self.optimizer,
+ param_name='lr',
+ power=power,
+ eta_min=min_lr,
+ end=end,
+ epoch_length=epoch_length)
+ self._test_scheduler_value(scheduler, targets, epochs=10)
+
+ def test_multi_scheduler_without_overlap_linear_multi_step(self):
+ # use Linear in the first 5 epochs and then use MultiStep
+ epochs = 12
+ single_targets = [0.025, 0.03125, 0.0375, 0.04375
+ ] + [0.05] * 4 + [0.005] * 3 + [0.0005] * 1
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler1 = LinearParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ start_factor=1 / 2,
+ begin=0,
+ end=5)
+ scheduler2 = MultiStepParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ gamma=0.1,
+ milestones=[3, 6],
+ begin=5,
+ end=12)
+ self._test_scheduler_value([scheduler1, scheduler2], targets, epochs)
+
+ def test_multi_scheduler_without_overlap_exp_cosine(self):
+ # use Exp in the first 5 epochs and then use Cosine
+ epochs = 10
+ single_targets1 = [0.05 * (0.9**x) for x in range(5)]
+ scheduler1 = ExponentialParamScheduler(
+ self.optimizer, param_name='lr', gamma=0.9, begin=0, end=5)
+
+ eta_min = 1e-10
+ single_targets2 = [
+ eta_min + (single_targets1[-1] - eta_min) *
+ (1 + math.cos(math.pi * x / 5)) / 2 for x in range(5)
+ ]
+ single_targets = single_targets1 + single_targets2
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler2 = CosineAnnealingParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ T_max=5,
+ eta_min=eta_min,
+ begin=5,
+ end=10)
+
+ self._test_scheduler_value([scheduler1, scheduler2], targets, epochs)
+
+ def test_multi_scheduler_with_overlap(self):
+ # use Linear at first 5 epochs together with MultiStep
+ epochs = 10
+ single_targets = [0.025, 0.03125, 0.0375, 0.004375
+ ] + [0.005] * 2 + [0.0005] * 3 + [0.00005] * 1
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler1 = LinearParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ start_factor=1 / 2,
+ begin=0,
+ end=5)
+ scheduler2 = MultiStepParamScheduler(
+ self.optimizer, param_name='lr', gamma=0.1, milestones=[3, 6, 9])
+ self._test_scheduler_value([scheduler1, scheduler2], targets, epochs)
+
+ def test_multi_scheduler_with_gap(self):
+ # use Exp in the first 5 epochs and the last 5 epochs use Cosine
+ # no scheduler in the middle 5 epochs
+ epochs = 15
+ single_targets1 = [0.05 * (0.9**x) for x in range(5)]
+ scheduler1 = ExponentialParamScheduler(
+ self.optimizer, param_name='lr', gamma=0.9, begin=0, end=5)
+
+ eta_min = 1e-10
+ single_targets2 = [
+ eta_min + (single_targets1[-1] - eta_min) *
+ (1 + math.cos(math.pi * x / 5)) / 2 for x in range(5)
+ ]
+ single_targets = single_targets1 + [single_targets1[-1]
+ ] * 5 + single_targets2
+ targets = [
+ single_targets, [x * self.layer2_mult for x in single_targets]
+ ]
+ scheduler2 = CosineAnnealingParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ T_max=5,
+ eta_min=eta_min,
+ begin=10,
+ end=15)
+
+ self._test_scheduler_value([scheduler1, scheduler2], targets, epochs)
+
+ def test_onecycle_scheduler(self):
+ # test invalid total steps
+ with self.assertRaises(ValueError):
+ OneCycleParamScheduler(
+ self.optimizer, param_name='lr', total_steps=-1)
+ # test invalid pct_start
+ with self.assertRaises(ValueError):
+ OneCycleParamScheduler(
+ self.optimizer, param_name='lr', total_steps=10, pct_start=-1)
+ # test invalid anneal_strategy
+ with self.assertRaises(ValueError):
+ OneCycleParamScheduler(
+ self.optimizer,
+ param_name='lr',
+ total_steps=10,
+ anneal_strategy='a')
+
+
+class TestParameterSchedulerOptimWrapper(TestParameterScheduler):
+
+ def setUp(self):
+ super().setUp()
+ self.optimizer = OptimWrapper(optimizer=self.optimizer)
diff --git a/testbed/open-mmlab__mmengine/tests/test_registry/test_build_functions.py b/testbed/open-mmlab__mmengine/tests/test_registry/test_build_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3bbb0986595a6668391124efce9102716d49f7a
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_registry/test_build_functions.py
@@ -0,0 +1,218 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import pytest
+
+from mmengine import (PARAM_SCHEDULERS, Config, ConfigDict, ManagerMixin,
+ Registry, build_from_cfg, build_model_from_cfg)
+from mmengine.utils import is_installed
+
+
+@pytest.mark.parametrize('cfg_type', [dict, ConfigDict, Config])
+def test_build_from_cfg(cfg_type):
+ BACKBONES = Registry('backbone')
+
+ @BACKBONES.register_module()
+ class ResNet:
+
+ def __init__(self, depth, stages=4):
+ self.depth = depth
+ self.stages = stages
+
+ @BACKBONES.register_module()
+ class ResNeXt:
+
+ def __init__(self, depth, stages=4):
+ self.depth = depth
+ self.stages = stages
+
+ # test `cfg` parameter
+ # `cfg` should be a dict, ConfigDict or Config object
+ with pytest.raises(
+ TypeError,
+ match=('cfg should be a dict, ConfigDict or Config, but got '
+ "")):
+ cfg = 'ResNet'
+ model = build_from_cfg(cfg, BACKBONES)
+
+ # `cfg` is a dict, ConfigDict or Config object
+ cfg = cfg_type(dict(type='ResNet', depth=50))
+ model = build_from_cfg(cfg, BACKBONES)
+ assert isinstance(model, ResNet)
+ assert model.depth == 50 and model.stages == 4
+
+ # `cfg` is a dict but it does not contain the key "type"
+ with pytest.raises(KeyError, match='must contain the key "type"'):
+ cfg = dict(depth=50, stages=4)
+ cfg = cfg_type(cfg)
+ model = build_from_cfg(cfg, BACKBONES)
+
+ # cfg['type'] should be a str or class
+ with pytest.raises(
+ TypeError,
+ match="type must be a str or valid type, but got "):
+ cfg = dict(type=1000)
+ cfg = cfg_type(cfg)
+ model = build_from_cfg(cfg, BACKBONES)
+
+ cfg = cfg_type(dict(type='ResNeXt', depth=50, stages=3))
+ model = build_from_cfg(cfg, BACKBONES)
+ assert isinstance(model, ResNeXt)
+ assert model.depth == 50 and model.stages == 3
+
+ cfg = cfg_type(dict(type=ResNet, depth=50))
+ model = build_from_cfg(cfg, BACKBONES)
+ assert isinstance(model, ResNet)
+ assert model.depth == 50 and model.stages == 4
+
+ # non-registered class
+ with pytest.raises(KeyError, match='VGG is not in the backbone registry'):
+ cfg = cfg_type(dict(type='VGG'))
+ model = build_from_cfg(cfg, BACKBONES)
+
+ # `cfg` contains unexpected arguments
+ with pytest.raises(TypeError):
+ cfg = cfg_type(dict(type='ResNet', non_existing_arg=50))
+ model = build_from_cfg(cfg, BACKBONES)
+
+ # test `default_args` parameter
+ cfg = cfg_type(dict(type='ResNet', depth=50))
+ model = build_from_cfg(cfg, BACKBONES, cfg_type(dict(stages=3)))
+ assert isinstance(model, ResNet)
+ assert model.depth == 50 and model.stages == 3
+
+ # default_args must be a dict or None
+ with pytest.raises(TypeError):
+ cfg = cfg_type(dict(type='ResNet', depth=50))
+ model = build_from_cfg(cfg, BACKBONES, default_args=1)
+
+ # cfg or default_args should contain the key "type"
+ with pytest.raises(KeyError, match='must contain the key "type"'):
+ cfg = cfg_type(dict(depth=50))
+ model = build_from_cfg(
+ cfg, BACKBONES, default_args=cfg_type(dict(stages=4)))
+
+ # "type" defined using default_args
+ cfg = cfg_type(dict(depth=50))
+ model = build_from_cfg(
+ cfg, BACKBONES, default_args=cfg_type(dict(type='ResNet')))
+ assert isinstance(model, ResNet)
+ assert model.depth == 50 and model.stages == 4
+
+ cfg = cfg_type(dict(depth=50))
+ model = build_from_cfg(
+ cfg, BACKBONES, default_args=cfg_type(dict(type=ResNet)))
+ assert isinstance(model, ResNet)
+ assert model.depth == 50 and model.stages == 4
+
+ # test `registry` parameter
+ # incorrect registry type
+ with pytest.raises(
+ TypeError,
+ match=('registry must be a mmengine.Registry object, but got '
+ "")):
+ cfg = cfg_type(dict(type='ResNet', depth=50))
+ model = build_from_cfg(cfg, 'BACKBONES')
+
+ VISUALIZER = Registry('visualizer')
+
+ @VISUALIZER.register_module()
+ class Visualizer(ManagerMixin):
+
+ def __init__(self, name):
+ super().__init__(name)
+
+ with pytest.raises(RuntimeError):
+ Visualizer.get_current_instance()
+ cfg = dict(type='Visualizer', name='visualizer')
+ build_from_cfg(cfg, VISUALIZER)
+ Visualizer.get_current_instance()
+
+
+@pytest.mark.skipif(not is_installed('torch'), reason='tests requires torch')
+def test_build_model_from_cfg():
+ import torch.nn as nn
+
+ BACKBONES = Registry('backbone', build_func=build_model_from_cfg)
+
+ @BACKBONES.register_module()
+ class ResNet(nn.Module):
+
+ def __init__(self, depth, stages=4):
+ super().__init__()
+ self.depth = depth
+ self.stages = stages
+
+ def forward(self, x):
+ return x
+
+ @BACKBONES.register_module()
+ class ResNeXt(nn.Module):
+
+ def __init__(self, depth, stages=4):
+ super().__init__()
+ self.depth = depth
+ self.stages = stages
+
+ def forward(self, x):
+ return x
+
+ cfg = dict(type='ResNet', depth=50)
+ model = BACKBONES.build(cfg)
+ assert isinstance(model, ResNet)
+ assert model.depth == 50 and model.stages == 4
+
+ cfg = dict(type='ResNeXt', depth=50, stages=3)
+ model = BACKBONES.build(cfg)
+ assert isinstance(model, ResNeXt)
+ assert model.depth == 50 and model.stages == 3
+
+ cfg = [
+ dict(type='ResNet', depth=50),
+ dict(type='ResNeXt', depth=50, stages=3)
+ ]
+ model = BACKBONES.build(cfg)
+ assert isinstance(model, nn.Sequential)
+ assert isinstance(model[0], ResNet)
+ assert model[0].depth == 50 and model[0].stages == 4
+ assert isinstance(model[1], ResNeXt)
+ assert model[1].depth == 50 and model[1].stages == 3
+
+ # test inherit `build_func` from parent
+ NEW_MODELS = Registry('models', parent=BACKBONES, scope='new')
+ assert NEW_MODELS.build_func is build_model_from_cfg
+
+ # test specify `build_func`
+ def pseudo_build(cfg):
+ return cfg
+
+ NEW_MODELS = Registry('models', parent=BACKBONES, build_func=pseudo_build)
+ assert NEW_MODELS.build_func is pseudo_build
+
+
+@pytest.mark.skipif(not is_installed('torch'), reason='tests requires torch')
+def test_build_sheduler_from_cfg():
+ import torch.nn as nn
+ from torch.optim import SGD
+ model = nn.Conv2d(1, 1, 1)
+ optimizer = SGD(model.parameters(), lr=0.1)
+ cfg = dict(
+ type='LinearParamScheduler',
+ optimizer=optimizer,
+ param_name='lr',
+ begin=0,
+ end=100)
+ sheduler = PARAM_SCHEDULERS.build(cfg)
+ assert sheduler.begin == 0
+ assert sheduler.end == 100
+
+ cfg = dict(
+ type='LinearParamScheduler',
+ convert_to_iter_based=True,
+ optimizer=optimizer,
+ param_name='lr',
+ begin=0,
+ end=100,
+ epoch_length=10)
+
+ sheduler = PARAM_SCHEDULERS.build(cfg)
+ assert sheduler.begin == 0
+ assert sheduler.end == 1000
diff --git a/testbed/open-mmlab__mmengine/tests/test_registry/test_default_scope.py b/testbed/open-mmlab__mmengine/tests/test_registry/test_default_scope.py
new file mode 100644
index 0000000000000000000000000000000000000000..0798f4a2c75831dd67559f3df5614fd6431dba3d
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_registry/test_default_scope.py
@@ -0,0 +1,48 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from collections import OrderedDict
+
+import pytest
+
+from mmengine.registry import DefaultScope
+
+
+class TestDefaultScope:
+
+ def test_scope(self):
+ default_scope = DefaultScope.get_instance('name1', scope_name='mmdet')
+ assert default_scope.scope_name == 'mmdet'
+ # `DefaultScope.get_instance` must have `scope_name` argument.
+ with pytest.raises(TypeError):
+ DefaultScope.get_instance('name2')
+
+ def test_get_current_instance(self):
+ DefaultScope._instance_dict = OrderedDict()
+ assert DefaultScope.get_current_instance() is None
+ DefaultScope.get_instance('instance_name', scope_name='mmengine')
+ default_scope = DefaultScope.get_current_instance()
+ assert default_scope.scope_name == 'mmengine'
+
+ def test_overwrite_default_scope(self):
+ origin_scope = DefaultScope.get_instance(
+ 'test_overwrite_default_scope', scope_name='origin_scope')
+ with DefaultScope.overwrite_default_scope(scope_name=None):
+ assert DefaultScope.get_current_instance(
+ ).scope_name == 'origin_scope'
+ with DefaultScope.overwrite_default_scope(scope_name='test_overwrite'):
+ assert DefaultScope.get_current_instance(
+ ).scope_name == 'test_overwrite'
+ assert DefaultScope.get_current_instance(
+ ).scope_name == origin_scope.scope_name == 'origin_scope'
+
+ # Test overwrite default scope immediately.
+ # Test sequentially overwrite.
+ with DefaultScope.overwrite_default_scope(scope_name='test_overwrite'):
+ pass
+ with DefaultScope.overwrite_default_scope(scope_name='test_overwrite'):
+ pass
+
+ # Test nested overwrite.
+ with DefaultScope.overwrite_default_scope(scope_name='test_overwrite'):
+ with DefaultScope.overwrite_default_scope(
+ scope_name='test_overwrite'):
+ pass
diff --git a/testbed/open-mmlab__mmengine/tests/test_registry/test_registry.py b/testbed/open-mmlab__mmengine/tests/test_registry/test_registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..16768d5c6a8bc9d4c85ffcfdcd7b62ae430488e2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_registry/test_registry.py
@@ -0,0 +1,668 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import time
+
+import pytest
+
+from mmengine.config import Config, ConfigDict # type: ignore
+from mmengine.registry import (DefaultScope, Registry, build_from_cfg,
+ build_model_from_cfg)
+from mmengine.utils import ManagerMixin
+
+
+class TestRegistry:
+
+ def test_init(self):
+ CATS = Registry('cat')
+ assert CATS.name == 'cat'
+ assert CATS.module_dict == {}
+ assert CATS.build_func is build_from_cfg
+ assert len(CATS) == 0
+
+ # test `build_func` parameter
+ def build_func(cfg, registry, default_args):
+ pass
+
+ CATS = Registry('cat', build_func=build_func)
+ assert CATS.build_func is build_func
+
+ # test `parent` parameter
+ # `parent` is either None or a `Registry` instance
+ with pytest.raises(AssertionError):
+ CATS = Registry('little_cat', parent='cat', scope='little_cat')
+
+ LITTLECATS = Registry('little_cat', parent=CATS, scope='little_cat')
+ assert LITTLECATS.parent is CATS
+ assert CATS._children.get('little_cat') is LITTLECATS
+
+ # test `scope` parameter
+ # `scope` is either None or a string
+ with pytest.raises(AssertionError):
+ CATS = Registry('cat', scope=1)
+
+ CATS = Registry('cat')
+ assert CATS.scope == 'test_registry'
+
+ CATS = Registry('cat', scope='cat')
+ assert CATS.scope == 'cat'
+
+ def test_split_scope_key(self):
+ DOGS = Registry('dogs')
+
+ scope, key = DOGS.split_scope_key('BloodHound')
+ assert scope is None and key == 'BloodHound'
+ scope, key = DOGS.split_scope_key('hound.BloodHound')
+ assert scope == 'hound' and key == 'BloodHound'
+ scope, key = DOGS.split_scope_key('hound.little_hound.Dachshund')
+ assert scope == 'hound' and key == 'little_hound.Dachshund'
+
+ def test_register_module(self):
+ CATS = Registry('cat')
+
+ @CATS.register_module()
+ def muchkin():
+ pass
+
+ assert CATS.get('muchkin') is muchkin
+ assert 'muchkin' in CATS
+
+ # can only decorate a class or a function
+ with pytest.raises(TypeError):
+
+ class Demo:
+
+ def some_method(self):
+ pass
+
+ method = Demo().some_method
+ CATS.register_module(name='some_method', module=method)
+
+ # test `name` parameter which must be either of None, a string or a
+ # sequence of string
+ # `name` is None
+ @CATS.register_module()
+ class BritishShorthair:
+ pass
+
+ assert len(CATS) == 2
+ assert CATS.get('BritishShorthair') is BritishShorthair
+
+ # `name` is a string
+ @CATS.register_module(name='Munchkin')
+ class Munchkin:
+ pass
+
+ assert len(CATS) == 3
+ assert CATS.get('Munchkin') is Munchkin
+ assert 'Munchkin' in CATS
+
+ # `name` is a sequence of string
+ @CATS.register_module(name=['Siamese', 'Siamese2'])
+ class SiameseCat:
+ pass
+
+ assert CATS.get('Siamese') is SiameseCat
+ assert CATS.get('Siamese2') is SiameseCat
+ assert len(CATS) == 5
+
+ # `name` is an invalid type
+ with pytest.raises(
+ TypeError,
+ match=('name must be None, an instance of str, or a sequence '
+ "of str, but got ")):
+
+ @CATS.register_module(name=7474741)
+ class SiameseCat:
+ pass
+
+ # test `force` parameter, which must be a boolean
+ # force is not a boolean
+ with pytest.raises(
+ TypeError,
+ match="force must be a boolean, but got "):
+
+ @CATS.register_module(force=1)
+ class BritishShorthair:
+ pass
+
+ # force=False
+ with pytest.raises(
+ KeyError,
+ match='BritishShorthair is already registered in cat '
+ 'at test_registry'):
+
+ @CATS.register_module()
+ class BritishShorthair:
+ pass
+
+ # force=True
+ @CATS.register_module(force=True)
+ class BritishShorthair:
+ pass
+
+ assert len(CATS) == 5
+
+ # test `module` parameter, which is either None or a class
+ # when the `register_module`` is called as a method rather than a
+ # decorator, which must be a class
+ with pytest.raises(
+ TypeError,
+ match='module must be a class or a function,'
+ " but got "):
+ CATS.register_module(module='string')
+
+ class SphynxCat:
+ pass
+
+ CATS.register_module(module=SphynxCat)
+ assert CATS.get('SphynxCat') is SphynxCat
+ assert len(CATS) == 6
+
+ CATS.register_module(name='Sphynx1', module=SphynxCat)
+ assert CATS.get('Sphynx1') is SphynxCat
+ assert len(CATS) == 7
+
+ CATS.register_module(name=['Sphynx2', 'Sphynx3'], module=SphynxCat)
+ assert CATS.get('Sphynx2') is SphynxCat
+ assert CATS.get('Sphynx3') is SphynxCat
+ assert len(CATS) == 9
+
+ def _build_registry(self):
+ """A helper function to build a Hierarchical Registry."""
+ # Hierarchical Registry
+ # DOGS
+ # _______|_______
+ # | |
+ # HOUNDS (hound) SAMOYEDS (samoyed)
+ # _______|_______ |
+ # | | |
+ # LITTLE_HOUNDS MID_HOUNDS LITTLE_SAMOYEDS
+ # (little_hound) (mid_hound) (little_samoyed)
+ registries = []
+ DOGS = Registry('dogs')
+ registries.append(DOGS)
+ HOUNDS = Registry('hounds', parent=DOGS, scope='hound')
+ registries.append(HOUNDS)
+ LITTLE_HOUNDS = Registry(
+ 'little hounds', parent=HOUNDS, scope='little_hound')
+ registries.append(LITTLE_HOUNDS)
+ MID_HOUNDS = Registry('mid hounds', parent=HOUNDS, scope='mid_hound')
+ registries.append(MID_HOUNDS)
+ SAMOYEDS = Registry('samoyeds', parent=DOGS, scope='samoyed')
+ registries.append(SAMOYEDS)
+ LITTLE_SAMOYEDS = Registry(
+ 'little samoyeds', parent=SAMOYEDS, scope='little_samoyed')
+ registries.append(LITTLE_SAMOYEDS)
+
+ return registries
+
+ def test__get_root_registry(self):
+ # Hierarchical Registry
+ # DOGS
+ # _______|_______
+ # | |
+ # HOUNDS (hound) SAMOYEDS (samoyed)
+ # _______|_______ |
+ # | | |
+ # LITTLE_HOUNDS MID_HOUNDS LITTLE_SAMOYEDS
+ # (little_hound) (mid_hound) (little_samoyed)
+ registries = self._build_registry()
+ DOGS, HOUNDS, LITTLE_HOUNDS, MID_HOUNDS = registries[:4]
+
+ assert DOGS._get_root_registry() is DOGS
+ assert HOUNDS._get_root_registry() is DOGS
+ assert LITTLE_HOUNDS._get_root_registry() is DOGS
+ assert MID_HOUNDS._get_root_registry() is DOGS
+
+ def test_get(self):
+ # Hierarchical Registry
+ # DOGS
+ # _______|_______
+ # | |
+ # HOUNDS (hound) SAMOYEDS (samoyed)
+ # _______|_______ |
+ # | | |
+ # LITTLE_HOUNDS MID_HOUNDS LITTLE_SAMOYEDS
+ # (little_hound) (mid_hound) (little_samoyed)
+ registries = self._build_registry()
+ DOGS, HOUNDS, LITTLE_HOUNDS = registries[:3]
+ MID_HOUNDS, SAMOYEDS, LITTLE_SAMOYEDS = registries[3:]
+
+ @DOGS.register_module()
+ class GoldenRetriever:
+ pass
+
+ assert len(DOGS) == 1
+ assert DOGS.get('GoldenRetriever') is GoldenRetriever
+
+ @HOUNDS.register_module()
+ class BloodHound:
+ pass
+
+ assert len(HOUNDS) == 1
+ # get key from current registry
+ assert HOUNDS.get('BloodHound') is BloodHound
+ # get key from its children
+ assert DOGS.get('hound.BloodHound') is BloodHound
+ # get key from current registry
+ assert HOUNDS.get('hound.BloodHound') is BloodHound
+
+ # If the key is not found in the current registry, then look for its
+ # parent
+ assert HOUNDS.get('GoldenRetriever') is GoldenRetriever
+
+ @LITTLE_HOUNDS.register_module()
+ class Dachshund:
+ pass
+
+ assert len(LITTLE_HOUNDS) == 1
+ # get key from current registry
+ assert LITTLE_HOUNDS.get('Dachshund') is Dachshund
+ # get key from its parent
+ assert LITTLE_HOUNDS.get('hound.BloodHound') is BloodHound
+ # get key from its children
+ assert HOUNDS.get('little_hound.Dachshund') is Dachshund
+ # get key from its descendants
+ assert DOGS.get('hound.little_hound.Dachshund') is Dachshund
+
+ # If the key is not found in the current registry, then look for its
+ # parent
+ assert LITTLE_HOUNDS.get('BloodHound') is BloodHound
+ assert LITTLE_HOUNDS.get('GoldenRetriever') is GoldenRetriever
+
+ @MID_HOUNDS.register_module()
+ class Beagle:
+ pass
+
+ # get key from its sibling registries
+ assert LITTLE_HOUNDS.get('hound.mid_hound.Beagle') is Beagle
+
+ @SAMOYEDS.register_module()
+ class PedigreeSamoyed:
+ pass
+
+ assert len(SAMOYEDS) == 1
+ # get key from its uncle
+ assert LITTLE_HOUNDS.get('samoyed.PedigreeSamoyed') is PedigreeSamoyed
+
+ @LITTLE_SAMOYEDS.register_module()
+ class LittlePedigreeSamoyed:
+ pass
+
+ # get key from its cousin
+ assert LITTLE_HOUNDS.get('samoyed.little_samoyed.LittlePedigreeSamoyed'
+ ) is LittlePedigreeSamoyed
+
+ # get key from its nephews
+ assert HOUNDS.get('samoyed.little_samoyed.LittlePedigreeSamoyed'
+ ) is LittlePedigreeSamoyed
+
+ # invalid keys
+ # GoldenRetrieverererer can not be found at LITTLE_HOUNDS modules
+ assert LITTLE_HOUNDS.get('GoldenRetrieverererer') is None
+ # samoyedddd is not a child of DOGS
+ assert DOGS.get('samoyedddd.PedigreeSamoyed') is None
+ # samoyed is a child of DOGS but LittlePedigreeSamoyed can not be found
+ # at SAMOYEDS modules
+ assert DOGS.get('samoyed.LittlePedigreeSamoyed') is None
+ assert LITTLE_HOUNDS.get('mid_hound.PedigreeSamoyedddddd') is None
+
+ def test__search_child(self):
+ # Hierarchical Registry
+ # DOGS
+ # _______|_______
+ # | |
+ # HOUNDS (hound) SAMOYEDS (samoyed)
+ # _______|_______ |
+ # | | |
+ # LITTLE_HOUNDS MID_HOUNDS LITTLE_SAMOYEDS
+ # (little_hound) (mid_hound) (little_samoyed)
+ registries = self._build_registry()
+ DOGS, HOUNDS, LITTLE_HOUNDS = registries[:3]
+
+ assert DOGS._search_child('hound') is HOUNDS
+ assert DOGS._search_child('not a child') is None
+ assert DOGS._search_child('little_hound') is LITTLE_HOUNDS
+ assert LITTLE_HOUNDS._search_child('hound') is None
+ assert LITTLE_HOUNDS._search_child('mid_hound') is None
+
+ @pytest.mark.parametrize('cfg_type', [dict, ConfigDict, Config])
+ def test_build(self, cfg_type):
+ # Hierarchical Registry
+ # DOGS
+ # _______|_______
+ # | |
+ # HOUNDS (hound) SAMOYEDS (samoyed)
+ # _______|_______ |
+ # | | |
+ # LITTLE_HOUNDS MID_HOUNDS LITTLE_SAMOYEDS
+ # (little_hound) (mid_hound) (little_samoyed)
+ registries = self._build_registry()
+ DOGS, HOUNDS, LITTLE_HOUNDS, MID_HOUNDS, SAMOYEDS = registries[:5]
+
+ @DOGS.register_module()
+ def bark(times=1):
+ return ' '.join(['woof'] * times)
+
+ bark_cfg = cfg_type(dict(type='bark', times=3))
+ assert DOGS.build(bark_cfg) == 'woof woof woof'
+
+ @DOGS.register_module()
+ class GoldenRetriever:
+ pass
+
+ gr_cfg = cfg_type(dict(type='GoldenRetriever'))
+ assert isinstance(DOGS.build(gr_cfg), GoldenRetriever)
+
+ @HOUNDS.register_module()
+ class BloodHound:
+ pass
+
+ bh_cfg = cfg_type(dict(type='BloodHound'))
+ assert isinstance(HOUNDS.build(bh_cfg), BloodHound)
+ assert isinstance(HOUNDS.build(gr_cfg), GoldenRetriever)
+
+ @LITTLE_HOUNDS.register_module()
+ class Dachshund:
+ pass
+
+ d_cfg = cfg_type(dict(type='Dachshund'))
+ assert isinstance(LITTLE_HOUNDS.build(d_cfg), Dachshund)
+
+ @MID_HOUNDS.register_module()
+ class Beagle:
+ pass
+
+ b_cfg = cfg_type(dict(type='Beagle'))
+ assert isinstance(MID_HOUNDS.build(b_cfg), Beagle)
+
+ # test `default_scope`
+ # switch the current registry to another registry
+ DefaultScope.get_instance(
+ f'test-{time.time()}', scope_name='mid_hound')
+ dog = LITTLE_HOUNDS.build(b_cfg)
+ assert isinstance(dog, Beagle)
+
+ # `default_scope` can not be found
+ DefaultScope.get_instance(
+ f'test2-{time.time()}', scope_name='scope-not-found')
+ dog = MID_HOUNDS.build(b_cfg)
+ assert isinstance(dog, Beagle)
+
+ # test overwrite default scope with `_scope_`
+ @SAMOYEDS.register_module()
+ class MySamoyed:
+
+ def __init__(self, friend):
+ self.friend = DOGS.build(friend)
+
+ @SAMOYEDS.register_module()
+ class YourSamoyed:
+ pass
+
+ s_cfg = cfg_type(
+ dict(
+ _scope_='samoyed',
+ type='MySamoyed',
+ friend=dict(type='hound.BloodHound')))
+ dog = DOGS.build(s_cfg)
+ assert isinstance(dog, MySamoyed)
+ assert isinstance(dog.friend, BloodHound)
+ assert DefaultScope.get_current_instance().scope_name != 'samoyed'
+
+ s_cfg = cfg_type(
+ dict(
+ _scope_='samoyed',
+ type='MySamoyed',
+ friend=dict(type='YourSamoyed')))
+ dog = DOGS.build(s_cfg)
+ assert isinstance(dog, MySamoyed)
+ assert isinstance(dog.friend, YourSamoyed)
+ assert DefaultScope.get_current_instance().scope_name != 'samoyed'
+
+ def test_switch_scope_and_registry(self):
+ DOGS = Registry('dogs')
+ HOUNDS = Registry('hounds', scope='hound', parent=DOGS)
+ SAMOYEDS = Registry('samoyeds', scope='samoyed', parent=DOGS)
+ CHIHUAHUA = Registry('chihuahuas', scope='chihuahua', parent=DOGS)
+
+ # Hierarchical Registry
+ # DOGS
+ # ___________________|___________________
+ # | | |
+ # HOUNDS (hound) SAMOYEDS (samoyed) CHIHUAHUA (chihuahua)
+
+ DefaultScope.get_instance(
+ f'scope_{time.time()}', scope_name='chihuahua')
+ assert DefaultScope.get_current_instance().scope_name == 'chihuahua'
+
+ # Test switch scope and get target registry.
+ with CHIHUAHUA.switch_scope_and_registry(scope='hound') as \
+ registry:
+ assert DefaultScope.get_current_instance().scope_name == 'hound'
+ assert id(registry) == id(HOUNDS)
+
+ # Test nested-ly switch scope.
+ with CHIHUAHUA.switch_scope_and_registry(scope='samoyed') as \
+ samoyed_registry:
+ assert DefaultScope.get_current_instance().scope_name == 'samoyed'
+ assert id(samoyed_registry) == id(SAMOYEDS)
+
+ with CHIHUAHUA.switch_scope_and_registry(scope='hound') as \
+ hound_registry:
+ assert DefaultScope.get_current_instance().scope_name == \
+ 'hound'
+ assert id(hound_registry) == id(HOUNDS)
+
+ # Test switch to original scope
+ assert DefaultScope.get_current_instance().scope_name == 'chihuahua'
+
+ # Test get an unknown registry.
+ with CHIHUAHUA.switch_scope_and_registry(scope='unknown') as \
+ registry:
+ assert id(registry) == id(CHIHUAHUA)
+ assert DefaultScope.get_current_instance().scope_name == 'unknown'
+
+ def test_repr(self):
+ CATS = Registry('cat')
+
+ @CATS.register_module()
+ class BritishShorthair:
+ pass
+
+ @CATS.register_module()
+ class Munchkin:
+ pass
+
+ repr_str = 'Registry(name=cat, items={'
+ repr_str += (
+ "'BritishShorthair': .BritishShorthair'>, ")
+ repr_str += (
+ "'Munchkin': .Munchkin'>")
+ repr_str += '})'
+ assert repr(CATS) == repr_str
+
+
+@pytest.mark.parametrize('cfg_type', [dict, ConfigDict, Config])
+def test_build_from_cfg(cfg_type):
+ BACKBONES = Registry('backbone')
+
+ @BACKBONES.register_module()
+ class ResNet:
+
+ def __init__(self, depth, stages=4):
+ self.depth = depth
+ self.stages = stages
+
+ @BACKBONES.register_module()
+ class ResNeXt:
+
+ def __init__(self, depth, stages=4):
+ self.depth = depth
+ self.stages = stages
+
+ # test `cfg` parameter
+ # `cfg` should be a dict, ConfigDict or Config object
+ with pytest.raises(
+ TypeError,
+ match=('cfg should be a dict, ConfigDict or Config, but got '
+ "")):
+ cfg = 'ResNet'
+ model = build_from_cfg(cfg, BACKBONES)
+
+ # `cfg` is a dict, ConfigDict or Config object
+ cfg = cfg_type(dict(type='ResNet', depth=50))
+ model = build_from_cfg(cfg, BACKBONES)
+ assert isinstance(model, ResNet)
+ assert model.depth == 50 and model.stages == 4
+
+ # `cfg` is a dict but it does not contain the key "type"
+ with pytest.raises(KeyError, match='must contain the key "type"'):
+ cfg = dict(depth=50, stages=4)
+ cfg = cfg_type(cfg)
+ model = build_from_cfg(cfg, BACKBONES)
+
+ # cfg['type'] should be a str or class
+ with pytest.raises(
+ TypeError,
+ match="type must be a str or valid type, but got "):
+ cfg = dict(type=1000)
+ cfg = cfg_type(cfg)
+ model = build_from_cfg(cfg, BACKBONES)
+
+ cfg = cfg_type(dict(type='ResNeXt', depth=50, stages=3))
+ model = build_from_cfg(cfg, BACKBONES)
+ assert isinstance(model, ResNeXt)
+ assert model.depth == 50 and model.stages == 3
+
+ cfg = cfg_type(dict(type=ResNet, depth=50))
+ model = build_from_cfg(cfg, BACKBONES)
+ assert isinstance(model, ResNet)
+ assert model.depth == 50 and model.stages == 4
+
+ # non-registered class
+ with pytest.raises(KeyError, match='VGG is not in the backbone registry'):
+ cfg = cfg_type(dict(type='VGG'))
+ model = build_from_cfg(cfg, BACKBONES)
+
+ # `cfg` contains unexpected arguments
+ with pytest.raises(TypeError):
+ cfg = cfg_type(dict(type='ResNet', non_existing_arg=50))
+ model = build_from_cfg(cfg, BACKBONES)
+
+ # test `default_args` parameter
+ cfg = cfg_type(dict(type='ResNet', depth=50))
+ model = build_from_cfg(cfg, BACKBONES, cfg_type(dict(stages=3)))
+ assert isinstance(model, ResNet)
+ assert model.depth == 50 and model.stages == 3
+
+ # default_args must be a dict or None
+ with pytest.raises(TypeError):
+ cfg = cfg_type(dict(type='ResNet', depth=50))
+ model = build_from_cfg(cfg, BACKBONES, default_args=1)
+
+ # cfg or default_args should contain the key "type"
+ with pytest.raises(KeyError, match='must contain the key "type"'):
+ cfg = cfg_type(dict(depth=50))
+ model = build_from_cfg(
+ cfg, BACKBONES, default_args=cfg_type(dict(stages=4)))
+
+ # "type" defined using default_args
+ cfg = cfg_type(dict(depth=50))
+ model = build_from_cfg(
+ cfg, BACKBONES, default_args=cfg_type(dict(type='ResNet')))
+ assert isinstance(model, ResNet)
+ assert model.depth == 50 and model.stages == 4
+
+ cfg = cfg_type(dict(depth=50))
+ model = build_from_cfg(
+ cfg, BACKBONES, default_args=cfg_type(dict(type=ResNet)))
+ assert isinstance(model, ResNet)
+ assert model.depth == 50 and model.stages == 4
+
+ # test `registry` parameter
+ # incorrect registry type
+ with pytest.raises(
+ TypeError,
+ match=('registry must be a mmengine.Registry object, but got '
+ "")):
+ cfg = cfg_type(dict(type='ResNet', depth=50))
+ model = build_from_cfg(cfg, 'BACKBONES')
+
+ VISUALIZER = Registry('visualizer')
+
+ @VISUALIZER.register_module()
+ class Visualizer(ManagerMixin):
+
+ def __init__(self, name):
+ super().__init__(name)
+
+ with pytest.raises(RuntimeError):
+ Visualizer.get_current_instance()
+ cfg = dict(type='Visualizer', name='visualizer')
+ build_from_cfg(cfg, VISUALIZER)
+ Visualizer.get_current_instance()
+
+
+def test_build_model_from_cfg():
+ try:
+ import torch.nn as nn
+ except ImportError:
+ pytest.skip('require torch')
+
+ BACKBONES = Registry('backbone', build_func=build_model_from_cfg)
+
+ @BACKBONES.register_module()
+ class ResNet(nn.Module):
+
+ def __init__(self, depth, stages=4):
+ super().__init__()
+ self.depth = depth
+ self.stages = stages
+
+ def forward(self, x):
+ return x
+
+ @BACKBONES.register_module()
+ class ResNeXt(nn.Module):
+
+ def __init__(self, depth, stages=4):
+ super().__init__()
+ self.depth = depth
+ self.stages = stages
+
+ def forward(self, x):
+ return x
+
+ cfg = dict(type='ResNet', depth=50)
+ model = BACKBONES.build(cfg)
+ assert isinstance(model, ResNet)
+ assert model.depth == 50 and model.stages == 4
+
+ cfg = dict(type='ResNeXt', depth=50, stages=3)
+ model = BACKBONES.build(cfg)
+ assert isinstance(model, ResNeXt)
+ assert model.depth == 50 and model.stages == 3
+
+ cfg = [
+ dict(type='ResNet', depth=50),
+ dict(type='ResNeXt', depth=50, stages=3)
+ ]
+ model = BACKBONES.build(cfg)
+ assert isinstance(model, nn.Sequential)
+ assert isinstance(model[0], ResNet)
+ assert model[0].depth == 50 and model[0].stages == 4
+ assert isinstance(model[1], ResNeXt)
+ assert model[1].depth == 50 and model[1].stages == 3
+
+ # test inherit `build_func` from parent
+ NEW_MODELS = Registry('models', parent=BACKBONES, scope='new')
+ assert NEW_MODELS.build_func is build_model_from_cfg
+
+ # test specify `build_func`
+ def pseudo_build(cfg):
+ return cfg
+
+ NEW_MODELS = Registry('models', parent=BACKBONES, build_func=pseudo_build)
+ assert NEW_MODELS.build_func is pseudo_build
diff --git a/testbed/open-mmlab__mmengine/tests/test_registry/test_registry_utils.py b/testbed/open-mmlab__mmengine/tests/test_registry/test_registry_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..35670435d7574982b0101df78e8f2ee7a7e511f9
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_registry/test_registry_utils.py
@@ -0,0 +1,64 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os.path as osp
+from tempfile import TemporaryDirectory
+from unittest import TestCase, skipIf
+
+from mmengine.registry import (Registry, count_registered_modules, root,
+ traverse_registry_tree)
+from mmengine.utils import is_installed
+
+
+class TestUtils(TestCase):
+
+ def test_traverse_registry_tree(self):
+ # Hierarchical Registry
+ # DOGS
+ # _______|_______
+ # | |
+ # HOUNDS (hound) SAMOYEDS (samoyed)
+ # _______|_______ |
+ # | | |
+ # LITTLE_HOUNDS MID_HOUNDS LITTLE_SAMOYEDS
+ # (little_hound) (mid_hound) (little_samoyed)
+ DOGS = Registry('dogs')
+ HOUNDS = Registry('dogs', parent=DOGS, scope='hound')
+ LITTLE_HOUNDS = Registry( # noqa
+ 'dogs', parent=HOUNDS, scope='little_hound')
+ MID_HOUNDS = Registry('dogs', parent=HOUNDS, scope='mid_hound')
+ SAMOYEDS = Registry('dogs', parent=DOGS, scope='samoyed')
+ LITTLE_SAMOYEDS = Registry( # noqa
+ 'dogs', parent=SAMOYEDS, scope='little_samoyed')
+
+ @DOGS.register_module()
+ class GoldenRetriever:
+ pass
+
+ # traversing the tree from the root
+ result = traverse_registry_tree(DOGS)
+ self.assertEqual(result[0]['num_modules'], 1)
+ self.assertEqual(len(result), 6)
+
+ # traversing the tree from leaf node
+ result_leaf = traverse_registry_tree(MID_HOUNDS)
+ # result from any node should be the same
+ self.assertEqual(result, result_leaf)
+
+ @skipIf(not is_installed('torch'), 'tests requires torch')
+ def test_count_all_registered_modules(self):
+ temp_dir = TemporaryDirectory()
+ results = count_registered_modules(temp_dir.name, verbose=True)
+ self.assertTrue(
+ osp.exists(
+ osp.join(temp_dir.name, 'modules_statistic_results.json')))
+ registries_info = results['registries']
+ for registry in registries_info:
+ self.assertTrue(hasattr(root, registry))
+ self.assertEqual(registries_info[registry][0]['num_modules'],
+ len(getattr(root, registry).module_dict))
+ temp_dir.cleanup()
+
+ # test not saving results
+ count_registered_modules(save_path=None, verbose=False)
+ self.assertFalse(
+ osp.exists(
+ osp.join(temp_dir.name, 'modules_statistic_results.json')))
diff --git a/testbed/open-mmlab__mmengine/tests/test_runner/test_amp.py b/testbed/open-mmlab__mmengine/tests/test_runner/test_amp.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ef605637832c361563ebf3da313abb75cef1e5e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_runner/test_amp.py
@@ -0,0 +1,81 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import unittest
+
+import torch
+import torch.nn as nn
+
+import mmengine
+from mmengine.device import get_device
+from mmengine.runner import autocast
+from mmengine.utils import digit_version
+from mmengine.utils.dl_utils import TORCH_VERSION
+
+
+class TestAmp(unittest.TestCase):
+
+ def test_autocast(self):
+ if not torch.cuda.is_available():
+ if digit_version(TORCH_VERSION) < digit_version('1.10.0'):
+ # `torch.cuda.amp.autocast` is only support in gpu mode, if
+ # cuda is not available, it will return an empty context and
+ # should not accept any arguments.
+ with self.assertRaisesRegex(RuntimeError,
+ 'If pytorch versions is '):
+ with autocast():
+ pass
+
+ with autocast(enabled=False):
+ layer = nn.Conv2d(1, 1, 1)
+ res = layer(torch.randn(1, 1, 1, 1))
+ self.assertEqual(res.dtype, torch.float32)
+
+ else:
+ with autocast(device_type='cpu'):
+ # torch.autocast support cpu mode.
+ layer = nn.Conv2d(1, 1, 1)
+ res = layer(torch.randn(1, 1, 1, 1))
+ self.assertIn(res.dtype, (torch.bfloat16, torch.float16))
+ with autocast(enabled=False):
+ res = layer(torch.randn(1, 1, 1, 1))
+ self.assertEqual(res.dtype, torch.float32)
+
+ else:
+ if digit_version(TORCH_VERSION) < digit_version('1.10.0'):
+ devices = ['cuda']
+ else:
+ devices = ['cpu', 'cuda']
+ for device in devices:
+ with autocast(device_type=device):
+ # torch.autocast support cpu and cuda mode.
+ layer = nn.Conv2d(1, 1, 1).to(device)
+ res = layer(torch.randn(1, 1, 1, 1).to(device))
+ self.assertIn(res.dtype, (torch.bfloat16, torch.float16))
+ with autocast(enabled=False, device_type=device):
+ res = layer(torch.randn(1, 1, 1, 1).to(device))
+ self.assertEqual(res.dtype, torch.float32)
+ # Test with fp32_enabled
+ with autocast(enabled=False, device_type=device):
+ layer = nn.Conv2d(1, 1, 1).to(device)
+ res = layer(torch.randn(1, 1, 1, 1).to(device))
+ self.assertEqual(res.dtype, torch.float32)
+
+ # Test mps
+ if digit_version(TORCH_VERSION) >= digit_version('1.12.0'):
+ mmengine.runner.amp.get_device = lambda: 'mps'
+ with autocast(enabled=False):
+ layer = nn.Conv2d(1, 1, 1)
+ res = layer(torch.randn(1, 1, 1, 1))
+ self.assertEqual(res.dtype, torch.float32)
+
+ with self.assertRaisesRegex(ValueError,
+ 'User specified autocast device_type'):
+ with autocast(enabled=True):
+ pass
+ # Native pytorch does not support mlu, here we simply test autocast
+ # will call `torch.autocast`, which will be overridden by mlu version
+ # pytorch
+ mmengine.runner.amp.get_device = lambda: 'mlu'
+ with self.assertRaises(RuntimeError):
+ with autocast(enabled=False):
+ pass
+ mmengine.runner.amp.get_device = get_device
diff --git a/testbed/open-mmlab__mmengine/tests/test_runner/test_checkpoint.py b/testbed/open-mmlab__mmengine/tests/test_runner/test_checkpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd7d6d286d27b672eb943d6c18e9a79b984dd26e
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_runner/test_checkpoint.py
@@ -0,0 +1,411 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import sys
+import tempfile
+from collections import OrderedDict
+from tempfile import TemporaryDirectory
+from unittest.mock import MagicMock, patch
+
+import pytest
+import torch
+import torch.nn as nn
+import torch.optim as optim
+from torch.nn.parallel import DataParallel
+
+from mmengine.fileio.file_client import PetrelBackend
+from mmengine.registry import MODEL_WRAPPERS
+from mmengine.runner.checkpoint import (CheckpointLoader,
+ _load_checkpoint_with_prefix,
+ get_state_dict, load_checkpoint,
+ load_from_local, load_from_pavi,
+ save_checkpoint)
+
+sys.modules['petrel_client'] = MagicMock()
+sys.modules['petrel_client.client'] = MagicMock()
+
+
+@MODEL_WRAPPERS.register_module()
+class DDPWrapper:
+
+ def __init__(self, module):
+ self.module = module
+
+
+class Block(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.conv = nn.Conv2d(3, 3, 1)
+ self.norm = nn.BatchNorm2d(3)
+
+
+class Model(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.block = Block()
+ self.conv = nn.Conv2d(3, 3, 1)
+
+
+class Mockpavimodel:
+
+ def __init__(self, name='fakename'):
+ self.name = name
+
+ def download(self, file):
+ pass
+
+
+def assert_tensor_equal(tensor_a, tensor_b):
+ assert tensor_a.eq(tensor_b).all()
+
+
+def test_get_state_dict():
+ if torch.__version__ == 'parrots':
+ state_dict_keys = {
+ 'block.conv.weight', 'block.conv.bias', 'block.norm.weight',
+ 'block.norm.bias', 'block.norm.running_mean',
+ 'block.norm.running_var', 'conv.weight', 'conv.bias'
+ }
+ else:
+ state_dict_keys = {
+ 'block.conv.weight', 'block.conv.bias', 'block.norm.weight',
+ 'block.norm.bias', 'block.norm.running_mean',
+ 'block.norm.running_var', 'block.norm.num_batches_tracked',
+ 'conv.weight', 'conv.bias'
+ }
+
+ model = Model()
+ state_dict = get_state_dict(model)
+ assert isinstance(state_dict, OrderedDict)
+ assert set(state_dict.keys()) == state_dict_keys
+
+ assert_tensor_equal(state_dict['block.conv.weight'],
+ model.block.conv.weight)
+ assert_tensor_equal(state_dict['block.conv.bias'], model.block.conv.bias)
+ assert_tensor_equal(state_dict['block.norm.weight'],
+ model.block.norm.weight)
+ assert_tensor_equal(state_dict['block.norm.bias'], model.block.norm.bias)
+ assert_tensor_equal(state_dict['block.norm.running_mean'],
+ model.block.norm.running_mean)
+ assert_tensor_equal(state_dict['block.norm.running_var'],
+ model.block.norm.running_var)
+ if torch.__version__ != 'parrots':
+ assert_tensor_equal(state_dict['block.norm.num_batches_tracked'],
+ model.block.norm.num_batches_tracked)
+ assert_tensor_equal(state_dict['conv.weight'], model.conv.weight)
+ assert_tensor_equal(state_dict['conv.bias'], model.conv.bias)
+
+ wrapped_model = DDPWrapper(model)
+ state_dict = get_state_dict(wrapped_model)
+ assert isinstance(state_dict, OrderedDict)
+ assert set(state_dict.keys()) == state_dict_keys
+ assert_tensor_equal(state_dict['block.conv.weight'],
+ wrapped_model.module.block.conv.weight)
+ assert_tensor_equal(state_dict['block.conv.bias'],
+ wrapped_model.module.block.conv.bias)
+ assert_tensor_equal(state_dict['block.norm.weight'],
+ wrapped_model.module.block.norm.weight)
+ assert_tensor_equal(state_dict['block.norm.bias'],
+ wrapped_model.module.block.norm.bias)
+ assert_tensor_equal(state_dict['block.norm.running_mean'],
+ wrapped_model.module.block.norm.running_mean)
+ assert_tensor_equal(state_dict['block.norm.running_var'],
+ wrapped_model.module.block.norm.running_var)
+ if torch.__version__ != 'parrots':
+ assert_tensor_equal(
+ state_dict['block.norm.num_batches_tracked'],
+ wrapped_model.module.block.norm.num_batches_tracked)
+ assert_tensor_equal(state_dict['conv.weight'],
+ wrapped_model.module.conv.weight)
+ assert_tensor_equal(state_dict['conv.bias'],
+ wrapped_model.module.conv.bias)
+
+ # wrapped inner module
+ for name, module in wrapped_model.module._modules.items():
+ module = DataParallel(module)
+ wrapped_model.module._modules[name] = module
+ state_dict = get_state_dict(wrapped_model)
+ assert isinstance(state_dict, OrderedDict)
+ assert set(state_dict.keys()) == state_dict_keys
+ assert_tensor_equal(state_dict['block.conv.weight'],
+ wrapped_model.module.block.module.conv.weight)
+ assert_tensor_equal(state_dict['block.conv.bias'],
+ wrapped_model.module.block.module.conv.bias)
+ assert_tensor_equal(state_dict['block.norm.weight'],
+ wrapped_model.module.block.module.norm.weight)
+ assert_tensor_equal(state_dict['block.norm.bias'],
+ wrapped_model.module.block.module.norm.bias)
+ assert_tensor_equal(state_dict['block.norm.running_mean'],
+ wrapped_model.module.block.module.norm.running_mean)
+ assert_tensor_equal(state_dict['block.norm.running_var'],
+ wrapped_model.module.block.module.norm.running_var)
+ if torch.__version__ != 'parrots':
+ assert_tensor_equal(
+ state_dict['block.norm.num_batches_tracked'],
+ wrapped_model.module.block.module.norm.num_batches_tracked)
+ assert_tensor_equal(state_dict['conv.weight'],
+ wrapped_model.module.conv.module.weight)
+ assert_tensor_equal(state_dict['conv.bias'],
+ wrapped_model.module.conv.module.bias)
+
+
+def test_load_pavimodel_dist():
+ sys.modules['pavi'] = MagicMock()
+ sys.modules['pavi.modelcloud'] = MagicMock()
+ pavimodel = Mockpavimodel()
+ import pavi
+ pavi.modelcloud.get = MagicMock(return_value=pavimodel)
+ with pytest.raises(AssertionError):
+ # test pavi prefix
+ _ = load_from_pavi('MyPaviFolder/checkpoint.pth')
+
+ with pytest.raises(FileNotFoundError):
+ # there is not such checkpoint for us to load
+ _ = load_from_pavi('pavi://checkpoint.pth')
+
+
+def test_load_checkpoint_with_prefix():
+
+ class FooModule(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.linear = nn.Linear(1, 2)
+ self.conv2d = nn.Conv2d(3, 1, 3)
+ self.conv2d_2 = nn.Conv2d(3, 2, 3)
+
+ model = FooModule()
+ nn.init.constant_(model.linear.weight, 1)
+ nn.init.constant_(model.linear.bias, 2)
+ nn.init.constant_(model.conv2d.weight, 3)
+ nn.init.constant_(model.conv2d.bias, 4)
+ nn.init.constant_(model.conv2d_2.weight, 5)
+ nn.init.constant_(model.conv2d_2.bias, 6)
+
+ with TemporaryDirectory():
+ torch.save(model.state_dict(), 'model.pth')
+ prefix = 'conv2d'
+ state_dict = _load_checkpoint_with_prefix(prefix, 'model.pth')
+ assert torch.equal(model.conv2d.state_dict()['weight'],
+ state_dict['weight'])
+ assert torch.equal(model.conv2d.state_dict()['bias'],
+ state_dict['bias'])
+
+ # test whether prefix is in pretrained model
+ with pytest.raises(AssertionError):
+ prefix = 'back'
+ _load_checkpoint_with_prefix(prefix, 'model.pth')
+
+
+def test_load_checkpoint():
+ import os
+ import re
+ import tempfile
+
+ class PrefixModel(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.backbone = Model()
+
+ pmodel = PrefixModel()
+ model = Model()
+ checkpoint_path = os.path.join(tempfile.gettempdir(), 'checkpoint.pth')
+
+ # add prefix
+ torch.save(model.state_dict(), checkpoint_path)
+ state_dict = load_checkpoint(
+ pmodel, checkpoint_path, revise_keys=[(r'^', 'backbone.')])
+ for key in pmodel.backbone.state_dict().keys():
+ assert torch.equal(pmodel.backbone.state_dict()[key], state_dict[key])
+ # strip prefix
+ torch.save(pmodel.state_dict(), checkpoint_path)
+ state_dict = load_checkpoint(
+ model, checkpoint_path, revise_keys=[(r'^backbone\.', '')])
+
+ for key in state_dict.keys():
+ key_stripped = re.sub(r'^backbone\.', '', key)
+ assert torch.equal(model.state_dict()[key_stripped], state_dict[key])
+ os.remove(checkpoint_path)
+
+
+def test_load_checkpoint_metadata():
+
+ class ModelV1(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.block = Block()
+ self.conv1 = nn.Conv2d(3, 3, 1)
+ self.conv2 = nn.Conv2d(3, 3, 1)
+ nn.init.normal_(self.conv1.weight)
+ nn.init.normal_(self.conv2.weight)
+
+ class ModelV2(nn.Module):
+ _version = 2
+
+ def __init__(self):
+ super().__init__()
+ self.block = Block()
+ self.conv0 = nn.Conv2d(3, 3, 1)
+ self.conv1 = nn.Conv2d(3, 3, 1)
+ nn.init.normal_(self.conv0.weight)
+ nn.init.normal_(self.conv1.weight)
+
+ def _load_from_state_dict(self, state_dict, prefix, local_metadata,
+ *args, **kwargs):
+ """load checkpoints."""
+
+ # Names of some parameters in has been changed.
+ version = local_metadata.get('version', None)
+ if version is None or version < 2:
+ state_dict_keys = list(state_dict.keys())
+ convert_map = {'conv1': 'conv0', 'conv2': 'conv1'}
+ for k in state_dict_keys:
+ for ori_str, new_str in convert_map.items():
+ if k.startswith(prefix + ori_str):
+ new_key = k.replace(ori_str, new_str)
+ state_dict[new_key] = state_dict[k]
+ del state_dict[k]
+
+ super()._load_from_state_dict(state_dict, prefix, local_metadata,
+ *args, **kwargs)
+
+ model_v1 = ModelV1()
+ model_v1_conv0_weight = model_v1.conv1.weight.detach()
+ model_v1_conv1_weight = model_v1.conv2.weight.detach()
+ model_v2 = ModelV2()
+ model_v2_conv0_weight = model_v2.conv0.weight.detach()
+ model_v2_conv1_weight = model_v2.conv1.weight.detach()
+ ckpt_v1_path = os.path.join(tempfile.gettempdir(), 'checkpoint_v1.pth')
+ ckpt_v2_path = os.path.join(tempfile.gettempdir(), 'checkpoint_v2.pth')
+
+ # Save checkpoint
+ save_checkpoint(model_v1.state_dict(), ckpt_v1_path)
+ save_checkpoint(model_v2.state_dict(), ckpt_v2_path)
+
+ # test load v1 model
+ load_checkpoint(model_v2, ckpt_v1_path)
+ assert torch.allclose(model_v2.conv0.weight, model_v1_conv0_weight)
+ assert torch.allclose(model_v2.conv1.weight, model_v1_conv1_weight)
+
+ # test load v2 model
+ load_checkpoint(model_v2, ckpt_v2_path)
+ assert torch.allclose(model_v2.conv0.weight, model_v2_conv0_weight)
+ assert torch.allclose(model_v2.conv1.weight, model_v2_conv1_weight)
+
+
+def test_checkpoint_loader():
+ filenames = [
+ 'http://xx.xx/xx.pth', 'https://xx.xx/xx.pth',
+ 'modelzoo://xx.xx/xx.pth', 'torchvision://xx.xx/xx.pth',
+ 'open-mmlab://xx.xx/xx.pth', 'openmmlab://xx.xx/xx.pth',
+ 'mmcls://xx.xx/xx.pth', 'pavi://xx.xx/xx.pth', 's3://xx.xx/xx.pth',
+ 'ss3://xx.xx/xx.pth', ' s3://xx.xx/xx.pth',
+ 'open-mmlab:s3://xx.xx/xx.pth', 'openmmlab:s3://xx.xx/xx.pth',
+ 'openmmlabs3://xx.xx/xx.pth', ':s3://xx.xx/xx.path'
+ ]
+ fn_names = [
+ 'load_from_http', 'load_from_http', 'load_from_torchvision',
+ 'load_from_torchvision', 'load_from_openmmlab', 'load_from_openmmlab',
+ 'load_from_mmcls', 'load_from_pavi', 'load_from_ceph',
+ 'load_from_local', 'load_from_local', 'load_from_ceph',
+ 'load_from_ceph', 'load_from_local', 'load_from_local'
+ ]
+
+ for filename, fn_name in zip(filenames, fn_names):
+ loader = CheckpointLoader._get_checkpoint_loader(filename)
+ assert loader.__name__ == fn_name
+
+ @CheckpointLoader.register_scheme(prefixes='ftp://')
+ def load_from_ftp(filename, map_location):
+ return dict(filename=filename)
+
+ # test register_loader
+ filename = 'ftp://xx.xx/xx.pth'
+ loader = CheckpointLoader._get_checkpoint_loader(filename)
+ assert loader.__name__ == 'load_from_ftp'
+
+ def load_from_ftp1(filename, map_location):
+ return dict(filename=filename)
+
+ # test duplicate registered error
+ with pytest.raises(KeyError):
+ CheckpointLoader.register_scheme('ftp://', load_from_ftp1)
+
+ # test force param
+ CheckpointLoader.register_scheme('ftp://', load_from_ftp1, force=True)
+ checkpoint = CheckpointLoader.load_checkpoint(filename)
+ assert checkpoint['filename'] == filename
+
+ # test print function name
+ loader = CheckpointLoader._get_checkpoint_loader(filename)
+ assert loader.__name__ == 'load_from_ftp1'
+
+ # test sort
+ @CheckpointLoader.register_scheme(prefixes='a/b')
+ def load_from_ab(filename, map_location):
+ return dict(filename=filename)
+
+ @CheckpointLoader.register_scheme(prefixes='a/b/c')
+ def load_from_abc(filename, map_location):
+ return dict(filename=filename)
+
+ filename = 'a/b/c/d'
+ loader = CheckpointLoader._get_checkpoint_loader(filename)
+ assert loader.__name__ == 'load_from_abc'
+
+
+def test_save_checkpoint(tmp_path):
+ model = Model()
+ optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.9)
+ # meta is not a dict
+ with pytest.raises(TypeError):
+ save_checkpoint(model, '/path/of/your/filename', meta='invalid type')
+
+ # 1. save to disk
+ filename = str(tmp_path / 'checkpoint1.pth')
+ save_checkpoint(model.state_dict(), filename)
+
+ filename = str(tmp_path / 'checkpoint2.pth')
+ checkpoint = dict(
+ model=model.state_dict(), optimizer=optimizer.state_dict())
+ save_checkpoint(checkpoint, filename)
+
+ filename = str(tmp_path / 'checkpoint3.pth')
+ save_checkpoint(
+ model.state_dict(), filename, backend_args={'backend': 'local'})
+
+ filename = str(tmp_path / 'checkpoint4.pth')
+ save_checkpoint(
+ model.state_dict(), filename, file_client_args={'backend': 'disk'})
+
+ # 2. save to petrel oss
+ with patch.object(PetrelBackend, 'put') as mock_method:
+ filename = 's3://path/of/your/checkpoint1.pth'
+ save_checkpoint(model.state_dict(), filename)
+ mock_method.assert_called()
+
+ with patch.object(PetrelBackend, 'put') as mock_method:
+ filename = 's3://path//of/your/checkpoint2.pth'
+ save_checkpoint(
+ model.state_dict(),
+ filename,
+ file_client_args={'backend': 'petrel'})
+ mock_method.assert_called()
+
+
+def test_load_from_local():
+ import os
+ home_path = os.path.expanduser('~')
+ checkpoint_path = os.path.join(
+ home_path, 'dummy_checkpoint_used_to_test_load_from_local.pth')
+ model = Model()
+ save_checkpoint(model.state_dict(), checkpoint_path)
+ checkpoint = load_from_local(
+ '~/dummy_checkpoint_used_to_test_load_from_local.pth',
+ map_location=None)
+ assert_tensor_equal(checkpoint['block.conv.weight'],
+ model.block.conv.weight)
+ os.remove(checkpoint_path)
diff --git a/testbed/open-mmlab__mmengine/tests/test_runner/test_log_processor.py b/testbed/open-mmlab__mmengine/tests/test_runner/test_log_processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..2affa73f9a7c90325253e7efa5577da92c2515ca
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_runner/test_log_processor.py
@@ -0,0 +1,261 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+from unittest.mock import MagicMock, patch
+
+import numpy as np
+import pytest
+import torch
+
+from mmengine.logging import HistoryBuffer, MessageHub, MMLogger
+from mmengine.runner import LogProcessor
+
+
+class TestLogProcessor:
+
+ def test_init(self):
+ log_processor = LogProcessor(
+ window_size=10, by_epoch=True, custom_cfg=None)
+ assert log_processor.by_epoch
+ assert log_processor.window_size == 10
+ assert log_processor.custom_cfg == []
+
+ def test_check_custom_cfg(self):
+ # ``by_epoch==False`` and `window_size='epoch'` in log config will
+ # raise AssertionError.
+ custom_cfg = [dict(data_src='loss', window_size='epoch')]
+ with pytest.raises(AssertionError):
+ LogProcessor(by_epoch=False, custom_cfg=custom_cfg)
+ # Duplicate log_name will raise AssertionError.
+ custom_cfg = [
+ dict(data_src='loss', log_name='loss_1'),
+ dict(data_src='loss', log_name='loss_1')
+ ]
+ with pytest.raises(AssertionError):
+ LogProcessor(custom_cfg=custom_cfg)
+ # Overwrite loss item twice will raise AssertionError.
+ custom_cfg = [dict(data_src='loss'), dict(data_src='loss')]
+ with pytest.raises(AssertionError):
+ LogProcessor(custom_cfg=custom_cfg)
+
+ custom_cfg = [
+ dict(data_src='loss_cls', window_size=100, method_name='min'),
+ dict(data_src='loss', log_name='loss_min', method_name='max'),
+ dict(data_src='loss', log_name='loss_max', method_name='max')
+ ]
+ LogProcessor(custom_cfg=custom_cfg)
+
+ def test_parse_windows_size(self):
+ log_processor = LogProcessor()
+ # Test parse 'epoch' window_size.
+ log_processor.custom_cfg = [
+ dict(data_src='loss_cls', window_size='epoch')
+ ]
+ custom_cfg = log_processor._parse_windows_size(self.runner, 1)
+ assert custom_cfg[0]['window_size'] == 2
+
+ # Test parse 'global' window_size.
+ log_processor.custom_cfg = [
+ dict(data_src='loss_cls', window_size='global')
+ ]
+ custom_cfg = log_processor._parse_windows_size(self.runner, 1)
+ assert custom_cfg[0]['window_size'] == 11
+
+ # Test parse int window_size
+ log_processor.custom_cfg = [dict(data_src='loss_cls', window_size=100)]
+ custom_cfg = log_processor._parse_windows_size(self.runner, 1)
+ assert custom_cfg[0]['window_size'] == 100
+
+ # Invalid type window_size will raise TypeError.
+ log_processor.custom_cfg = [dict(data_src='loss_cls', window_size=[])]
+ with pytest.raises(TypeError):
+ log_processor._parse_windows_size(custom_cfg, self.runner)
+
+ @pytest.mark.parametrize('by_epoch,mode',
+ ([True, 'train'], [False, 'train'], [True, 'val'],
+ [False, 'val'], [True, 'test'], [False, 'test']))
+ def test_get_log_after_iter(self, by_epoch, mode):
+ # Prepare LoggerHook
+ log_processor = LogProcessor(by_epoch=by_epoch)
+ log_processor._get_max_memory = MagicMock(return_value='100')
+ eta = 40
+ self.runner.message_hub.update_info('eta', eta)
+ # Prepare training information.
+ if mode == 'train':
+ train_logs = dict(lr=0.1, time=1.0, data_time=1.0, loss_cls=1.0)
+ else:
+ train_logs = dict(time=1.0, data_time=1.0, loss_cls=1.0)
+ log_processor._collect_scalars = MagicMock(return_value=train_logs)
+ tag, out = log_processor.get_log_after_iter(self.runner, 1, mode)
+ # Verify that the correct context have been logged.
+ cur_loop = log_processor._get_cur_loop(self.runner, mode)
+ if by_epoch:
+ if mode in ['train', 'val']:
+ cur_epoch = log_processor._get_epoch(self.runner, mode)
+ log_str = (f'Epoch({mode}) [{cur_epoch}][ 2/'
+ f'{len(cur_loop.dataloader)}] ')
+ else:
+ log_str = (f'Epoch({mode}) [2/{len(cur_loop.dataloader)}] ')
+
+ if mode == 'train':
+ log_str += f"lr: {train_logs['lr']:.4e} "
+ else:
+ log_str += ' '
+
+ log_str += (f'eta: 0:00:40 '
+ f"time: {train_logs['time']:.4f} "
+ f"data_time: {train_logs['data_time']:.4f} ")
+
+ if torch.cuda.is_available():
+ log_str += 'memory: 100 '
+ if mode == 'train':
+ log_str += f"loss_cls: {train_logs['loss_cls']:.4f}"
+ assert out == log_str
+ else:
+ if mode == 'train':
+ max_iters = self.runner.max_iters
+ log_str = f'Iter({mode}) [11/{max_iters}] '
+ elif mode == 'val':
+ max_iters = len(cur_loop.dataloader)
+ log_str = f'Iter({mode}) [ 2/{max_iters}] '
+ else:
+ max_iters = len(cur_loop.dataloader)
+ log_str = f'Iter({mode}) [2/{max_iters}] '
+
+ if mode == 'train':
+ log_str += f"lr: {train_logs['lr']:.4e} "
+ else:
+ log_str += ' '
+
+ log_str += (f'eta: 0:00:40 '
+ f"time: {train_logs['time']:.4f} "
+ f"data_time: {train_logs['data_time']:.4f} ")
+
+ if torch.cuda.is_available():
+ log_str += 'memory: 100 '
+
+ if mode == 'train':
+ log_str += f"loss_cls: {train_logs['loss_cls']:.4f}"
+ assert out == log_str
+
+ @pytest.mark.parametrize(
+ 'by_epoch,mode',
+ ([True, 'val'], [False, 'val'], [True, 'test'], [False, 'test']))
+ def test_log_val(self, by_epoch, mode):
+ # Prepare LoggerHook
+ log_processor = LogProcessor(by_epoch=by_epoch)
+ # Prepare validation information.
+ val_logs = dict(accuracy=0.9, data_time=1.0)
+ log_processor._collect_scalars = MagicMock(return_value=val_logs)
+ _, out = log_processor.get_log_after_epoch(self.runner, 2, mode)
+ if by_epoch:
+ if mode == 'test':
+ assert out == 'Epoch(test) [5/5] accuracy: 0.9000'
+ else:
+ assert out == 'Epoch(val) [1][10/10] accuracy: 0.9000'
+ else:
+ if mode == 'test':
+ assert out == 'Iter(test) [5/5] accuracy: 0.9000'
+ else:
+ assert out == 'Iter(val) [10/10] accuracy: 0.9000'
+
+ def test_collect_scalars(self):
+ history_count = np.ones(100)
+ time_scalars = np.random.randn(100)
+ loss_cls_scalars = np.random.randn(100)
+ lr_scalars = np.random.randn(100)
+ metric_scalars = np.random.randn(100)
+
+ history_time_buffer = HistoryBuffer(time_scalars, history_count)
+ histroy_loss_cls = HistoryBuffer(loss_cls_scalars, history_count)
+ history_lr_buffer = HistoryBuffer(lr_scalars, history_count)
+ history_metric_buffer = HistoryBuffer(metric_scalars, history_count)
+
+ custom_cfg = [
+ dict(data_src='time', method_name='max', log_name='time_max')
+ ]
+ logger_hook = LogProcessor(custom_cfg=custom_cfg)
+ # Collect with prefix.
+ log_scalars = {
+ 'train/time': history_time_buffer,
+ 'lr': history_lr_buffer,
+ 'train/loss_cls': histroy_loss_cls,
+ 'val/metric': history_metric_buffer
+ }
+ self.runner.message_hub._log_scalars = log_scalars
+ tag = logger_hook._collect_scalars(
+ copy.deepcopy(custom_cfg), self.runner, mode='train')
+ # Test training key in tag.
+ assert list(tag.keys()) == ['time', 'loss_cls', 'time_max']
+ # Test statistics lr with `current`, loss and time with 'mean'
+ assert tag['time'] == time_scalars[-10:].mean()
+ assert tag['time_max'] == time_scalars.max()
+ assert tag['loss_cls'] == loss_cls_scalars[-10:].mean()
+
+ tag = logger_hook._collect_scalars(
+ copy.deepcopy(custom_cfg), self.runner, mode='val')
+ assert list(tag.keys()) == ['metric']
+ assert tag['metric'] == metric_scalars[-1]
+
+ @patch('torch.cuda.max_memory_allocated', MagicMock())
+ @patch('torch.cuda.reset_peak_memory_stats', MagicMock())
+ def test_get_max_memory(self):
+ logger_hook = LogProcessor()
+ runner = MagicMock()
+ runner.world_size = 1
+ runner.model = torch.nn.Linear(1, 1)
+ logger_hook._get_max_memory(runner)
+ torch.cuda.max_memory_allocated.assert_called()
+ torch.cuda.reset_peak_memory_stats.assert_called()
+
+ def test_get_iter(self):
+ log_processor = LogProcessor()
+ # Get global iter when `inner_iter=False`
+ iter = log_processor._get_iter(self.runner)
+ assert iter == 11
+ # Get inner iter
+ iter = log_processor._get_iter(self.runner, 1)
+ assert iter == 2
+ # Still get global iter when `logger_hook.by_epoch==False`
+ log_processor.by_epoch = False
+ iter = log_processor._get_iter(self.runner, 1)
+ assert iter == 11
+
+ def test_get_epoch(self):
+ log_processor = LogProcessor()
+ epoch = log_processor._get_epoch(self.runner, 'train')
+ assert epoch == 2
+ epoch = log_processor._get_epoch(self.runner, 'val')
+ assert epoch == 1
+ with pytest.raises(ValueError):
+ log_processor._get_epoch(self.runner, 'test')
+
+ def test_get_cur_loop(self):
+ log_processor = LogProcessor()
+ loop = log_processor._get_cur_loop(self.runner, 'train')
+ assert len(loop.dataloader) == 20
+ loop = log_processor._get_cur_loop(self.runner, 'val')
+ assert len(loop.dataloader) == 10
+ loop = log_processor._get_cur_loop(self.runner, 'test')
+ assert len(loop.dataloader) == 5
+
+ def setup(self):
+ runner = MagicMock()
+ runner.epoch = 1
+ runner.max_epochs = 10
+ runner.iter = 10
+ runner.max_iters = 50
+ runner.train_dataloader = [0] * 20
+ runner.val_dataloader = [0] * 10
+ runner.test_dataloader = [0] * 5
+ runner.train_loop.dataloader = [0] * 20
+ runner.val_loop.dataloader = [0] * 10
+ runner.test_loop.dataloader = [0] * 5
+ logger = MMLogger.get_instance('log_processor_test')
+ runner.logger = logger
+ message_hub = MessageHub.get_instance('log_processor_test')
+ for i in range(10):
+ message_hub.update_scalar('train/loss', 10 - i)
+ for i in range(10):
+ message_hub.update_scalar('val/acc', i * 0.1)
+ runner.message_hub = message_hub
+ self.runner = runner
diff --git a/testbed/open-mmlab__mmengine/tests/test_runner/test_priority.py b/testbed/open-mmlab__mmengine/tests/test_runner/test_priority.py
new file mode 100644
index 0000000000000000000000000000000000000000..2065897887a6de446edc9cfbc4fa4105d8250da4
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_runner/test_priority.py
@@ -0,0 +1,29 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import pytest
+
+from mmengine.runner import Priority, get_priority
+
+
+def test_get_priority():
+ # test `priority` parameter which can be int, str or Priority
+ # `priority` is an integer
+ assert get_priority(10) == 10
+ # `priority` is an integer but it exceeds the valid ranges
+ with pytest.raises(ValueError, match='priority must be between 0 and 100'):
+ get_priority(-1)
+ with pytest.raises(ValueError, match='priority must be between 0 and 100'):
+ get_priority(101)
+
+ # `priority` is a Priority enum value
+ assert get_priority(Priority.HIGHEST) == 0
+ assert get_priority(Priority.LOWEST) == 100
+
+ # `priority` is a string
+ assert get_priority('HIGHEST') == 0
+ assert get_priority('LOWEST') == 100
+
+ # `priority` is an invalid type
+ with pytest.raises(
+ TypeError,
+ match='priority must be an integer or Priority enum value'):
+ get_priority([10])
diff --git a/testbed/open-mmlab__mmengine/tests/test_runner/test_runner.py b/testbed/open-mmlab__mmengine/tests/test_runner/test_runner.py
new file mode 100644
index 0000000000000000000000000000000000000000..acb9b447b25b212a75226ca21fede566a152dc05
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_runner/test_runner.py
@@ -0,0 +1,2348 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import logging
+import os
+import os.path as osp
+import shutil
+import tempfile
+from unittest import TestCase
+
+import numpy as np
+import torch
+import torch.nn as nn
+from torch.nn.parallel import DistributedDataParallel
+from torch.optim import SGD, Adam
+from torch.utils.data import DataLoader, Dataset
+
+from mmengine.config import Config
+from mmengine.dataset import COLLATE_FUNCTIONS, DefaultSampler, pseudo_collate
+from mmengine.evaluator import BaseMetric, Evaluator
+from mmengine.hooks import (CheckpointHook, DistSamplerSeedHook, Hook,
+ IterTimerHook, LoggerHook, ParamSchedulerHook,
+ RuntimeInfoHook)
+from mmengine.logging import MessageHub, MMLogger
+from mmengine.model import BaseDataPreprocessor, BaseModel, ImgDataPreprocessor
+from mmengine.optim import (DefaultOptimWrapperConstructor, MultiStepLR,
+ OptimWrapper, OptimWrapperDict, StepLR)
+from mmengine.registry import (DATASETS, EVALUATOR, HOOKS, LOG_PROCESSORS,
+ LOOPS, METRICS, MODEL_WRAPPERS, MODELS,
+ OPTIM_WRAPPER_CONSTRUCTORS, OPTIM_WRAPPERS,
+ PARAM_SCHEDULERS, RUNNERS, Registry)
+from mmengine.runner import (BaseLoop, EpochBasedTrainLoop, IterBasedTrainLoop,
+ LogProcessor, Runner, TestLoop, ValLoop)
+from mmengine.runner.loops import _InfiniteDataloaderIterator
+from mmengine.runner.priority import Priority, get_priority
+from mmengine.utils import digit_version, is_list_of
+from mmengine.utils.dl_utils import TORCH_VERSION
+from mmengine.visualization import Visualizer
+
+
+class ToyModel(BaseModel):
+
+ def __init__(self, data_preprocessor=None):
+ super().__init__(data_preprocessor=data_preprocessor)
+ self.linear1 = nn.Linear(2, 2)
+ self.linear2 = nn.Linear(2, 1)
+
+ def forward(self, inputs, data_sample, mode='tensor'):
+ if isinstance(inputs, list):
+ inputs = torch.stack(inputs)
+ if isinstance(data_sample, list):
+ data_sample = torch.stack(data_sample)
+ outputs = self.linear1(inputs)
+ outputs = self.linear2(outputs)
+
+ if mode == 'tensor':
+ return outputs
+ elif mode == 'loss':
+ loss = (data_sample - outputs).sum()
+ outputs = dict(loss=loss)
+ return outputs
+ elif mode == 'predict':
+ return outputs
+
+
+class ToyModel1(ToyModel):
+
+ def __init__(self):
+ super().__init__()
+
+
+class ToySyncBNModel(BaseModel):
+
+ def __init__(self):
+ super().__init__()
+ self.conv = nn.Conv2d(3, 8, 2)
+ self.bn = nn.SyncBatchNorm(8)
+
+ def forward(self, inputs, data_sample, mode='tensor'):
+ data_sample = torch.stack(data_sample)
+ inputs = torch.stack(inputs)
+ outputs = self.conv(inputs)
+ outputs = self.bn(outputs)
+
+ if mode == 'tensor':
+ return outputs
+ elif mode == 'loss':
+ loss = (data_sample - outputs).sum()
+ outputs = dict(loss=loss)
+ return outputs
+ elif mode == 'predict':
+ outputs = dict(log_vars=dict(a=1, b=0.5))
+ return outputs
+
+
+class ToyGANModel(BaseModel):
+
+ def __init__(self):
+ super().__init__()
+ self.linear1 = nn.Linear(2, 1)
+ self.linear2 = nn.Linear(2, 1)
+
+ def forward(self, inputs, data_sample, mode='tensor'):
+ data_sample = torch.stack(data_sample)
+ inputs = torch.stack(inputs)
+ output1 = self.linear1(inputs)
+ output2 = self.linear2(inputs)
+
+ if mode == 'tensor':
+ return output1, output2
+ elif mode == 'loss':
+ loss1 = (data_sample - output1).sum()
+ loss2 = (data_sample - output2).sum()
+ outputs = dict(linear1=loss1, linear2=loss2)
+ return outputs
+ elif mode == 'predict':
+ return output1, output2
+
+ def train_step(self, data, optim_wrapper):
+ data = self.data_preprocessor(data)
+ loss = self(**data, mode='loss')
+ optim_wrapper['linear1'].update_params(loss['linear1'])
+ optim_wrapper['linear2'].update_params(loss['linear2'])
+ return loss
+
+
+class CustomModelWrapper(nn.Module):
+
+ def __init__(self, module):
+ super().__init__()
+ self.model = module
+
+
+class ToyMultipleOptimizerConstructor:
+
+ def __init__(self, optim_wrapper_cfg, paramwise_cfg=None):
+ if not isinstance(optim_wrapper_cfg, dict):
+ raise TypeError('optimizer_cfg should be a dict',
+ f'but got {type(optim_wrapper_cfg)}')
+ assert paramwise_cfg is None, (
+ 'parawise_cfg should be set in each optimizer separately')
+ self.optim_wrapper_cfg = optim_wrapper_cfg
+ self.constructors = {}
+ for key, cfg in self.optim_wrapper_cfg.items():
+ _cfg = cfg.copy()
+ paramwise_cfg_ = _cfg.pop('paramwise_cfg', None)
+ self.constructors[key] = DefaultOptimWrapperConstructor(
+ _cfg, paramwise_cfg_)
+
+ def __call__(self, model: nn.Module) -> OptimWrapperDict:
+ optimizers = {}
+ while hasattr(model, 'module'):
+ model = model.module
+
+ for key, constructor in self.constructors.items():
+ module = getattr(model, key)
+ optimizers[key] = constructor(module)
+ return OptimWrapperDict(**optimizers)
+
+
+class ToyDataset(Dataset):
+ METAINFO = dict() # type: ignore
+ data = torch.randn(12, 2)
+ label = torch.ones(12)
+
+ @property
+ def metainfo(self):
+ return self.METAINFO
+
+ def __len__(self):
+ return self.data.size(0)
+
+ def __getitem__(self, index):
+ return dict(inputs=self.data[index], data_sample=self.label[index])
+
+
+class ToyDatasetNoMeta(Dataset):
+ data = torch.randn(12, 2)
+ label = torch.ones(12)
+
+ def __len__(self):
+ return self.data.size(0)
+
+ def __getitem__(self, index):
+ return dict(inputs=self.data[index], data_sample=self.label[index])
+
+
+class ToyMetric1(BaseMetric):
+
+ def __init__(self, collect_device='cpu', dummy_metrics=None):
+ super().__init__(collect_device=collect_device)
+ self.dummy_metrics = dummy_metrics
+
+ def process(self, data_batch, predictions):
+ result = {'acc': 1}
+ self.results.append(result)
+
+ def compute_metrics(self, results):
+ return dict(acc=1)
+
+
+class ToyMetric2(BaseMetric):
+
+ def __init__(self, collect_device='cpu', dummy_metrics=None):
+ super().__init__(collect_device=collect_device)
+ self.dummy_metrics = dummy_metrics
+
+ def process(self, data_batch, predictions):
+ result = {'acc': 1}
+ self.results.append(result)
+
+ def compute_metrics(self, results):
+ return dict(acc=1)
+
+
+class ToyOptimWrapper(OptimWrapper):
+ ...
+
+
+class ToyHook(Hook):
+ priority = 'Lowest'
+
+ def before_train_epoch(self, runner):
+ pass
+
+
+class ToyHook2(Hook):
+ priority = 'Lowest'
+
+ def after_train_epoch(self, runner):
+ pass
+
+
+class CustomTrainLoop(BaseLoop):
+
+ def __init__(self, runner, dataloader, max_epochs):
+ super().__init__(runner, dataloader)
+ self._max_epochs = max_epochs
+
+ def run(self) -> None:
+ pass
+
+
+class CustomValLoop(BaseLoop):
+
+ def __init__(self, runner, dataloader, evaluator):
+ super().__init__(runner, dataloader)
+ self._runner = runner
+
+ if isinstance(evaluator, dict) or is_list_of(evaluator, dict):
+ self.evaluator = runner.build_evaluator(evaluator) # type: ignore
+ else:
+ self.evaluator = evaluator
+
+ def run(self) -> None:
+ pass
+
+
+class CustomTestLoop(BaseLoop):
+
+ def __init__(self, runner, dataloader, evaluator):
+ super().__init__(runner, dataloader)
+ self._runner = runner
+
+ if isinstance(evaluator, dict) or is_list_of(evaluator, dict):
+ self.evaluator = runner.build_evaluator(evaluator) # type: ignore
+ else:
+ self.evaluator = evaluator
+
+ def run(self) -> None:
+ pass
+
+
+class CustomLogProcessor(LogProcessor):
+
+ def __init__(self, window_size=10, by_epoch=True, custom_cfg=None):
+ self.window_size = window_size
+ self.by_epoch = by_epoch
+ self.custom_cfg = custom_cfg if custom_cfg else []
+ self._check_custom_cfg()
+
+
+class CustomRunner(Runner):
+
+ def __init__(self,
+ model,
+ work_dir,
+ train_dataloader=None,
+ val_dataloader=None,
+ test_dataloader=None,
+ train_cfg=None,
+ val_cfg=None,
+ test_cfg=None,
+ auto_scale_lr=None,
+ optim_wrapper=None,
+ param_scheduler=None,
+ val_evaluator=None,
+ test_evaluator=None,
+ default_hooks=None,
+ custom_hooks=None,
+ data_preprocessor=None,
+ load_from=None,
+ resume=False,
+ launcher='none',
+ env_cfg=dict(dist_cfg=dict(backend='nccl')),
+ log_processor=None,
+ log_level='INFO',
+ visualizer=None,
+ default_scope=None,
+ randomness=dict(seed=None),
+ experiment_name=None,
+ cfg=None):
+ pass
+
+ def setup_env(self, env_cfg):
+ pass
+
+
+class ToyEvaluator(Evaluator):
+
+ def __init__(self, metrics):
+ super().__init__(metrics)
+
+
+def collate_fn(data_batch):
+ return pseudo_collate(data_batch)
+
+
+def custom_collate(data_batch, pad_value):
+ return pseudo_collate(data_batch)
+
+
+class TestRunner(TestCase):
+
+ def setUp(self):
+ MODELS.register_module(module=ToyModel, force=True)
+ MODELS.register_module(module=ToyModel1, force=True)
+ MODELS.register_module(module=ToySyncBNModel, force=True)
+ MODELS.register_module(module=ToyGANModel, force=True)
+ MODEL_WRAPPERS.register_module(module=CustomModelWrapper, force=True)
+ OPTIM_WRAPPER_CONSTRUCTORS.register_module(
+ module=ToyMultipleOptimizerConstructor, force=True)
+ DATASETS.register_module(module=ToyDataset, force=True)
+ DATASETS.register_module(module=ToyDatasetNoMeta, force=True)
+ METRICS.register_module(module=ToyMetric1, force=True)
+ METRICS.register_module(module=ToyMetric2, force=True)
+ OPTIM_WRAPPERS.register_module(module=ToyOptimWrapper, force=True)
+ HOOKS.register_module(module=ToyHook, force=True)
+ HOOKS.register_module(module=ToyHook2, force=True)
+ LOOPS.register_module(module=CustomTrainLoop, force=True)
+ LOOPS.register_module(module=CustomValLoop, force=True)
+ LOOPS.register_module(module=CustomTestLoop, force=True)
+ LOG_PROCESSORS.register_module(module=CustomLogProcessor, force=True)
+ RUNNERS.register_module(module=CustomRunner, force=True)
+ EVALUATOR.register_module(module=ToyEvaluator, force=True)
+ COLLATE_FUNCTIONS.register_module(module=custom_collate, force=True)
+
+ self.temp_dir = tempfile.mkdtemp()
+ epoch_based_cfg = dict(
+ model=dict(type='ToyModel'),
+ work_dir=self.temp_dir,
+ train_dataloader=dict(
+ dataset=dict(type='ToyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ batch_size=3,
+ num_workers=0),
+ val_dataloader=dict(
+ dataset=dict(type='ToyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=False),
+ batch_size=3,
+ num_workers=0),
+ test_dataloader=dict(
+ dataset=dict(type='ToyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=False),
+ batch_size=3,
+ num_workers=0),
+ auto_scale_lr=dict(base_batch_size=16, enable=False),
+ optim_wrapper=dict(
+ type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01)),
+ param_scheduler=dict(type='MultiStepLR', milestones=[1, 2]),
+ val_evaluator=dict(type='ToyMetric1'),
+ test_evaluator=dict(type='ToyMetric1'),
+ train_cfg=dict(
+ by_epoch=True, max_epochs=3, val_interval=1, val_begin=1),
+ val_cfg=dict(),
+ test_cfg=dict(),
+ custom_hooks=[],
+ default_hooks=dict(
+ runtime_info=dict(type='RuntimeInfoHook'),
+ timer=dict(type='IterTimerHook'),
+ logger=dict(type='LoggerHook'),
+ param_scheduler=dict(type='ParamSchedulerHook'),
+ checkpoint=dict(
+ type='CheckpointHook', interval=1, by_epoch=True),
+ sampler_seed=dict(type='DistSamplerSeedHook')),
+ data_preprocessor=None,
+ launcher='none',
+ env_cfg=dict(dist_cfg=dict(backend='nccl')),
+ )
+ self.epoch_based_cfg = Config(epoch_based_cfg)
+ self.iter_based_cfg = copy.deepcopy(self.epoch_based_cfg)
+ self.iter_based_cfg.train_dataloader = dict(
+ dataset=dict(type='ToyDataset'),
+ sampler=dict(type='InfiniteSampler', shuffle=True),
+ batch_size=3,
+ num_workers=0)
+ self.iter_based_cfg.train_cfg = dict(by_epoch=False, max_iters=12)
+ self.iter_based_cfg.default_hooks = dict(
+ runtime_info=dict(type='RuntimeInfoHook'),
+ timer=dict(type='IterTimerHook'),
+ logger=dict(type='LoggerHook'),
+ param_scheduler=dict(type='ParamSchedulerHook'),
+ checkpoint=dict(type='CheckpointHook', interval=1, by_epoch=False),
+ sampler_seed=dict(type='DistSamplerSeedHook'))
+
+ def tearDown(self):
+ # `FileHandler` should be closed in Windows, otherwise we cannot
+ # delete the temporary directory
+ MODELS.module_dict.pop('ToyModel')
+ MODELS.module_dict.pop('ToyModel1')
+ MODELS.module_dict.pop('ToySyncBNModel')
+ MODELS.module_dict.pop('ToyGANModel')
+ MODEL_WRAPPERS.module_dict.pop('CustomModelWrapper')
+ OPTIM_WRAPPER_CONSTRUCTORS.module_dict.pop(
+ 'ToyMultipleOptimizerConstructor')
+ OPTIM_WRAPPERS.module_dict.pop('ToyOptimWrapper')
+ DATASETS.module_dict.pop('ToyDataset')
+ DATASETS.module_dict.pop('ToyDatasetNoMeta')
+ METRICS.module_dict.pop('ToyMetric1')
+ METRICS.module_dict.pop('ToyMetric2')
+ HOOKS.module_dict.pop('ToyHook')
+ HOOKS.module_dict.pop('ToyHook2')
+ LOOPS.module_dict.pop('CustomTrainLoop')
+ LOOPS.module_dict.pop('CustomValLoop')
+ LOOPS.module_dict.pop('CustomTestLoop')
+ LOG_PROCESSORS.module_dict.pop('CustomLogProcessor')
+ RUNNERS.module_dict.pop('CustomRunner')
+ EVALUATOR.module_dict.pop('ToyEvaluator')
+ COLLATE_FUNCTIONS.module_dict.pop('custom_collate')
+
+ logging.shutdown()
+ MMLogger._instance_dict.clear()
+ shutil.rmtree(self.temp_dir)
+
+ def test_init(self):
+ # 1. test arguments
+ # 1.1 train_dataloader, train_cfg, optimizer and param_scheduler
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_init1'
+ cfg.pop('train_cfg')
+ with self.assertRaisesRegex(ValueError, 'either all None or not None'):
+ Runner(**cfg)
+
+ # all of training related configs are None and param_scheduler should
+ # also be None
+ cfg.experiment_name = 'test_init2'
+ cfg.pop('train_dataloader')
+ cfg.pop('optim_wrapper')
+ cfg.pop('param_scheduler')
+ runner = Runner(**cfg)
+ self.assertIsInstance(runner, Runner)
+
+ # all of training related configs are not None
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_init3'
+ runner = Runner(**cfg)
+ self.assertIsInstance(runner, Runner)
+
+ # all of training related configs are not None and param_scheduler
+ # can be None
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_init4'
+ cfg.pop('param_scheduler')
+ runner = Runner(**cfg)
+ self.assertIsInstance(runner, Runner)
+ self.assertEqual(runner.param_schedulers, None)
+
+ # param_scheduler should be None when optimizer is None
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_init5'
+ cfg.pop('train_cfg')
+ cfg.pop('train_dataloader')
+ cfg.pop('optim_wrapper')
+ with self.assertRaisesRegex(ValueError, 'should be None'):
+ runner = Runner(**cfg)
+
+ # 1.2 val_dataloader, val_evaluator, val_cfg
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_init6'
+ cfg.pop('val_cfg')
+ with self.assertRaisesRegex(ValueError, 'either all None or not None'):
+ Runner(**cfg)
+
+ cfg.experiment_name = 'test_init7'
+ cfg.pop('val_dataloader')
+ cfg.pop('val_evaluator')
+ runner = Runner(**cfg)
+ self.assertIsInstance(runner, Runner)
+
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_init8'
+ runner = Runner(**cfg)
+ self.assertIsInstance(runner, Runner)
+
+ # 1.3 test_dataloader, test_evaluator and test_cfg
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_init9'
+ cfg.pop('test_cfg')
+ with self.assertRaisesRegex(ValueError, 'either all None or not None'):
+ runner = Runner(**cfg)
+
+ cfg.experiment_name = 'test_init10'
+ cfg.pop('test_dataloader')
+ cfg.pop('test_evaluator')
+ runner = Runner(**cfg)
+ self.assertIsInstance(runner, Runner)
+
+ # 1.4 test env params
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_init11'
+ runner = Runner(**cfg)
+ self.assertFalse(runner.distributed)
+ self.assertFalse(runner.deterministic)
+
+ # 1.5 message_hub, logger and visualizer
+ # they are all not specified
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_init12'
+ runner = Runner(**cfg)
+ self.assertIsInstance(runner.logger, MMLogger)
+ self.assertIsInstance(runner.message_hub, MessageHub)
+ self.assertIsInstance(runner.visualizer, Visualizer)
+
+ # they are all specified
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_init13'
+ cfg.log_level = 'INFO'
+ cfg.visualizer = None
+ runner = Runner(**cfg)
+ self.assertIsInstance(runner.logger, MMLogger)
+ self.assertIsInstance(runner.message_hub, MessageHub)
+ self.assertIsInstance(runner.visualizer, Visualizer)
+
+ assert runner.distributed is False
+ assert runner.seed is not None
+ assert runner.work_dir == self.temp_dir
+
+ # 2 model should be initialized
+ self.assertIsInstance(runner.model,
+ (nn.Module, DistributedDataParallel))
+ self.assertEqual(runner.model_name, 'ToyModel')
+
+ # 3. test lazy initialization
+ self.assertIsInstance(runner._train_dataloader, dict)
+ self.assertIsInstance(runner._val_dataloader, dict)
+ self.assertIsInstance(runner._test_dataloader, dict)
+ self.assertIsInstance(runner.optim_wrapper, dict)
+ self.assertIsInstance(runner.param_schedulers, dict)
+
+ # After calling runner.train(),
+ # train_dataloader and val_loader should be initialized but
+ # test_dataloader should also be dict
+ runner.train()
+
+ self.assertIsInstance(runner._train_loop, BaseLoop)
+ self.assertIsInstance(runner.train_dataloader, DataLoader)
+ self.assertIsInstance(runner.optim_wrapper, OptimWrapper)
+ self.assertIsInstance(runner.param_schedulers[0], MultiStepLR)
+ self.assertIsInstance(runner._val_loop, BaseLoop)
+ self.assertIsInstance(runner._val_loop.dataloader, DataLoader)
+ self.assertIsInstance(runner._val_loop.evaluator, Evaluator)
+
+ # After calling runner.test(), test_dataloader should be initialized
+ self.assertIsInstance(runner._test_loop, dict)
+ runner.test()
+ self.assertIsInstance(runner._test_loop, BaseLoop)
+ self.assertIsInstance(runner._test_loop.dataloader, DataLoader)
+ self.assertIsInstance(runner._test_loop.evaluator, Evaluator)
+
+ # 4. initialize runner with objects rather than config
+ model = ToyModel()
+ optim_wrapper = OptimWrapper(SGD(
+ model.parameters(),
+ lr=0.01,
+ ))
+ toy_hook = ToyHook()
+ toy_hook2 = ToyHook2()
+
+ train_dataloader = DataLoader(ToyDataset(), collate_fn=collate_fn)
+ val_dataloader = DataLoader(ToyDataset(), collate_fn=collate_fn)
+ test_dataloader = DataLoader(ToyDataset(), collate_fn=collate_fn)
+ runner = Runner(
+ model=model,
+ work_dir=self.temp_dir,
+ train_cfg=dict(
+ by_epoch=True, max_epochs=3, val_interval=1, val_begin=1),
+ train_dataloader=train_dataloader,
+ optim_wrapper=optim_wrapper,
+ param_scheduler=MultiStepLR(optim_wrapper, milestones=[1, 2]),
+ val_cfg=dict(),
+ val_dataloader=val_dataloader,
+ val_evaluator=[ToyMetric1()],
+ test_cfg=dict(),
+ test_dataloader=test_dataloader,
+ test_evaluator=[ToyMetric1()],
+ default_hooks=dict(param_scheduler=toy_hook),
+ custom_hooks=[toy_hook2],
+ experiment_name='test_init14')
+ runner.train()
+ runner.test()
+
+ # 5. Test building multiple runners. In Windows, nccl could not be
+ # available, and this test will be skipped.
+ if torch.cuda.is_available() and torch.distributed.is_nccl_available():
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_init15'
+ cfg.launcher = 'pytorch'
+ os.environ['MASTER_ADDR'] = '127.0.0.1'
+ os.environ['MASTER_PORT'] = '29600'
+ os.environ['RANK'] = '0'
+ os.environ['WORLD_SIZE'] = '1'
+ os.environ['LOCAL_RANK'] = '0'
+ Runner(**cfg)
+ cfg.experiment_name = 'test_init16'
+ Runner(**cfg)
+
+ # 6.1 Test initializing with empty scheduler.
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_init17'
+ cfg.param_scheduler = None
+ runner = Runner(**cfg)
+ self.assertIsNone(runner.param_schedulers)
+
+ # 6.2 Test initializing single scheduler.
+ cfg.experiment_name = 'test_init18'
+ cfg.param_scheduler = dict(type='MultiStepLR', milestones=[1, 2])
+ Runner(**cfg)
+
+ # 6.3 Test initializing list of scheduler.
+ cfg.param_scheduler = [
+ dict(type='MultiStepLR', milestones=[1, 2]),
+ dict(type='MultiStepLR', milestones=[2, 3])
+ ]
+ cfg.experiment_name = 'test_init19'
+ Runner(**cfg)
+
+ # 6.4 Test initializing 2 schedulers for 2 optimizers.
+ cfg.param_scheduler = dict(
+ linear1=dict(type='MultiStepLR', milestones=[1, 2]),
+ linear2=dict(type='MultiStepLR', milestones=[1, 2]),
+ )
+ cfg.experiment_name = 'test_init20'
+ Runner(**cfg)
+
+ # 6.5 Test initializing 2 schedulers for 2 optimizers.
+ cfg.param_scheduler = dict(
+ linear1=[dict(type='MultiStepLR', milestones=[1, 2])],
+ linear2=[dict(type='MultiStepLR', milestones=[1, 2])],
+ )
+ cfg.experiment_name = 'test_init21'
+ Runner(**cfg)
+
+ # 6.6 Test initializing with `_ParameterScheduler`.
+ optimizer = SGD(nn.Linear(1, 1).parameters(), lr=0.1)
+ cfg.param_scheduler = MultiStepLR(
+ milestones=[1, 2], optimizer=optimizer)
+ cfg.experiment_name = 'test_init22'
+ Runner(**cfg)
+
+ # 6.7 Test initializing with list of `_ParameterScheduler`.
+ cfg.param_scheduler = [
+ MultiStepLR(milestones=[1, 2], optimizer=optimizer)
+ ]
+ cfg.experiment_name = 'test_init23'
+ Runner(**cfg)
+
+ # 6.8 Test initializing with 2 `_ParameterScheduler` for 2 optimizers.
+ cfg.param_scheduler = dict(
+ linear1=MultiStepLR(milestones=[1, 2], optimizer=optimizer),
+ linear2=MultiStepLR(milestones=[1, 2], optimizer=optimizer))
+ cfg.experiment_name = 'test_init24'
+ Runner(**cfg)
+
+ # 6.9 Test initializing with 2 list of `_ParameterScheduler` for 2
+ # optimizers.
+ cfg.param_scheduler = dict(
+ linear1=[MultiStepLR(milestones=[1, 2], optimizer=optimizer)],
+ linear2=[MultiStepLR(milestones=[1, 2], optimizer=optimizer)])
+ cfg.experiment_name = 'test_init25'
+ Runner(**cfg)
+
+ # 6.10 Test initializing with error type scheduler.
+ cfg.param_scheduler = dict(linear1='error_type')
+ cfg.experiment_name = 'test_init26'
+ with self.assertRaisesRegex(AssertionError, 'Each value of'):
+ Runner(**cfg)
+
+ cfg.param_scheduler = 'error_type'
+ cfg.experiment_name = 'test_init27'
+ with self.assertRaisesRegex(TypeError,
+ '`param_scheduler` should be a'):
+ Runner(**cfg)
+
+ def test_dump_config(self):
+ # dump config from dict.
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ for idx, cfg in enumerate((cfg, cfg._cfg_dict)):
+ cfg.experiment_name = f'test_dump{idx}'
+ runner = Runner.from_cfg(cfg=cfg)
+ assert osp.exists(
+ osp.join(runner.work_dir, f'{runner.timestamp}.py'))
+ # dump config from file.
+ with tempfile.TemporaryDirectory() as temp_config_dir:
+ # Set `delete=Flase` and close the file to make it
+ # work in Windows.
+ temp_config_file = tempfile.NamedTemporaryFile(
+ dir=temp_config_dir, suffix='.py', delete=False)
+ temp_config_file.close()
+ file_cfg = Config(
+ self.epoch_based_cfg._cfg_dict,
+ filename=temp_config_file.name)
+ file_cfg.experiment_name = f'test_dump2{idx}'
+ runner = Runner.from_cfg(cfg=file_cfg)
+ assert osp.exists(
+ osp.join(runner.work_dir,
+ osp.basename(temp_config_file.name)))
+
+ def test_from_cfg(self):
+ runner = Runner.from_cfg(cfg=self.epoch_based_cfg)
+ self.assertIsInstance(runner, Runner)
+
+ def test_setup_env(self):
+ # TODO
+ pass
+
+ def test_build_logger(self):
+ self.epoch_based_cfg.experiment_name = 'test_build_logger1'
+ runner = Runner.from_cfg(self.epoch_based_cfg)
+ self.assertIsInstance(runner.logger, MMLogger)
+ self.assertEqual(runner.experiment_name, runner.logger.instance_name)
+
+ # input is a dict
+ logger = runner.build_logger(name='test_build_logger2')
+ self.assertIsInstance(logger, MMLogger)
+ self.assertEqual(logger.instance_name, 'test_build_logger2')
+
+ # input is a dict but does not contain name key
+ runner._experiment_name = 'test_build_logger3'
+ logger = runner.build_logger()
+ self.assertIsInstance(logger, MMLogger)
+ self.assertEqual(logger.instance_name, 'test_build_logger3')
+
+ def test_build_message_hub(self):
+ self.epoch_based_cfg.experiment_name = 'test_build_message_hub1'
+ runner = Runner.from_cfg(self.epoch_based_cfg)
+ self.assertIsInstance(runner.message_hub, MessageHub)
+ self.assertEqual(runner.message_hub.instance_name,
+ runner.experiment_name)
+
+ # input is a dict
+ message_hub_cfg = dict(name='test_build_message_hub2')
+ message_hub = runner.build_message_hub(message_hub_cfg)
+ self.assertIsInstance(message_hub, MessageHub)
+ self.assertEqual(message_hub.instance_name, 'test_build_message_hub2')
+
+ # input is a dict but does not contain name key
+ runner._experiment_name = 'test_build_message_hub3'
+ message_hub_cfg = dict()
+ message_hub = runner.build_message_hub(message_hub_cfg)
+ self.assertIsInstance(message_hub, MessageHub)
+ self.assertEqual(message_hub.instance_name, 'test_build_message_hub3')
+
+ # input is not a valid type
+ with self.assertRaisesRegex(TypeError, 'message_hub should be'):
+ runner.build_message_hub('invalid-type')
+
+ def test_build_visualizer(self):
+ self.epoch_based_cfg.experiment_name = 'test_build_visualizer1'
+ runner = Runner.from_cfg(self.epoch_based_cfg)
+ self.assertIsInstance(runner.visualizer, Visualizer)
+ self.assertEqual(runner.experiment_name,
+ runner.visualizer.instance_name)
+
+ # input is a Visualizer object
+ self.assertEqual(
+ id(runner.build_visualizer(runner.visualizer)),
+ id(runner.visualizer))
+
+ # input is a dict
+ visualizer_cfg = dict(type='Visualizer', name='test_build_visualizer2')
+ visualizer = runner.build_visualizer(visualizer_cfg)
+ self.assertIsInstance(visualizer, Visualizer)
+ self.assertEqual(visualizer.instance_name, 'test_build_visualizer2')
+
+ # input is a dict but does not contain name key
+ runner._experiment_name = 'test_build_visualizer3'
+ visualizer_cfg = None
+ visualizer = runner.build_visualizer(visualizer_cfg)
+ self.assertIsInstance(visualizer, Visualizer)
+ self.assertEqual(visualizer.instance_name, 'test_build_visualizer3')
+
+ # input is not a valid type
+ with self.assertRaisesRegex(TypeError, 'visualizer should be'):
+ runner.build_visualizer('invalid-type')
+
+ def test_default_scope(self):
+ TOY_SCHEDULERS = Registry(
+ 'parameter scheduler', parent=PARAM_SCHEDULERS, scope='toy')
+
+ @TOY_SCHEDULERS.register_module(force=True)
+ class ToyScheduler(MultiStepLR):
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ self.epoch_based_cfg.param_scheduler = dict(
+ type='ToyScheduler', milestones=[1, 2])
+ self.epoch_based_cfg.default_scope = 'toy'
+
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_default_scope'
+ runner = Runner.from_cfg(cfg)
+ runner.train()
+ self.assertIsInstance(runner.param_schedulers[0], ToyScheduler)
+
+ def test_build_model(self):
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_build_model1'
+ runner = Runner.from_cfg(cfg)
+ self.assertIsInstance(runner.model, ToyModel)
+ self.assertIsInstance(runner.model.data_preprocessor,
+ BaseDataPreprocessor)
+
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_data_preprocessor'
+ cfg.data_preprocessor = dict(type='ImgDataPreprocessor')
+ runner = Runner.from_cfg(cfg)
+ # data_preprocessor is passed to used if no `data_preprocessor`
+ # in model config.
+ self.assertIsInstance(runner.model.data_preprocessor,
+ ImgDataPreprocessor)
+
+ # input should be a nn.Module object or dict
+ with self.assertRaisesRegex(TypeError, 'model should be'):
+ runner.build_model('invalid-type')
+
+ # input is a nn.Module object
+ _model = ToyModel1()
+ model = runner.build_model(_model)
+ self.assertEqual(id(model), id(_model))
+
+ # input is a dict
+ model = runner.build_model(dict(type='ToyModel1'))
+ self.assertIsInstance(model, ToyModel1)
+
+ def test_wrap_model(self):
+ # revert sync batchnorm
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_revert_syncbn'
+ cfg.model = dict(type='ToySyncBNModel')
+ runner = Runner.from_cfg(cfg)
+ self.assertIsInstance(runner.model, BaseModel)
+ assert not isinstance(runner.model.bn, nn.SyncBatchNorm)
+
+ # custom model wrapper
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_wrap_model'
+ cfg.model_wrapper_cfg = dict(type='CustomModelWrapper')
+ runner = Runner.from_cfg(cfg)
+ self.assertIsInstance(runner.model, BaseModel)
+
+ # Test with ddp wrapper
+ if torch.cuda.is_available() and torch.distributed.is_nccl_available():
+ os.environ['MASTER_ADDR'] = '127.0.0.1'
+ os.environ['MASTER_PORT'] = '29515'
+ os.environ['RANK'] = str(0)
+ os.environ['WORLD_SIZE'] = str(1)
+ cfg.launcher = 'pytorch'
+ cfg.experiment_name = 'test_wrap_model1'
+ runner = Runner.from_cfg(cfg)
+ self.assertIsInstance(runner.model, CustomModelWrapper)
+
+ # Test cfg.sync_bn = 'torch', when model does not have BN layer
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.launcher = 'pytorch'
+ cfg.experiment_name = 'test_wrap_model2'
+ cfg.sync_bn = 'torch'
+ cfg.model_wrapper_cfg = dict(type='CustomModelWrapper')
+ runner.from_cfg(cfg)
+
+ @MODELS.register_module(force=True)
+ class ToyBN(BaseModel):
+
+ def __init__(self):
+ super().__init__()
+ self.bn = nn.BatchNorm2d(2)
+
+ def forward(self, *args, **kwargs):
+ pass
+
+ cfg.model = dict(type='ToyBN')
+ cfg.experiment_name = 'test_data_preprocessor2'
+ runner = Runner.from_cfg(cfg)
+ self.assertIsInstance(runner.model.model.bn,
+ torch.nn.SyncBatchNorm)
+
+ cfg.sync_bn = 'unknown'
+ cfg.experiment_name = 'test_data_preprocessor3'
+ with self.assertRaises(ValueError):
+ Runner.from_cfg(cfg)
+
+ def test_scale_lr(self):
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_scale_lr'
+ runner = Runner.from_cfg(cfg)
+
+ # When no base_batch_size in auto_scale_lr, an
+ # assertion error will raise.
+ auto_scale_lr = dict(enable=True)
+ optim_wrapper = OptimWrapper(SGD(runner.model.parameters(), lr=0.01))
+ with self.assertRaises(AssertionError):
+ runner.scale_lr(optim_wrapper, auto_scale_lr)
+
+ # When auto_scale_lr is None or enable is False, the lr will
+ # not be linearly scaled.
+ auto_scale_lr = dict(base_batch_size=16, enable=False)
+ optim_wrapper = OptimWrapper(SGD(runner.model.parameters(), lr=0.01))
+ runner.scale_lr(optim_wrapper)
+ self.assertEqual(optim_wrapper.optimizer.param_groups[0]['lr'], 0.01)
+ runner.scale_lr(optim_wrapper, auto_scale_lr)
+ self.assertEqual(optim_wrapper.optimizer.param_groups[0]['lr'], 0.01)
+
+ # When auto_scale_lr is correct and enable is True, the lr will
+ # be linearly scaled.
+ auto_scale_lr = dict(base_batch_size=16, enable=True)
+ real_bs = runner.world_size * cfg.train_dataloader['batch_size']
+ optim_wrapper = OptimWrapper(SGD(runner.model.parameters(), lr=0.01))
+ runner.scale_lr(optim_wrapper, auto_scale_lr)
+ self.assertEqual(optim_wrapper.optimizer.param_groups[0]['lr'],
+ 0.01 * (real_bs / 16))
+
+ # Test when optim_wrapper is an OptimWrapperDict
+ optim_wrapper = OptimWrapper(SGD(runner.model.parameters(), lr=0.01))
+ wrapper_dict = OptimWrapperDict(wrapper=optim_wrapper)
+ runner.scale_lr(wrapper_dict, auto_scale_lr)
+ scaled_lr = wrapper_dict['wrapper'].optimizer.param_groups[0]['lr']
+ self.assertEqual(scaled_lr, 0.01 * (real_bs / 16))
+
+ def test_build_optim_wrapper(self):
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_build_optim_wrapper'
+ runner = Runner.from_cfg(cfg)
+
+ # input should be an Optimizer object or dict
+ with self.assertRaisesRegex(TypeError, 'optimizer wrapper should be'):
+ runner.build_optim_wrapper('invalid-type')
+
+ # 1. test one optimizer
+ # 1.1 input is an Optimizer object
+ optimizer = SGD(runner.model.parameters(), lr=0.01)
+ optim_wrapper = OptimWrapper(optimizer)
+ optim_wrapper = runner.build_optim_wrapper(optim_wrapper)
+ self.assertEqual(id(optimizer), id(optim_wrapper.optimizer))
+
+ # 1.2 input is a dict
+ optim_wrapper = runner.build_optim_wrapper(
+ dict(type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01)))
+ self.assertIsInstance(optim_wrapper, OptimWrapper)
+
+ # 1.3 use default OptimWrapper type.
+ optim_wrapper = runner.build_optim_wrapper(
+ dict(optimizer=dict(type='SGD', lr=0.01)))
+ self.assertIsInstance(optim_wrapper, OptimWrapper)
+
+ # 2. test multiple optmizers
+ # 2.1 input is a dict which contains multiple optimizer objects
+ optimizer1 = SGD(runner.model.linear1.parameters(), lr=0.01)
+ optim_wrapper1 = OptimWrapper(optimizer1)
+ optimizer2 = Adam(runner.model.linear2.parameters(), lr=0.02)
+ optim_wrapper2 = OptimWrapper(optimizer2)
+ optim_wrapper_cfg = dict(key1=optim_wrapper1, key2=optim_wrapper2)
+ optim_wrapper = runner.build_optim_wrapper(optim_wrapper_cfg)
+ self.assertIsInstance(optim_wrapper, OptimWrapperDict)
+ self.assertIsInstance(optim_wrapper['key1'].optimizer, SGD)
+ self.assertIsInstance(optim_wrapper['key2'].optimizer, Adam)
+
+ # 2.2 each item mush be an optimizer object when "type" and
+ # "constructor" are not in optimizer
+ optimizer1 = SGD(runner.model.linear1.parameters(), lr=0.01)
+ optim_wrapper1 = OptimWrapper(optimizer1)
+ optim_wrapper2 = dict(
+ type='OptimWrapper', optimizer=dict(type='Adam', lr=0.01))
+ optim_cfg = dict(key1=optim_wrapper1, key2=optim_wrapper2)
+ with self.assertRaisesRegex(ValueError,
+ 'each item mush be an optimizer object'):
+ runner.build_optim_wrapper(optim_cfg)
+
+ # 2.3 input is a dict which contains multiple configs
+ optim_wrapper_cfg = dict(
+ linear1=dict(
+ type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01)),
+ linear2=dict(
+ type='OptimWrapper', optimizer=dict(type='Adam', lr=0.02)),
+ constructor='ToyMultipleOptimizerConstructor')
+ optim_wrapper = runner.build_optim_wrapper(optim_wrapper_cfg)
+ self.assertIsInstance(optim_wrapper, OptimWrapperDict)
+ self.assertIsInstance(optim_wrapper['linear1'].optimizer, SGD)
+ self.assertIsInstance(optim_wrapper['linear2'].optimizer, Adam)
+
+ # 2.4 input is a dict which contains optimizer instance.
+ model = nn.Linear(1, 1)
+ optimizer = SGD(model.parameters(), lr=0.1)
+ optim_wrapper_cfg = dict(optimizer=optimizer)
+ optim_wrapper = runner.build_optim_wrapper(optim_wrapper_cfg)
+ self.assertIsInstance(optim_wrapper, OptimWrapper)
+ self.assertIs(optim_wrapper.optimizer, optimizer)
+
+ # Specify the type of optimizer wrapper
+ model = nn.Linear(1, 1)
+ optimizer = SGD(model.parameters(), lr=0.1)
+ optim_wrapper_cfg = dict(
+ optimizer=optimizer, type='ToyOptimWrapper', accumulative_counts=2)
+ optim_wrapper = runner.build_optim_wrapper(optim_wrapper_cfg)
+ self.assertIsInstance(optim_wrapper, ToyOptimWrapper)
+ self.assertIs(optim_wrapper.optimizer, optimizer)
+ self.assertEqual(optim_wrapper._accumulative_counts, 2)
+
+ def test_build_param_scheduler(self):
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_build_param_scheduler'
+ runner = Runner.from_cfg(cfg)
+
+ # `build_optim_wrapper` should be called before
+ # `build_param_scheduler`
+ cfg = dict(type='MultiStepLR', milestones=[1, 2])
+ runner.optim_wrapper = dict(
+ key1=dict(
+ type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01)),
+ key2=dict(
+ type='OptimWrapper', optimizer=dict(type='Adam', lr=0.02)),
+ )
+ with self.assertRaisesRegex(AssertionError, 'should be called before'):
+ runner.build_param_scheduler(cfg)
+
+ runner.optim_wrapper = runner.build_optim_wrapper(
+ dict(type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01)))
+ param_schedulers = runner.build_param_scheduler(cfg)
+ self.assertIsInstance(param_schedulers, list)
+ self.assertEqual(len(param_schedulers), 1)
+ self.assertIsInstance(param_schedulers[0], MultiStepLR)
+
+ # 1. test one optimizer and one parameter scheduler
+ # 1.1 input is a ParamScheduler object
+ param_scheduler = MultiStepLR(runner.optim_wrapper, milestones=[1, 2])
+ param_schedulers = runner.build_param_scheduler(param_scheduler)
+ self.assertEqual(len(param_schedulers), 1)
+ self.assertEqual(id(param_schedulers[0]), id(param_scheduler))
+
+ # 1.2 input is a dict
+ param_schedulers = runner.build_param_scheduler(param_scheduler)
+ self.assertEqual(len(param_schedulers), 1)
+ self.assertIsInstance(param_schedulers[0], MultiStepLR)
+
+ # 2. test one optimizer and list of parameter schedulers
+ # 2.1 input is a list of dict
+ cfg = [
+ dict(type='MultiStepLR', milestones=[1, 2]),
+ dict(type='StepLR', step_size=1)
+ ]
+ param_schedulers = runner.build_param_scheduler(cfg)
+ self.assertEqual(len(param_schedulers), 2)
+ self.assertIsInstance(param_schedulers[0], MultiStepLR)
+ self.assertIsInstance(param_schedulers[1], StepLR)
+
+ # 2.2 input is a list and some items are ParamScheduler objects
+ cfg = [param_scheduler, dict(type='StepLR', step_size=1)]
+ param_schedulers = runner.build_param_scheduler(cfg)
+ self.assertEqual(len(param_schedulers), 2)
+ self.assertIsInstance(param_schedulers[0], MultiStepLR)
+ self.assertIsInstance(param_schedulers[1], StepLR)
+
+ # 3. test multiple optimizers and list of parameter schedulers
+ optimizer1 = SGD(runner.model.linear1.parameters(), lr=0.01)
+ optim_wrapper1 = OptimWrapper(optimizer1)
+ optimizer2 = Adam(runner.model.linear2.parameters(), lr=0.02)
+ optim_wrapper2 = OptimWrapper(optimizer2)
+ optim_wrapper_cfg = dict(key1=optim_wrapper1, key2=optim_wrapper2)
+ runner.optim_wrapper = runner.build_optim_wrapper(optim_wrapper_cfg)
+ cfg = [
+ dict(type='MultiStepLR', milestones=[1, 2]),
+ dict(type='StepLR', step_size=1)
+ ]
+ param_schedulers = runner.build_param_scheduler(cfg)
+ print(param_schedulers)
+ self.assertIsInstance(param_schedulers, dict)
+ self.assertEqual(len(param_schedulers), 2)
+ self.assertEqual(len(param_schedulers['key1']), 2)
+ self.assertEqual(len(param_schedulers['key2']), 2)
+
+ # 4. test multiple optimizers and multiple parameter shceduers
+ cfg = dict(
+ key1=dict(type='MultiStepLR', milestones=[1, 2]),
+ key2=[
+ dict(type='MultiStepLR', milestones=[1, 2]),
+ dict(type='StepLR', step_size=1)
+ ])
+ param_schedulers = runner.build_param_scheduler(cfg)
+ self.assertIsInstance(param_schedulers, dict)
+ self.assertEqual(len(param_schedulers), 2)
+ self.assertEqual(len(param_schedulers['key1']), 1)
+ self.assertEqual(len(param_schedulers['key2']), 2)
+
+ # 5. test converting epoch-based scheduler to iter-based
+ runner.optim_wrapper = runner.build_optim_wrapper(
+ dict(type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01)))
+
+ # 5.1 train loop should be built before converting scheduler
+ cfg = dict(
+ type='MultiStepLR', milestones=[1, 2], convert_to_iter_based=True)
+
+ # 5.2 convert epoch-based to iter-based scheduler
+ cfg = dict(
+ type='MultiStepLR',
+ milestones=[1, 2],
+ begin=1,
+ end=7,
+ convert_to_iter_based=True)
+ runner._train_loop = runner.build_train_loop(runner.train_loop)
+ param_schedulers = runner.build_param_scheduler(cfg)
+ self.assertFalse(param_schedulers[0].by_epoch)
+ self.assertEqual(param_schedulers[0].begin, 4)
+ self.assertEqual(param_schedulers[0].end, 28)
+
+ # 6. test set default end of schedulers
+ cfg = dict(type='MultiStepLR', milestones=[1, 2], begin=1)
+ param_schedulers = runner.build_param_scheduler(cfg)
+ self.assertTrue(param_schedulers[0].by_epoch)
+ self.assertEqual(param_schedulers[0].begin, 1)
+ # runner.max_epochs = 3
+ self.assertEqual(param_schedulers[0].end, 3)
+
+ cfg = dict(
+ type='MultiStepLR',
+ milestones=[1, 2],
+ begin=1,
+ convert_to_iter_based=True)
+ param_schedulers = runner.build_param_scheduler(cfg)
+ self.assertFalse(param_schedulers[0].by_epoch)
+ self.assertEqual(param_schedulers[0].begin, 4)
+ # runner.max_iters = 3*4
+ self.assertEqual(param_schedulers[0].end, 12)
+
+ def test_build_evaluator(self):
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_build_evaluator'
+ runner = Runner.from_cfg(cfg)
+
+ # input is a BaseEvaluator or ComposedEvaluator object
+ evaluator = Evaluator(ToyMetric1())
+ self.assertEqual(id(runner.build_evaluator(evaluator)), id(evaluator))
+
+ evaluator = Evaluator([ToyMetric1(), ToyMetric2()])
+ self.assertEqual(id(runner.build_evaluator(evaluator)), id(evaluator))
+
+ # input is a dict
+ evaluator = dict(type='ToyMetric1')
+ self.assertIsInstance(runner.build_evaluator(evaluator), Evaluator)
+
+ # input is a list of dict
+ evaluator = [dict(type='ToyMetric1'), dict(type='ToyMetric2')]
+ self.assertIsInstance(runner.build_evaluator(evaluator), Evaluator)
+
+ # input is a list of built metric.
+ metric = [ToyMetric1(), ToyMetric2()]
+ _evaluator = runner.build_evaluator(metric)
+ self.assertIs(_evaluator.metrics[0], metric[0])
+ self.assertIs(_evaluator.metrics[1], metric[1])
+
+ # test collect device
+ evaluator = [
+ dict(type='ToyMetric1', collect_device='cpu'),
+ dict(type='ToyMetric2', collect_device='gpu')
+ ]
+ _evaluator = runner.build_evaluator(evaluator)
+ self.assertEqual(_evaluator.metrics[0].collect_device, 'cpu')
+ self.assertEqual(_evaluator.metrics[1].collect_device, 'gpu')
+
+ # test build a customize evaluator
+ evaluator = dict(
+ type='ToyEvaluator',
+ metrics=[
+ dict(type='ToyMetric1', collect_device='cpu'),
+ dict(type='ToyMetric2', collect_device='gpu')
+ ])
+ _evaluator = runner.build_evaluator(evaluator)
+ self.assertIsInstance(runner.build_evaluator(evaluator), ToyEvaluator)
+ self.assertEqual(_evaluator.metrics[0].collect_device, 'cpu')
+ self.assertEqual(_evaluator.metrics[1].collect_device, 'gpu')
+
+ # test evaluator must be a Evaluator instance
+ with self.assertRaisesRegex(TypeError, 'evaluator should be'):
+ _evaluator = runner.build_evaluator(ToyMetric1())
+
+ def test_build_dataloader(self):
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_build_dataloader'
+ runner = Runner.from_cfg(cfg)
+
+ cfg = dict(
+ dataset=dict(type='ToyDataset'),
+ sampler=dict(type='DefaultSampler', shuffle=True),
+ batch_size=1,
+ num_workers=0)
+ seed = np.random.randint(2**31)
+ dataloader = runner.build_dataloader(cfg, seed=seed)
+ self.assertIsInstance(dataloader, DataLoader)
+ self.assertIsInstance(dataloader.dataset, ToyDataset)
+ self.assertIsInstance(dataloader.sampler, DefaultSampler)
+ self.assertEqual(dataloader.sampler.seed, seed)
+
+ # diff_rank_seed is True
+ dataloader = runner.build_dataloader(
+ cfg, seed=seed, diff_rank_seed=True)
+ self.assertNotEqual(dataloader.sampler.seed, seed)
+
+ def test_build_train_loop(self):
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_build_train_loop'
+ runner = Runner.from_cfg(cfg)
+
+ # input should be a Loop object or dict
+ with self.assertRaisesRegex(TypeError, 'should be'):
+ runner.build_train_loop('invalid-type')
+
+ # Only one of type or by_epoch can exist in cfg
+ cfg = dict(type='EpochBasedTrainLoop', by_epoch=True, max_epochs=3)
+ with self.assertRaisesRegex(RuntimeError, 'Only one'):
+ runner.build_train_loop(cfg)
+
+ # input is a dict and contains type key
+ cfg = dict(type='EpochBasedTrainLoop', max_epochs=3)
+ loop = runner.build_train_loop(cfg)
+ self.assertIsInstance(loop, EpochBasedTrainLoop)
+
+ cfg = dict(type='IterBasedTrainLoop', max_iters=3)
+ loop = runner.build_train_loop(cfg)
+ self.assertIsInstance(loop, IterBasedTrainLoop)
+
+ # input is a dict and does not contain type key
+ cfg = dict(by_epoch=True, max_epochs=3)
+ loop = runner.build_train_loop(cfg)
+ self.assertIsInstance(loop, EpochBasedTrainLoop)
+
+ cfg = dict(by_epoch=False, max_iters=3)
+ loop = runner.build_train_loop(cfg)
+ self.assertIsInstance(loop, IterBasedTrainLoop)
+
+ # input is a Loop object
+ self.assertEqual(id(runner.build_train_loop(loop)), id(loop))
+
+ # param_schedulers can be None
+ cfg = dict(type='EpochBasedTrainLoop', max_epochs=3)
+ runner.param_schedulers = None
+ loop = runner.build_train_loop(cfg)
+ self.assertIsInstance(loop, EpochBasedTrainLoop)
+
+ # test custom training loop
+ cfg = dict(type='CustomTrainLoop', max_epochs=3)
+ loop = runner.build_train_loop(cfg)
+ self.assertIsInstance(loop, CustomTrainLoop)
+
+ def test_build_val_loop(self):
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_build_val_loop'
+ runner = Runner.from_cfg(cfg)
+
+ # input should be a Loop object or dict
+ with self.assertRaisesRegex(TypeError, 'should be'):
+ runner.build_test_loop('invalid-type')
+
+ # input is a dict and contains type key
+ cfg = dict(type='ValLoop')
+ loop = runner.build_test_loop(cfg)
+ self.assertIsInstance(loop, ValLoop)
+
+ # input is a dict but does not contain type key
+ cfg = dict()
+ loop = runner.build_val_loop(cfg)
+ self.assertIsInstance(loop, ValLoop)
+
+ # input is a Loop object
+ self.assertEqual(id(runner.build_val_loop(loop)), id(loop))
+
+ # test custom validation loop
+ cfg = dict(type='CustomValLoop')
+ loop = runner.build_val_loop(cfg)
+ self.assertIsInstance(loop, CustomValLoop)
+
+ def test_build_test_loop(self):
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_build_test_loop'
+ runner = Runner.from_cfg(cfg)
+
+ # input should be a Loop object or dict
+ with self.assertRaisesRegex(TypeError, 'should be'):
+ runner.build_test_loop('invalid-type')
+
+ # input is a dict and contains type key
+ cfg = dict(type='TestLoop')
+ loop = runner.build_test_loop(cfg)
+ self.assertIsInstance(loop, TestLoop)
+
+ # input is a dict but does not contain type key
+ cfg = dict()
+ loop = runner.build_test_loop(cfg)
+ self.assertIsInstance(loop, TestLoop)
+
+ # input is a Loop object
+ self.assertEqual(id(runner.build_test_loop(loop)), id(loop))
+
+ # test custom validation loop
+ cfg = dict(type='CustomTestLoop')
+ loop = runner.build_val_loop(cfg)
+ self.assertIsInstance(loop, CustomTestLoop)
+
+ def test_build_log_processor(self):
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_build_log_processor'
+ runner = Runner.from_cfg(cfg)
+
+ # input should be a LogProcessor object or dict
+ with self.assertRaisesRegex(TypeError, 'should be'):
+ runner.build_log_processor('invalid-type')
+
+ # input is a dict and contains type key
+ cfg = dict(type='LogProcessor')
+ log_processor = runner.build_log_processor(cfg)
+ self.assertIsInstance(log_processor, LogProcessor)
+
+ # input is a dict but does not contain type key
+ cfg = dict()
+ log_processor = runner.build_log_processor(cfg)
+ self.assertIsInstance(log_processor, LogProcessor)
+
+ # input is a LogProcessor object
+ self.assertEqual(
+ id(runner.build_log_processor(log_processor)), id(log_processor))
+
+ # test custom validation log_processor
+ cfg = dict(type='CustomLogProcessor')
+ log_processor = runner.build_log_processor(cfg)
+ self.assertIsInstance(log_processor, CustomLogProcessor)
+
+ def test_train(self):
+ # 1. test `self.train_loop` is None
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_train1'
+ cfg.pop('train_dataloader')
+ cfg.pop('train_cfg')
+ cfg.pop('optim_wrapper')
+ cfg.pop('param_scheduler')
+ runner = Runner.from_cfg(cfg)
+ with self.assertRaisesRegex(RuntimeError, 'should not be None'):
+ runner.train()
+
+ # 2. test iter and epoch counter of EpochBasedTrainLoop and timing of
+ # running ValLoop
+ epoch_results = []
+ epoch_targets = [i for i in range(3)]
+ iter_results = []
+ iter_targets = [i for i in range(4 * 3)]
+ batch_idx_results = []
+ batch_idx_targets = [i for i in range(4)] * 3 # train and val
+ val_epoch_results = []
+ val_epoch_targets = [i for i in range(2, 4)]
+
+ @HOOKS.register_module(force=True)
+ class TestEpochHook(Hook):
+
+ def before_train_epoch(self, runner):
+ epoch_results.append(runner.epoch)
+
+ def before_train_iter(self, runner, batch_idx, data_batch=None):
+ iter_results.append(runner.iter)
+ batch_idx_results.append(batch_idx)
+
+ def before_val_epoch(self, runner):
+ val_epoch_results.append(runner.epoch)
+
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_train2'
+ cfg.custom_hooks = [dict(type='TestEpochHook', priority=50)]
+ cfg.train_cfg = dict(by_epoch=True, max_epochs=3, val_begin=2)
+ runner = Runner.from_cfg(cfg)
+ runner.train()
+ self.assertEqual(runner.optim_wrapper._inner_count, 12)
+ self.assertEqual(runner.optim_wrapper._max_counts, 12)
+
+ assert isinstance(runner.train_loop, EpochBasedTrainLoop)
+
+ for result, target, in zip(epoch_results, epoch_targets):
+ self.assertEqual(result, target)
+ for result, target, in zip(iter_results, iter_targets):
+ self.assertEqual(result, target)
+ for result, target, in zip(batch_idx_results, batch_idx_targets):
+ self.assertEqual(result, target)
+ for result, target, in zip(val_epoch_results, val_epoch_targets):
+ self.assertEqual(result, target)
+
+ # 3. test iter and epoch counter of IterBasedTrainLoop and timing of
+ # running ValLoop
+ epoch_results = []
+ iter_results = []
+ batch_idx_results = []
+ val_iter_results = []
+ val_batch_idx_results = []
+ iter_targets = [i for i in range(12)]
+ batch_idx_targets = [i for i in range(12)]
+ val_iter_targets = [i for i in range(4, 12)]
+ val_batch_idx_targets = [i for i in range(4)] * 2
+
+ @HOOKS.register_module(force=True)
+ class TestIterHook(Hook):
+
+ def before_train_epoch(self, runner):
+ epoch_results.append(runner.epoch)
+
+ def before_train_iter(self, runner, batch_idx, data_batch=None):
+ iter_results.append(runner.iter)
+ batch_idx_results.append(batch_idx)
+
+ def before_val_iter(self, runner, batch_idx, data_batch=None):
+ val_epoch_results.append(runner.iter)
+ val_batch_idx_results.append(batch_idx)
+
+ cfg = copy.deepcopy(self.iter_based_cfg)
+ cfg.experiment_name = 'test_train3'
+ cfg.custom_hooks = [dict(type='TestIterHook', priority=50)]
+ cfg.train_cfg = dict(
+ by_epoch=False, max_iters=12, val_interval=4, val_begin=4)
+ runner = Runner.from_cfg(cfg)
+ runner.train()
+
+ self.assertEqual(runner.optim_wrapper._inner_count, 12)
+ self.assertEqual(runner.optim_wrapper._max_counts, 12)
+ assert isinstance(runner.train_loop, IterBasedTrainLoop)
+
+ self.assertEqual(len(epoch_results), 1)
+ self.assertEqual(epoch_results[0], 0)
+ self.assertEqual(runner.val_interval, 4)
+ self.assertEqual(runner.val_begin, 4)
+ for result, target, in zip(iter_results, iter_targets):
+ self.assertEqual(result, target)
+ for result, target, in zip(batch_idx_results, batch_idx_targets):
+ self.assertEqual(result, target)
+ for result, target, in zip(val_iter_results, val_iter_targets):
+ self.assertEqual(result, target)
+ for result, target, in zip(val_batch_idx_results,
+ val_batch_idx_targets):
+ self.assertEqual(result, target)
+
+ # 4. test iter and epoch counter of IterBasedTrainLoop and timing of
+ # running ValLoop without InfiniteSampler
+ epoch_results = []
+ iter_results = []
+ batch_idx_results = []
+ val_iter_results = []
+ val_batch_idx_results = []
+ iter_targets = [i for i in range(12)]
+ batch_idx_targets = [i for i in range(12)]
+ val_iter_targets = [i for i in range(4, 12)]
+ val_batch_idx_targets = [i for i in range(4)] * 2
+
+ cfg = copy.deepcopy(self.iter_based_cfg)
+ cfg.experiment_name = 'test_train4'
+ cfg.train_dataloader.sampler = dict(
+ type='DefaultSampler', shuffle=True)
+ cfg.custom_hooks = [dict(type='TestIterHook', priority=50)]
+ cfg.train_cfg = dict(
+ by_epoch=False, max_iters=12, val_interval=4, val_begin=4)
+ runner = Runner.from_cfg(cfg)
+ with self.assertWarnsRegex(
+ Warning,
+ 'Reach the end of the dataloader, it will be restarted and '
+ 'continue to iterate.'):
+ runner.train()
+
+ assert isinstance(runner.train_loop, IterBasedTrainLoop)
+ assert isinstance(runner.train_loop.dataloader_iterator,
+ _InfiniteDataloaderIterator)
+
+ self.assertEqual(len(epoch_results), 1)
+ self.assertEqual(epoch_results[0], 0)
+ self.assertEqual(runner.val_interval, 4)
+ self.assertEqual(runner.val_begin, 4)
+ for result, target, in zip(iter_results, iter_targets):
+ self.assertEqual(result, target)
+ for result, target, in zip(batch_idx_results, batch_idx_targets):
+ self.assertEqual(result, target)
+ for result, target, in zip(val_iter_results, val_iter_targets):
+ self.assertEqual(result, target)
+ for result, target, in zip(val_batch_idx_results,
+ val_batch_idx_targets):
+ self.assertEqual(result, target)
+
+ # 5.1 test dynamic interval in IterBasedTrainLoop
+ max_iters = 12
+ interval = 5
+ dynamic_intervals = [(11, 2)]
+ iter_results = []
+ iter_targets = [5, 10, 12]
+ val_interval_results = []
+ val_interval_targets = [5] * 10 + [2] * 2
+
+ @HOOKS.register_module(force=True)
+ class TestIterDynamicIntervalHook(Hook):
+
+ def before_val(self, runner):
+ iter_results.append(runner.iter)
+
+ def before_train_iter(self, runner, batch_idx, data_batch=None):
+ val_interval_results.append(runner.train_loop.val_interval)
+
+ cfg = copy.deepcopy(self.iter_based_cfg)
+ cfg.experiment_name = 'test_train5'
+ cfg.train_dataloader.sampler = dict(
+ type='DefaultSampler', shuffle=True)
+ cfg.custom_hooks = [
+ dict(type='TestIterDynamicIntervalHook', priority=50)
+ ]
+ cfg.train_cfg = dict(
+ by_epoch=False,
+ max_iters=max_iters,
+ val_interval=interval,
+ dynamic_intervals=dynamic_intervals)
+ runner = Runner.from_cfg(cfg)
+ runner.train()
+ for result, target, in zip(iter_results, iter_targets):
+ self.assertEqual(result, target)
+ for result, target, in zip(val_interval_results, val_interval_targets):
+ self.assertEqual(result, target)
+
+ # 5.2 test dynamic interval in EpochBasedTrainLoop
+ max_epochs = 12
+ interval = 5
+ dynamic_intervals = [(11, 2)]
+ epoch_results = []
+ epoch_targets = [5, 10, 12]
+ val_interval_results = []
+ val_interval_targets = [5] * 10 + [2] * 2
+
+ @HOOKS.register_module(force=True)
+ class TestEpochDynamicIntervalHook(Hook):
+
+ def before_val_epoch(self, runner):
+ epoch_results.append(runner.epoch)
+
+ def before_train_epoch(self, runner):
+ val_interval_results.append(runner.train_loop.val_interval)
+
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_train6'
+ cfg.train_dataloader.sampler = dict(
+ type='DefaultSampler', shuffle=True)
+ cfg.custom_hooks = [
+ dict(type='TestEpochDynamicIntervalHook', priority=50)
+ ]
+ cfg.train_cfg = dict(
+ by_epoch=True,
+ max_epochs=max_epochs,
+ val_interval=interval,
+ dynamic_intervals=dynamic_intervals)
+ runner = Runner.from_cfg(cfg)
+ runner.train()
+ for result, target, in zip(epoch_results, epoch_targets):
+ self.assertEqual(result, target)
+ for result, target, in zip(val_interval_results, val_interval_targets):
+ self.assertEqual(result, target)
+
+ # 7. test init weights
+ @MODELS.register_module(force=True)
+ class ToyModel2(ToyModel):
+
+ def __init__(self):
+ super().__init__()
+ self.initiailzed = False
+
+ def init_weights(self):
+ self.initiailzed = True
+
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_train7'
+ runner = Runner.from_cfg(cfg)
+ model = ToyModel2()
+ runner.model = model
+ runner.train()
+ self.assertTrue(model.initiailzed)
+
+ # 8.1 test train with multiple optimizer and single list of schedulers.
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_train8'
+ cfg.param_scheduler = dict(type='MultiStepLR', milestones=[1, 2])
+ cfg.optim_wrapper = dict(
+ linear1=dict(
+ type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01)),
+ linear2=dict(
+ type='OptimWrapper', optimizer=dict(type='Adam', lr=0.02)),
+ constructor='ToyMultipleOptimizerConstructor')
+ cfg.model = dict(type='ToyGANModel')
+ runner = runner.from_cfg(cfg)
+ runner.train()
+
+ # 8.1 Test train with multiple optimizer and single schedulers.
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_train8.1.1'
+ cfg.param_scheduler = dict(type='MultiStepLR', milestones=[1, 2])
+ cfg.optim_wrapper = dict(
+ linear1=dict(
+ type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01)),
+ linear2=dict(
+ type='OptimWrapper', optimizer=dict(type='Adam', lr=0.02)),
+ constructor='ToyMultipleOptimizerConstructor')
+ cfg.model = dict(type='ToyGANModel')
+ runner = runner.from_cfg(cfg)
+ runner.train()
+
+ # Test list like single scheduler.
+ cfg.experiment_name = 'test_train8.1.2'
+ cfg.param_scheduler = [dict(type='MultiStepLR', milestones=[1, 2])]
+ runner = runner.from_cfg(cfg)
+ runner.train()
+
+ # 8.2 Test train with multiple optimizer and multiple schedulers.
+ cfg.experiment_name = 'test_train8.2.1'
+ cfg.param_scheduler = dict(
+ linear1=dict(type='MultiStepLR', milestones=[1, 2]),
+ linear2=dict(type='MultiStepLR', milestones=[1, 2]),
+ )
+ runner = runner.from_cfg(cfg)
+ runner.train()
+
+ cfg.experiment_name = 'test_train8.2.2'
+ cfg.param_scheduler = dict(
+ linear1=[dict(type='MultiStepLR', milestones=[1, 2])],
+ linear2=[dict(type='MultiStepLR', milestones=[1, 2])],
+ )
+ runner = runner.from_cfg(cfg)
+ runner.train()
+
+ # 9 Test training with a dataset without metainfo
+ cfg.experiment_name = 'test_train9'
+ cfg = copy.deepcopy(cfg)
+ cfg.train_dataloader.dataset = dict(type='ToyDatasetNoMeta')
+ runner = runner.from_cfg(cfg)
+ runner.train()
+
+ # 10.1 Test build dataloader with default collate function
+ cfg = copy.deepcopy(self.iter_based_cfg)
+ cfg.experiment_name = 'test_train10.1'
+ cfg.train_dataloader.update(collate_fn=dict(type='default_collate'))
+ runner = Runner.from_cfg(cfg)
+ runner.train()
+
+ # 10.2 Test build dataloader with custom collate function
+ cfg = copy.deepcopy(self.iter_based_cfg)
+ cfg.experiment_name = 'test_train10.2'
+ cfg.train_dataloader.update(
+ collate_fn=dict(type='custom_collate', pad_value=100))
+ runner = Runner.from_cfg(cfg)
+ runner.train()
+
+ # 11 test build dataloader without default arguments of collate
+ # function.
+ with self.assertRaises(TypeError):
+ cfg = copy.deepcopy(self.iter_based_cfg)
+ cfg.experiment_name = 'test_train11'
+ cfg.train_dataloader.update(collate_fn=dict(type='custom_collate'))
+ runner = Runner.from_cfg(cfg)
+ runner.train()
+
+ # 12.1 Test train with model, which does not inherit from BaseModel
+ @MODELS.register_module(force=True)
+ class ToyModel3(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.linear = nn.Linear(1, 1)
+
+ def train_step(self, *args, **kwargs):
+ return dict(loss=torch.tensor(1))
+
+ cfg = copy.deepcopy(self.iter_based_cfg)
+ cfg.pop('val_cfg')
+ cfg.pop('val_dataloader')
+ cfg.pop('val_evaluator')
+ cfg.model = dict(type='ToyModel3')
+ cfg.experiment_name = 'test_train12.1'
+ runner = Runner.from_cfg(cfg)
+ runner.train()
+
+ # 12.2 Test val_step should be implemented if val_cfg is not None
+ cfg = copy.deepcopy(self.iter_based_cfg)
+ cfg.model = dict(type='ToyModel3')
+ cfg.experiment_name = 'test_train12.2'
+ runner = Runner.from_cfg(cfg)
+
+ with self.assertRaisesRegex(AssertionError, 'If you want to validate'):
+ runner.train()
+
+ def test_val(self):
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_val1'
+ cfg.pop('val_dataloader')
+ cfg.pop('val_cfg')
+ cfg.pop('val_evaluator')
+ runner = Runner.from_cfg(cfg)
+ with self.assertRaisesRegex(RuntimeError, 'should not be None'):
+ runner.val()
+
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_val2'
+ runner = Runner.from_cfg(cfg)
+ runner.val()
+
+ # test run val without train and test components
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_individually_val'
+ cfg.pop('train_dataloader')
+ cfg.pop('train_cfg')
+ cfg.pop('optim_wrapper')
+ cfg.pop('param_scheduler')
+ cfg.pop('test_dataloader')
+ cfg.pop('test_cfg')
+ cfg.pop('test_evaluator')
+ runner = Runner.from_cfg(cfg)
+
+ # Test default fp32 `autocast` context.
+ predictions = []
+
+ def get_outputs_callback(module, inputs, outputs):
+ predictions.append(outputs)
+
+ runner.model.register_forward_hook(get_outputs_callback)
+ runner.val()
+ self.assertEqual(predictions[0].dtype, torch.float32)
+ predictions.clear()
+
+ # Test fp16 `autocast` context.
+ cfg.experiment_name = 'test_val3'
+ cfg.val_cfg = dict(fp16=True)
+ runner = Runner.from_cfg(cfg)
+ runner.model.register_forward_hook(get_outputs_callback)
+ if (digit_version(TORCH_VERSION) < digit_version('1.10.0')
+ and not torch.cuda.is_available()):
+ with self.assertRaisesRegex(RuntimeError, 'If pytorch versions'):
+ runner.val()
+ else:
+ runner.val()
+ self.assertIn(predictions[0].dtype,
+ (torch.float16, torch.bfloat16))
+
+ def test_test(self):
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_test1'
+ cfg.pop('test_dataloader')
+ cfg.pop('test_cfg')
+ cfg.pop('test_evaluator')
+ runner = Runner.from_cfg(cfg)
+ with self.assertRaisesRegex(RuntimeError, 'should not be None'):
+ runner.test()
+
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_test2'
+ runner = Runner.from_cfg(cfg)
+ runner.test()
+ # Test run test without building train loop.
+ self.assertIsInstance(runner._train_loop, dict)
+
+ # test run test without train and test components
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_individually_test'
+ cfg.pop('train_dataloader')
+ cfg.pop('train_cfg')
+ cfg.pop('optim_wrapper')
+ cfg.pop('param_scheduler')
+ cfg.pop('val_dataloader')
+ cfg.pop('val_cfg')
+ cfg.pop('val_evaluator')
+ runner = Runner.from_cfg(cfg)
+
+ # Test default fp32 `autocast` context.
+ predictions = []
+
+ def get_outputs_callback(module, inputs, outputs):
+ predictions.append(outputs)
+
+ runner.model.register_forward_hook(get_outputs_callback)
+ runner.test()
+ self.assertEqual(predictions[0].dtype, torch.float32)
+ predictions.clear()
+
+ # Test fp16 `autocast` context.
+ cfg.experiment_name = 'test_val3'
+ cfg.test_cfg = dict(fp16=True)
+ runner = Runner.from_cfg(cfg)
+ runner.model.register_forward_hook(get_outputs_callback)
+ if (digit_version(TORCH_VERSION) < digit_version('1.10.0')
+ and not torch.cuda.is_available()):
+ with self.assertRaisesRegex(RuntimeError, 'If pytorch versions'):
+ runner.test()
+ else:
+ runner.test()
+ self.assertIn(predictions[0].dtype,
+ (torch.float16, torch.bfloat16))
+
+ def test_register_hook(self):
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_register_hook'
+ runner = Runner.from_cfg(cfg)
+ runner._hooks = []
+
+ # 1. test `hook` parameter
+ # 1.1 `hook` should be either a Hook object or dict
+ with self.assertRaisesRegex(
+ TypeError, 'hook should be an instance of Hook or dict'):
+ runner.register_hook(['string'])
+
+ # 1.2 `hook` is a dict
+ timer_cfg = dict(type='IterTimerHook')
+ runner.register_hook(timer_cfg)
+ self.assertEqual(len(runner._hooks), 1)
+ self.assertTrue(isinstance(runner._hooks[0], IterTimerHook))
+ # default priority of `IterTimerHook` is 'NORMAL'
+ self.assertEqual(
+ get_priority(runner._hooks[0].priority), get_priority('NORMAL'))
+
+ runner._hooks = []
+ # 1.2.1 `hook` is a dict and contains `priority` field
+ # set the priority of `IterTimerHook` as 'BELOW_NORMAL'
+ timer_cfg = dict(type='IterTimerHook', priority='BELOW_NORMAL')
+ runner.register_hook(timer_cfg)
+ self.assertEqual(len(runner._hooks), 1)
+ self.assertTrue(isinstance(runner._hooks[0], IterTimerHook))
+ self.assertEqual(
+ get_priority(runner._hooks[0].priority),
+ get_priority('BELOW_NORMAL'))
+
+ # 1.3 `hook` is a hook object
+ runtime_info_hook = RuntimeInfoHook()
+ runner.register_hook(runtime_info_hook)
+ self.assertEqual(len(runner._hooks), 2)
+ # The priority of `runtime_info_hook` is `HIGH` which is greater than
+ # `IterTimerHook`, so the first item of `_hooks` should be
+ # `runtime_info_hook`
+ self.assertTrue(isinstance(runner._hooks[0], RuntimeInfoHook))
+ self.assertEqual(
+ get_priority(runner._hooks[0].priority), get_priority('VERY_HIGH'))
+
+ # 2. test `priority` parameter
+ # `priority` argument is not None and it will be set as priority of
+ # hook
+ param_scheduler_cfg = dict(type='ParamSchedulerHook', priority='LOW')
+ runner.register_hook(param_scheduler_cfg, priority='VERY_LOW')
+ self.assertEqual(len(runner._hooks), 3)
+ self.assertTrue(isinstance(runner._hooks[2], ParamSchedulerHook))
+ self.assertEqual(
+ get_priority(runner._hooks[2].priority), get_priority('VERY_LOW'))
+
+ # `priority` is Priority
+ logger_cfg = dict(type='LoggerHook', priority='BELOW_NORMAL')
+ runner.register_hook(logger_cfg, priority=Priority.VERY_LOW)
+ self.assertEqual(len(runner._hooks), 4)
+ self.assertTrue(isinstance(runner._hooks[3], LoggerHook))
+ self.assertEqual(
+ get_priority(runner._hooks[3].priority), get_priority('VERY_LOW'))
+
+ def test_default_hooks(self):
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_default_hooks'
+ runner = Runner.from_cfg(cfg)
+ runner._hooks = []
+
+ # register 7 hooks by default
+ runner.register_default_hooks()
+ self.assertEqual(len(runner._hooks), 6)
+ # the third registered hook should be `DistSamplerSeedHook`
+ self.assertTrue(isinstance(runner._hooks[2], DistSamplerSeedHook))
+ # the fifth registered hook should be `ParamSchedulerHook`
+ self.assertTrue(isinstance(runner._hooks[4], ParamSchedulerHook))
+
+ runner._hooks = []
+ # remove `ParamSchedulerHook` from default hooks
+ runner.register_default_hooks(hooks=dict(timer=None))
+ self.assertEqual(len(runner._hooks), 5)
+ # `ParamSchedulerHook` was popped so the fifth is `CheckpointHook`
+ self.assertTrue(isinstance(runner._hooks[4], CheckpointHook))
+
+ # add a new default hook
+ runner._hooks = []
+ runner.register_default_hooks(hooks=dict(ToyHook=dict(type='ToyHook')))
+ self.assertEqual(len(runner._hooks), 7)
+ self.assertTrue(isinstance(runner._hooks[6], ToyHook))
+
+ def test_custom_hooks(self):
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_custom_hooks'
+ runner = Runner.from_cfg(cfg)
+
+ self.assertEqual(len(runner._hooks), 6)
+ custom_hooks = [dict(type='ToyHook')]
+ runner.register_custom_hooks(custom_hooks)
+ self.assertEqual(len(runner._hooks), 7)
+ self.assertTrue(isinstance(runner._hooks[6], ToyHook))
+
+ def test_register_hooks(self):
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_register_hooks'
+ runner = Runner.from_cfg(cfg)
+
+ runner._hooks = []
+ custom_hooks = [dict(type='ToyHook')]
+ runner.register_hooks(custom_hooks=custom_hooks)
+ # six default hooks + custom hook (ToyHook)
+ self.assertEqual(len(runner._hooks), 7)
+ self.assertTrue(isinstance(runner._hooks[6], ToyHook))
+
+ def test_custom_loop(self):
+ # test custom loop with additional hook
+ @LOOPS.register_module(force=True)
+ class CustomTrainLoop2(IterBasedTrainLoop):
+ """Custom train loop with additional warmup stage."""
+
+ def __init__(self, runner, dataloader, max_iters, warmup_loader,
+ max_warmup_iters):
+ super().__init__(
+ runner=runner, dataloader=dataloader, max_iters=max_iters)
+ self.warmup_loader = self.runner.build_dataloader(
+ warmup_loader)
+ self.max_warmup_iters = max_warmup_iters
+
+ def run(self):
+ self.runner.call_hook('before_train')
+ self.runner.cur_dataloader = self.warmup_loader
+ for idx, data_batch in enumerate(self.warmup_loader, 1):
+ self.warmup_iter(data_batch)
+ if idx == self.max_warmup_iters:
+ break
+
+ self.runner.cur_dataloader = self.warmup_loader
+ self.runner.call_hook('before_train_epoch')
+ while self.runner.iter < self._max_iters:
+ data_batch = next(self.dataloader_iterator)
+ self.run_iter(data_batch)
+ self.runner.call_hook('after_train_epoch')
+
+ self.runner.call_hook('after_train')
+
+ def warmup_iter(self, data_batch):
+ self.runner.call_hook(
+ 'before_warmup_iter', data_batch=data_batch)
+ train_logs = self.runner.model.train_step(
+ data_batch, self.runner.optim_wrapper)
+ self.runner.message_hub.update_info('train_logs', train_logs)
+ self.runner.call_hook(
+ 'after_warmup_iter', data_batch=data_batch)
+
+ before_warmup_iter_results = []
+ after_warmup_iter_results = []
+
+ @HOOKS.register_module(force=True)
+ class TestWarmupHook(Hook):
+ """test custom train loop."""
+
+ def before_warmup_iter(self, runner, data_batch=None):
+ before_warmup_iter_results.append('before')
+
+ def after_warmup_iter(self, runner, data_batch=None, outputs=None):
+ after_warmup_iter_results.append('after')
+
+ self.iter_based_cfg.train_cfg = dict(
+ type='CustomTrainLoop2',
+ max_iters=10,
+ warmup_loader=dict(
+ dataset=dict(type='ToyDataset'),
+ sampler=dict(type='InfiniteSampler', shuffle=True),
+ batch_size=1,
+ num_workers=0),
+ max_warmup_iters=5)
+ self.iter_based_cfg.custom_hooks = [
+ dict(type='TestWarmupHook', priority=50)
+ ]
+ self.iter_based_cfg.experiment_name = 'test_custom_loop'
+ runner = Runner.from_cfg(self.iter_based_cfg)
+ runner.train()
+
+ self.assertIsInstance(runner.train_loop, CustomTrainLoop2)
+
+ # test custom hook triggered as expected
+ self.assertEqual(len(before_warmup_iter_results), 5)
+ self.assertEqual(len(after_warmup_iter_results), 5)
+ for before, after in zip(before_warmup_iter_results,
+ after_warmup_iter_results):
+ self.assertEqual(before, 'before')
+ self.assertEqual(after, 'after')
+
+ def test_checkpoint(self):
+ # 1. test epoch based
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_checkpoint1'
+ runner = Runner.from_cfg(cfg)
+ runner.train()
+
+ # 1.1 test `save_checkpoint` which is called by `CheckpointHook`
+ path = osp.join(self.temp_dir, 'epoch_3.pth')
+ self.assertTrue(osp.exists(path))
+ self.assertFalse(osp.exists(osp.join(self.temp_dir, 'epoch_4.pth')))
+
+ ckpt = torch.load(path)
+ self.assertEqual(ckpt['meta']['epoch'], 3)
+ self.assertEqual(ckpt['meta']['iter'], 12)
+ self.assertEqual(ckpt['meta']['experiment_name'],
+ runner.experiment_name)
+ self.assertEqual(ckpt['meta']['seed'], runner.seed)
+ assert isinstance(ckpt['optimizer'], dict)
+ assert isinstance(ckpt['param_schedulers'], list)
+ self.assertIsInstance(ckpt['message_hub'], dict)
+ message_hub = MessageHub.get_instance('test_ckpt')
+ message_hub.load_state_dict(ckpt['message_hub'])
+ self.assertEqual(message_hub.get_info('epoch'), 2)
+ self.assertEqual(message_hub.get_info('iter'), 11)
+
+ # 1.2 test `load_checkpoint`
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_checkpoint2'
+ cfg.optim_wrapper = dict(type='SGD', lr=0.2)
+ cfg.param_scheduler = dict(type='MultiStepLR', milestones=[1, 2, 3])
+ runner = Runner.from_cfg(cfg)
+ runner.load_checkpoint(path)
+ self.assertEqual(runner.epoch, 0)
+ self.assertEqual(runner.iter, 0)
+ self.assertTrue(runner._has_loaded)
+ # load checkpoint will not initialize optimizer and param_schedulers
+ # objects
+ self.assertIsInstance(runner.optim_wrapper, dict)
+ self.assertIsInstance(runner.param_schedulers, dict)
+
+ # 1.3.1 test `resume`
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_checkpoint3'
+ cfg.optim_wrapper = dict(
+ type='OptimWrapper', optimizer=dict(type='SGD', lr=0.2))
+ cfg.param_scheduler = dict(type='MultiStepLR', milestones=[1, 2, 3])
+ runner = Runner.from_cfg(cfg)
+ runner.resume(path)
+ self.assertEqual(runner.epoch, 3)
+ self.assertEqual(runner.iter, 12)
+ self.assertTrue(runner._has_loaded)
+ self.assertIsInstance(runner.optim_wrapper.optimizer, SGD)
+ self.assertIsInstance(runner.optim_wrapper.optimizer, SGD)
+ self.assertEqual(runner.optim_wrapper.param_groups[0]['lr'], 0.0001)
+ self.assertIsInstance(runner.param_schedulers[0], MultiStepLR)
+ self.assertEqual(runner.param_schedulers[0].milestones, {1: 1, 2: 1})
+ self.assertIsInstance(runner.message_hub, MessageHub)
+ self.assertEqual(runner.message_hub.get_info('epoch'), 2)
+ self.assertEqual(runner.message_hub.get_info('iter'), 11)
+ self.assertEqual(MessageHub.get_current_instance().get_info('epoch'),
+ 2)
+ self.assertEqual(MessageHub.get_current_instance().get_info('iter'),
+ 11)
+
+ # 1.3.2 test resume with unmatched dataset_meta
+ ckpt_modified = copy.deepcopy(ckpt)
+ ckpt_modified['meta']['dataset_meta'] = {'CLASSES': ['cat', 'dog']}
+ # ckpt_modified['meta']['seed'] = 123
+ path_modified = osp.join(self.temp_dir, 'modified.pth')
+ torch.save(ckpt_modified, path_modified)
+ with self.assertWarnsRegex(
+ Warning, 'The dataset metainfo from the resumed checkpoint is '
+ 'different from the current training dataset, please '
+ 'check the correctness of the checkpoint or the training '
+ 'dataset.'):
+ runner.resume(path_modified)
+
+ # 1.3.3 test resume with unmatched seed
+ ckpt_modified = copy.deepcopy(ckpt)
+ ckpt_modified['meta']['seed'] = 123
+ path_modified = osp.join(self.temp_dir, 'modified.pth')
+ torch.save(ckpt_modified, path_modified)
+ with self.assertWarnsRegex(
+ Warning, 'The value of random seed in the checkpoint'):
+ runner.resume(path_modified)
+
+ # 1.3.3 test resume with no seed and dataset meta
+ ckpt_modified = copy.deepcopy(ckpt)
+ ckpt_modified['meta'].pop('seed')
+ ckpt_modified['meta'].pop('dataset_meta')
+ path_modified = osp.join(self.temp_dir, 'modified.pth')
+ torch.save(ckpt_modified, path_modified)
+ runner.resume(path_modified)
+
+ # 1.4 test auto resume
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_checkpoint4'
+ cfg.resume = True
+ runner = Runner.from_cfg(cfg)
+ runner.load_or_resume()
+ self.assertEqual(runner.epoch, 3)
+ self.assertEqual(runner.iter, 12)
+ self.assertTrue(runner._has_loaded)
+ self.assertIsInstance(runner.optim_wrapper.optimizer, SGD)
+ self.assertIsInstance(runner.param_schedulers[0], MultiStepLR)
+
+ # 1.5 test resume from a specified checkpoint
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_checkpoint5'
+ cfg.resume = True
+ cfg.load_from = osp.join(self.temp_dir, 'epoch_1.pth')
+ runner = Runner.from_cfg(cfg)
+ runner.load_or_resume()
+ self.assertEqual(runner.epoch, 1)
+ self.assertEqual(runner.iter, 4)
+ self.assertTrue(runner._has_loaded)
+ self.assertIsInstance(runner.optim_wrapper.optimizer, SGD)
+ self.assertIsInstance(runner.param_schedulers[0], MultiStepLR)
+
+ # 1.6 multiple optimizers
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_checkpoint6'
+ cfg.optim_wrapper = dict(
+ linear1=dict(
+ type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01)),
+ linear2=dict(
+ type='OptimWrapper', optimizer=dict(type='Adam', lr=0.02)),
+ constructor='ToyMultipleOptimizerConstructor')
+ cfg.model = dict(type='ToyGANModel')
+ # disable OptimizerHook because it only works with one optimizer
+ runner = Runner.from_cfg(cfg)
+ runner.train()
+ path = osp.join(self.temp_dir, 'epoch_3.pth')
+ self.assertTrue(osp.exists(path))
+ self.assertEqual(runner.optim_wrapper['linear1'].param_groups[0]['lr'],
+ 0.0001)
+ self.assertIsInstance(runner.optim_wrapper['linear2'].optimizer, Adam)
+ self.assertEqual(runner.optim_wrapper['linear2'].param_groups[0]['lr'],
+ 0.0002)
+
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_checkpoint7'
+ cfg.optim_wrapper = dict(
+ linear1=dict(
+ type='OptimWrapper', optimizer=dict(type='SGD', lr=0.2)),
+ linear2=dict(
+ type='OptimWrapper', optimizer=dict(type='Adam', lr=0.03)),
+ constructor='ToyMultipleOptimizerConstructor')
+ cfg.model = dict(type='ToyGANModel')
+ cfg.param_scheduler = dict(type='MultiStepLR', milestones=[1, 2, 3])
+ runner = Runner.from_cfg(cfg)
+ runner.resume(path)
+ self.assertIsInstance(runner.optim_wrapper, OptimWrapperDict)
+ self.assertIsInstance(runner.optim_wrapper['linear1'].optimizer, SGD)
+ self.assertEqual(runner.optim_wrapper['linear1'].param_groups[0]['lr'],
+ 0.0001)
+ self.assertIsInstance(runner.optim_wrapper['linear2'].optimizer, Adam)
+ self.assertEqual(runner.optim_wrapper['linear2'].param_groups[0]['lr'],
+ 0.0002)
+ self.assertIsInstance(runner.param_schedulers, dict)
+ self.assertEqual(len(runner.param_schedulers['linear1']), 1)
+ self.assertIsInstance(runner.param_schedulers['linear1'][0],
+ MultiStepLR)
+ self.assertEqual(runner.param_schedulers['linear1'][0].milestones, {
+ 1: 1,
+ 2: 1
+ })
+ self.assertEqual(len(runner.param_schedulers['linear2']), 1)
+ self.assertIsInstance(runner.param_schedulers['linear2'][0],
+ MultiStepLR)
+ self.assertEqual(runner.param_schedulers['linear2'][0].milestones, {
+ 1: 1,
+ 2: 1
+ })
+
+ # 2. test iter based
+ cfg = copy.deepcopy(self.iter_based_cfg)
+ cfg.experiment_name = 'test_checkpoint8'
+ runner = Runner.from_cfg(cfg)
+ runner.train()
+
+ # 2.1 test `save_checkpoint` which is called by `CheckpointHook`
+ path = osp.join(self.temp_dir, 'iter_12.pth')
+ self.assertTrue(osp.exists(path))
+ self.assertFalse(osp.exists(osp.join(self.temp_dir, 'epoch_13.pth')))
+
+ ckpt = torch.load(path)
+ self.assertEqual(ckpt['meta']['epoch'], 0)
+ self.assertEqual(ckpt['meta']['iter'], 12)
+ assert isinstance(ckpt['optimizer'], dict)
+ assert isinstance(ckpt['param_schedulers'], list)
+ self.assertIsInstance(ckpt['message_hub'], dict)
+ message_hub.load_state_dict(ckpt['message_hub'])
+ self.assertEqual(message_hub.get_info('epoch'), 0)
+ self.assertEqual(message_hub.get_info('iter'), 11)
+
+ # 2.2 test `load_checkpoint`
+ cfg = copy.deepcopy(self.iter_based_cfg)
+ cfg.experiment_name = 'test_checkpoint9'
+ runner = Runner.from_cfg(cfg)
+ runner.load_checkpoint(path)
+ self.assertEqual(runner.epoch, 0)
+ self.assertEqual(runner.iter, 0)
+ self.assertTrue(runner._has_loaded)
+
+ # 2.3 test `resume`
+ cfg = copy.deepcopy(self.iter_based_cfg)
+ cfg.experiment_name = 'test_checkpoint10'
+ runner = Runner.from_cfg(cfg)
+ runner.resume(path)
+ self.assertEqual(runner.epoch, 0)
+ self.assertEqual(runner.iter, 12)
+ self.assertTrue(runner._has_loaded)
+ self.assertIsInstance(runner.optim_wrapper.optimizer, SGD)
+ self.assertIsInstance(runner.param_schedulers[0], MultiStepLR)
+ self.assertEqual(runner.message_hub.get_info('epoch'), 0)
+ self.assertEqual(runner.message_hub.get_info('iter'), 11)
+
+ # 2.4 test auto resume
+ cfg = copy.deepcopy(self.iter_based_cfg)
+ cfg.experiment_name = 'test_checkpoint11'
+ cfg.resume = True
+ runner = Runner.from_cfg(cfg)
+ runner.load_or_resume()
+ self.assertEqual(runner.epoch, 0)
+ self.assertEqual(runner.iter, 12)
+ self.assertTrue(runner._has_loaded)
+ self.assertIsInstance(runner.optim_wrapper.optimizer, SGD)
+ self.assertIsInstance(runner.param_schedulers[0], MultiStepLR)
+
+ # 2.5 test resume from a specified checkpoint
+ cfg = copy.deepcopy(self.iter_based_cfg)
+ cfg.experiment_name = 'test_checkpoint12'
+ cfg.resume = True
+ cfg.load_from = osp.join(self.temp_dir, 'iter_3.pth')
+ runner = Runner.from_cfg(cfg)
+ runner.load_or_resume()
+ self.assertEqual(runner.epoch, 0)
+ self.assertEqual(runner.iter, 3)
+ self.assertTrue(runner._has_loaded)
+ self.assertIsInstance(runner.optim_wrapper.optimizer, SGD)
+ self.assertIsInstance(runner.param_schedulers[0], MultiStepLR)
+
+ # 2.6 test resumed message_hub has the history value.
+ cfg = copy.deepcopy(self.iter_based_cfg)
+ cfg.experiment_name = 'test_checkpoint13'
+ cfg.resume = True
+ cfg.load_from = osp.join(self.temp_dir, 'iter_3.pth')
+ runner = Runner.from_cfg(cfg)
+ runner.load_or_resume()
+ assert len(runner.message_hub.log_scalars['train/lr'].data[1]) == 3
+ assert len(MessageHub.get_current_instance().log_scalars['train/lr'].
+ data[1]) == 3
+
+ # 2.7.1 test `resume` 2 optimizers and 1 scheduler list.
+ path = osp.join(self.temp_dir, 'epoch_3.pth')
+ optim_cfg = dict(
+ linear1=dict(
+ type='OptimWrapper', optimizer=dict(type='SGD', lr=0.01)),
+ linear2=dict(
+ type='OptimWrapper', optimizer=dict(type='Adam', lr=0.02)),
+ constructor='ToyMultipleOptimizerConstructor')
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_checkpoint14'
+ cfg.optim_wrapper = optim_cfg
+ cfg.param_scheduler = dict(type='MultiStepLR', milestones=[1, 2, 3])
+ cfg.model = dict(type='ToyGANModel')
+ resumed_cfg = copy.deepcopy(cfg)
+ runner = Runner.from_cfg(cfg)
+ runner.train()
+ resumed_cfg.experiment_name = 'test_checkpoint15'
+ runner = Runner.from_cfg(resumed_cfg)
+ runner.resume(path)
+ self.assertEqual(len(runner.param_schedulers['linear1']), 1)
+ self.assertEqual(len(runner.param_schedulers['linear2']), 1)
+ self.assertIsInstance(runner.param_schedulers['linear1'][0],
+ MultiStepLR)
+ self.assertIsInstance(runner.param_schedulers['linear2'][0],
+ MultiStepLR)
+
+ # 2.7.2 test `resume` 2 optimizers and 2 scheduler list.
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_checkpoint16'
+ cfg.optim_wrapper = optim_cfg
+ cfg.param_scheduler = dict(
+ linear1=dict(type='MultiStepLR', milestones=[1, 2, 3]),
+ linear2=dict(type='StepLR', gamma=0.1, step_size=3))
+ cfg.model = dict(type='ToyGANModel')
+ resumed_cfg = copy.deepcopy(cfg)
+ runner = Runner.from_cfg(cfg)
+ runner.train()
+ resumed_cfg.experiment_name = 'test_checkpoint17'
+ runner = Runner.from_cfg(resumed_cfg)
+ runner.resume(path)
+ self.assertEqual(len(runner.param_schedulers['linear1']), 1)
+ self.assertEqual(len(runner.param_schedulers['linear2']), 1)
+ self.assertIsInstance(runner.param_schedulers['linear1'][0],
+ MultiStepLR)
+ self.assertIsInstance(runner.param_schedulers['linear2'][0], StepLR)
+
+ # 2.7.3 test `resume` 2 optimizers and 0 sheduler list.
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_checkpoint18'
+ cfg.optim_wrapper = optim_cfg
+ cfg.model = dict(type='ToyGANModel')
+ cfg.param_scheduler = None
+ resumed_cfg = copy.deepcopy(cfg)
+ runner = Runner.from_cfg(cfg)
+ runner.train()
+ resumed_cfg.experiment_name = 'test_checkpoint19'
+ runner = Runner.from_cfg(resumed_cfg)
+ runner.resume(path)
+ self.assertIsNone(runner.param_schedulers)
+
+ def test_build_runner(self):
+ # No need to test other cases which have been tested in
+ # `test_build_from_cfg`
+ # test custom runner
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_build_runner1'
+ cfg.runner_type = 'CustomRunner'
+ assert isinstance(RUNNERS.build(cfg), CustomRunner)
+
+ # test default runner
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_build_runner2'
+ assert isinstance(RUNNERS.build(cfg), Runner)
+
+ def test_get_hooks_info(self):
+ # test get_hooks_info() function
+ cfg = copy.deepcopy(self.epoch_based_cfg)
+ cfg.experiment_name = 'test_get_hooks_info_from_test_runner_py'
+ cfg.runner_type = 'Runner'
+ runner = RUNNERS.build(cfg)
+ self.assertIsInstance(runner, Runner)
+ target_str = ('after_train_iter:\n'
+ '(VERY_HIGH ) RuntimeInfoHook \n'
+ '(NORMAL ) IterTimerHook \n'
+ '(BELOW_NORMAL) LoggerHook \n'
+ '(LOW ) ParamSchedulerHook \n'
+ '(VERY_LOW ) CheckpointHook \n')
+ self.assertIn(target_str, runner.get_hooks_info(),
+ 'target string is not in logged hooks information.')
diff --git a/testbed/open-mmlab__mmengine/tests/test_structures/test_data_element.py b/testbed/open-mmlab__mmengine/tests/test_structures/test_data_element.py
new file mode 100644
index 0000000000000000000000000000000000000000..883ae401d45c5d8094b0ee9518672723dd83a6e6
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_structures/test_data_element.py
@@ -0,0 +1,460 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import random
+from unittest import TestCase
+
+import numpy as np
+import pytest
+import torch
+
+from mmengine.structures import BaseDataElement
+
+
+class DetDataSample(BaseDataElement):
+
+ @property
+ def proposals(self):
+ return self._proposals
+
+ @proposals.setter
+ def proposals(self, value):
+ self.set_field(value=value, name='_proposals', dtype=BaseDataElement)
+
+ @proposals.deleter
+ def proposals(self):
+ del self._proposals
+
+ @property
+ def gt_instances(self):
+ return self._gt_instances
+
+ @gt_instances.setter
+ def gt_instances(self, value):
+ self.set_field(
+ value=value, name='_gt_instances', dtype=BaseDataElement)
+
+ @gt_instances.deleter
+ def gt_instances(self):
+ del self._gt_instances
+
+ @property
+ def pred_instances(self):
+ return self._pred_instances
+
+ @pred_instances.setter
+ def pred_instances(self, value):
+ self.set_field(
+ value=value, name='_pred_instances', dtype=BaseDataElement)
+
+ @pred_instances.deleter
+ def pred_instances(self):
+ del self._pred_instances
+
+
+class TestBaseDataElement(TestCase):
+
+ def setup_data(self):
+ metainfo = dict(
+ img_id=random.randint(0, 100),
+ img_shape=(random.randint(400, 600), random.randint(400, 600)))
+ gt_instances = BaseDataElement(
+ bboxes=torch.rand((5, 4)), labels=torch.rand((5, )))
+ pred_instances = BaseDataElement(
+ bboxes=torch.rand((5, 4)), scores=torch.rand((5, )))
+ data = dict(gt_instances=gt_instances, pred_instances=pred_instances)
+ return metainfo, data
+
+ def is_equal(self, x, y):
+ assert type(x) == type(y)
+ if isinstance(
+ x, (int, float, str, list, tuple, dict, set, BaseDataElement)):
+ return x == y
+ elif isinstance(x, (torch.Tensor, np.ndarray)):
+ return (x == y).all()
+
+ def check_key_value(self, instances, metainfo=None, data=None):
+ # check the existence of keys in metainfo, data, and instances
+ if metainfo:
+ for k, v in metainfo.items():
+ assert k in instances
+ assert k in instances.all_keys()
+ assert k in instances.metainfo_keys()
+ assert k not in instances.keys()
+ assert self.is_equal(instances.get(k), v)
+ assert self.is_equal(getattr(instances, k), v)
+ if data:
+ for k, v in data.items():
+ assert k in instances
+ assert k in instances.keys()
+ assert k not in instances.metainfo_keys()
+ assert k in instances.all_keys()
+ assert self.is_equal(instances.get(k), v)
+ assert self.is_equal(getattr(instances, k), v)
+
+ def check_data_device(self, instances, device):
+ # assert instances.device == device
+ for v in instances.values():
+ if isinstance(v, torch.Tensor):
+ assert v.device == torch.device(device)
+ elif isinstance(v, BaseDataElement):
+ self.check_data_device(v, device)
+
+ def check_data_dtype(self, instances, dtype):
+ for v in instances.values():
+ if isinstance(v, (torch.Tensor, np.ndarray)):
+ assert isinstance(v, dtype)
+ if isinstance(v, BaseDataElement):
+ self.check_data_dtype(v, dtype)
+
+ def check_requires_grad(self, instances):
+ for v in instances.values():
+ if isinstance(v, torch.Tensor):
+ assert v.requires_grad is False
+ if isinstance(v, BaseDataElement):
+ self.check_requires_grad(v)
+
+ def test_init(self):
+ # initialization with no data and metainfo
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement()
+ for k in metainfo:
+ assert k not in instances
+ assert instances.get(k, None) is None
+ for k in data:
+ assert k not in instances
+ assert instances.get(k, 'abc') == 'abc'
+
+ # initialization with kwargs
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo, **data)
+ self.check_key_value(instances, metainfo, data)
+
+ # initialization with args
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo)
+ self.check_key_value(instances, metainfo)
+ instances = BaseDataElement(**data)
+ self.check_key_value(instances, data=data)
+
+ def test_new(self):
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo, **data)
+
+ # test new() with no arguments
+ new_instances = instances.new()
+ assert type(new_instances) == type(instances)
+ # After deepcopy, the address of new data'element will be same as
+ # origin, but when change new data' element will not effect the origin
+ # element and will have new address
+ _, data = self.setup_data()
+ new_instances.set_data(data)
+ assert not self.is_equal(new_instances.gt_instances,
+ instances.gt_instances)
+ self.check_key_value(new_instances, metainfo, data)
+
+ # test new() with arguments
+ metainfo, data = self.setup_data()
+ new_instances = instances.new(metainfo=metainfo, **data)
+ assert type(new_instances) == type(instances)
+ assert id(new_instances.gt_instances) != id(instances.gt_instances)
+ _, new_data = self.setup_data()
+ new_instances.set_data(new_data)
+ assert id(new_instances.gt_instances) != id(data['gt_instances'])
+ self.check_key_value(new_instances, metainfo, new_data)
+
+ metainfo, data = self.setup_data()
+ new_instances = instances.new(metainfo=metainfo)
+
+ def test_clone(self):
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo, **data)
+ new_instances = instances.clone()
+ assert type(new_instances) == type(instances)
+
+ def test_set_metainfo(self):
+ metainfo, _ = self.setup_data()
+ instances = BaseDataElement()
+ instances.set_metainfo(metainfo)
+ self.check_key_value(instances, metainfo=metainfo)
+
+ # test setting existing keys and new keys
+ new_metainfo, _ = self.setup_data()
+ new_metainfo.update(other=123)
+ instances.set_metainfo(new_metainfo)
+ self.check_key_value(instances, metainfo=new_metainfo)
+
+ # test have the same key in data
+ _, data = self.setup_data()
+ instances = BaseDataElement(**data)
+ _, data = self.setup_data()
+ with self.assertRaises(AttributeError):
+ instances.set_metainfo(data)
+
+ with self.assertRaises(AssertionError):
+ instances.set_metainfo(123)
+
+ def test_set_data(self):
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement()
+
+ instances.gt_instances = data['gt_instances']
+ instances.pred_instances = data['pred_instances']
+ self.check_key_value(instances, data=data)
+
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement()
+ instances.set_data(data)
+ self.check_key_value(instances, data=data)
+
+ # a.xx only set data rather than metainfo
+ instances.img_shape = metainfo['img_shape']
+ instances.img_id = metainfo['img_id']
+ self.check_key_value(instances, data=metainfo)
+
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo, **data)
+ with self.assertRaises(AttributeError):
+ instances.img_shape = metainfo['img_shape']
+
+ # test set '_metainfo_fields' or '_data_fields'
+ with self.assertRaises(AttributeError):
+ instances._metainfo_fields = 1
+ with self.assertRaises(AttributeError):
+ instances._data_fields = 1
+
+ with self.assertRaises(AssertionError):
+ instances.set_data(123)
+
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo, **data)
+ with pytest.raises(AttributeError):
+ instances.set_data(dict(img_id=1))
+
+ def test_update(self):
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo, **data)
+ proposals = BaseDataElement(
+ bboxes=torch.rand((5, 4)), scores=torch.rand((5, )))
+ new_instances = BaseDataElement(proposals=proposals)
+ instances.update(new_instances)
+ self.check_key_value(instances, metainfo,
+ data.update(dict(proposals=proposals)))
+
+ def test_delete_modify(self):
+ random.seed(10)
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo, **data)
+
+ new_metainfo, new_data = self.setup_data()
+ # avoid generating same metainfo, data
+ while True:
+ if new_metainfo['img_id'] == metainfo['img_id'] or new_metainfo[
+ 'img_shape'] == metainfo['img_shape']:
+ new_metainfo, new_data = self.setup_data()
+ else:
+ break
+ instances.gt_instances = new_data['gt_instances']
+ instances.pred_instances = new_data['pred_instances']
+
+ # a.xx only set data rather than metainfo
+ instances.set_metainfo(new_metainfo)
+ self.check_key_value(instances, new_metainfo, new_data)
+
+ assert not self.is_equal(instances.gt_instances, data['gt_instances'])
+ assert not self.is_equal(instances.pred_instances,
+ data['pred_instances'])
+ assert not self.is_equal(instances.img_id, metainfo['img_id'])
+ assert not self.is_equal(instances.img_shape, metainfo['img_shape'])
+
+ del instances.gt_instances
+ del instances.img_id
+ assert not self.is_equal(
+ instances.pop('pred_instances', None), data['pred_instances'])
+ with self.assertRaises(AttributeError):
+ del instances.pred_instances
+
+ assert 'gt_instances' not in instances
+ assert 'pred_instances' not in instances
+ assert 'img_id' not in instances
+ assert instances.pop('gt_instances', None) is None
+ # test pop not exist key without default
+ with self.assertRaises(KeyError):
+ instances.pop('gt_instances')
+ assert instances.pop('pred_instances', 'abcdef') == 'abcdef'
+
+ assert instances.pop('img_id', None) is None
+ # test pop not exist key without default
+ with self.assertRaises(KeyError):
+ instances.pop('img_id')
+ assert instances.pop('img_shape') == new_metainfo['img_shape']
+
+ # test del '_metainfo_fields' or '_data_fields'
+ with self.assertRaises(AttributeError):
+ del instances._metainfo_fields
+ with self.assertRaises(AttributeError):
+ del instances._data_fields
+
+ @pytest.mark.skipif(
+ not torch.cuda.is_available(), reason='GPU is required!')
+ def test_cuda(self):
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo, **data)
+
+ cuda_instances = instances.cuda()
+ self.check_data_device(cuda_instances, 'cuda:0')
+
+ # here we further test to convert from cuda to cpu
+ cpu_instances = cuda_instances.cpu()
+ self.check_data_device(cpu_instances, 'cpu')
+ del cuda_instances
+
+ cuda_instances = instances.to('cuda:0')
+ self.check_data_device(cuda_instances, 'cuda:0')
+
+ def test_cpu(self):
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo, **data)
+ self.check_data_device(instances, 'cpu')
+
+ cpu_instances = instances.cpu()
+ # assert cpu_instances.device == 'cpu'
+ assert cpu_instances.gt_instances.bboxes.device == torch.device('cpu')
+ assert cpu_instances.gt_instances.labels.device == torch.device('cpu')
+
+ def test_numpy_tensor(self):
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo, **data)
+
+ np_instances = instances.numpy()
+ self.check_data_dtype(np_instances, np.ndarray)
+
+ tensor_instances = np_instances.to_tensor()
+ self.check_data_dtype(tensor_instances, torch.Tensor)
+
+ def test_detach(self):
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo, **data)
+ instances.detach()
+ self.check_requires_grad(instances)
+
+ def test_repr(self):
+ metainfo = dict(img_shape=(800, 1196, 3))
+ gt_instances = BaseDataElement(
+ metainfo=metainfo, det_labels=torch.LongTensor([0, 1, 2, 3]))
+ sample = BaseDataElement(metainfo=metainfo, gt_instances=gt_instances)
+ address = hex(id(sample))
+ address_gt_instances = hex(id(sample.gt_instances))
+ assert repr(sample) == (
+ '\n'
+ f') at {address}>')
+
+ def test_set_fields(self):
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo)
+ for key, value in data.items():
+ instances.set_field(name=key, value=value, dtype=BaseDataElement)
+ self.check_key_value(instances, data=data)
+
+ # test type check
+ _, data = self.setup_data()
+ instances = BaseDataElement()
+ for key, value in data.items():
+ with self.assertRaises(AssertionError):
+ instances.set_field(name=key, value=value, dtype=torch.Tensor)
+
+ def test_inheritance(self):
+
+ det_sample = DetDataSample()
+
+ # test set
+ proposals = BaseDataElement(bboxes=torch.rand((5, 4)))
+ det_sample.proposals = proposals
+ assert 'proposals' in det_sample
+
+ # test get
+ assert det_sample.proposals == proposals
+
+ # test delete
+ del det_sample.proposals
+ assert 'proposals' not in det_sample
+
+ # test the data whether meet the requirements
+ with self.assertRaises(AssertionError):
+ det_sample.proposals = torch.rand((5, 4))
+
+ def test_values(self):
+ # test_metainfo_values
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo, **data)
+ assert len(instances.metainfo_values()) == len(metainfo.values())
+ # test_all_values
+ assert len(instances.all_values()) == len(metainfo.values()) + len(
+ data.values())
+
+ # test_values
+ assert len(instances.values()) == len(data.values())
+
+ def test_keys(self):
+ # test_metainfo_keys
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo, **data)
+ assert len(instances.metainfo_keys()) == len(metainfo.keys())
+
+ # test_all_keys
+ assert len(
+ instances.all_keys()) == len(data.keys()) + len(metainfo.keys())
+
+ # test_keys
+ assert len(instances.keys()) == len(data.keys())
+
+ det_sample = DetDataSample()
+ proposals = BaseDataElement(bboxes=torch.rand((5, 4)))
+ det_sample.proposals = proposals
+ assert '_proposals' not in det_sample.keys()
+
+ def test_items(self):
+ # test_metainfo_items
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo, **data)
+ assert len(dict(instances.metainfo_items())) == len(
+ dict(metainfo.items()))
+ # test_all_items
+ assert len(dict(instances.all_items())) == len(dict(
+ metainfo.items())) + len(dict(data.items()))
+
+ # test_items
+ assert len(dict(instances.items())) == len(dict(data.items()))
+
+ def test_to_dict(self):
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo, **data)
+ dict_instances = instances.to_dict()
+ # test convert BaseDataElement to dict
+ for k in instances.all_keys():
+ # all keys in instances should be in dict_instances
+ assert k in dict_instances
+ assert isinstance(dict_instances, dict)
+ # sub data element should also be converted to dict
+ assert isinstance(dict_instances['gt_instances'], dict)
+ assert isinstance(dict_instances['pred_instances'], dict)
+
+ det_sample = DetDataSample()
+ proposals = BaseDataElement(bboxes=torch.rand((5, 4)))
+ det_sample.proposals = proposals
+ dict_sample = det_sample.to_dict()
+ assert '_proposals' not in dict_sample
+ assert 'proposals' in dict_sample
+
+ def test_metainfo(self):
+ # test metainfo property
+ metainfo, data = self.setup_data()
+ instances = BaseDataElement(metainfo=metainfo, **data)
+ self.assertDictEqual(instances.metainfo, metainfo)
diff --git a/testbed/open-mmlab__mmengine/tests/test_structures/test_instance_data.py b/testbed/open-mmlab__mmengine/tests/test_structures/test_instance_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe4a1b26038a2a9e59f76c3851241f04f982359f
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_structures/test_instance_data.py
@@ -0,0 +1,223 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import itertools
+import random
+from unittest import TestCase
+
+import numpy as np
+import pytest
+import torch
+
+from mmengine.structures import BaseDataElement, InstanceData
+
+
+class TmpObject:
+
+ def __init__(self, tmp) -> None:
+ assert isinstance(tmp, list)
+ if len(tmp) > 0:
+ for t in tmp:
+ assert isinstance(t, list)
+ self.tmp = tmp
+
+ def __len__(self):
+ return len(self.tmp)
+
+ def __getitem__(self, item):
+ if isinstance(item, int):
+ if item >= len(self) or item < -len(self): # type:ignore
+ raise IndexError(f'Index {item} out of range!')
+ else:
+ # keep the dimension
+ item = slice(item, None, len(self))
+ return TmpObject(self.tmp[item])
+
+ @staticmethod
+ def cat(tmp_objs):
+ assert all(isinstance(results, TmpObject) for results in tmp_objs)
+ if len(tmp_objs) == 1:
+ return tmp_objs[0]
+ tmp_list = [tmp_obj.tmp for tmp_obj in tmp_objs]
+ tmp_list = list(itertools.chain(*tmp_list))
+ new_data = TmpObject(tmp_list)
+ return new_data
+
+ def __repr__(self):
+ return str(self.tmp)
+
+
+class TmpObjectWithoutCat:
+
+ def __init__(self, tmp) -> None:
+ assert isinstance(tmp, list)
+ if len(tmp) > 0:
+ for t in tmp:
+ assert isinstance(t, list)
+ self.tmp = tmp
+
+ def __len__(self):
+ return len(self.tmp)
+
+ def __getitem__(self, item):
+ if isinstance(item, int):
+ if item >= len(self) or item < -len(self): # type:ignore
+ raise IndexError(f'Index {item} out of range!')
+ else:
+ # keep the dimension
+ item = slice(item, None, len(self))
+ return TmpObjectWithoutCat(self.tmp[item])
+
+ def __repr__(self):
+ return str(self.tmp)
+
+
+class TestInstanceData(TestCase):
+
+ def setup_data(self):
+ metainfo = dict(
+ img_id=random.randint(0, 100),
+ img_shape=(random.randint(400, 600), random.randint(400, 600)))
+ instances_infos = [1] * 5
+ bboxes = torch.rand((5, 4))
+ labels = np.random.rand(5)
+ kps = [[1, 1], [2, 2], [3, 3], [4, 4], [5, 5]]
+ ids = (1, 2, 3, 4, 5)
+ name_ids = '12345'
+ polygons = TmpObject(np.arange(25).reshape((5, -1)).tolist())
+ instance_data = InstanceData(
+ metainfo=metainfo,
+ bboxes=bboxes,
+ labels=labels,
+ polygons=polygons,
+ kps=kps,
+ ids=ids,
+ name_ids=name_ids,
+ instances_infos=instances_infos)
+ return instance_data
+
+ def test_set_data(self):
+ instance_data = self.setup_data()
+
+ # test set '_metainfo_fields' or '_data_fields'
+ with self.assertRaises(AttributeError):
+ instance_data._metainfo_fields = 1
+ with self.assertRaises(AttributeError):
+ instance_data._data_fields = 1
+
+ # The data length in InstanceData must be the same
+ with self.assertRaises(AssertionError):
+ instance_data.keypoints = torch.rand((17, 2))
+
+ instance_data.keypoints = torch.rand((5, 2))
+ assert 'keypoints' in instance_data
+
+ def test_getitem(self):
+ instance_data = InstanceData()
+ # length must be greater than 0
+ with self.assertRaises(IndexError):
+ instance_data[1]
+
+ instance_data = self.setup_data()
+ assert len(instance_data) == 5
+ slice_instance_data = instance_data[:2]
+ assert len(slice_instance_data) == 2
+ slice_instance_data = instance_data[1]
+ assert len(slice_instance_data) == 1
+ # assert the index should in 0 ~ len(instance_data) -1
+ with pytest.raises(IndexError):
+ instance_data[5]
+
+ # isinstance(str, slice, int, torch.LongTensor, torch.BoolTensor)
+ item = torch.Tensor([1, 2, 3, 4]) # float
+ with pytest.raises(AssertionError):
+ instance_data[item]
+
+ # when input is a bool tensor, the shape of
+ # the input at index 0 should equal to
+ # the value length in instance_data_field
+ with pytest.raises(AssertionError):
+ instance_data[item.bool()]
+
+ # test LongTensor
+ long_tensor = torch.randint(5, (2, ))
+ long_index_instance_data = instance_data[long_tensor]
+ assert len(long_index_instance_data) == len(long_tensor)
+
+ # test BoolTensor
+ bool_tensor = torch.rand(5) > 0.5
+ bool_index_instance_data = instance_data[bool_tensor]
+ assert len(bool_index_instance_data) == bool_tensor.sum()
+ bool_tensor = torch.rand(5) > 1
+ empty_instance_data = instance_data[bool_tensor]
+ assert len(empty_instance_data) == bool_tensor.sum()
+
+ # test list index
+ list_index = [1, 2]
+ list_index_instance_data = instance_data[list_index]
+ assert len(list_index_instance_data) == len(list_index)
+
+ # test list bool
+ list_bool = [True, False, True, False, False]
+ list_bool_instance_data = instance_data[list_bool]
+ assert len(list_bool_instance_data) == 2
+
+ # test numpy
+ long_numpy = np.random.randint(5, size=2)
+ long_numpy_instance_data = instance_data[long_numpy]
+ assert len(long_numpy_instance_data) == len(long_numpy)
+
+ bool_numpy = np.random.rand(5) > 0.5
+ bool_numpy_instance_data = instance_data[bool_numpy]
+ assert len(bool_numpy_instance_data) == bool_numpy.sum()
+
+ # without cat
+ instance_data.polygons = TmpObjectWithoutCat(
+ np.arange(25).reshape((5, -1)).tolist())
+ bool_numpy = np.random.rand(5) > 0.5
+ with pytest.raises(
+ ValueError,
+ match=('The type of `polygons` is '
+ f'`{type(instance_data.polygons)}`, '
+ 'which has no attribute of `cat`, so it does not '
+ f'support slice with `bool`')):
+ bool_numpy_instance_data = instance_data[bool_numpy]
+
+ def test_cat(self):
+ instance_data_1 = self.setup_data()
+ instance_data_2 = self.setup_data()
+ cat_instance_data = InstanceData.cat(
+ [instance_data_1, instance_data_2])
+ assert len(cat_instance_data) == 10
+
+ # All inputs must be InstanceData
+ instance_data_2 = BaseDataElement(
+ bboxes=torch.rand((5, 4)), labels=torch.rand((5, )))
+ with self.assertRaises(AssertionError):
+ InstanceData.cat([instance_data_1, instance_data_2])
+
+ # Input List length must be greater than 0
+ with self.assertRaises(AssertionError):
+ InstanceData.cat([])
+ instance_data_2 = instance_data_1.clone()
+ instance_data_2 = instance_data_2[torch.zeros(5) > 0.5]
+ cat_instance_data = InstanceData.cat(
+ [instance_data_1, instance_data_2])
+ cat_instance_data = InstanceData.cat([instance_data_1])
+ assert len(cat_instance_data) == 5
+
+ # test custom data cat
+ instance_data_1.polygons = TmpObjectWithoutCat(
+ np.arange(25).reshape((5, -1)).tolist())
+ instance_data_2 = instance_data_1.clone()
+ with pytest.raises(
+ ValueError,
+ match=('The type of `polygons` is '
+ f'`{type(instance_data_1.polygons)}` '
+ 'which has no attribute of `cat`')):
+ cat_instance_data = InstanceData.cat(
+ [instance_data_1, instance_data_2])
+
+ def test_len(self):
+ instance_data = self.setup_data()
+ assert len(instance_data) == 5
+ instance_data = InstanceData()
+ assert len(instance_data) == 0
diff --git a/testbed/open-mmlab__mmengine/tests/test_structures/test_label_data.py b/testbed/open-mmlab__mmengine/tests/test_structures/test_label_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c73bca76762b5def89db4784db6adce1d0bbab2
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_structures/test_label_data.py
@@ -0,0 +1,60 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from unittest import TestCase
+
+import pytest
+import torch
+
+from mmengine.structures import LabelData
+
+
+class TestLabelData(TestCase):
+
+ def test_label_to_onehot(self):
+ item = torch.tensor([1], dtype=torch.int64)
+ num_classes = 10
+ onehot = LabelData.label_to_onehot(label=item, num_classes=num_classes)
+ assert tuple(onehot.shape) == (num_classes, )
+ assert onehot.device == item.device
+ # item is not onehot
+ with self.assertRaises(AssertionError):
+ LabelData.label_to_onehot(label='item', num_classes=num_classes)
+
+ # item'max bigger than num_classes
+ with self.assertRaises(AssertionError):
+ LabelData.label_to_onehot(
+ torch.tensor([11], dtype=torch.int64), num_classes)
+ onehot = LabelData.label_to_onehot(
+ label=torch.tensor([], dtype=torch.int64), num_classes=num_classes)
+ assert (onehot == torch.zeros((num_classes, ),
+ dtype=torch.int64)).all()
+
+ def test_onehot_to_label(self):
+ # item is not onehot
+ with self.assertRaisesRegex(
+ ValueError,
+ 'input is not one-hot and can not convert to label'):
+ LabelData.onehot_to_label(
+ onehot=torch.tensor([2], dtype=torch.int64))
+
+ with self.assertRaises(AssertionError):
+ LabelData.onehot_to_label(onehot='item')
+
+ item = torch.arange(0, 9)
+ onehot = LabelData.label_to_onehot(item, num_classes=10)
+ label = LabelData.onehot_to_label(onehot)
+ assert (label == item).all()
+ assert label.device == item.device
+ item = torch.tensor([2])
+ onehot = LabelData.label_to_onehot(item, num_classes=10)
+ label = LabelData.onehot_to_label(onehot)
+ assert label == item
+ assert label.device == item.device
+
+ @pytest.mark.skipif(
+ not torch.cuda.is_available(), reason='GPU is required!')
+ def test_cuda(self):
+ item = torch.arange(0, 9).cuda()
+ onehot = LabelData.label_to_onehot(item, num_classes=10)
+ assert item.device == onehot.device
+ label = LabelData.onehot_to_label(onehot)
+ assert label.device == onehot.device
diff --git a/testbed/open-mmlab__mmengine/tests/test_structures/test_pixel_data.py b/testbed/open-mmlab__mmengine/tests/test_structures/test_pixel_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ca80373af6706b732a9a9e09ab5f9dc96e89d27
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_structures/test_pixel_data.py
@@ -0,0 +1,83 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import random
+from unittest import TestCase
+
+import numpy as np
+import pytest
+import torch
+
+from mmengine.structures import PixelData
+
+
+class TestPixelData(TestCase):
+
+ def setup_data(self):
+ metainfo = dict(
+ img_id=random.randint(0, 100),
+ img_shape=(random.randint(400, 600), random.randint(400, 600)))
+ image = np.random.randint(0, 255, (4, 20, 40))
+ featmap = torch.randint(0, 255, (10, 20, 40))
+ pixel_data = PixelData(metainfo=metainfo, image=image, featmap=featmap)
+ return pixel_data
+
+ def test_set_data(self):
+ pixel_data = self.setup_data()
+
+ # test set '_metainfo_fields' or '_data_fields'
+ with self.assertRaises(AttributeError):
+ pixel_data._metainfo_fields = 1
+ with self.assertRaises(AttributeError):
+ pixel_data._data_fields = 1
+
+ # value only supports (torch.Tensor, np.ndarray)
+ with self.assertRaises(AssertionError):
+ pixel_data.v = 'value'
+
+ # The width and height must be the same
+ with self.assertRaises(AssertionError):
+ pixel_data.map2 = torch.randint(0, 255, (3, 21, 41))
+
+ # The dimension must be 3 or 2
+ with self.assertRaises(AssertionError):
+ pixel_data.map2 = torch.randint(0, 255, (1, 3, 20, 40))
+
+ pixel_data.map2 = torch.randint(0, 255, (3, 20, 40))
+ assert 'map2' in pixel_data
+
+ pixel_data.map3 = torch.randint(0, 255, (20, 40))
+ assert tuple(pixel_data.map3.shape) == (1, 20, 40)
+
+ def test_getitem(self):
+ pixel_data = PixelData()
+
+ pixel_data = self.setup_data()
+ slice_pixel_data = pixel_data[10:15, 20:30]
+ assert slice_pixel_data.shape == (5, 10)
+
+ pixel_data = self.setup_data()
+ slice_pixel_data = pixel_data[10, 20:30]
+ assert slice_pixel_data.shape == (1, 10)
+
+ # must be tuple
+ item = torch.Tensor([1, 2, 3, 4])
+ with pytest.raises(
+ TypeError,
+ match=f'Unsupported type {type(item)} for slicing PixelData'):
+ pixel_data[item]
+ item = 1
+ with pytest.raises(
+ TypeError,
+ match=f'Unsupported type {type(item)} for slicing PixelData'):
+ pixel_data[item]
+ item = (5.5, 5)
+ with pytest.raises(
+ TypeError,
+ match=('The type of element in input must be int or slice, '
+ f'but got {type(item[0])}')):
+ pixel_data[item]
+
+ def test_shape(self):
+ pixel_data = self.setup_data()
+ assert pixel_data.shape == (20, 40)
+ pixel_data = PixelData()
+ assert pixel_data.shape is None
diff --git a/testbed/open-mmlab__mmengine/tests/test_testing/test_compare.py b/testbed/open-mmlab__mmengine/tests/test_testing/test_compare.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd4e79bc57986ee67068c617cd32e32bf6ee2d33
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_testing/test_compare.py
@@ -0,0 +1,197 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import numpy as np
+import pytest
+
+import mmengine.testing as testing
+
+try:
+ import torch
+except ImportError:
+ torch = None
+else:
+ import torch.nn as nn
+
+
+def test_assert_dict_contains_subset():
+ dict_obj = {'a': 'test1', 'b': 2, 'c': (4, 6)}
+
+ # case 1
+ expected_subset = {'a': 'test1', 'b': 2, 'c': (4, 6)}
+ assert testing.assert_dict_contains_subset(dict_obj, expected_subset)
+
+ # case 2
+ expected_subset = {'a': 'test1', 'b': 2, 'c': (6, 4)}
+ assert not testing.assert_dict_contains_subset(dict_obj, expected_subset)
+
+ # case 3
+ expected_subset = {'a': 'test1', 'b': 2, 'c': None}
+ assert not testing.assert_dict_contains_subset(dict_obj, expected_subset)
+
+ # case 4
+ expected_subset = {'a': 'test1', 'b': 2, 'd': (4, 6)}
+ assert not testing.assert_dict_contains_subset(dict_obj, expected_subset)
+
+ # case 5
+ dict_obj = {
+ 'a': 'test1',
+ 'b': 2,
+ 'c': (4, 6),
+ 'd': np.array([[5, 3, 5], [1, 2, 3]])
+ }
+ expected_subset = {
+ 'a': 'test1',
+ 'b': 2,
+ 'c': (4, 6),
+ 'd': np.array([[5, 3, 5], [6, 2, 3]])
+ }
+ assert not testing.assert_dict_contains_subset(dict_obj, expected_subset)
+
+ # case 6
+ dict_obj = {'a': 'test1', 'b': 2, 'c': (4, 6), 'd': np.array([[1]])}
+ expected_subset = {'a': 'test1', 'b': 2, 'c': (4, 6), 'd': np.array([[1]])}
+ assert testing.assert_dict_contains_subset(dict_obj, expected_subset)
+
+ if torch is not None:
+ dict_obj = {
+ 'a': 'test1',
+ 'b': 2,
+ 'c': (4, 6),
+ 'd': torch.tensor([5, 3, 5])
+ }
+
+ # case 7
+ expected_subset = {'d': torch.tensor([5, 5, 5])}
+ assert not testing.assert_dict_contains_subset(dict_obj,
+ expected_subset)
+
+ # case 8
+ expected_subset = {'d': torch.tensor([[5, 3, 5], [4, 1, 2]])}
+ assert not testing.assert_dict_contains_subset(dict_obj,
+ expected_subset)
+
+
+def test_assert_attrs_equal():
+
+ class TestExample:
+ a, b, c = 1, ('wvi', 3), [4.5, 3.14]
+
+ def test_func(self):
+ return self.b
+
+ # case 1
+ assert testing.assert_attrs_equal(TestExample, {
+ 'a': 1,
+ 'b': ('wvi', 3),
+ 'c': [4.5, 3.14]
+ })
+
+ # case 2
+ assert not testing.assert_attrs_equal(TestExample, {
+ 'a': 1,
+ 'b': ('wvi', 3),
+ 'c': [4.5, 3.14, 2]
+ })
+
+ # case 3
+ assert not testing.assert_attrs_equal(TestExample, {
+ 'bc': 54,
+ 'c': [4.5, 3.14]
+ })
+
+ # case 4
+ assert testing.assert_attrs_equal(TestExample, {
+ 'b': ('wvi', 3),
+ 'test_func': TestExample.test_func
+ })
+
+ if torch is not None:
+
+ class TestExample:
+ a, b = torch.tensor([1]), torch.tensor([4, 5])
+
+ # case 5
+ assert testing.assert_attrs_equal(TestExample, {
+ 'a': torch.tensor([1]),
+ 'b': torch.tensor([4, 5])
+ })
+
+ # case 6
+ assert not testing.assert_attrs_equal(TestExample, {
+ 'a': torch.tensor([1]),
+ 'b': torch.tensor([4, 6])
+ })
+
+
+assert_dict_has_keys_data_1 = [({
+ 'res_layer': 1,
+ 'norm_layer': 2,
+ 'dense_layer': 3
+})]
+assert_dict_has_keys_data_2 = [(['res_layer', 'dense_layer'], True),
+ (['res_layer', 'conv_layer'], False)]
+
+
+@pytest.mark.parametrize('obj', assert_dict_has_keys_data_1)
+@pytest.mark.parametrize('expected_keys, ret_value',
+ assert_dict_has_keys_data_2)
+def test_assert_dict_has_keys(obj, expected_keys, ret_value):
+ assert testing.assert_dict_has_keys(obj, expected_keys) == ret_value
+
+
+assert_keys_equal_data_1 = [(['res_layer', 'norm_layer', 'dense_layer'])]
+assert_keys_equal_data_2 = [(['res_layer', 'norm_layer', 'dense_layer'], True),
+ (['res_layer', 'dense_layer', 'norm_layer'], True),
+ (['res_layer', 'norm_layer'], False),
+ (['res_layer', 'conv_layer', 'norm_layer'], False)]
+
+
+@pytest.mark.parametrize('result_keys', assert_keys_equal_data_1)
+@pytest.mark.parametrize('target_keys, ret_value', assert_keys_equal_data_2)
+def test_assert_keys_equal(result_keys, target_keys, ret_value):
+ assert testing.assert_keys_equal(result_keys, target_keys) == ret_value
+
+
+@pytest.mark.skipif(torch is None, reason='requires torch library')
+def test_assert_is_norm_layer():
+ # case 1
+ assert not testing.assert_is_norm_layer(nn.Conv3d(3, 64, 3))
+
+ # case 2
+ assert testing.assert_is_norm_layer(nn.BatchNorm3d(128))
+
+ # case 3
+ assert testing.assert_is_norm_layer(nn.GroupNorm(8, 64))
+
+ # case 4
+ assert not testing.assert_is_norm_layer(nn.Sigmoid())
+
+
+@pytest.mark.skipif(torch is None, reason='requires torch library')
+def test_assert_params_all_zeros():
+ demo_module = nn.Conv2d(3, 64, 3)
+ nn.init.constant_(demo_module.weight, 0)
+ nn.init.constant_(demo_module.bias, 0)
+ assert testing.assert_params_all_zeros(demo_module)
+
+ nn.init.xavier_normal_(demo_module.weight)
+ nn.init.constant_(demo_module.bias, 0)
+ assert not testing.assert_params_all_zeros(demo_module)
+
+ demo_module = nn.Linear(2048, 400, bias=False)
+ nn.init.constant_(demo_module.weight, 0)
+ assert testing.assert_params_all_zeros(demo_module)
+
+ nn.init.normal_(demo_module.weight, mean=0, std=0.01)
+ assert not testing.assert_params_all_zeros(demo_module)
+
+
+def test_check_python_script(capsys):
+ testing.check_python_script('./tests/data/scripts/hello.py zz')
+ captured = capsys.readouterr().out
+ assert captured == 'hello zz!\n'
+ testing.check_python_script('./tests/data/scripts/hello.py agent')
+ captured = capsys.readouterr().out
+ assert captured == 'hello agent!\n'
+ # Make sure that wrong cmd raises an error
+ with pytest.raises(SystemExit):
+ testing.check_python_script('./tests/data/scripts/hello.py li zz')
diff --git a/testbed/open-mmlab__mmengine/tests/test_testing/test_runner_test_case.py b/testbed/open-mmlab__mmengine/tests/test_testing/test_runner_test_case.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d41c03531da7e4d0be7d9ea326ff0925d65adc5
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_testing/test_runner_test_case.py
@@ -0,0 +1,58 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+
+from mmengine import Config
+from mmengine.logging import MessageHub, MMLogger
+from mmengine.registry import DefaultScope
+from mmengine.testing import RunnerTestCase
+from mmengine.visualization import Visualizer
+
+
+class TestRunnerTestCase(RunnerTestCase):
+
+ def test_setup(self):
+ self.assertIsInstance(self.epoch_based_cfg, Config)
+ self.assertIsInstance(self.iter_based_cfg, Config)
+ self.assertIn('MASTER_ADDR', self.dist_cfg)
+ self.assertIn('MASTER_PORT', self.dist_cfg)
+ self.assertIn('RANK', self.dist_cfg)
+ self.assertIn('WORLD_SIZE', self.dist_cfg)
+ self.assertIn('LOCAL_RANK', self.dist_cfg)
+
+ def test_tearDown(self):
+ self.tearDown()
+ self.assertEqual(MMLogger._instance_dict, {})
+ self.assertEqual(MessageHub._instance_dict, {})
+ self.assertEqual(Visualizer._instance_dict, {})
+ self.assertEqual(DefaultScope._instance_dict, {})
+ # tearDown should not be called twice.
+ self.tearDown = super(RunnerTestCase, self).tearDown
+
+ def test_build_runner(self):
+ runner = self.build_runner(self.epoch_based_cfg)
+ runner.train()
+ runner.val()
+ runner.test()
+
+ runner = self.build_runner(self.iter_based_cfg)
+ runner.train()
+ runner.val()
+ runner.test()
+
+ def test_experiment_name(self):
+ runner1 = self.build_runner(self.epoch_based_cfg)
+ runner2 = self.build_runner(self.epoch_based_cfg)
+ self.assertNotEqual(runner1.experiment_name, runner2.experiment_name)
+
+ def test_init_dist(self):
+ self.setup_dist_env()
+ self.assertEqual(
+ str(self.dist_cfg['MASTER_PORT']), os.environ['MASTER_PORT'])
+ self.assertEqual(self.dist_cfg['MASTER_ADDR'],
+ os.environ['MASTER_ADDR'])
+ self.assertEqual(self.dist_cfg['RANK'], os.environ['RANK'])
+ self.assertEqual(self.dist_cfg['LOCAL_RANK'], os.environ['LOCAL_RANK'])
+ self.assertEqual(self.dist_cfg['WORLD_SIZE'], os.environ['WORLD_SIZE'])
+ fisrt_port = os.environ['MASTER_ADDR']
+ self.setup_dist_env()
+ self.assertNotEqual(fisrt_port, os.environ['MASTER_PORT'])
diff --git a/testbed/open-mmlab__mmengine/tests/test_utils/test_dl_utils/test_get_env.py b/testbed/open-mmlab__mmengine/tests/test_utils/test_dl_utils/test_get_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..38d258acbe75e7e7ea6ab302df4aebded52dd028
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_utils/test_dl_utils/test_get_env.py
@@ -0,0 +1,26 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import sys
+from unittest import TestCase
+
+import mmengine
+from mmengine.utils.dl_utils import collect_env
+
+
+class TestCollectEnv(TestCase):
+
+ def test_collect_env(self):
+ env_info = collect_env()
+ expected_keys = [
+ 'sys.platform', 'Python', 'CUDA available', 'PyTorch',
+ 'PyTorch compiling details', 'OpenCV', 'MMEngine', 'GCC'
+ ]
+ for key in expected_keys:
+ assert key in env_info
+
+ if env_info['CUDA available']:
+ for key in ['CUDA_HOME', 'NVCC']:
+ assert key in env_info
+
+ assert env_info['sys.platform'] == sys.platform
+ assert env_info['Python'] == sys.version.replace('\n', '')
+ assert env_info['MMEngine'] == mmengine.__version__
diff --git a/testbed/open-mmlab__mmengine/tests/test_utils/test_dl_utils/test_setup_env.py b/testbed/open-mmlab__mmengine/tests/test_utils/test_dl_utils/test_setup_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ca98b43112450c44bca63e6f969d3599dc9500c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_utils/test_dl_utils/test_setup_env.py
@@ -0,0 +1,58 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import multiprocessing as mp
+import os
+import platform
+
+import cv2
+
+from mmengine.utils.dl_utils import set_multi_processing
+
+
+def test_setup_multi_processes():
+ # temp save system setting
+ sys_start_mehod = mp.get_start_method(allow_none=True)
+ sys_cv_threads = cv2.getNumThreads()
+ # pop and temp save system env vars
+ sys_omp_threads = os.environ.pop('OMP_NUM_THREADS', default=None)
+ sys_mkl_threads = os.environ.pop('MKL_NUM_THREADS', default=None)
+
+ # test distributed
+ set_multi_processing(distributed=True)
+ assert os.getenv('OMP_NUM_THREADS') == '1'
+ assert os.getenv('MKL_NUM_THREADS') == '1'
+ # when set to 0, the num threads will be 1
+ assert cv2.getNumThreads() == 1
+ if platform.system() != 'Windows':
+ assert mp.get_start_method() == 'fork'
+
+ # test num workers <= 1
+ os.environ.pop('OMP_NUM_THREADS')
+ os.environ.pop('MKL_NUM_THREADS')
+ set_multi_processing(distributed=False)
+ assert 'OMP_NUM_THREADS' not in os.environ
+ assert 'MKL_NUM_THREADS' not in os.environ
+
+ # test manually set env var
+ os.environ['OMP_NUM_THREADS'] = '4'
+ set_multi_processing(distributed=False)
+ assert os.getenv('OMP_NUM_THREADS') == '4'
+
+ # test manually set opencv threads and mp start method
+ config = dict(
+ mp_start_method='spawn', opencv_num_threads=4, distributed=True)
+ set_multi_processing(**config)
+ assert cv2.getNumThreads() == 4
+ assert mp.get_start_method() == 'spawn'
+
+ # revert setting to avoid affecting other programs
+ if sys_start_mehod:
+ mp.set_start_method(sys_start_mehod, force=True)
+ cv2.setNumThreads(sys_cv_threads)
+ if sys_omp_threads:
+ os.environ['OMP_NUM_THREADS'] = sys_omp_threads
+ else:
+ os.environ.pop('OMP_NUM_THREADS')
+ if sys_mkl_threads:
+ os.environ['MKL_NUM_THREADS'] = sys_mkl_threads
+ else:
+ os.environ.pop('MKL_NUM_THREADS')
diff --git a/testbed/open-mmlab__mmengine/tests/test_utils/test_dl_utils/test_time_counter.py b/testbed/open-mmlab__mmengine/tests/test_utils/test_dl_utils/test_time_counter.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c7d884ab9641cbde7844aca140863c35c9b73cc
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_utils/test_dl_utils/test_time_counter.py
@@ -0,0 +1,55 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import time
+import unittest
+
+from mmengine.utils.dl_utils.time_counter import TimeCounter
+
+
+class TestTimeCounter(unittest.TestCase):
+
+ def test_decorate_timer(self):
+
+ @TimeCounter()
+ def demo_fun():
+ time.sleep(0.1)
+
+ demo_fun()
+
+ @TimeCounter()
+ def demo_fun():
+ time.sleep(0.1)
+
+ for _ in range(10):
+ demo_fun()
+
+ @TimeCounter(log_interval=2, with_sync=False, tag='demo_fun1')
+ def demo_fun():
+ time.sleep(0.1)
+
+ demo_fun()
+
+ # warmup_interval must be greater than 0
+ with self.assertRaises(AssertionError):
+
+ @TimeCounter(warmup_interval=0)
+ def demo_fun():
+ time.sleep(0.1)
+
+ def test_context_timer(self):
+
+ # tag must be specified in context mode
+ with self.assertRaises(AssertionError):
+ with TimeCounter():
+ time.sleep(0.1)
+
+ # warmup_interval must be greater than 0
+ with self.assertRaises(AssertionError):
+ with TimeCounter(warmup_interval=0, tag='func_1'):
+ time.sleep(0.1)
+
+ with TimeCounter(tag='func_1'):
+ time.sleep(0.1)
+
+ for _ in range(10):
+ with TimeCounter(log_interval=2, with_sync=False, tag='func_2'):
+ time.sleep(0.1)
diff --git a/testbed/open-mmlab__mmengine/tests/test_utils/test_dl_utils/test_torch_ops.py b/testbed/open-mmlab__mmengine/tests/test_utils/test_dl_utils/test_torch_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fffaf7f539f3989a57b299d27357743788eff37
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_utils/test_dl_utils/test_torch_ops.py
@@ -0,0 +1,15 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import pytest
+import torch
+
+from mmengine.utils.dl_utils import torch_meshgrid
+
+
+def test_torch_meshgrid():
+ # torch_meshgrid should not throw warning
+ with pytest.warns(None) as record:
+ x = torch.tensor([1, 2, 3])
+ y = torch.tensor([4, 5, 6])
+ grid_x, grid_y = torch_meshgrid(x, y)
+
+ assert len(record) == 0
diff --git a/testbed/open-mmlab__mmengine/tests/test_utils/test_dl_utils/test_trace.py b/testbed/open-mmlab__mmengine/tests/test_utils/test_dl_utils/test_trace.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4ff6fea8770b4546441c8aa68219ebc33a7845c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_utils/test_dl_utils/test_trace.py
@@ -0,0 +1,26 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import pytest
+import torch
+
+from mmengine.utils import digit_version
+from mmengine.utils.dl_utils import is_jit_tracing
+
+
+@pytest.mark.skipif(
+ digit_version(torch.__version__) < digit_version('1.6.0'),
+ reason='torch.jit.is_tracing is not available before 1.6.0')
+def test_is_jit_tracing():
+
+ def foo(x):
+ if is_jit_tracing():
+ return x
+ else:
+ return x.tolist()
+
+ x = torch.rand(3)
+ # test without trace
+ assert isinstance(foo(x), list)
+
+ # test with trace
+ traced_foo = torch.jit.trace(foo, (torch.rand(1), ))
+ assert isinstance(traced_foo(x), torch.Tensor)
diff --git a/testbed/open-mmlab__mmengine/tests/test_utils/test_manager.py b/testbed/open-mmlab__mmengine/tests/test_utils/test_manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..be9348e2d5dfd6fd3ab174d5e279d711f31ef18d
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_utils/test_manager.py
@@ -0,0 +1,76 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import pytest
+
+from mmengine.utils import ManagerMeta, ManagerMixin
+
+
+class SubClassA(ManagerMixin):
+
+ def __init__(self, name='', *args, **kwargs):
+ super().__init__(name, *args, **kwargs)
+
+
+class SubClassB(ManagerMixin):
+
+ def __init__(self, name='', *args, **kwargs):
+ super().__init__(name, *args, **kwargs)
+
+
+class TestGlobalMeta:
+
+ def test_init(self):
+ # Subclass's constructor does not contain name arguments will raise an
+ # error.
+ with pytest.raises(AssertionError):
+
+ class SubClassNoName1(metaclass=ManagerMeta):
+
+ def __init__(self, a, *args, **kwargs):
+ pass
+
+ # Valid subclass.
+ class GlobalAccessible1(metaclass=ManagerMeta):
+
+ def __init__(self, name):
+ self.name = name
+
+
+class TestManagerMixin:
+
+ def test_init(self):
+ # test create instance by name.
+ base_cls = ManagerMixin('name')
+ assert base_cls.instance_name == 'name'
+
+ def test_get_instance(self):
+ # SubClass should manage their own `_instance_dict`.
+ with pytest.raises(RuntimeError):
+ SubClassA.get_current_instance()
+ SubClassA.get_instance('instance_a')
+ SubClassB.get_instance('instance_b')
+ assert SubClassB._instance_dict != SubClassA._instance_dict
+
+ # Test `message_hub` can create by name.
+ message_hub = SubClassA.get_instance('name1')
+ assert message_hub.instance_name == 'name1'
+ # No arguments will raise an assertion error.
+
+ SubClassA.get_instance('name2')
+ message_hub = SubClassA.get_current_instance()
+ message_hub.mark = -1
+ assert message_hub.instance_name == 'name2'
+ # Test get latest `message_hub` repeatedly.
+ message_hub = SubClassA.get_instance('name3')
+ assert message_hub.instance_name == 'name3'
+ message_hub = SubClassA.get_current_instance()
+ assert message_hub.instance_name == 'name3'
+ # Test get name2 repeatedly.
+ message_hub = SubClassA.get_instance('name2')
+ assert message_hub.mark == -1
+ # Non-string instance name will raise `AssertionError`.
+ with pytest.raises(AssertionError):
+ SubClassA.get_instance(name=1)
+ # `get_instance` should not accept other arguments if corresponding
+ # instance has been created.
+ with pytest.raises(AssertionError):
+ SubClassA.get_instance('name2', a=1, b=2)
diff --git a/testbed/open-mmlab__mmengine/tests/test_utils/test_misc.py b/testbed/open-mmlab__mmengine/tests/test_utils/test_misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..95d7a006bddb35d80e208d97ec29a7bd4c4cfd8c
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_utils/test_misc.py
@@ -0,0 +1,285 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import pytest
+
+from mmengine import MMLogger
+# yapf: disable
+from mmengine.utils.misc import (concat_list, deprecated_api_warning,
+ deprecated_function, has_method,
+ import_modules_from_strings, is_list_of,
+ is_method_overridden, is_seq_of, is_tuple_of,
+ iter_cast, list_cast, requires_executable,
+ requires_package, slice_list, to_1tuple,
+ to_2tuple, to_3tuple, to_4tuple, to_ntuple,
+ tuple_cast)
+
+# yapf: enable
+
+
+def test_to_ntuple():
+ single_number = 2
+ assert to_1tuple(single_number) == (single_number, )
+ assert to_2tuple(single_number) == (single_number, single_number)
+ assert to_3tuple(single_number) == (single_number, single_number,
+ single_number)
+ assert to_4tuple(single_number) == (single_number, single_number,
+ single_number, single_number)
+ assert to_ntuple(5)(single_number) == (single_number, single_number,
+ single_number, single_number,
+ single_number)
+ assert to_ntuple(6)(single_number) == (single_number, single_number,
+ single_number, single_number,
+ single_number, single_number)
+
+
+def test_iter_cast():
+ assert list_cast([1, 2, 3], int) == [1, 2, 3]
+ assert list_cast(['1.1', 2, '3'], float) == [1.1, 2.0, 3.0]
+ assert list_cast([1, 2, 3], str) == ['1', '2', '3']
+ assert tuple_cast((1, 2, 3), str) == ('1', '2', '3')
+ assert next(iter_cast([1, 2, 3], str)) == '1'
+ with pytest.raises(TypeError):
+ iter_cast([1, 2, 3], '')
+ with pytest.raises(TypeError):
+ iter_cast(1, str)
+
+
+def test_is_seq_of():
+ assert is_seq_of([1.0, 2.0, 3.0], float)
+ assert is_seq_of([(1, ), (2, ), (3, )], tuple)
+ assert is_seq_of((1.0, 2.0, 3.0), float)
+ assert is_list_of([1.0, 2.0, 3.0], float)
+ assert not is_seq_of((1.0, 2.0, 3.0), float, seq_type=list)
+ assert not is_tuple_of([1.0, 2.0, 3.0], float)
+ assert not is_seq_of([1.0, 2, 3], int)
+ assert not is_seq_of((1.0, 2, 3), int)
+
+
+def test_slice_list():
+ in_list = [1, 2, 3, 4, 5, 6]
+ assert slice_list(in_list, [1, 2, 3]) == [[1], [2, 3], [4, 5, 6]]
+ assert slice_list(in_list, [len(in_list)]) == [in_list]
+ with pytest.raises(TypeError):
+ slice_list(in_list, 2.0)
+ with pytest.raises(ValueError):
+ slice_list(in_list, [1, 2])
+
+
+def test_concat_list():
+ assert concat_list([[1, 2]]) == [1, 2]
+ assert concat_list([[1, 2], [3, 4, 5], [6]]) == [1, 2, 3, 4, 5, 6]
+
+
+def test_requires_package(capsys):
+
+ @requires_package('nnn')
+ def func_a():
+ pass
+
+ @requires_package(['numpy', 'n1', 'n2'])
+ def func_b():
+ pass
+
+ @requires_package('numpy')
+ def func_c():
+ return 1
+
+ with pytest.raises(RuntimeError):
+ func_a()
+ out, _ = capsys.readouterr()
+ assert out == ('Prerequisites "nnn" are required in method "func_a" but '
+ 'not found, please install them first.\n')
+
+ with pytest.raises(RuntimeError):
+ func_b()
+ out, _ = capsys.readouterr()
+ assert out == (
+ 'Prerequisites "n1, n2" are required in method "func_b" but not found,'
+ ' please install them first.\n')
+
+ assert func_c() == 1
+
+
+def test_requires_executable(capsys):
+
+ @requires_executable('nnn')
+ def func_a():
+ pass
+
+ @requires_executable(['ls', 'n1', 'n2'])
+ def func_b():
+ pass
+
+ @requires_executable('mv')
+ def func_c():
+ return 1
+
+ with pytest.raises(RuntimeError):
+ func_a()
+ out, _ = capsys.readouterr()
+ assert out == ('Prerequisites "nnn" are required in method "func_a" but '
+ 'not found, please install them first.\n')
+
+ with pytest.raises(RuntimeError):
+ func_b()
+ out, _ = capsys.readouterr()
+ assert out == (
+ 'Prerequisites "n1, n2" are required in method "func_b" but not found,'
+ ' please install them first.\n')
+
+ assert func_c() == 1
+
+
+def test_import_modules_from_strings():
+ # multiple imports
+ import os.path as osp_
+ import sys as sys_
+ osp, sys = import_modules_from_strings(['os.path', 'sys'])
+ assert osp == osp_
+ assert sys == sys_
+
+ # single imports
+ osp = import_modules_from_strings('os.path')
+ assert osp == osp_
+ # No imports
+ assert import_modules_from_strings(None) is None
+ assert import_modules_from_strings([]) is None
+ assert import_modules_from_strings('') is None
+ # Unsupported types
+ with pytest.raises(TypeError):
+ import_modules_from_strings(1)
+ with pytest.raises(TypeError):
+ import_modules_from_strings([1])
+ # Failed imports
+ with pytest.raises(ImportError):
+ import_modules_from_strings('_not_implemented_module')
+ with pytest.warns(UserWarning):
+ imported = import_modules_from_strings(
+ '_not_implemented_module', allow_failed_imports=True)
+ assert imported is None
+ with pytest.warns(UserWarning):
+ imported = import_modules_from_strings(['os.path', '_not_implemented'],
+ allow_failed_imports=True)
+ assert imported[0] == osp
+ assert imported[1] is None
+
+
+def test_is_method_overridden():
+
+ class Base:
+
+ def foo1():
+ pass
+
+ def foo2():
+ pass
+
+ class Sub(Base):
+
+ def foo1():
+ pass
+
+ # test passing sub class directly
+ assert is_method_overridden('foo1', Base, Sub)
+ assert not is_method_overridden('foo2', Base, Sub)
+
+ # test passing instance of sub class
+ sub_instance = Sub()
+ assert is_method_overridden('foo1', Base, sub_instance)
+ assert not is_method_overridden('foo2', Base, sub_instance)
+
+ # base_class should be a class, not instance
+ base_instance = Base()
+ with pytest.raises(AssertionError):
+ is_method_overridden('foo1', base_instance, sub_instance)
+
+
+def test_has_method():
+
+ class Foo:
+
+ def __init__(self, name):
+ self.name = name
+
+ def print_name(self):
+ print(self.name)
+
+ foo = Foo('foo')
+ assert not has_method(foo, 'name')
+ assert has_method(foo, 'print_name')
+
+
+def test_deprecated_api_warning():
+
+ @deprecated_api_warning(name_dict=dict(old_key='new_key'))
+ def dummy_func(new_key=1):
+ return new_key
+
+ # replace `old_key` to `new_key`
+ assert dummy_func(old_key=2) == 2
+
+ # The expected behavior is to replace the
+ # deprecated key `old_key` to `new_key`,
+ # but got them in the arguments at the same time
+ with pytest.raises(AssertionError):
+ dummy_func(old_key=1, new_key=2)
+
+
+def test_deprecated_function():
+
+ @deprecated_function('0.2.0', '0.3.0', 'toy instruction')
+ def deprecated_demo(arg1: int, arg2: int) -> tuple:
+ """This is a long summary. This is a long summary. This is a long
+ summary. This is a long summary.
+
+ Args:
+ arg1 (int): Long description with a line break. Long description
+ with a line break.
+ arg2 (int): short description.
+
+ Returns:
+ Long description without a line break. Long description without
+ a line break.
+ """
+
+ return arg1, arg2
+
+ MMLogger.get_instance('test_deprecated_function')
+ deprecated_demo(1, 2)
+ # out, _ = capsys.readouterr()
+ # assert "'test_misc.deprecated_demo' is deprecated" in out
+ assert (1, 2) == deprecated_demo(1, 2)
+
+ expected_docstring = \
+ """.. deprecated:: 0.2.0
+ Deprecated and will be removed in version 0.3.0.
+ Please toy instruction.
+
+
+ This is a long summary. This is a long summary. This is a long
+ summary. This is a long summary.
+
+ Args:
+ arg1 (int): Long description with a line break. Long description
+ with a line break.
+ arg2 (int): short description.
+
+ Returns:
+ Long description without a line break. Long description without
+ a line break.
+ """ # noqa: E122
+ assert expected_docstring.strip(' ') == deprecated_demo.__doc__
+ MMLogger._instance_dict.clear()
+
+ # Test with short summary without args.
+ @deprecated_function('0.2.0', '0.3.0', 'toy instruction')
+ def deprecated_demo1():
+ """Short summary."""
+
+ expected_docstring = \
+ """.. deprecated:: 0.2.0
+ Deprecated and will be removed in version 0.3.0.
+ Please toy instruction.
+
+
+ Short summary.""" # noqa: E122
+ assert expected_docstring.strip(' ') == deprecated_demo1.__doc__
diff --git a/testbed/open-mmlab__mmengine/tests/test_utils/test_progressbar.py b/testbed/open-mmlab__mmengine/tests/test_utils/test_progressbar.py
new file mode 100644
index 0000000000000000000000000000000000000000..04e7cb8457885afe2abae7693da08615e6703c78
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_utils/test_progressbar.py
@@ -0,0 +1,164 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import time
+from io import StringIO
+from unittest.mock import patch
+
+import mmengine
+
+
+def reset_string_io(io):
+ io.truncate(0)
+ io.seek(0)
+
+
+class TestProgressBar:
+
+ def test_start(self):
+ out = StringIO()
+ bar_width = 20
+ # without total task num
+ prog_bar = mmengine.ProgressBar(bar_width=bar_width, file=out)
+ assert out.getvalue() == 'completed: 0, elapsed: 0s'
+ reset_string_io(out)
+ prog_bar = mmengine.ProgressBar(
+ bar_width=bar_width, start=False, file=out)
+ assert out.getvalue() == ''
+ reset_string_io(out)
+ prog_bar.start()
+ assert out.getvalue() == 'completed: 0, elapsed: 0s'
+ # with total task num
+ reset_string_io(out)
+ prog_bar = mmengine.ProgressBar(10, bar_width=bar_width, file=out)
+ assert out.getvalue() == f'[{" " * bar_width}] 0/10, elapsed: 0s, ETA:'
+ reset_string_io(out)
+ prog_bar = mmengine.ProgressBar(
+ 10, bar_width=bar_width, start=False, file=out)
+ assert out.getvalue() == ''
+ reset_string_io(out)
+ prog_bar.start()
+ assert out.getvalue() == f'[{" " * bar_width}] 0/10, elapsed: 0s, ETA:'
+
+ def test_update(self):
+ out = StringIO()
+ bar_width = 20
+ # without total task num
+ prog_bar = mmengine.ProgressBar(bar_width=bar_width, file=out)
+ time.sleep(1)
+ reset_string_io(out)
+ prog_bar.update()
+ assert out.getvalue() == 'completed: 1, elapsed: 1s, 1.0 tasks/s'
+ reset_string_io(out)
+ # with total task num
+ prog_bar = mmengine.ProgressBar(10, bar_width=bar_width, file=out)
+ time.sleep(1)
+ reset_string_io(out)
+ prog_bar.update()
+ assert out.getvalue() == f'\r[{">" * 2 + " " * 18}] 1/10, 1.0 ' \
+ 'task/s, elapsed: 1s, ETA: 9s'
+
+ def test_adaptive_length(self):
+ with patch.dict('os.environ', {'COLUMNS': '80'}):
+ out = StringIO()
+ bar_width = 20
+ prog_bar = mmengine.ProgressBar(10, bar_width=bar_width, file=out)
+ time.sleep(1)
+ reset_string_io(out)
+ prog_bar.update()
+ assert len(out.getvalue()) == 66
+
+ os.environ['COLUMNS'] = '30'
+ reset_string_io(out)
+ prog_bar.update()
+ assert len(out.getvalue()) == 48
+
+ os.environ['COLUMNS'] = '60'
+ reset_string_io(out)
+ prog_bar.update()
+ assert len(out.getvalue()) == 60
+
+
+def sleep_1s(num):
+ time.sleep(1)
+ return num
+
+
+def test_track_progress_list():
+ out = StringIO()
+ ret = mmengine.track_progress(sleep_1s, [1, 2, 3], bar_width=3, file=out)
+ assert out.getvalue() == (
+ '[ ] 0/3, elapsed: 0s, ETA:'
+ '\r[> ] 1/3, 1.0 task/s, elapsed: 1s, ETA: 2s'
+ '\r[>> ] 2/3, 1.0 task/s, elapsed: 2s, ETA: 1s'
+ '\r[>>>] 3/3, 1.0 task/s, elapsed: 3s, ETA: 0s\n')
+ assert ret == [1, 2, 3]
+
+
+def test_track_progress_iterator():
+ out = StringIO()
+ ret = mmengine.track_progress(
+ sleep_1s, ((i for i in [1, 2, 3]), 3), bar_width=3, file=out)
+ assert out.getvalue() == (
+ '[ ] 0/3, elapsed: 0s, ETA:'
+ '\r[> ] 1/3, 1.0 task/s, elapsed: 1s, ETA: 2s'
+ '\r[>> ] 2/3, 1.0 task/s, elapsed: 2s, ETA: 1s'
+ '\r[>>>] 3/3, 1.0 task/s, elapsed: 3s, ETA: 0s\n')
+ assert ret == [1, 2, 3]
+
+
+def test_track_iter_progress():
+ out = StringIO()
+ ret = []
+ for num in mmengine.track_iter_progress([1, 2, 3], bar_width=3, file=out):
+ ret.append(sleep_1s(num))
+ assert out.getvalue() == (
+ '[ ] 0/3, elapsed: 0s, ETA:'
+ '\r[> ] 1/3, 1.0 task/s, elapsed: 1s, ETA: 2s'
+ '\r[>> ] 2/3, 1.0 task/s, elapsed: 2s, ETA: 1s'
+ '\r[>>>] 3/3, 1.0 task/s, elapsed: 3s, ETA: 0s\n')
+ assert ret == [1, 2, 3]
+
+
+def test_track_enum_progress():
+ out = StringIO()
+ ret = []
+ count = []
+ for i, num in enumerate(
+ mmengine.track_iter_progress([1, 2, 3], bar_width=3, file=out)):
+ ret.append(sleep_1s(num))
+ count.append(i)
+ assert out.getvalue() == (
+ '[ ] 0/3, elapsed: 0s, ETA:'
+ '\r[> ] 1/3, 1.0 task/s, elapsed: 1s, ETA: 2s'
+ '\r[>> ] 2/3, 1.0 task/s, elapsed: 2s, ETA: 1s'
+ '\r[>>>] 3/3, 1.0 task/s, elapsed: 3s, ETA: 0s\n')
+ assert ret == [1, 2, 3]
+ assert count == [0, 1, 2]
+
+
+def test_track_parallel_progress_list():
+ out = StringIO()
+ results = mmengine.track_parallel_progress(
+ sleep_1s, [1, 2, 3, 4], 2, bar_width=4, file=out)
+ # The following cannot pass CI on Github Action
+ # assert out.getvalue() == (
+ # '[ ] 0/4, elapsed: 0s, ETA:'
+ # '\r[> ] 1/4, 1.0 task/s, elapsed: 1s, ETA: 3s'
+ # '\r[>> ] 2/4, 2.0 task/s, elapsed: 1s, ETA: 1s'
+ # '\r[>>> ] 3/4, 1.5 task/s, elapsed: 2s, ETA: 1s'
+ # '\r[>>>>] 4/4, 2.0 task/s, elapsed: 2s, ETA: 0s\n')
+ assert results == [1, 2, 3, 4]
+
+
+def test_track_parallel_progress_iterator():
+ out = StringIO()
+ results = mmengine.track_parallel_progress(
+ sleep_1s, ((i for i in [1, 2, 3, 4]), 4), 2, bar_width=4, file=out)
+ # The following cannot pass CI on Github Action
+ # assert out.getvalue() == (
+ # '[ ] 0/4, elapsed: 0s, ETA:'
+ # '\r[> ] 1/4, 1.0 task/s, elapsed: 1s, ETA: 3s'
+ # '\r[>> ] 2/4, 2.0 task/s, elapsed: 1s, ETA: 1s'
+ # '\r[>>> ] 3/4, 1.5 task/s, elapsed: 2s, ETA: 1s'
+ # '\r[>>>>] 4/4, 2.0 task/s, elapsed: 2s, ETA: 0s\n')
+ assert results == [1, 2, 3, 4]
diff --git a/testbed/open-mmlab__mmengine/tests/test_utils/test_timer.py b/testbed/open-mmlab__mmengine/tests/test_utils/test_timer.py
new file mode 100644
index 0000000000000000000000000000000000000000..570f7ea380dddb261a5ff16a7e0e3b5c30960f9b
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_utils/test_timer.py
@@ -0,0 +1,51 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import platform
+import time
+
+import pytest
+
+import mmengine
+
+
+@pytest.mark.skipif(
+ platform.system() != 'Linux', reason='Only test `Timer` in linux!')
+def test_timer_init():
+ timer = mmengine.Timer(start=False)
+ assert not timer.is_running
+ timer.start()
+ assert timer.is_running
+ timer = mmengine.Timer()
+ assert timer.is_running
+
+
+@pytest.mark.skipif(
+ platform.system() != 'Linux', reason='Only test `Timer` in linux!')
+def test_timer_run():
+ timer = mmengine.Timer()
+ time.sleep(1)
+ # In Windows, the error could be larger than 20ms. More details in
+ # https://stackoverflow.com/questions/11657734/sleep-for-exact-time-in-python. # noqa: E501
+ assert abs(timer.since_start() - 1) < 3e-2
+ time.sleep(1)
+ assert abs(timer.since_last_check() - 1) < 3e-2
+ assert abs(timer.since_start() - 2) < 3e-2
+ timer = mmengine.Timer(False)
+ with pytest.raises(mmengine.TimerError):
+ timer.since_start()
+ with pytest.raises(mmengine.TimerError):
+ timer.since_last_check()
+
+
+@pytest.mark.skipif(
+ platform.system() != 'Linux', reason='Only test `Timer` in linux!')
+def test_timer_context(capsys):
+ with mmengine.Timer():
+ time.sleep(1)
+ out, _ = capsys.readouterr()
+ # In Windows, the error could be larger than 20ms. More details in
+ # https://stackoverflow.com/questions/11657734/sleep-for-exact-time-in-python. # noqa: E501
+ assert abs(float(out) - 1) < 3e-2
+ with mmengine.Timer(print_tmpl='time: {:.1f}s'):
+ time.sleep(1)
+ out, _ = capsys.readouterr()
+ assert out == 'time: 1.0s\n'
diff --git a/testbed/open-mmlab__mmengine/tests/test_visualizer/test_vis_backend.py b/testbed/open-mmlab__mmengine/tests/test_visualizer/test_vis_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..78151f7a8d7ee5bd6c7f30cfabc2889bfbe80311
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_visualizer/test_vis_backend.py
@@ -0,0 +1,243 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import shutil
+import sys
+from unittest.mock import MagicMock
+
+import numpy as np
+import pytest
+import torch
+
+from mmengine import Config
+from mmengine.fileio import load
+from mmengine.registry import VISBACKENDS
+from mmengine.visualization import (LocalVisBackend, TensorboardVisBackend,
+ WandbVisBackend)
+
+
+class TestLocalVisBackend:
+
+ def test_init(self):
+ # 'config_save_file' format must be py
+ with pytest.raises(AssertionError):
+ LocalVisBackend('temp_dir', config_save_file='a.txt')
+
+ # 'scalar_save_file' format must be json
+ with pytest.raises(AssertionError):
+ LocalVisBackend('temp_dir', scalar_save_file='a.yaml')
+
+ local_vis_backend = VISBACKENDS.build(
+ dict(type='LocalVisBackend', save_dir='temp_dir'))
+ assert isinstance(local_vis_backend, LocalVisBackend)
+
+ def test_experiment(self):
+ local_vis_backend = LocalVisBackend('temp_dir')
+ assert local_vis_backend.experiment == local_vis_backend
+
+ def test_add_config(self):
+ cfg = Config(dict(a=1, b=dict(b1=[0, 1])))
+ local_vis_backend = LocalVisBackend('temp_dir')
+ local_vis_backend.add_config(cfg)
+ assert os.path.exists(local_vis_backend._config_save_file)
+ shutil.rmtree('temp_dir')
+
+ def test_add_image(self):
+ image = np.random.randint(0, 256, size=(10, 10, 3))
+ local_vis_backend = LocalVisBackend('temp_dir')
+
+ # image must be in np.uint8 format
+ with pytest.raises(AssertionError):
+ local_vis_backend.add_image('img', image)
+
+ local_vis_backend.add_image('img', image.astype(np.uint8))
+ assert os.path.exists(
+ os.path.join(local_vis_backend._img_save_dir, 'img_0.png'))
+ local_vis_backend.add_image('img', image.astype(np.uint8), step=2)
+ assert os.path.exists(
+ os.path.join(local_vis_backend._img_save_dir, 'img_2.png'))
+ shutil.rmtree('temp_dir')
+
+ def test_add_scalar(self):
+ local_vis_backend = LocalVisBackend('temp_dir')
+ local_vis_backend.add_scalar('map', 0.9)
+ out_dict = load(local_vis_backend._scalar_save_file, 'json')
+ assert out_dict == {'map': 0.9, 'step': 0}
+ shutil.rmtree('temp_dir')
+
+ # test append mode
+ local_vis_backend = LocalVisBackend('temp_dir')
+ local_vis_backend.add_scalar('map', 1, step=0)
+ local_vis_backend.add_scalar('map', 0.95, step=1)
+ # local_vis_backend.add_scalar('map', torch.IntTensor(1), step=2)
+ local_vis_backend.add_scalar('map', np.array(0.9), step=2)
+ with open(local_vis_backend._scalar_save_file) as f:
+ out_dict = f.read()
+ assert out_dict == '{"map": 1, "step": 0}\n' \
+ '{"map": 0.95, "step": 1}\n' \
+ '{"map": 0.9, "step": 2}\n'
+ shutil.rmtree('temp_dir')
+
+ local_vis_backend = LocalVisBackend('temp_dir')
+ local_vis_backend.add_scalar('map', torch.tensor(1.))
+ assert os.path.exists(local_vis_backend._scalar_save_file)
+ shutil.rmtree('temp_dir')
+
+ def test_add_scalars(self):
+ input_dict = {'map': 0.7, 'acc': 0.9}
+ local_vis_backend = LocalVisBackend('temp_dir')
+ local_vis_backend.add_scalars(input_dict)
+ assert input_dict == {'map': 0.7, 'acc': 0.9}
+ out_dict = load(local_vis_backend._scalar_save_file, 'json')
+ assert out_dict == {'map': 0.7, 'acc': 0.9, 'step': 0}
+
+ # test append mode
+ local_vis_backend.add_scalars({'map': 0.8, 'acc': 0.8}, step=1)
+ with open(local_vis_backend._scalar_save_file) as f:
+ out_dict = f.read()
+ assert out_dict == '{"map": 0.7, "acc": 0.9, ' \
+ '"step": 0}\n{"map": 0.8, "acc": 0.8, "step": 1}\n'
+
+ # test file_path
+ local_vis_backend.add_scalars(input_dict, file_path='temp.json')
+ assert os.path.exists(local_vis_backend._scalar_save_file)
+ assert os.path.exists(
+ os.path.join(local_vis_backend._save_dir, 'temp.json'))
+
+ # file_path and scalar_save_file cannot be the same
+ with pytest.raises(AssertionError):
+ local_vis_backend.add_scalars(input_dict, file_path='scalars.json')
+
+ shutil.rmtree('temp_dir')
+
+
+class TestTensorboardVisBackend:
+ sys.modules['torch.utils.tensorboard'] = MagicMock()
+ sys.modules['tensorboardX'] = MagicMock()
+
+ def test_init(self):
+ TensorboardVisBackend('temp_dir')
+ VISBACKENDS.build(
+ dict(type='TensorboardVisBackend', save_dir='temp_dir'))
+
+ def test_experiment(self):
+ tensorboard_vis_backend = TensorboardVisBackend('temp_dir')
+ assert (tensorboard_vis_backend.experiment ==
+ tensorboard_vis_backend._tensorboard)
+ shutil.rmtree('temp_dir')
+
+ def test_add_config(self):
+ cfg = Config(dict(a=1, b=dict(b1=[0, 1])))
+ tensorboard_vis_backend = TensorboardVisBackend('temp_dir')
+ tensorboard_vis_backend.add_config(cfg)
+ shutil.rmtree('temp_dir')
+
+ def test_add_image(self):
+ image = np.random.randint(0, 256, size=(10, 10, 3)).astype(np.uint8)
+ tensorboard_vis_backend = TensorboardVisBackend('temp_dir')
+ tensorboard_vis_backend.add_image('img', image)
+ tensorboard_vis_backend.add_image('img', image, step=2)
+ shutil.rmtree('temp_dir')
+
+ def test_add_scalar(self):
+ tensorboard_vis_backend = TensorboardVisBackend('temp_dir')
+ tensorboard_vis_backend.add_scalar('map', 0.9)
+ # test append mode
+ tensorboard_vis_backend.add_scalar('map', 0.9, step=0)
+ tensorboard_vis_backend.add_scalar('map', 0.95, step=1)
+ # test with numpy
+ with pytest.warns(None) as record:
+ tensorboard_vis_backend.add_scalar('map', np.array(0.9), step=0)
+ tensorboard_vis_backend.add_scalar('map', np.array(0.95), step=1)
+ tensorboard_vis_backend.add_scalar('map', np.array(9), step=0)
+ tensorboard_vis_backend.add_scalar('map', np.array(95), step=1)
+ tensorboard_vis_backend.add_scalar('map', np.array([9])[0], step=0)
+ tensorboard_vis_backend.add_scalar(
+ 'map', np.array([95])[0], step=1)
+ assert len(record) == 0
+ # test with tensor
+ tensorboard_vis_backend.add_scalar('map', torch.tensor(0.9), step=0)
+ tensorboard_vis_backend.add_scalar('map', torch.tensor(0.95), step=1)
+ # Unprocessable data will output a warning message
+ with pytest.warns(Warning):
+ tensorboard_vis_backend.add_scalar('map', [0.95])
+ shutil.rmtree('temp_dir')
+
+ def test_add_scalars(self):
+ tensorboard_vis_backend = TensorboardVisBackend('temp_dir')
+ # The step value must be passed through the parameter
+ with pytest.raises(AssertionError):
+ tensorboard_vis_backend.add_scalars({
+ 'map': 0.7,
+ 'acc': 0.9,
+ 'step': 1
+ })
+
+ # Unprocessable data will output a warning message
+ with pytest.warns(Warning):
+ tensorboard_vis_backend.add_scalars({
+ 'map': [1, 2],
+ })
+
+ input_dict = {'map': 0.7, 'acc': 0.9}
+ tensorboard_vis_backend.add_scalars(input_dict)
+ # test append mode
+ tensorboard_vis_backend.add_scalars({'map': 0.8, 'acc': 0.8}, step=1)
+ shutil.rmtree('temp_dir')
+
+ def test_close(self):
+ tensorboard_vis_backend = TensorboardVisBackend('temp_dir')
+ tensorboard_vis_backend._init_env()
+ tensorboard_vis_backend.close()
+ shutil.rmtree('temp_dir')
+
+
+class TestWandbVisBackend:
+ sys.modules['wandb'] = MagicMock()
+ sys.modules['wandb.run'] = MagicMock()
+
+ def test_init(self):
+ WandbVisBackend('temp_dir')
+ VISBACKENDS.build(dict(type='WandbVisBackend', save_dir='temp_dir'))
+
+ def test_experiment(self):
+ wandb_vis_backend = WandbVisBackend('temp_dir')
+ assert wandb_vis_backend.experiment == wandb_vis_backend._wandb
+ shutil.rmtree('temp_dir')
+
+ def test_add_config(self):
+ cfg = Config(dict(a=1, b=dict(b1=[0, 1])))
+ wandb_vis_backend = WandbVisBackend('temp_dir', log_code_name='code')
+ _wandb = wandb_vis_backend.experiment
+ _wandb.run.dir = 'temp_dir'
+ wandb_vis_backend.add_config(cfg)
+ shutil.rmtree('temp_dir')
+
+ def test_add_image(self):
+ image = np.random.randint(0, 256, size=(10, 10, 3)).astype(np.uint8)
+ wandb_vis_backend = WandbVisBackend('temp_dir')
+ wandb_vis_backend.add_image('img', image)
+ wandb_vis_backend.add_image('img', image)
+ shutil.rmtree('temp_dir')
+
+ def test_add_scalar(self):
+ wandb_vis_backend = WandbVisBackend('temp_dir')
+ wandb_vis_backend.add_scalar('map', 0.9)
+ # test append mode
+ wandb_vis_backend.add_scalar('map', 0.9)
+ wandb_vis_backend.add_scalar('map', 0.95)
+ shutil.rmtree('temp_dir')
+
+ def test_add_scalars(self):
+ wandb_vis_backend = WandbVisBackend('temp_dir')
+ input_dict = {'map': 0.7, 'acc': 0.9}
+ wandb_vis_backend.add_scalars(input_dict)
+ # test append mode
+ wandb_vis_backend.add_scalars({'map': 0.8, 'acc': 0.8})
+ wandb_vis_backend.add_scalars({'map': [0.8], 'acc': 0.8})
+ shutil.rmtree('temp_dir')
+
+ def test_close(self):
+ wandb_vis_backend = WandbVisBackend('temp_dir')
+ wandb_vis_backend._init_env()
+ wandb_vis_backend.close()
+ shutil.rmtree('temp_dir')
diff --git a/testbed/open-mmlab__mmengine/tests/test_visualizer/test_visualizer.py b/testbed/open-mmlab__mmengine/tests/test_visualizer/test_visualizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb4b39033765bac10402bea08b2edbb2966b6e41
--- /dev/null
+++ b/testbed/open-mmlab__mmengine/tests/test_visualizer/test_visualizer.py
@@ -0,0 +1,585 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import time
+from typing import Any
+from unittest import TestCase
+
+import numpy as np
+import pytest
+import torch
+import torch.nn as nn
+
+from mmengine import VISBACKENDS, Config
+from mmengine.visualization import Visualizer
+
+
+@VISBACKENDS.register_module()
+class MockVisBackend:
+
+ def __init__(self, save_dir: str):
+ self._save_dir = save_dir
+ self._close = False
+
+ @property
+ def experiment(self) -> Any:
+ return self
+
+ def add_config(self, config, **kwargs) -> None:
+ self._add_config = True
+
+ def add_graph(self, model, data_batch, **kwargs) -> None:
+ self._add_graph = True
+
+ def add_image(self, name, image, step=0, **kwargs) -> None:
+ self._add_image = True
+
+ def add_scalar(self, name, value, step=0, **kwargs) -> None:
+ self._add_scalar = True
+
+ def add_scalars(self,
+ scalar_dict,
+ step=0,
+ file_path=None,
+ **kwargs) -> None:
+ self._add_scalars = True
+
+ def close(self) -> None:
+ """close an opened object."""
+ self._close = True
+
+
+class TestVisualizer(TestCase):
+
+ def setUp(self):
+ """Setup the demo image in every test method.
+
+ TestCase calls functions in this order: setUp() -> testMethod() ->
+ tearDown() -> cleanUp()
+ """
+ self.image = np.random.randint(
+ 0, 256, size=(10, 10, 3)).astype('uint8')
+ self.vis_backend_cfg = [
+ dict(type='MockVisBackend', name='mock1'),
+ dict(type='MockVisBackend', name='mock2')
+ ]
+
+ def test_init(self):
+ visualizer = Visualizer(image=self.image)
+ visualizer.get_image()
+
+ # test save_dir
+ with pytest.warns(
+ Warning,
+ match='`Visualizer` backend is not initialized '
+ 'because save_dir is None.'):
+ Visualizer()
+
+ visualizer = Visualizer(
+ vis_backends=copy.deepcopy(self.vis_backend_cfg))
+ assert visualizer.get_backend('mock1') is None
+
+ visualizer = Visualizer(
+ vis_backends=copy.deepcopy(self.vis_backend_cfg),
+ save_dir='temp_dir')
+ assert isinstance(visualizer.get_backend('mock1'), MockVisBackend)
+ assert len(visualizer._vis_backends) == 2
+
+ # test empty list
+ with pytest.raises(AssertionError):
+ Visualizer(vis_backends=[], save_dir='temp_dir')
+
+ # test name
+ # If one of them has a name attribute, all backends must
+ # use the name attribute
+ with pytest.raises(RuntimeError):
+ Visualizer(
+ vis_backends=[
+ dict(type='MockVisBackend'),
+ dict(type='MockVisBackend', name='mock2')
+ ],
+ save_dir='temp_dir')
+
+ # The name fields cannot be the same
+ with pytest.raises(RuntimeError):
+ Visualizer(
+ vis_backends=[
+ dict(type='MockVisBackend'),
+ dict(type='MockVisBackend')
+ ],
+ save_dir='temp_dir')
+
+ with pytest.raises(RuntimeError):
+ Visualizer(
+ vis_backends=[
+ dict(type='MockVisBackend', name='mock1'),
+ dict(type='MockVisBackend', name='mock1')
+ ],
+ save_dir='temp_dir')
+
+ # test global init
+ instance_name = 'visualizer' + str(time.time())
+ visualizer = Visualizer.get_instance(
+ instance_name,
+ vis_backends=copy.deepcopy(self.vis_backend_cfg),
+ save_dir='temp_dir')
+ assert len(visualizer._vis_backends) == 2
+ visualizer_any = Visualizer.get_instance(instance_name)
+ assert visualizer_any == visualizer
+
+ def test_set_image(self):
+ visualizer = Visualizer()
+ visualizer.set_image(self.image)
+ with pytest.raises(AssertionError):
+ visualizer.set_image(None)
+
+ def test_get_image(self):
+ visualizer = Visualizer(image=self.image)
+ visualizer.get_image()
+
+ def test_draw_bboxes(self):
+ visualizer = Visualizer(image=self.image)
+
+ # only support 4 or nx4 tensor and numpy
+ visualizer.draw_bboxes(torch.tensor([1, 1, 2, 2]))
+ # valid bbox
+ visualizer.draw_bboxes(torch.tensor([1, 1, 1, 2]))
+ bboxes = torch.tensor([[1, 1, 2, 2], [1, 2, 2, 2.5]])
+ visualizer.draw_bboxes(
+ bboxes, alpha=0.5, edge_colors=(255, 0, 0), line_styles='-')
+ bboxes = bboxes.numpy()
+ visualizer.draw_bboxes(bboxes)
+
+ # test invalid bbox
+ with pytest.raises(AssertionError):
+ # x1 > x2
+ visualizer.draw_bboxes(torch.tensor([5, 1, 2, 2]))
+
+ # test out of bounds
+ with pytest.warns(
+ UserWarning,
+ match='Warning: The bbox is out of bounds,'
+ ' the drawn bbox may not be in the image'):
+ visualizer.draw_bboxes(torch.tensor([1, 1, 20, 2]))
+
+ # test incorrect bbox format
+ with pytest.raises(TypeError):
+ visualizer.draw_bboxes([1, 1, 2, 2])
+
+ def test_close(self):
+ visualizer = Visualizer(
+ image=self.image,
+ vis_backends=copy.deepcopy(self.vis_backend_cfg),
+ save_dir='temp_dir')
+
+ for name in ['mock1', 'mock2']:
+ assert visualizer.get_backend(name)._close is False
+ visualizer.close()
+ for name in ['mock1', 'mock2']:
+ assert visualizer.get_backend(name)._close is True
+
+ def test_draw_points(self):
+ visualizer = Visualizer(image=self.image)
+
+ with pytest.raises(TypeError):
+ visualizer.draw_points(positions=[1, 2])
+ with pytest.raises(AssertionError):
+ visualizer.draw_points(positions=np.array([1, 2, 3]))
+ # test color
+ visualizer.draw_points(
+ positions=torch.tensor([[1, 1], [3, 3]]),
+ colors=['g', (255, 255, 0)])
+ visualizer.draw_points(
+ positions=torch.tensor([[1, 1], [3, 3]]),
+ colors=['g', (255, 255, 0)],
+ marker='.',
+ sizes=[1, 5])
+
+ def test_draw_texts(self):
+ visualizer = Visualizer(image=self.image)
+
+ # only support tensor and numpy
+ visualizer.draw_texts(
+ 'text1', positions=torch.tensor([5, 5]), colors=(0, 255, 0))
+ visualizer.draw_texts(['text1', 'text2'],
+ positions=torch.tensor([[5, 5], [3, 3]]),
+ colors=[(255, 0, 0), (255, 0, 0)])
+ visualizer.draw_texts('text1', positions=np.array([5, 5]))
+ visualizer.draw_texts(['text1', 'text2'],
+ positions=np.array([[5, 5], [3, 3]]))
+ visualizer.draw_texts(
+ 'text1',
+ positions=torch.tensor([5, 5]),
+ bboxes=dict(facecolor='r', alpha=0.6))
+ # test out of bounds
+ with pytest.warns(
+ UserWarning,
+ match='Warning: The text is out of bounds,'
+ ' the drawn text may not be in the image'):
+ visualizer.draw_texts('text1', positions=torch.tensor([15, 5]))
+
+ # test incorrect format
+ with pytest.raises(TypeError):
+ visualizer.draw_texts('text', positions=[5, 5])
+
+ # test length mismatch
+ with pytest.raises(AssertionError):
+ visualizer.draw_texts(['text1', 'text2'],
+ positions=torch.tensor([5, 5]))
+ with pytest.raises(AssertionError):
+ visualizer.draw_texts(
+ 'text1', positions=torch.tensor([[5, 5], [3, 3]]))
+ with pytest.raises(AssertionError):
+ visualizer.draw_texts(['text1', 'test2'],
+ positions=torch.tensor([[5, 5], [3, 3]]),
+ colors=['r'])
+ with pytest.raises(AssertionError):
+ visualizer.draw_texts(['text1', 'test2'],
+ positions=torch.tensor([[5, 5], [3, 3]]),
+ vertical_alignments=['top'])
+ with pytest.raises(AssertionError):
+ visualizer.draw_texts(['text1', 'test2'],
+ positions=torch.tensor([[5, 5], [3, 3]]),
+ horizontal_alignments=['left'])
+ with pytest.raises(AssertionError):
+ visualizer.draw_texts(['text1', 'test2'],
+ positions=torch.tensor([[5, 5], [3, 3]]),
+ font_sizes=[1])
+
+ # test type valid
+ with pytest.raises(TypeError):
+ visualizer.draw_texts(['text1', 'test2'],
+ positions=torch.tensor([[5, 5], [3, 3]]),
+ font_sizes='b')
+
+ def test_draw_lines(self):
+ visualizer = Visualizer(image=self.image)
+
+ # only support tensor and numpy
+ visualizer.draw_lines(
+ x_datas=torch.tensor([1, 5]), y_datas=torch.tensor([2, 6]))
+ visualizer.draw_lines(
+ x_datas=np.array([[1, 5], [2, 4]]),
+ y_datas=np.array([[2, 6], [4, 7]]))
+ visualizer.draw_lines(
+ x_datas=np.array([[1, 5], [2, 4]]),
+ y_datas=np.array([[2, 6], [4, 7]]),
+ colors='r',
+ line_styles=['-', '-.'],
+ line_widths=[1, 2])
+ # test out of bounds
+ with pytest.warns(
+ UserWarning,
+ match='Warning: The line is out of bounds,'
+ ' the drawn line may not be in the image'):
+ visualizer.draw_lines(
+ x_datas=torch.tensor([12, 5]), y_datas=torch.tensor([2, 6]))
+
+ # test incorrect format
+ with pytest.raises(TypeError):
+ visualizer.draw_lines(x_datas=[5, 5], y_datas=torch.tensor([2, 6]))
+ with pytest.raises(TypeError):
+ visualizer.draw_lines(y_datas=[5, 5], x_datas=torch.tensor([2, 6]))
+
+ # test length mismatch
+ with pytest.raises(AssertionError):
+ visualizer.draw_lines(
+ x_datas=torch.tensor([1, 5]),
+ y_datas=torch.tensor([[2, 6], [4, 7]]))
+
+ def test_draw_circles(self):
+ visualizer = Visualizer(image=self.image)
+
+ # only support tensor and numpy
+ visualizer.draw_circles(torch.tensor([1, 5]), torch.tensor([1]))
+ visualizer.draw_circles(np.array([1, 5]), np.array([1]))
+ visualizer.draw_circles(
+ torch.tensor([[1, 5], [2, 6]]), radius=torch.tensor([1, 2]))
+
+ # test face_colors
+ visualizer.draw_circles(
+ torch.tensor([[1, 5], [2, 6]]),
+ radius=torch.tensor([1, 2]),
+ face_colors=(255, 0, 0),
+ edge_colors=(255, 0, 0))
+
+ # test config
+ visualizer.draw_circles(
+ torch.tensor([[1, 5], [2, 6]]),
+ radius=torch.tensor([1, 2]),
+ edge_colors=['g', 'r'],
+ line_styles=['-', '-.'],
+ line_widths=[1, 2])
+
+ # test out of bounds
+ with pytest.warns(
+ UserWarning,
+ match='Warning: The circle is out of bounds,'
+ ' the drawn circle may not be in the image'):
+ visualizer.draw_circles(
+ torch.tensor([12, 5]), radius=torch.tensor([1]))
+ visualizer.draw_circles(
+ torch.tensor([1, 5]), radius=torch.tensor([10]))
+
+ # test incorrect format
+ with pytest.raises(TypeError):
+ visualizer.draw_circles([1, 5], radius=torch.tensor([1]))
+ with pytest.raises(TypeError):
+ visualizer.draw_circles(np.array([1, 5]), radius=10)
+
+ # test length mismatch
+ with pytest.raises(AssertionError):
+ visualizer.draw_circles(
+ torch.tensor([[1, 5]]), radius=torch.tensor([1, 2]))
+
+ def test_draw_polygons(self):
+ visualizer = Visualizer(image=self.image)
+ # shape Nx2 or list[Nx2]
+ visualizer.draw_polygons(torch.tensor([[1, 1], [2, 2], [3, 4]]))
+ visualizer.draw_polygons(np.array([[1, 1], [2, 2], [3, 4]]))
+ visualizer.draw_polygons([
+ np.array([[1, 1], [2, 2], [3, 4]]),
+ torch.tensor([[1, 1], [2, 2], [3, 4]])
+ ])
+ visualizer.draw_polygons(
+ polygons=[
+ np.array([[1, 1], [2, 2], [3, 4]]),
+ torch.tensor([[1, 1], [2, 2], [3, 4]])
+ ],
+ face_colors=(255, 0, 0),
+ edge_colors=(255, 0, 0))
+ visualizer.draw_polygons(
+ polygons=[
+ np.array([[1, 1], [2, 2], [3, 4]]),
+ torch.tensor([[1, 1], [2, 2], [3, 4]])
+ ],
+ edge_colors=['r', 'g'],
+ line_styles='-',
+ line_widths=[2, 1])
+
+ # test out of bounds
+ with pytest.warns(
+ UserWarning,
+ match='Warning: The polygon is out of bounds,'
+ ' the drawn polygon may not be in the image'):
+ visualizer.draw_polygons(torch.tensor([[1, 1], [2, 2], [16, 4]]))
+
+ def test_draw_binary_masks(self):
+ binary_mask = np.random.randint(0, 2, size=(10, 10)).astype(bool)
+ visualizer = Visualizer(image=self.image)
+ visualizer.draw_binary_masks(binary_mask)
+ visualizer.draw_binary_masks(torch.from_numpy(binary_mask))
+ # multi binary
+ binary_mask = np.random.randint(0, 2, size=(2, 10, 10)).astype(bool)
+ visualizer = Visualizer(image=self.image)
+ visualizer.draw_binary_masks(binary_mask, colors=['r', (0, 255, 0)])
+ # test the error that the size of mask and image are different.
+ with pytest.raises(AssertionError):
+ binary_mask = np.random.randint(0, 2, size=(8, 10)).astype(bool)
+ visualizer.draw_binary_masks(binary_mask)
+
+ # test non binary mask error
+ binary_mask = np.random.randint(0, 2, size=(10, 10, 3)).astype(bool)
+ with pytest.raises(AssertionError):
+ visualizer.draw_binary_masks(binary_mask)
+
+ # test color dim
+ with pytest.raises(AssertionError):
+ visualizer.draw_binary_masks(
+ binary_mask, colors=np.array([1, 22, 4, 45]))
+ binary_mask = np.random.randint(0, 2, size=(10, 10))
+ with pytest.raises(AssertionError):
+ visualizer.draw_binary_masks(binary_mask)
+
+ def test_draw_featmap(self):
+ visualizer = Visualizer()
+ image = np.random.randint(0, 256, size=(3, 3, 3), dtype='uint8')
+
+ # must be Tensor
+ with pytest.raises(
+ AssertionError,
+ match='`featmap` should be torch.Tensor, but got '
+ ""):
+ visualizer.draw_featmap(np.ones((3, 3, 3)))
+
+ # test tensor format
+ with pytest.raises(
+ AssertionError, match='Input dimension must be 3, but got 4'):
+ visualizer.draw_featmap(torch.randn(1, 1, 3, 3))
+
+ # test overlaid_image shape
+ with pytest.warns(Warning):
+ visualizer.draw_featmap(torch.randn(1, 4, 3), overlaid_image=image)
+
+ # test resize_shape
+ featmap = visualizer.draw_featmap(
+ torch.randn(1, 4, 3), resize_shape=(6, 7))
+ assert featmap.shape[:2] == (6, 7)
+ featmap = visualizer.draw_featmap(
+ torch.randn(1, 4, 3), overlaid_image=image, resize_shape=(6, 7))
+ assert featmap.shape[:2] == (6, 7)
+
+ # test channel_reduction parameter
+ # mode only supports 'squeeze_mean' and 'select_max'
+ with pytest.raises(AssertionError):
+ visualizer.draw_featmap(
+ torch.randn(2, 3, 3), channel_reduction='xx')
+
+ featmap = visualizer.draw_featmap(
+ torch.randn(2, 3, 3), channel_reduction='squeeze_mean')
+ assert featmap.shape[:2] == (3, 3)
+ featmap = visualizer.draw_featmap(
+ torch.randn(2, 3, 3), channel_reduction='select_max')
+ assert featmap.shape[:2] == (3, 3)
+ featmap = visualizer.draw_featmap(
+ torch.randn(2, 4, 3),
+ overlaid_image=image,
+ channel_reduction='select_max')
+ assert featmap.shape[:2] == (3, 3)
+
+ # test topk parameter
+ with pytest.raises(
+ AssertionError,
+ match='The input tensor channel dimension must be 1 or 3 '
+ 'when topk is less than 1, but the channel '
+ 'dimension you input is 6, you can use the '
+ 'channel_reduction parameter or set topk '
+ 'greater than 0 to solve the error'):
+ visualizer.draw_featmap(
+ torch.randn(6, 3, 3), channel_reduction=None, topk=0)
+
+ featmap = visualizer.draw_featmap(
+ torch.randn(6, 3, 3), channel_reduction='select_max', topk=10)
+ assert featmap.shape[:2] == (3, 3)
+ featmap = visualizer.draw_featmap(
+ torch.randn(1, 4, 3), channel_reduction=None, topk=-1)
+ assert featmap.shape[:2] == (4, 3)
+
+ featmap = visualizer.draw_featmap(
+ torch.randn(3, 4, 3),
+ overlaid_image=image,
+ channel_reduction=None,
+ topk=-1)
+ assert featmap.shape[:2] == (3, 3)
+ featmap = visualizer.draw_featmap(
+ torch.randn(6, 3, 3),
+ channel_reduction=None,
+ topk=4,
+ arrangement=(2, 2))
+ assert featmap.shape[:2] == (6, 6)
+ featmap = visualizer.draw_featmap(
+ torch.randn(6, 3, 3),
+ channel_reduction=None,
+ topk=4,
+ arrangement=(1, 4))
+ assert featmap.shape[:2] == (3, 12)
+ with pytest.raises(
+ AssertionError,
+ match='The product of row and col in the `arrangement` '
+ 'is less than topk, please set '
+ 'the `arrangement` correctly'):
+ visualizer.draw_featmap(
+ torch.randn(6, 3, 3),
+ channel_reduction=None,
+ topk=4,
+ arrangement=(1, 2))
+
+ # test gray
+ featmap = visualizer.draw_featmap(
+ torch.randn(6, 3, 3),
+ overlaid_image=np.random.randint(
+ 0, 256, size=(3, 3), dtype='uint8'),
+ channel_reduction=None,
+ topk=4,
+ arrangement=(2, 2))
+ assert featmap.shape[:2] == (6, 6)
+
+ def test_chain_call(self):
+ visualizer = Visualizer(image=self.image)
+ binary_mask = np.random.randint(0, 2, size=(10, 10)).astype(bool)
+ visualizer.draw_bboxes(torch.tensor([1, 1, 2, 2])). \
+ draw_texts('test', torch.tensor([5, 5])). \
+ draw_lines(x_datas=torch.tensor([1, 5]),
+ y_datas=torch.tensor([2, 6])). \
+ draw_circles(torch.tensor([1, 5]), radius=torch.tensor([2])). \
+ draw_polygons(torch.tensor([[1, 1], [2, 2], [3, 4]])). \
+ draw_binary_masks(binary_mask)
+
+ def test_get_backend(self):
+ visualizer = Visualizer(
+ image=self.image,
+ vis_backends=copy.deepcopy(self.vis_backend_cfg),
+ save_dir='temp_dir')
+ for name in ['mock1', 'mock2']:
+ assert isinstance(visualizer.get_backend(name), MockVisBackend)
+
+ def test_add_config(self):
+ visualizer = Visualizer(
+ vis_backends=copy.deepcopy(self.vis_backend_cfg),
+ save_dir='temp_dir')
+
+ cfg = Config(dict(a=1, b=dict(b1=[0, 1])))
+ visualizer.add_config(cfg)
+ for name in ['mock1', 'mock2']:
+ assert visualizer.get_backend(name)._add_config is True
+
+ def test_add_graph(self):
+ visualizer = Visualizer(
+ vis_backends=copy.deepcopy(self.vis_backend_cfg),
+ save_dir='temp_dir')
+
+ class Model(nn.Module):
+
+ def __init__(self):
+ super().__init__()
+ self.conv = nn.Conv2d(1, 2, 1)
+
+ def forward(self, x, y=None):
+ return self.conv(x)
+
+ visualizer.add_graph(Model(), np.zeros([1, 1, 3, 3]))
+ for name in ['mock1', 'mock2']:
+ assert visualizer.get_backend(name)._add_graph is True
+
+ def test_add_image(self):
+ image = np.random.randint(0, 256, size=(10, 10, 3)).astype(np.uint8)
+ visualizer = Visualizer(
+ vis_backends=copy.deepcopy(self.vis_backend_cfg),
+ save_dir='temp_dir')
+
+ visualizer.add_image('img', image)
+ for name in ['mock1', 'mock2']:
+ assert visualizer.get_backend(name)._add_image is True
+
+ def test_add_scalar(self):
+ visualizer = Visualizer(
+ vis_backends=copy.deepcopy(self.vis_backend_cfg),
+ save_dir='temp_dir')
+ visualizer.add_scalar('map', 0.9, step=0)
+ for name in ['mock1', 'mock2']:
+ assert visualizer.get_backend(name)._add_scalar is True
+
+ def test_add_scalars(self):
+ visualizer = Visualizer(
+ vis_backends=copy.deepcopy(self.vis_backend_cfg),
+ save_dir='temp_dir')
+ input_dict = {'map': 0.7, 'acc': 0.9}
+ visualizer.add_scalars(input_dict)
+ for name in ['mock1', 'mock2']:
+ assert visualizer.get_backend(name)._add_scalars is True
+
+ def test_get_instance(self):
+
+ class DetLocalVisualizer(Visualizer):
+
+ def __init__(self, name):
+ super().__init__(name)
+
+ visualizer1 = DetLocalVisualizer.get_instance('name1')
+ visualizer2 = Visualizer.get_current_instance()
+ visualizer3 = DetLocalVisualizer.get_current_instance()
+ assert id(visualizer1) == id(visualizer2) == id(visualizer3)
+
+ def test_data_info(self):
+ visualizer = Visualizer()
+ visualizer.dataset_meta = {'class': 'cat'}
+ assert visualizer.dataset_meta['class'] == 'cat'
diff --git a/testbed/openvinotoolkit__datumaro/.github/pull_request_template.md b/testbed/openvinotoolkit__datumaro/.github/pull_request_template.md
new file mode 100644
index 0000000000000000000000000000000000000000..d40cfb94da00d5c3b6410a2ee08d1f3d67309a2e
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/.github/pull_request_template.md
@@ -0,0 +1,40 @@
+
+
+### Summary
+
+
+### How to test
+
+
+### Checklist
+
+- [ ] I submit my changes into the `develop` branch
+- [ ] I have added description of my changes into [CHANGELOG](https://github.com/openvinotoolkit/datumaro/blob/develop/CHANGELOG.md)
+- [ ] I have updated the [documentation](
+ https://github.com/openvinotoolkit/datumaro/tree/develop/docs) accordingly
+- [ ] I have added tests to cover my changes
+- [ ] I have [linked related issues](
+ https://help.github.com/en/github/managing-your-work-on-github/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword))
+
+### License
+
+- [ ] I submit _my code changes_ under the same [MIT License](
+ https://github.com/opencv/cvat/blob/develop/LICENSE) that covers the project.
+ Feel free to contact the maintainers if that's a concern.
+- [ ] I have updated the license header for each file (see an example below)
+
+```python
+# Copyright (C) 2020 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+```
diff --git a/testbed/openvinotoolkit__datumaro/datumaro/cli/__main__.py b/testbed/openvinotoolkit__datumaro/datumaro/cli/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..80a8805f56606f0a73bb608fd7e5134ad39e0e26
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/datumaro/cli/__main__.py
@@ -0,0 +1,125 @@
+
+# Copyright (C) 2019-2020 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+
+import argparse
+import logging as log
+import sys
+
+from . import contexts, commands
+from .util import CliException, add_subparser
+from ..version import VERSION
+
+
+_log_levels = {
+ 'debug': log.DEBUG,
+ 'info': log.INFO,
+ 'warning': log.WARNING,
+ 'error': log.ERROR,
+ 'critical': log.CRITICAL
+}
+
+def loglevel(name):
+ return _log_levels[name]
+
+class _LogManager:
+ @classmethod
+ def init_logger(cls, args=None):
+ # Define minimalistic parser only to obtain loglevel
+ parser = argparse.ArgumentParser(add_help=False)
+ cls._define_loglevel_option(parser)
+ args, _ = parser.parse_known_args(args)
+
+ log.basicConfig(format='%(asctime)s %(levelname)s: %(message)s',
+ level=args.loglevel)
+
+ @staticmethod
+ def _define_loglevel_option(parser):
+ parser.add_argument('--loglevel', type=loglevel, default='info',
+ help="Logging level (options: %s; default: %s)" % \
+ (', '.join(_log_levels.keys()), "%(default)s"))
+ return parser
+
+
+def _make_subcommands_help(commands, help_line_start=0):
+ desc = ""
+ for command_name, _, command_help in commands:
+ desc += (" %-" + str(max(0, help_line_start - 2 - 1)) + "s%s\n") % \
+ (command_name, command_help)
+ return desc
+
+def make_parser():
+ parser = argparse.ArgumentParser(prog="datumaro",
+ description="Dataset Framework",
+ formatter_class=argparse.RawDescriptionHelpFormatter)
+
+ parser.add_argument('--version', action='version', version=VERSION)
+ _LogManager._define_loglevel_option(parser)
+
+ known_contexts = [
+ ('project', contexts.project, "Actions on projects (datasets)"),
+ ('source', contexts.source, "Actions on data sources"),
+ ('model', contexts.model, "Actions on models"),
+ ]
+ known_commands = [
+ ('create', commands.create, "Create project"),
+ ('add', commands.add, "Add source to project"),
+ ('remove', commands.remove, "Remove source from project"),
+ ('export', commands.export, "Export project"),
+ ('explain', commands.explain, "Run Explainable AI algorithm for model"),
+ ('merge', commands.merge, "Merge datasets"),
+ ('convert', commands.convert, "Convert dataset"),
+ ]
+
+ # Argparse doesn't support subparser groups:
+ # https://stackoverflow.com/questions/32017020/grouping-argparse-subparser-arguments
+ help_line_start = max((len(e[0]) for e in known_contexts + known_commands),
+ default=0)
+ help_line_start = max((2 + help_line_start) // 4 + 1, 6) * 4 # align to tabs
+ subcommands_desc = ""
+ if known_contexts:
+ subcommands_desc += "Contexts:\n"
+ subcommands_desc += _make_subcommands_help(known_contexts,
+ help_line_start)
+ if known_commands:
+ if subcommands_desc:
+ subcommands_desc += "\n"
+ subcommands_desc += "Commands:\n"
+ subcommands_desc += _make_subcommands_help(known_commands,
+ help_line_start)
+ if subcommands_desc:
+ subcommands_desc += \
+ "\nRun '%s COMMAND --help' for more information on a command." % \
+ parser.prog
+
+ subcommands = parser.add_subparsers(title=subcommands_desc,
+ description="", help=argparse.SUPPRESS)
+ for command_name, command, _ in known_contexts + known_commands:
+ add_subparser(subcommands, command_name, command.build_parser)
+
+ return parser
+
+
+def main(args=None):
+ _LogManager.init_logger(args)
+
+ parser = make_parser()
+ args = parser.parse_args(args)
+
+ if 'command' not in args:
+ parser.print_help()
+ return 1
+
+ try:
+ return args.command(args)
+ except CliException as e:
+ log.error(e)
+ return 1
+ except Exception as e:
+ log.error(e)
+ raise
+
+
+if __name__ == '__main__':
+ sys.exit(main())
\ No newline at end of file
diff --git a/testbed/openvinotoolkit__datumaro/datumaro/cli/commands/__init__.py b/testbed/openvinotoolkit__datumaro/datumaro/cli/commands/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe74bc2b091eb636ad35904b597ba9b3c0dfc081
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/datumaro/cli/commands/__init__.py
@@ -0,0 +1,6 @@
+
+# Copyright (C) 2019-2020 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+
+from . import add, create, explain, export, remove, merge, convert
diff --git a/testbed/openvinotoolkit__datumaro/datumaro/cli/commands/add.py b/testbed/openvinotoolkit__datumaro/datumaro/cli/commands/add.py
new file mode 100644
index 0000000000000000000000000000000000000000..288d7c047c50cbbee095877f998b1f9d52c91850
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/datumaro/cli/commands/add.py
@@ -0,0 +1,8 @@
+
+# Copyright (C) 2019-2020 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+
+# pylint: disable=unused-import
+
+from ..contexts.source import build_add_parser as build_parser
diff --git a/testbed/openvinotoolkit__datumaro/datumaro/cli/commands/create.py b/testbed/openvinotoolkit__datumaro/datumaro/cli/commands/create.py
new file mode 100644
index 0000000000000000000000000000000000000000..97e3c9b4cf78e55d76792576a562d6793e25942f
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/datumaro/cli/commands/create.py
@@ -0,0 +1,8 @@
+
+# Copyright (C) 2019-2020 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+
+# pylint: disable=unused-import
+
+from ..contexts.project import build_create_parser as build_parser
\ No newline at end of file
diff --git a/testbed/openvinotoolkit__datumaro/datumaro/cli/commands/explain.py b/testbed/openvinotoolkit__datumaro/datumaro/cli/commands/explain.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d5d16b2af288e74f5190c39b1519a42c2b06340
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/datumaro/cli/commands/explain.py
@@ -0,0 +1,183 @@
+
+# Copyright (C) 2019-2020 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+
+import argparse
+import logging as log
+import os
+import os.path as osp
+
+from datumaro.components.project import Project
+from datumaro.util.command_targets import (TargetKinds, target_selector,
+ ProjectTarget, SourceTarget, ImageTarget, is_project_path)
+from datumaro.util.image import load_image, save_image
+from ..util import MultilineFormatter
+from ..util.project import load_project
+
+
+def build_parser(parser_ctor=argparse.ArgumentParser):
+ parser = parser_ctor(help="Run Explainable AI algorithm",
+ description="Runs an explainable AI algorithm for a model.")
+
+ parser.add_argument('-m', '--model', required=True,
+ help="Model to use for inference")
+ parser.add_argument('-t', '--target', default=None,
+ help="Inference target - image, source, project "
+ "(default: current dir)")
+ parser.add_argument('-o', '--output-dir', dest='save_dir', default=None,
+ help="Directory to save output (default: display only)")
+
+ method_sp = parser.add_subparsers(dest='algorithm')
+
+ rise_parser = method_sp.add_parser('rise',
+ description="""
+ RISE: Randomized Input Sampling for
+ Explanation of Black-box Models algorithm|n
+ |n
+ See explanations at: https://arxiv.org/pdf/1806.07421.pdf
+ """,
+ formatter_class=MultilineFormatter)
+ rise_parser.add_argument('-s', '--max-samples', default=None, type=int,
+ help="Number of algorithm iterations (default: mask size ^ 2)")
+ rise_parser.add_argument('--mw', '--mask-width',
+ dest='mask_width', default=7, type=int,
+ help="Mask width (default: %(default)s)")
+ rise_parser.add_argument('--mh', '--mask-height',
+ dest='mask_height', default=7, type=int,
+ help="Mask height (default: %(default)s)")
+ rise_parser.add_argument('--prob', default=0.5, type=float,
+ help="Mask pixel inclusion probability (default: %(default)s)")
+ rise_parser.add_argument('--iou', '--iou-thresh',
+ dest='iou_thresh', default=0.9, type=float,
+ help="IoU match threshold for detections (default: %(default)s)")
+ rise_parser.add_argument('--nms', '--nms-iou-thresh',
+ dest='nms_iou_thresh', default=0.0, type=float,
+ help="IoU match threshold in Non-maxima suppression (default: no NMS)")
+ rise_parser.add_argument('--conf', '--det-conf-thresh',
+ dest='det_conf_thresh', default=0.0, type=float,
+ help="Confidence threshold for detections (default: include all)")
+ rise_parser.add_argument('-b', '--batch-size', default=1, type=int,
+ help="Inference batch size (default: %(default)s)")
+ rise_parser.add_argument('--display', action='store_true',
+ help="Visualize results during computations")
+
+ parser.add_argument('-p', '--project', dest='project_dir', default='.',
+ help="Directory of the project to operate on (default: current dir)")
+ parser.set_defaults(command=explain_command)
+
+ return parser
+
+def explain_command(args):
+ project_path = args.project_dir
+ if is_project_path(project_path):
+ project = Project.load(project_path)
+ else:
+ project = None
+ args.target = target_selector(
+ ProjectTarget(is_default=True, project=project),
+ SourceTarget(project=project),
+ ImageTarget()
+ )(args.target)
+ if args.target[0] == TargetKinds.project:
+ if is_project_path(args.target[1]):
+ args.project_dir = osp.dirname(osp.abspath(args.target[1]))
+
+
+ import cv2
+ from matplotlib import cm
+
+ project = load_project(args.project_dir)
+
+ model = project.make_executable_model(args.model)
+
+ if str(args.algorithm).lower() != 'rise':
+ raise NotImplementedError()
+
+ from datumaro.components.algorithms.rise import RISE
+ rise = RISE(model,
+ max_samples=args.max_samples,
+ mask_width=args.mask_width,
+ mask_height=args.mask_height,
+ prob=args.prob,
+ iou_thresh=args.iou_thresh,
+ nms_thresh=args.nms_iou_thresh,
+ det_conf_thresh=args.det_conf_thresh,
+ batch_size=args.batch_size)
+
+ if args.target[0] == TargetKinds.image:
+ image_path = args.target[1]
+ image = load_image(image_path)
+
+ log.info("Running inference explanation for '%s'" % image_path)
+ heatmap_iter = rise.apply(image, progressive=args.display)
+
+ image = image / 255.0
+ file_name = osp.splitext(osp.basename(image_path))[0]
+ if args.display:
+ for i, heatmaps in enumerate(heatmap_iter):
+ for j, heatmap in enumerate(heatmaps):
+ hm_painted = cm.jet(heatmap)[:, :, 2::-1]
+ disp = (image + hm_painted) / 2
+ cv2.imshow('heatmap-%s' % j, hm_painted)
+ cv2.imshow(file_name + '-heatmap-%s' % j, disp)
+ cv2.waitKey(10)
+ print("Iter", i, "of", args.max_samples, end='\r')
+ else:
+ heatmaps = next(heatmap_iter)
+
+ if args.save_dir is not None:
+ log.info("Saving inference heatmaps at '%s'" % args.save_dir)
+ os.makedirs(args.save_dir, exist_ok=True)
+
+ for j, heatmap in enumerate(heatmaps):
+ save_path = osp.join(args.save_dir,
+ file_name + '-heatmap-%s.png' % j)
+ save_image(save_path, heatmap * 255.0)
+ else:
+ for j, heatmap in enumerate(heatmaps):
+ disp = (image + cm.jet(heatmap)[:, :, 2::-1]) / 2
+ cv2.imshow(file_name + '-heatmap-%s' % j, disp)
+ cv2.waitKey(0)
+ elif args.target[0] == TargetKinds.source or \
+ args.target[0] == TargetKinds.project:
+ if args.target[0] == TargetKinds.source:
+ source_name = args.target[1]
+ dataset = project.make_source_project(source_name).make_dataset()
+ log.info("Running inference explanation for '%s'" % source_name)
+ else:
+ project_name = project.config.project_name
+ dataset = project.make_dataset()
+ log.info("Running inference explanation for '%s'" % project_name)
+
+ for item in dataset:
+ image = item.image.data
+ if image is None:
+ log.warn(
+ "Dataset item %s does not have image data. Skipping." % \
+ (item.id))
+ continue
+
+ heatmap_iter = rise.apply(image)
+
+ image = image / 255.0
+ heatmaps = next(heatmap_iter)
+
+ if args.save_dir is not None:
+ log.info("Saving inference heatmaps to '%s'" % args.save_dir)
+ os.makedirs(args.save_dir, exist_ok=True)
+
+ for j, heatmap in enumerate(heatmaps):
+ save_image(osp.join(args.save_dir,
+ item.id + '-heatmap-%s.png' % j),
+ heatmap * 255.0, create_dir=True)
+
+ if not args.save_dir or args.display:
+ for j, heatmap in enumerate(heatmaps):
+ disp = (image + cm.jet(heatmap)[:, :, 2::-1]) / 2
+ cv2.imshow(item.id + '-heatmap-%s' % j, disp)
+ cv2.waitKey(0)
+ else:
+ raise NotImplementedError()
+
+ return 0
diff --git a/testbed/openvinotoolkit__datumaro/datumaro/cli/contexts/model/__init__.py b/testbed/openvinotoolkit__datumaro/datumaro/cli/contexts/model/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..69b7da1eae2dd6aa37decee2501815bd3d90d858
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/datumaro/cli/contexts/model/__init__.py
@@ -0,0 +1,183 @@
+
+# Copyright (C) 2019-2020 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+
+import argparse
+import logging as log
+import os
+import os.path as osp
+import re
+
+from datumaro.components.config import DEFAULT_FORMAT
+from datumaro.components.project import Environment
+
+from ...util import CliException, MultilineFormatter, add_subparser
+from ...util.project import load_project, \
+ generate_next_name, generate_next_file_name
+
+
+def build_add_parser(parser_ctor=argparse.ArgumentParser):
+ builtins = sorted(Environment().launchers.items)
+
+ parser = parser_ctor(help="Add model to project",
+ description="""
+ Registers an executable model into a project. A model requires
+ a launcher to be executed. Each launcher has its own options, which
+ are passed after '--' separator, pass '-- -h' for more info.
+ |n
+ List of builtin launchers: %s
+ """ % ', '.join(builtins),
+ formatter_class=MultilineFormatter)
+
+ parser.add_argument('-l', '--launcher', required=True,
+ help="Model launcher")
+ parser.add_argument('extra_args', nargs=argparse.REMAINDER, default=None,
+ help="Additional arguments for converter (pass '-- -h' for help)")
+ parser.add_argument('--copy', action='store_true',
+ help="Copy the model to the project")
+ parser.add_argument('-n', '--name', default=None,
+ help="Name of the model to be added (default: generate automatically)")
+ parser.add_argument('--overwrite', action='store_true',
+ help="Overwrite if exists")
+ parser.add_argument('-p', '--project', dest='project_dir', default='.',
+ help="Directory of the project to operate on (default: current dir)")
+ parser.set_defaults(command=add_command)
+
+ return parser
+
+def add_command(args):
+ project = load_project(args.project_dir)
+
+ if args.name:
+ if not args.overwrite and args.name in project.config.models:
+ raise CliException("Model '%s' already exists "
+ "(pass --overwrite to overwrite)" % args.name)
+ else:
+ args.name = generate_next_name(
+ project.config.models, 'model', '-', default=0)
+ assert args.name not in project.config.models, args.name
+
+ try:
+ launcher = project.env.launchers.get(args.launcher)
+ except KeyError:
+ raise CliException("Launcher '%s' is not found" % args.launcher)
+
+ cli_plugin = getattr(launcher, 'cli_plugin', launcher)
+ model_args = cli_plugin.from_cmdline(args.extra_args)
+
+ if args.copy:
+ log.info("Copying model data")
+
+ model_dir = project.local_model_dir(args.name)
+ os.makedirs(model_dir, exist_ok=False)
+
+ try:
+ cli_plugin.copy_model(model_dir, model_args)
+ except (AttributeError, NotImplementedError):
+ log.error("Can't copy: copying is not available for '%s' models" % \
+ args.launcher)
+
+ log.info("Checking the model")
+ project.add_model(args.name, {
+ 'launcher': args.launcher,
+ 'options': model_args,
+ })
+ project.make_executable_model(args.name)
+
+ project.save()
+
+ log.info("Model '%s' with launcher '%s' has been added to project '%s'" % \
+ (args.name, args.launcher, project.config.project_name))
+
+ return 0
+
+def build_remove_parser(parser_ctor=argparse.ArgumentParser):
+ parser = parser_ctor()
+
+ parser.add_argument('name',
+ help="Name of the model to be removed")
+ parser.add_argument('-p', '--project', dest='project_dir', default='.',
+ help="Directory of the project to operate on (default: current dir)")
+ parser.set_defaults(command=remove_command)
+
+ return parser
+
+def remove_command(args):
+ project = load_project(args.project_dir)
+
+ project.remove_model(args.name)
+ project.save()
+
+ return 0
+
+def build_run_parser(parser_ctor=argparse.ArgumentParser):
+ parser = parser_ctor()
+
+ parser.add_argument('-o', '--output-dir', dest='dst_dir',
+ help="Directory to save output")
+ parser.add_argument('-m', '--model', dest='model_name', required=True,
+ help="Model to apply to the project")
+ parser.add_argument('-p', '--project', dest='project_dir', default='.',
+ help="Directory of the project to operate on (default: current dir)")
+ parser.add_argument('--overwrite', action='store_true',
+ help="Overwrite if exists")
+ parser.set_defaults(command=run_command)
+
+ return parser
+
+def run_command(args):
+ project = load_project(args.project_dir)
+
+ dst_dir = args.dst_dir
+ if dst_dir:
+ if not args.overwrite and osp.isdir(dst_dir) and os.listdir(dst_dir):
+ raise CliException("Directory '%s' already exists "
+ "(pass --overwrite overwrite)" % dst_dir)
+ else:
+ dst_dir = generate_next_file_name('%s-inference' % \
+ project.config.project_name)
+
+ project.make_dataset().apply_model(
+ save_dir=osp.abspath(dst_dir),
+ model=args.model_name)
+
+ log.info("Inference results have been saved to '%s'" % dst_dir)
+
+ return 0
+
+def build_info_parser(parser_ctor=argparse.ArgumentParser):
+ parser = parser_ctor()
+
+ parser.add_argument('-n', '--name',
+ help="Model name")
+ parser.add_argument('-v', '--verbose', action='store_true',
+ help="Show details")
+ parser.add_argument('-p', '--project', dest='project_dir', default='.',
+ help="Directory of the project to operate on (default: current dir)")
+ parser.set_defaults(command=info_command)
+
+ return parser
+
+def info_command(args):
+ project = load_project(args.project_dir)
+
+ if args.name:
+ model = project.get_model(args.name)
+ print(model)
+ else:
+ for name, conf in project.config.models.items():
+ print(name)
+ if args.verbose:
+ print(dict(conf))
+
+def build_parser(parser_ctor=argparse.ArgumentParser):
+ parser = parser_ctor()
+
+ subparsers = parser.add_subparsers()
+ add_subparser(subparsers, 'add', build_add_parser)
+ add_subparser(subparsers, 'remove', build_remove_parser)
+ add_subparser(subparsers, 'run', build_run_parser)
+ add_subparser(subparsers, 'info', build_info_parser)
+
+ return parser
diff --git a/testbed/openvinotoolkit__datumaro/datumaro/cli/contexts/project/diff.py b/testbed/openvinotoolkit__datumaro/datumaro/cli/contexts/project/diff.py
new file mode 100644
index 0000000000000000000000000000000000000000..358f3860574f7c6b1cedbe492f147e12815bada1
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/datumaro/cli/contexts/project/diff.py
@@ -0,0 +1,290 @@
+
+# Copyright (C) 2019-2020 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+
+from collections import Counter
+from enum import Enum
+import numpy as np
+import os
+import os.path as osp
+
+_formats = ['simple']
+
+import warnings
+with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ import tensorboardX as tb
+ _formats.append('tensorboard')
+
+from datumaro.components.extractor import AnnotationType
+from datumaro.util.image import save_image
+
+
+Format = Enum('Formats', _formats)
+
+class DiffVisualizer:
+ Format = Format
+ DEFAULT_FORMAT = Format.simple
+
+ _UNMATCHED_LABEL = -1
+
+
+ def __init__(self, comparator, save_dir, output_format=DEFAULT_FORMAT):
+ self.comparator = comparator
+
+ if isinstance(output_format, str):
+ output_format = Format[output_format]
+ assert output_format in Format
+ self.output_format = output_format
+
+ self.save_dir = save_dir
+ if output_format is Format.tensorboard:
+ logdir = osp.join(self.save_dir, 'logs', 'diff')
+ self.file_writer = tb.SummaryWriter(logdir)
+ if output_format is Format.simple:
+ self.label_diff_writer = None
+
+ self.categories = {}
+
+ self.label_confusion_matrix = Counter()
+ self.bbox_confusion_matrix = Counter()
+
+ def save_dataset_diff(self, extractor_a, extractor_b):
+ if self.save_dir:
+ os.makedirs(self.save_dir, exist_ok=True)
+
+ if len(extractor_a) != len(extractor_b):
+ print("Datasets have different lengths: %s vs %s" % \
+ (len(extractor_a), len(extractor_b)))
+
+ self.categories = {}
+
+ label_mismatch = self.comparator. \
+ compare_dataset_labels(extractor_a, extractor_b)
+ if label_mismatch is None:
+ print("Datasets have no label information")
+ elif len(label_mismatch) != 0:
+ print("Datasets have mismatching labels:")
+ for a_label, b_label in label_mismatch:
+ if a_label is None:
+ print(" > %s" % b_label.name)
+ elif b_label is None:
+ print(" < %s" % a_label.name)
+ else:
+ print(" %s != %s" % (a_label.name, b_label.name))
+ else:
+ self.categories.update(extractor_a.categories())
+ self.categories.update(extractor_b.categories())
+
+ self.label_confusion_matrix = Counter()
+ self.bbox_confusion_matrix = Counter()
+
+ if self.output_format is Format.tensorboard:
+ self.file_writer.reopen()
+
+ ids_a = set((item.id, item.subset) for item in extractor_a)
+ ids_b = set((item.id, item.subset) for item in extractor_b)
+ ids = ids_a & ids_b
+
+ if len(ids) != len(ids_a):
+ print("Unmatched items in the first dataset: ")
+ print(ids_a - ids)
+ if len(ids) != len(ids_b):
+ print("Unmatched items in the second dataset: ")
+ print(ids_b - ids)
+
+ for item_id, item_subset in ids:
+ item_a = extractor_a.get(item_id, item_subset)
+ item_b = extractor_a.get(item_id, item_subset)
+
+ label_diff = self.comparator.compare_item_labels(item_a, item_b)
+ self.update_label_confusion(label_diff)
+
+ bbox_diff = self.comparator.compare_item_bboxes(item_a, item_b)
+ self.update_bbox_confusion(bbox_diff)
+
+ self.save_item_label_diff(item_a, item_b, label_diff)
+ self.save_item_bbox_diff(item_a, item_b, bbox_diff)
+
+ if len(self.label_confusion_matrix) != 0:
+ self.save_conf_matrix(self.label_confusion_matrix,
+ 'labels_confusion.png')
+ if len(self.bbox_confusion_matrix) != 0:
+ self.save_conf_matrix(self.bbox_confusion_matrix,
+ 'bbox_confusion.png')
+
+ if self.output_format is Format.tensorboard:
+ self.file_writer.flush()
+ self.file_writer.close()
+ elif self.output_format is Format.simple:
+ if self.label_diff_writer:
+ self.label_diff_writer.flush()
+ self.label_diff_writer.close()
+
+ def update_label_confusion(self, label_diff):
+ matches, a_unmatched, b_unmatched = label_diff
+ for label in matches:
+ self.label_confusion_matrix[(label, label)] += 1
+ for a_label in a_unmatched:
+ self.label_confusion_matrix[(a_label, self._UNMATCHED_LABEL)] += 1
+ for b_label in b_unmatched:
+ self.label_confusion_matrix[(self._UNMATCHED_LABEL, b_label)] += 1
+
+ def update_bbox_confusion(self, bbox_diff):
+ matches, mispred, a_unmatched, b_unmatched = bbox_diff
+ for a_bbox, b_bbox in matches:
+ self.bbox_confusion_matrix[(a_bbox.label, b_bbox.label)] += 1
+ for a_bbox, b_bbox in mispred:
+ self.bbox_confusion_matrix[(a_bbox.label, b_bbox.label)] += 1
+ for a_bbox in a_unmatched:
+ self.bbox_confusion_matrix[(a_bbox.label, self._UNMATCHED_LABEL)] += 1
+ for b_bbox in b_unmatched:
+ self.bbox_confusion_matrix[(self._UNMATCHED_LABEL, b_bbox.label)] += 1
+
+ @classmethod
+ def draw_text_with_background(cls, frame, text, origin,
+ font=None, scale=1.0,
+ color=(0, 0, 0), thickness=1, bgcolor=(1, 1, 1)):
+ import cv2
+
+ if not font:
+ font = cv2.FONT_HERSHEY_SIMPLEX
+
+ text_size, baseline = cv2.getTextSize(text, font, scale, thickness)
+ cv2.rectangle(frame,
+ tuple((origin + (0, baseline)).astype(int)),
+ tuple((origin + (text_size[0], -text_size[1])).astype(int)),
+ bgcolor, cv2.FILLED)
+ cv2.putText(frame, text,
+ tuple(origin.astype(int)),
+ font, scale, color, thickness)
+ return text_size, baseline
+
+ def draw_detection_roi(self, frame, x, y, w, h, label, conf, color):
+ import cv2
+
+ cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)
+
+ text = '%s %.2f%%' % (label, 100.0 * conf)
+ text_scale = 0.5
+ font = cv2.FONT_HERSHEY_SIMPLEX
+ text_size = cv2.getTextSize(text, font, text_scale, 1)
+ line_height = np.array([0, text_size[0][1]])
+ self.draw_text_with_background(frame, text,
+ np.array([x, y]) - line_height * 0.5,
+ font, scale=text_scale, color=[255 - c for c in color])
+
+ def get_label(self, label_id):
+ cat = self.categories.get(AnnotationType.label)
+ if cat is None:
+ return str(label_id)
+ return cat.items[label_id].name
+
+ def draw_bbox(self, img, shape, color):
+ x, y, w, h = shape.get_bbox()
+ self.draw_detection_roi(img, int(x), int(y), int(w), int(h),
+ self.get_label(shape.label), shape.attributes.get('score', 1),
+ color)
+
+ def get_label_diff_file(self):
+ if self.label_diff_writer is None:
+ self.label_diff_writer = \
+ open(osp.join(self.save_dir, 'label_diff.txt'), 'w')
+ return self.label_diff_writer
+
+ def save_item_label_diff(self, item_a, item_b, diff):
+ _, a_unmatched, b_unmatched = diff
+
+ if 0 < len(a_unmatched) + len(b_unmatched):
+ if self.output_format is Format.simple:
+ f = self.get_label_diff_file()
+ f.write(item_a.id + '\n')
+ for a_label in a_unmatched:
+ f.write(' >%s\n' % self.get_label(a_label))
+ for b_label in b_unmatched:
+ f.write(' <%s\n' % self.get_label(b_label))
+ elif self.output_format is Format.tensorboard:
+ tag = item_a.id
+ for a_label in a_unmatched:
+ self.file_writer.add_text(tag,
+ '>%s\n' % self.get_label(a_label))
+ for b_label in b_unmatched:
+ self.file_writer.add_text(tag,
+ '<%s\n' % self.get_label(b_label))
+
+ def save_item_bbox_diff(self, item_a, item_b, diff):
+ _, mispred, a_unmatched, b_unmatched = diff
+
+ if 0 < len(a_unmatched) + len(b_unmatched) + len(mispred):
+ img_a = item_a.image.data.copy()
+ img_b = img_a.copy()
+ for a_bbox, b_bbox in mispred:
+ self.draw_bbox(img_a, a_bbox, (0, 255, 0))
+ self.draw_bbox(img_b, b_bbox, (0, 0, 255))
+ for a_bbox in a_unmatched:
+ self.draw_bbox(img_a, a_bbox, (255, 255, 0))
+ for b_bbox in b_unmatched:
+ self.draw_bbox(img_b, b_bbox, (255, 255, 0))
+
+ img = np.hstack([img_a, img_b])
+
+ path = osp.join(self.save_dir, item_a.id)
+
+ if self.output_format is Format.simple:
+ save_image(path + '.png', img, create_dir=True)
+ elif self.output_format is Format.tensorboard:
+ self.save_as_tensorboard(img, path)
+
+ def save_as_tensorboard(self, img, name):
+ img = img[:, :, ::-1] # to RGB
+ img = np.transpose(img, (2, 0, 1)) # to (C, H, W)
+ img = img.astype(dtype=np.uint8)
+ self.file_writer.add_image(name, img)
+
+ def save_conf_matrix(self, conf_matrix, filename):
+ import matplotlib.pyplot as plt
+
+ classes = None
+ label_categories = self.categories.get(AnnotationType.label)
+ if label_categories is not None:
+ classes = { id: c.name for id, c in enumerate(label_categories.items) }
+ if classes is None:
+ classes = { c: 'label_%s' % c for c, _ in conf_matrix }
+ classes[self._UNMATCHED_LABEL] = 'unmatched'
+
+ class_idx = { id: i for i, id in enumerate(classes.keys()) }
+ matrix = np.zeros((len(classes), len(classes)), dtype=int)
+ for idx_pair in conf_matrix:
+ index = (class_idx[idx_pair[0]], class_idx[idx_pair[1]])
+ matrix[index] = conf_matrix[idx_pair]
+
+ labels = [label for id, label in classes.items()]
+
+ fig = plt.figure()
+ fig.add_subplot(111)
+ table = plt.table(
+ cellText=matrix,
+ colLabels=labels,
+ rowLabels=labels,
+ loc ='center')
+ table.auto_set_font_size(False)
+ table.set_fontsize(8)
+ table.scale(3, 3)
+ # Removing ticks and spines enables you to get the figure only with table
+ plt.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)
+ plt.tick_params(axis='y', which='both', right=False, left=False, labelleft=False)
+ for pos in ['right','top','bottom','left']:
+ plt.gca().spines[pos].set_visible(False)
+
+ for idx_pair in conf_matrix:
+ i = class_idx[idx_pair[0]]
+ j = class_idx[idx_pair[1]]
+ if conf_matrix[idx_pair] != 0:
+ if i != j:
+ table._cells[(i + 1, j)].set_facecolor('#FF0000')
+ else:
+ table._cells[(i + 1, j)].set_facecolor('#00FF00')
+
+ plt.savefig(osp.join(self.save_dir, filename),
+ bbox_inches='tight', pad_inches=0.05)
diff --git a/testbed/openvinotoolkit__datumaro/datumaro/components/algorithms/rise.py b/testbed/openvinotoolkit__datumaro/datumaro/components/algorithms/rise.py
new file mode 100644
index 0000000000000000000000000000000000000000..3fb9a895c1066f4878df7f5eddfc76f481008052
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/datumaro/components/algorithms/rise.py
@@ -0,0 +1,203 @@
+
+# Copyright (C) 2019-2020 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+
+# pylint: disable=unused-variable
+
+import numpy as np
+from math import ceil
+
+from datumaro.components.extractor import AnnotationType
+from datumaro.util.annotation_util import nms
+
+
+def flatmatvec(mat):
+ return np.reshape(mat, (len(mat), -1))
+
+def expand(array, axis=None):
+ if axis is None:
+ axis = len(array.shape)
+ return np.expand_dims(array, axis=axis)
+
+class RISE:
+ """
+ Implements RISE: Randomized Input Sampling for
+ Explanation of Black-box Models algorithm
+ See explanations at: https://arxiv.org/pdf/1806.07421.pdf
+ """
+
+ def __init__(self, model,
+ max_samples=None, mask_width=7, mask_height=7, prob=0.5,
+ iou_thresh=0.9, nms_thresh=0.0, det_conf_thresh=0.0,
+ batch_size=1):
+ self.model = model
+ self.max_samples = max_samples
+ self.mask_height = mask_height
+ self.mask_width = mask_width
+ self.prob = prob
+ self.iou_thresh = iou_thresh
+ self.nms_thresh = nms_thresh
+ self.det_conf_thresh = det_conf_thresh
+ self.batch_size = batch_size
+
+ @staticmethod
+ def split_outputs(annotations):
+ labels = []
+ bboxes = []
+ for r in annotations:
+ if r.type is AnnotationType.label:
+ labels.append(r)
+ elif r.type is AnnotationType.bbox:
+ bboxes.append(r)
+ return labels, bboxes
+
+ def normalize_hmaps(self, heatmaps, counts):
+ eps = np.finfo(heatmaps.dtype).eps
+ mhmaps = flatmatvec(heatmaps)
+ mhmaps /= expand(counts * self.prob + eps)
+ mhmaps -= expand(np.min(mhmaps, axis=1))
+ mhmaps /= expand(np.max(mhmaps, axis=1) + eps)
+ return np.reshape(mhmaps, heatmaps.shape)
+
+ def apply(self, image, progressive=False):
+ import cv2
+
+ assert len(image.shape) in [2, 3], \
+ "Expected an input image in (H, W, C) format"
+ if len(image.shape) == 3:
+ assert image.shape[2] in [3, 4], "Expected BGR or BGRA input"
+ image = image[:, :, :3].astype(np.float32)
+
+ model = self.model
+ iou_thresh = self.iou_thresh
+
+ image_size = np.array((image.shape[:2]))
+ mask_size = np.array((self.mask_height, self.mask_width))
+ cell_size = np.ceil(image_size / mask_size)
+ upsampled_size = np.ceil((mask_size + 1) * cell_size)
+
+ rng = lambda shape=None: np.random.rand(*shape)
+ samples = np.prod(image_size)
+ if self.max_samples is not None:
+ samples = min(self.max_samples, samples)
+ batch_size = self.batch_size
+
+ result = next(iter(model.launch(expand(image, 0))))
+ result_labels, result_bboxes = self.split_outputs(result)
+ if 0 < self.det_conf_thresh:
+ result_bboxes = [b for b in result_bboxes \
+ if self.det_conf_thresh <= b.attributes['score']]
+ if 0 < self.nms_thresh:
+ result_bboxes = nms(result_bboxes, self.nms_thresh)
+
+ predicted_labels = set()
+ if len(result_labels) != 0:
+ predicted_label = max(result_labels,
+ key=lambda r: r.attributes['score']).label
+ predicted_labels.add(predicted_label)
+ if len(result_bboxes) != 0:
+ for bbox in result_bboxes:
+ predicted_labels.add(bbox.label)
+ predicted_labels = { label: idx \
+ for idx, label in enumerate(predicted_labels) }
+
+ predicted_bboxes = result_bboxes
+
+ heatmaps_count = len(predicted_labels) + len(predicted_bboxes)
+ heatmaps = np.zeros((heatmaps_count, *image_size), dtype=np.float32)
+ total_counts = np.zeros(heatmaps_count, dtype=np.int32)
+ confs = np.zeros(heatmaps_count, dtype=np.float32)
+
+ heatmap_id = 0
+
+ label_heatmaps = None
+ label_total_counts = None
+ label_confs = None
+ if len(predicted_labels) != 0:
+ step = len(predicted_labels)
+ label_heatmaps = heatmaps[heatmap_id : heatmap_id + step]
+ label_total_counts = total_counts[heatmap_id : heatmap_id + step]
+ label_confs = confs[heatmap_id : heatmap_id + step]
+ heatmap_id += step
+
+ bbox_heatmaps = None
+ bbox_total_counts = None
+ bbox_confs = None
+ if len(predicted_bboxes) != 0:
+ step = len(predicted_bboxes)
+ bbox_heatmaps = heatmaps[heatmap_id : heatmap_id + step]
+ bbox_total_counts = total_counts[heatmap_id : heatmap_id + step]
+ bbox_confs = confs[heatmap_id : heatmap_id + step]
+ heatmap_id += step
+
+ ups_mask = np.empty(upsampled_size.astype(int), dtype=np.float32)
+ masks = np.empty((batch_size, *image_size), dtype=np.float32)
+
+ full_batch_inputs = np.empty((batch_size, *image.shape), dtype=np.float32)
+ current_heatmaps = np.empty_like(heatmaps)
+ for b in range(ceil(samples / batch_size)):
+ batch_pos = b * batch_size
+ current_batch_size = min(samples - batch_pos, batch_size)
+
+ batch_masks = masks[: current_batch_size]
+ for i in range(current_batch_size):
+ mask = (rng(mask_size) < self.prob).astype(np.float32)
+ cv2.resize(mask, (int(upsampled_size[1]), int(upsampled_size[0])),
+ ups_mask)
+
+ offsets = np.round(rng((2,)) * cell_size)
+ mask = ups_mask[
+ int(offsets[0]):int(image_size[0] + offsets[0]),
+ int(offsets[1]):int(image_size[1] + offsets[1]) ]
+ batch_masks[i] = mask
+
+ batch_inputs = full_batch_inputs[:current_batch_size]
+ np.multiply(expand(batch_masks), expand(image, 0), out=batch_inputs)
+
+ results = model.launch(batch_inputs)
+ for mask, result in zip(batch_masks, results):
+ result_labels, result_bboxes = self.split_outputs(result)
+
+ confs.fill(0)
+ if len(predicted_labels) != 0:
+ for r in result_labels:
+ idx = predicted_labels.get(r.label, None)
+ if idx is not None:
+ label_total_counts[idx] += 1
+ label_confs[idx] += r.attributes['score']
+ for r in result_bboxes:
+ idx = predicted_labels.get(r.label, None)
+ if idx is not None:
+ label_total_counts[idx] += 1
+ label_confs[idx] += r.attributes['score']
+
+ if len(predicted_bboxes) != 0 and len(result_bboxes) != 0:
+ if 0 < self.det_conf_thresh:
+ result_bboxes = [b for b in result_bboxes \
+ if self.det_conf_thresh <= b.attributes['score']]
+ if 0 < self.nms_thresh:
+ result_bboxes = nms(result_bboxes, self.nms_thresh)
+
+ for detection in result_bboxes:
+ for pred_idx, pred in enumerate(predicted_bboxes):
+ if pred.label != detection.label:
+ continue
+
+ iou = pred.iou(detection)
+ assert iou == -1 or 0 <= iou and iou <= 1
+ if iou < iou_thresh:
+ continue
+
+ bbox_total_counts[pred_idx] += 1
+
+ conf = detection.attributes['score']
+ bbox_confs[pred_idx] += conf
+
+ np.multiply.outer(confs, mask, out=current_heatmaps)
+ heatmaps += current_heatmaps
+
+ if progressive:
+ yield self.normalize_hmaps(heatmaps.copy(), total_counts)
+
+ yield self.normalize_hmaps(heatmaps, total_counts)
\ No newline at end of file
diff --git a/testbed/openvinotoolkit__datumaro/datumaro/components/config.py b/testbed/openvinotoolkit__datumaro/datumaro/components/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..a79cda151b517a8d46451829b3d69ff9271f0d02
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/datumaro/components/config.py
@@ -0,0 +1,237 @@
+
+# Copyright (C) 2019-2020 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+
+import yaml
+
+
+class Schema:
+ class Item:
+ def __init__(self, ctor, internal=False):
+ self.ctor = ctor
+ self.internal = internal
+
+ def __call__(self, *args, **kwargs):
+ return self.ctor(*args, **kwargs)
+
+ def __init__(self, items=None, fallback=None):
+ self._items = {}
+ if items is not None:
+ self._items.update(items)
+ self._fallback = fallback
+
+ def _get_items(self, allow_fallback=True):
+ all_items = {}
+
+ if allow_fallback and self._fallback is not None:
+ all_items.update(self._fallback)
+ all_items.update(self._items)
+
+ return all_items
+
+ def items(self, allow_fallback=True):
+ return self._get_items(allow_fallback=allow_fallback).items()
+
+ def keys(self, allow_fallback=True):
+ return self._get_items(allow_fallback=allow_fallback).keys()
+
+ def values(self, allow_fallback=True):
+ return self._get_items(allow_fallback=allow_fallback).values()
+
+ def __contains__(self, key):
+ return key in self.keys()
+
+ def __len__(self):
+ return len(self._get_items())
+
+ def __iter__(self):
+ return iter(self._get_items())
+
+ def __getitem__(self, key):
+ default = object()
+ value = self.get(key, default=default)
+ if value is default:
+ raise KeyError('Key "%s" does not exist' % (key))
+ return value
+
+ def get(self, key, default=None):
+ found = self._items.get(key, default)
+ if found is not default:
+ return found
+
+ if self._fallback is not None:
+ return self._fallback.get(key, default)
+
+class SchemaBuilder:
+ def __init__(self):
+ self._items = {}
+
+ def add(self, name, ctor=str, internal=False):
+ if name in self._items:
+ raise KeyError('Key "%s" already exists' % (name))
+
+ self._items[name] = Schema.Item(ctor, internal=internal)
+ return self
+
+ def build(self):
+ return Schema(self._items)
+
+class Config:
+ def __init__(self, config=None, fallback=None, schema=None, mutable=True):
+ # schema should be established first
+ self.__dict__['_schema'] = schema
+ self.__dict__['_mutable'] = True
+
+ self.__dict__['_config'] = {}
+ if fallback is not None:
+ for k, v in fallback.items(allow_fallback=False):
+ self.set(k, v)
+ if config is not None:
+ self.update(config)
+
+ self.__dict__['_mutable'] = mutable
+
+ def _items(self, allow_fallback=True, allow_internal=True):
+ all_config = {}
+ if allow_fallback and self._schema is not None:
+ for key, item in self._schema.items():
+ all_config[key] = item()
+ all_config.update(self._config)
+
+ if not allow_internal and self._schema is not None:
+ for key, item in self._schema.items():
+ if item.internal:
+ all_config.pop(key)
+ return all_config
+
+ def items(self, allow_fallback=True, allow_internal=True):
+ return self._items(
+ allow_fallback=allow_fallback,
+ allow_internal=allow_internal
+ ).items()
+
+ def keys(self, allow_fallback=True, allow_internal=True):
+ return self._items(
+ allow_fallback=allow_fallback,
+ allow_internal=allow_internal
+ ).keys()
+
+ def values(self, allow_fallback=True, allow_internal=True):
+ return self._items(
+ allow_fallback=allow_fallback,
+ allow_internal=allow_internal
+ ).values()
+
+ def __contains__(self, key):
+ return key in self.keys()
+
+ def __len__(self):
+ return len(self.items())
+
+ def __iter__(self):
+ return iter(self.keys())
+
+ def __getitem__(self, key):
+ default = object()
+ value = self.get(key, default=default)
+ if value is default:
+ raise KeyError('Key "%s" does not exist' % (key))
+ return value
+
+ def __setitem__(self, key, value):
+ return self.set(key, value)
+
+ def __getattr__(self, key):
+ return self.get(key)
+
+ def __setattr__(self, key, value):
+ return self.set(key, value)
+
+ def __eq__(self, other):
+ try:
+ for k, my_v in self.items(allow_internal=False):
+ other_v = other[k]
+ if my_v != other_v:
+ return False
+ return True
+ except Exception:
+ return False
+
+ def update(self, other):
+ for k, v in other.items():
+ self.set(k, v)
+
+ def remove(self, key):
+ if not self._mutable:
+ raise Exception("Cannot set value of immutable object")
+
+ self._config.pop(key, None)
+
+ def get(self, key, default=None):
+ found = self._config.get(key, default)
+ if found is not default:
+ return found
+
+ if self._schema is not None:
+ found = self._schema.get(key, default)
+ if found is not default:
+ # ignore mutability
+ found = found()
+ self._config[key] = found
+ return found
+
+ return found
+
+ def set(self, key, value):
+ if not self._mutable:
+ raise Exception("Cannot set value of immutable object")
+
+ if self._schema is not None:
+ if key not in self._schema:
+ raise Exception("Can not set key '%s' - schema mismatch" % (key))
+
+ schema_entry = self._schema[key]
+ schema_entry_instance = schema_entry()
+ if not isinstance(value, type(schema_entry_instance)):
+ if isinstance(value, dict) and \
+ isinstance(schema_entry_instance, Config):
+ schema_entry_instance.update(value)
+ value = schema_entry_instance
+ else:
+ raise Exception("Can not set key '%s' - schema mismatch" % (key))
+
+ self._config[key] = value
+ return value
+
+ @staticmethod
+ def parse(path):
+ with open(path, 'r') as f:
+ return Config(yaml.safe_load(f))
+
+ @staticmethod
+ def yaml_representer(dumper, value):
+ return dumper.represent_data(
+ value._items(allow_internal=False, allow_fallback=False))
+
+ def dump(self, path):
+ with open(path, 'w+') as f:
+ yaml.dump(self, f)
+
+yaml.add_multi_representer(Config, Config.yaml_representer)
+
+
+class DefaultConfig(Config):
+ def __init__(self, default=None):
+ super().__init__()
+ self.__dict__['_default'] = default
+
+ def set(self, key, value):
+ if key not in self.keys(allow_fallback=False):
+ value = self._default(value)
+ return super().set(key, value)
+ else:
+ return super().set(key, value)
+
+
+DEFAULT_FORMAT = 'datumaro'
\ No newline at end of file
diff --git a/testbed/openvinotoolkit__datumaro/datumaro/components/project.py b/testbed/openvinotoolkit__datumaro/datumaro/components/project.py
new file mode 100644
index 0000000000000000000000000000000000000000..094dd22ffe747dac47a5d83c1b207c866043379e
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/datumaro/components/project.py
@@ -0,0 +1,669 @@
+# Copyright (C) 2019-2020 Intel Corporation
+#
+# SPDX-License-Identifier: MIT
+
+from collections import defaultdict
+from glob import glob
+import git
+import importlib
+import inspect
+import logging as log
+import os
+import os.path as osp
+import shutil
+import sys
+
+from datumaro.components.config import Config, DEFAULT_FORMAT
+from datumaro.components.config_model import (Model, Source,
+ PROJECT_DEFAULT_CONFIG, PROJECT_SCHEMA)
+from datumaro.components.launcher import ModelTransform
+from datumaro.components.dataset import Dataset
+
+
+def import_foreign_module(name, path, package=None):
+ module = None
+ default_path = sys.path.copy()
+ try:
+ sys.path = [ osp.abspath(path), ] + default_path
+ sys.modules.pop(name, None) # remove from cache
+ module = importlib.import_module(name, package=package)
+ sys.modules.pop(name) # remove from cache
+ except Exception:
+ raise
+ finally:
+ sys.path = default_path
+ return module
+
+
+class Registry:
+ def __init__(self, config=None, item_type=None):
+ self.item_type = item_type
+
+ self.items = {}
+
+ if config is not None:
+ self.load(config)
+
+ def load(self, config):
+ pass
+
+ def register(self, name, value):
+ if self.item_type:
+ value = self.item_type(value)
+ self.items[name] = value
+ return value
+
+ def unregister(self, name):
+ return self.items.pop(name, None)
+
+ def get(self, key):
+ return self.items[key] # returns a class / ctor
+
+
+class ModelRegistry(Registry):
+ def __init__(self, config=None):
+ super().__init__(config, item_type=Model)
+
+ def load(self, config):
+ # TODO: list default dir, insert values
+ if 'models' in config:
+ for name, model in config.models.items():
+ self.register(name, model)
+
+
+class SourceRegistry(Registry):
+ def __init__(self, config=None):
+ super().__init__(config, item_type=Source)
+
+ def load(self, config):
+ # TODO: list default dir, insert values
+ if 'sources' in config:
+ for name, source in config.sources.items():
+ self.register(name, source)
+
+class PluginRegistry(Registry):
+ def __init__(self, config=None, builtin=None, local=None):
+ super().__init__(config)
+
+ from datumaro.components.cli_plugin import CliPlugin
+
+ if builtin is not None:
+ for v in builtin:
+ k = CliPlugin._get_name(v)
+ self.register(k, v)
+ if local is not None:
+ for v in local:
+ k = CliPlugin._get_name(v)
+ self.register(k, v)
+
+class GitWrapper:
+ def __init__(self, config=None):
+ self.repo = None
+
+ if config is not None and config.project_dir:
+ self.init(config.project_dir)
+
+ @staticmethod
+ def _git_dir(base_path):
+ return osp.join(base_path, '.git')
+
+ @classmethod
+ def spawn(cls, path):
+ spawn = not osp.isdir(cls._git_dir(path))
+ repo = git.Repo.init(path=path)
+ if spawn:
+ repo.config_writer().set_value("user", "name", "User") \
+ .set_value("user", "email", "user@nowhere.com") \
+ .release()
+ # gitpython does not support init, use git directly
+ repo.git.init()
+ repo.git.commit('-m', 'Initial commit', '--allow-empty')
+ return repo
+
+ def init(self, path):
+ self.repo = self.spawn(path)
+ return self.repo
+
+ def is_initialized(self):
+ return self.repo is not None
+
+ def create_submodule(self, name, dst_dir, **kwargs):
+ self.repo.create_submodule(name, dst_dir, **kwargs)
+
+ def has_submodule(self, name):
+ return name in [submodule.name for submodule in self.repo.submodules]
+
+ def remove_submodule(self, name, **kwargs):
+ return self.repo.submodule(name).remove(**kwargs)
+
+def load_project_as_dataset(url):
+ # symbol forward declaration
+ raise NotImplementedError()
+
+class Environment:
+ _builtin_plugins = None
+ PROJECT_EXTRACTOR_NAME = 'datumaro_project'
+
+ def __init__(self, config=None):
+ config = Config(config,
+ fallback=PROJECT_DEFAULT_CONFIG, schema=PROJECT_SCHEMA)
+
+ self.models = ModelRegistry(config)
+ self.sources = SourceRegistry(config)
+
+ self.git = GitWrapper(config)
+
+ env_dir = osp.join(config.project_dir, config.env_dir)
+ builtin = self._load_builtin_plugins()
+ custom = self._load_plugins2(osp.join(env_dir, config.plugins_dir))
+ select = lambda seq, t: [e for e in seq if issubclass(e, t)]
+ from datumaro.components.extractor import Transform
+ from datumaro.components.extractor import SourceExtractor
+ from datumaro.components.extractor import Importer
+ from datumaro.components.converter import Converter
+ from datumaro.components.launcher import Launcher
+ self.extractors = PluginRegistry(
+ builtin=select(builtin, SourceExtractor),
+ local=select(custom, SourceExtractor)
+ )
+ self.extractors.register(self.PROJECT_EXTRACTOR_NAME,
+ load_project_as_dataset)
+
+ self.importers = PluginRegistry(
+ builtin=select(builtin, Importer),
+ local=select(custom, Importer)
+ )
+ self.launchers = PluginRegistry(
+ builtin=select(builtin, Launcher),
+ local=select(custom, Launcher)
+ )
+ self.converters = PluginRegistry(
+ builtin=select(builtin, Converter),
+ local=select(custom, Converter)
+ )
+ self.transforms = PluginRegistry(
+ builtin=select(builtin, Transform),
+ local=select(custom, Transform)
+ )
+
+ @staticmethod
+ def _find_plugins(plugins_dir):
+ plugins = []
+ if not osp.exists(plugins_dir):
+ return plugins
+
+ for plugin_name in os.listdir(plugins_dir):
+ p = osp.join(plugins_dir, plugin_name)
+ if osp.isfile(p) and p.endswith('.py'):
+ plugins.append((plugins_dir, plugin_name, None))
+ elif osp.isdir(p):
+ plugins += [(plugins_dir,
+ osp.splitext(plugin_name)[0] + '.' + osp.basename(p),
+ osp.splitext(plugin_name)[0]
+ )
+ for p in glob(osp.join(p, '*.py'))]
+ return plugins
+
+ @classmethod
+ def _import_module(cls, module_dir, module_name, types, package=None):
+ module = import_foreign_module(osp.splitext(module_name)[0], module_dir,
+ package=package)
+
+ exports = []
+ if hasattr(module, 'exports'):
+ exports = module.exports
+ else:
+ for symbol in dir(module):
+ if symbol.startswith('_'):
+ continue
+ exports.append(getattr(module, symbol))
+
+ exports = [s for s in exports
+ if inspect.isclass(s) and issubclass(s, types) and not s in types]
+
+ return exports
+
+ @classmethod
+ def _load_plugins(cls, plugins_dir, types):
+ types = tuple(types)
+
+ plugins = cls._find_plugins(plugins_dir)
+
+ all_exports = []
+ for module_dir, module_name, package in plugins:
+ try:
+ exports = cls._import_module(module_dir, module_name, types,
+ package)
+ except Exception as e:
+ module_search_error = ImportError
+ try:
+ module_search_error = ModuleNotFoundError # python 3.6+
+ except NameError:
+ pass
+
+ message = ["Failed to import module '%s': %s", module_name, e]
+ if isinstance(e, module_search_error):
+ log.debug(*message)
+ else:
+ log.warning(*message)
+ continue
+
+ log.debug("Imported the following symbols from %s: %s" % \
+ (
+ module_name,
+ ', '.join(s.__name__ for s in exports)
+ )
+ )
+ all_exports.extend(exports)
+
+ return all_exports
+
+ @classmethod
+ def _load_builtin_plugins(cls):
+ if not cls._builtin_plugins:
+ plugins_dir = osp.join(
+ __file__[: __file__.rfind(osp.join('datumaro', 'components'))],
+ osp.join('datumaro', 'plugins')
+ )
+ assert osp.isdir(plugins_dir), plugins_dir
+ cls._builtin_plugins = cls._load_plugins2(plugins_dir)
+ return cls._builtin_plugins
+
+ @classmethod
+ def _load_plugins2(cls, plugins_dir):
+ from datumaro.components.extractor import Transform
+ from datumaro.components.extractor import SourceExtractor
+ from datumaro.components.extractor import Importer
+ from datumaro.components.converter import Converter
+ from datumaro.components.launcher import Launcher
+ types = [SourceExtractor, Converter, Importer, Launcher, Transform]
+
+ return cls._load_plugins(plugins_dir, types)
+
+ def make_extractor(self, name, *args, **kwargs):
+ return self.extractors.get(name)(*args, **kwargs)
+
+ def make_importer(self, name, *args, **kwargs):
+ return self.importers.get(name)(*args, **kwargs)
+
+ def make_launcher(self, name, *args, **kwargs):
+ return self.launchers.get(name)(*args, **kwargs)
+
+ def make_converter(self, name, *args, **kwargs):
+ return self.converters.get(name)(*args, **kwargs)
+
+ def register_model(self, name, model):
+ self.models.register(name, model)
+
+ def unregister_model(self, name):
+ self.models.unregister(name)
+
+class ProjectDataset(Dataset):
+ def __init__(self, project):
+ super().__init__()
+
+ self._project = project
+ config = self.config
+ env = self.env
+
+ sources = {}
+ for s_name, source in config.sources.items():
+ s_format = source.format or env.PROJECT_EXTRACTOR_NAME
+ options = {}
+ options.update(source.options)
+
+ url = source.url
+ if not source.url:
+ url = osp.join(config.project_dir, config.sources_dir, s_name)
+ sources[s_name] = env.make_extractor(s_format, url, **options)
+ self._sources = sources
+
+ own_source = None
+ own_source_dir = osp.join(config.project_dir, config.dataset_dir)
+ if config.project_dir and osp.isdir(own_source_dir):
+ log.disable(log.INFO)
+ own_source = env.make_importer(DEFAULT_FORMAT)(own_source_dir) \
+ .make_dataset()
+ log.disable(log.NOTSET)
+
+ # merge categories
+ # TODO: implement properly with merging and annotations remapping
+ categories = self._merge_categories(s.categories()
+ for s in self._sources.values())
+ # ovewrite with own categories
+ if own_source is not None and (not categories or len(own_source) != 0):
+ categories.update(own_source.categories())
+ self._categories = categories
+
+ # merge items
+ subsets = defaultdict(lambda: self.Subset(self))
+ for source_name, source in self._sources.items():
+ log.debug("Loading '%s' source contents..." % source_name)
+ for item in source:
+ existing_item = subsets[item.subset].items.get(item.id)
+ if existing_item is not None:
+ path = existing_item.path
+ if item.path != path:
+ path = None # NOTE: move to our own dataset
+ item = self._merge_items(existing_item, item, path=path)
+ else:
+ s_config = config.sources[source_name]
+ if s_config and \
+ s_config.format != env.PROJECT_EXTRACTOR_NAME:
+ # NOTE: consider imported sources as our own dataset
+ path = None
+ else:
+ path = [source_name] + (item.path or [])
+ item = item.wrap(path=path)
+
+ subsets[item.subset].items[item.id] = item
+
+ # override with our items, fallback to existing images
+ if own_source is not None:
+ log.debug("Loading own dataset...")
+ for item in own_source:
+ existing_item = subsets[item.subset].items.get(item.id)
+ if existing_item is not None:
+ item = item.wrap(path=None,
+ image=self._merge_images(existing_item, item))
+
+ subsets[item.subset].items[item.id] = item
+
+ # TODO: implement subset remapping when needed
+ subsets_filter = config.subsets
+ if len(subsets_filter) != 0:
+ subsets = { k: v for k, v in subsets.items() if k in subsets_filter}
+ self._subsets = dict(subsets)
+
+ self._length = None
+
+ def iterate_own(self):
+ return self.select(lambda item: not item.path)
+
+ def get(self, item_id, subset=None, path=None):
+ if path:
+ source = path[0]
+ rest_path = path[1:]
+ return self._sources[source].get(
+ item_id=item_id, subset=subset, path=rest_path)
+ return super().get(item_id, subset)
+
+ def put(self, item, item_id=None, subset=None, path=None):
+ if path is None:
+ path = item.path
+
+ if path:
+ source = path[0]
+ rest_path = path[1:]
+ # TODO: reverse remapping
+ self._sources[source].put(item,
+ item_id=item_id, subset=subset, path=rest_path)
+
+ if item_id is None:
+ item_id = item.id
+ if subset is None:
+ subset = item.subset
+
+ item = item.wrap(path=path)
+ if subset not in self._subsets:
+ self._subsets[subset] = self.Subset(self)
+ self._subsets[subset].items[item_id] = item
+ self._length = None
+
+ return item
+
+ def save(self, save_dir=None, merge=False, recursive=True,
+ save_images=False):
+ if save_dir is None:
+ assert self.config.project_dir
+ save_dir = self.config.project_dir
+ project = self._project
+ else:
+ merge = True
+
+ if merge:
+ project = Project(Config(self.config))
+ project.config.remove('sources')
+
+ save_dir = osp.abspath(save_dir)
+ dataset_save_dir = osp.join(save_dir, project.config.dataset_dir)
+
+ converter_kwargs = {
+ 'save_images': save_images,
+ }
+
+ save_dir_existed = osp.exists(save_dir)
+ try:
+ os.makedirs(save_dir, exist_ok=True)
+ os.makedirs(dataset_save_dir, exist_ok=True)
+
+ if merge:
+ # merge and save the resulting dataset
+ self.env.converters.get(DEFAULT_FORMAT).convert(
+ self, dataset_save_dir, **converter_kwargs)
+ else:
+ if recursive:
+ # children items should already be updated
+ # so we just save them recursively
+ for source in self._sources.values():
+ if isinstance(source, ProjectDataset):
+ source.save(**converter_kwargs)
+
+ self.env.converters.get(DEFAULT_FORMAT).convert(
+ self.iterate_own(), dataset_save_dir, **converter_kwargs)
+
+ project.save(save_dir)
+ except BaseException:
+ if not save_dir_existed and osp.isdir(save_dir):
+ shutil.rmtree(save_dir, ignore_errors=True)
+ raise
+
+ @property
+ def env(self):
+ return self._project.env
+
+ @property
+ def config(self):
+ return self._project.config
+
+ @property
+ def sources(self):
+ return self._sources
+
+ def _save_branch_project(self, extractor, save_dir=None):
+ extractor = Dataset.from_extractors(extractor) # apply lazy transforms
+
+ # NOTE: probably this function should be in the ViewModel layer
+ save_dir = osp.abspath(save_dir)
+ if save_dir:
+ dst_project = Project()
+ else:
+ if not self.config.project_dir:
+ raise Exception("Either a save directory or a project "
+ "directory should be specified")
+ save_dir = self.config.project_dir
+
+ dst_project = Project(Config(self.config))
+ dst_project.config.remove('project_dir')
+ dst_project.config.remove('sources')
+ dst_project.config.project_name = osp.basename(save_dir)
+
+ dst_dataset = dst_project.make_dataset()
+ dst_dataset.define_categories(extractor.categories())
+ dst_dataset.update(extractor)
+
+ dst_dataset.save(save_dir=save_dir, merge=True)
+
+ def transform_project(self, method, save_dir=None, **method_kwargs):
+ # NOTE: probably this function should be in the ViewModel layer
+ if isinstance(method, str):
+ method = self.env.make_transform(method)
+
+ transformed = self.transform(method, **method_kwargs)
+ self._save_branch_project(transformed, save_dir=save_dir)
+
+ def apply_model(self, model, save_dir=None, batch_size=1):
+ # NOTE: probably this function should be in the ViewModel layer
+ if isinstance(model, str):
+ launcher = self._project.make_executable_model(model)
+
+ self.transform_project(ModelTransform, launcher=launcher,
+ save_dir=save_dir, batch_size=batch_size)
+
+ def export_project(self, save_dir, converter,
+ filter_expr=None, filter_annotations=False, remove_empty=False):
+ # NOTE: probably this function should be in the ViewModel layer
+ dataset = self
+ if filter_expr:
+ dataset = dataset.filter(filter_expr,
+ filter_annotations=filter_annotations,
+ remove_empty=remove_empty)
+
+ save_dir = osp.abspath(save_dir)
+ save_dir_existed = osp.exists(save_dir)
+ try:
+ os.makedirs(save_dir, exist_ok=True)
+ converter(dataset, save_dir)
+ except BaseException:
+ if not save_dir_existed:
+ shutil.rmtree(save_dir)
+ raise
+
+ def filter_project(self, filter_expr, filter_annotations=False,
+ save_dir=None, remove_empty=False):
+ # NOTE: probably this function should be in the ViewModel layer
+ dataset = self
+ if filter_expr:
+ dataset = dataset.filter(filter_expr,
+ filter_annotations=filter_annotations,
+ remove_empty=remove_empty)
+ self._save_branch_project(dataset, save_dir=save_dir)
+
+class Project:
+ @classmethod
+ def load(cls, path):
+ path = osp.abspath(path)
+ config_path = osp.join(path, PROJECT_DEFAULT_CONFIG.env_dir,
+ PROJECT_DEFAULT_CONFIG.project_filename)
+ config = Config.parse(config_path)
+ config.project_dir = path
+ config.project_filename = osp.basename(config_path)
+ return Project(config)
+
+ def save(self, save_dir=None):
+ config = self.config
+
+ if save_dir is None:
+ assert config.project_dir
+ project_dir = config.project_dir
+ else:
+ project_dir = save_dir
+
+ env_dir = osp.join(project_dir, config.env_dir)
+ save_dir = osp.abspath(env_dir)
+
+ project_dir_existed = osp.exists(project_dir)
+ env_dir_existed = osp.exists(env_dir)
+ try:
+ os.makedirs(save_dir, exist_ok=True)
+
+ config_path = osp.join(save_dir, config.project_filename)
+ config.dump(config_path)
+ except BaseException:
+ if not env_dir_existed:
+ shutil.rmtree(save_dir, ignore_errors=True)
+ if not project_dir_existed:
+ shutil.rmtree(project_dir, ignore_errors=True)
+ raise
+
+ @staticmethod
+ def generate(save_dir, config=None):
+ config = Config(config)
+ config.project_dir = save_dir
+ project = Project(config)
+ project.save(save_dir)
+ return project
+
+ @staticmethod
+ def import_from(path, dataset_format, env=None, **kwargs):
+ if env is None:
+ env = Environment()
+ importer = env.make_importer(dataset_format)
+ return importer(path, **kwargs)
+
+ def __init__(self, config=None):
+ self.config = Config(config,
+ fallback=PROJECT_DEFAULT_CONFIG, schema=PROJECT_SCHEMA)
+ self.env = Environment(self.config)
+
+ def make_dataset(self):
+ return ProjectDataset(self)
+
+ def add_source(self, name, value=None):
+ if value is None or isinstance(value, (dict, Config)):
+ value = Source(value)
+ self.config.sources[name] = value
+ self.env.sources.register(name, value)
+
+ def remove_source(self, name):
+ self.config.sources.remove(name)
+ self.env.sources.unregister(name)
+
+ def get_source(self, name):
+ try:
+ return self.config.sources[name]
+ except KeyError:
+ raise KeyError("Source '%s' is not found" % name)
+
+ def get_subsets(self):
+ return self.config.subsets
+
+ def set_subsets(self, value):
+ if not value:
+ self.config.remove('subsets')
+ else:
+ self.config.subsets = value
+
+ def add_model(self, name, value=None):
+ if value is None or isinstance(value, (dict, Config)):
+ value = Model(value)
+ self.env.register_model(name, value)
+ self.config.models[name] = value
+
+ def get_model(self, name):
+ try:
+ return self.env.models.get(name)
+ except KeyError:
+ raise KeyError("Model '%s' is not found" % name)
+
+ def remove_model(self, name):
+ self.config.models.remove(name)
+ self.env.unregister_model(name)
+
+ def make_executable_model(self, name):
+ model = self.get_model(name)
+ return self.env.make_launcher(model.launcher,
+ **model.options, model_dir=self.local_model_dir(name))
+
+ def make_source_project(self, name):
+ source = self.get_source(name)
+
+ config = Config(self.config)
+ config.remove('sources')
+ config.remove('subsets')
+ project = Project(config)
+ project.add_source(name, source)
+ return project
+
+ def local_model_dir(self, model_name):
+ return osp.join(
+ self.config.env_dir, self.config.models_dir, model_name)
+
+ def local_source_dir(self, source_name):
+ return osp.join(self.config.sources_dir, source_name)
+
+# pylint: disable=function-redefined
+def load_project_as_dataset(url):
+ # implement the function declared above
+ return Project.load(url).make_dataset()
+# pylint: enable=function-redefined
diff --git a/testbed/openvinotoolkit__datumaro/tests/assets/camvid_dataset/test.txt b/testbed/openvinotoolkit__datumaro/tests/assets/camvid_dataset/test.txt
new file mode 100644
index 0000000000000000000000000000000000000000..59fec40c0825b0f9a0ccb0bfa3c22d77ebdc31e0
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/tests/assets/camvid_dataset/test.txt
@@ -0,0 +1,2 @@
+/test/0001TP_008550.png /testannot/0001TP_008550.png
+/test/0001TP_008580.png /testannot/0001TP_008580.png
\ No newline at end of file
diff --git a/testbed/openvinotoolkit__datumaro/tests/assets/camvid_dataset/train.txt b/testbed/openvinotoolkit__datumaro/tests/assets/camvid_dataset/train.txt
new file mode 100644
index 0000000000000000000000000000000000000000..4383878eb705ba5f6308654dbb859c8ff0945236
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/tests/assets/camvid_dataset/train.txt
@@ -0,0 +1 @@
+/train/0001TP_006690.png /trainannot/0001TP_006690.png
\ No newline at end of file
diff --git a/testbed/openvinotoolkit__datumaro/tests/assets/camvid_dataset/val.txt b/testbed/openvinotoolkit__datumaro/tests/assets/camvid_dataset/val.txt
new file mode 100644
index 0000000000000000000000000000000000000000..b834086d65ca5134939fe051e7b0045d138728a2
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/tests/assets/camvid_dataset/val.txt
@@ -0,0 +1 @@
+/val/0016E5_07959.png /valannot/0016E5_07959.png
\ No newline at end of file
diff --git a/testbed/openvinotoolkit__datumaro/tests/assets/cvat_dataset/for_images/train.xml b/testbed/openvinotoolkit__datumaro/tests/assets/cvat_dataset/for_images/train.xml
new file mode 100644
index 0000000000000000000000000000000000000000..023464840d087008b340842323010f059362577b
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/tests/assets/cvat_dataset/for_images/train.xml
@@ -0,0 +1,45 @@
+
+ 1.1
+
+
+ True
+ annotation
+
+
+ label1
+
+
+ a1
+ checkbox
+ false
+ false
+true
+
+
+ a2
+ radio
+ v1
+ v1
+v2
+v3
+
+
+
+
+ label2
+
+
+
+
+
+
+ true
+ v3
+
+
+
+
+
+
+
+
diff --git a/testbed/openvinotoolkit__datumaro/tests/assets/cvat_dataset/for_video/annotations.xml b/testbed/openvinotoolkit__datumaro/tests/assets/cvat_dataset/for_video/annotations.xml
new file mode 100644
index 0000000000000000000000000000000000000000..5a68f811a2e1f7708aed6f21db1b903b1ccc204c
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/tests/assets/cvat_dataset/for_video/annotations.xml
@@ -0,0 +1,92 @@
+
+
+ 1.1
+
+
+ 5
+ v1
+ 4
+ interpolation
+ 2
+
+ 2020-04-23 08:57:24.614217+00:00
+ 2020-04-23 09:04:48.168008+00:00
+ 10
+ 19
+ step=3
+ True
+
+
+ klhg
+
+
+ hgl
+ True
+ select
+ jk
+ jk
+hgkf
+
+
+
+
+ z U k
+
+
+
+
+ II
+
+
+
+
+
+
+ 3
+ 0
+ 3
+ http://localhost:7000/?id=3
+
+
+ 4
+ 2
+ 3
+ http://localhost:7000/?id=4
+
+
+
+ max
+
+
+
+
+ 25
+ 20
+
+
+ 2020-04-23 09:05:02.335612+00:00
+ t.mp4
+
+
+
+
+
+
+
+
+
+
+
+ hgkf
+
+
+ jk
+
+
+
+
+
+
+
+
+
diff --git a/testbed/openvinotoolkit__datumaro/tests/test_image.py b/testbed/openvinotoolkit__datumaro/tests/test_image.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f4ef81c4f954e22d3bf825310b659b66a975963
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/tests/test_image.py
@@ -0,0 +1,64 @@
+from itertools import product
+import numpy as np
+import os.path as osp
+
+from unittest import TestCase
+
+import datumaro.util.image as image_module
+from datumaro.util.test_utils import TestDir
+
+
+class ImageOperationsTest(TestCase):
+ def setUp(self):
+ self.default_backend = image_module._IMAGE_BACKEND
+
+ def tearDown(self):
+ image_module._IMAGE_BACKEND = self.default_backend
+
+ def test_save_and_load_backends(self):
+ backends = image_module._IMAGE_BACKENDS
+ for save_backend, load_backend, c in product(backends, backends, [1, 3]):
+ with TestDir() as test_dir:
+ if c == 1:
+ src_image = np.random.randint(0, 255 + 1, (2, 4))
+ else:
+ src_image = np.random.randint(0, 255 + 1, (2, 4, c))
+ path = osp.join(test_dir, 'img.png') # lossless
+
+ image_module._IMAGE_BACKEND = save_backend
+ image_module.save_image(path, src_image, jpeg_quality=100)
+
+ image_module._IMAGE_BACKEND = load_backend
+ dst_image = image_module.load_image(path)
+
+ self.assertTrue(np.array_equal(src_image, dst_image),
+ 'save: %s, load: %s' % (save_backend, load_backend))
+
+ def test_encode_and_decode_backends(self):
+ backends = image_module._IMAGE_BACKENDS
+ for save_backend, load_backend, c in product(backends, backends, [1, 3]):
+ if c == 1:
+ src_image = np.random.randint(0, 255 + 1, (2, 4))
+ else:
+ src_image = np.random.randint(0, 255 + 1, (2, 4, c))
+
+ image_module._IMAGE_BACKEND = save_backend
+ buffer = image_module.encode_image(src_image, '.png',
+ jpeg_quality=100) # lossless
+
+ image_module._IMAGE_BACKEND = load_backend
+ dst_image = image_module.decode_image(buffer)
+
+ self.assertTrue(np.array_equal(src_image, dst_image),
+ 'save: %s, load: %s' % (save_backend, load_backend))
+
+ def test_save_image_to_inexistent_dir_raises_error(self):
+ with self.assertRaises(FileNotFoundError):
+ image_module.save_image('some/path.jpg', np.ones((5, 4, 3)),
+ create_dir=False)
+
+ def test_save_image_can_create_dir(self):
+ with TestDir() as test_dir:
+ path = osp.join(test_dir, 'some', 'path.jpg')
+ image_module.save_image(path, np.ones((5, 4, 3)), create_dir=True)
+ self.assertTrue(osp.isfile(path))
diff --git a/testbed/openvinotoolkit__datumaro/tests/test_masks.py b/testbed/openvinotoolkit__datumaro/tests/test_masks.py
new file mode 100644
index 0000000000000000000000000000000000000000..4396966089fbbe615d0bc3df2226395169230f09
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/tests/test_masks.py
@@ -0,0 +1,197 @@
+import numpy as np
+
+from unittest import TestCase
+
+import datumaro.util.mask_tools as mask_tools
+from datumaro.components.extractor import CompiledMask
+
+
+class PolygonConversionsTest(TestCase):
+ def test_mask_can_be_converted_to_polygon(self):
+ mask = np.array([
+ [0, 1, 1, 1, 0, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 0, 1, 0, 1, 0, 0],
+ [0, 0, 0, 1, 0, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ ])
+ expected = [
+ [1, 0, 3, 0, 3, 2, 1, 0],
+ [5, 0, 8, 0, 5, 3],
+ ]
+
+ computed = mask_tools.mask_to_polygons(mask)
+
+ self.assertEqual(len(expected), len(computed))
+
+ def test_can_crop_covered_segments(self):
+ image_size = [7, 7]
+ initial = [
+ [1, 1, 6, 1, 6, 6, 1, 6], # rectangle
+ mask_tools.mask_to_rle(np.array([
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 1, 1, 0],
+ [0, 1, 1, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0, 1, 0],
+ [0, 1, 1, 0, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ ])),
+ [1, 1, 6, 6, 1, 6], # lower-left triangle
+ ]
+ expected = [
+ np.array([
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ ]), # half-covered
+ np.array([
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 1, 1, 0],
+ [0, 0, 0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ ]), # half-covered
+ mask_tools.rles_to_mask([initial[2]], *image_size), # unchanged
+ ]
+
+ computed = mask_tools.crop_covered_segments(initial, *image_size,
+ ratio_tolerance=0, return_masks=True)
+
+ self.assertEqual(len(initial), len(computed))
+ for i, (e_mask, c_mask) in enumerate(zip(expected, computed)):
+ self.assertTrue(np.array_equal(e_mask, c_mask),
+ '#%s: %s\n%s\n' % (i, e_mask, c_mask))
+
+ def _test_mask_to_rle(self, source_mask):
+ rle_uncompressed = mask_tools.mask_to_rle(source_mask)
+
+ from pycocotools import mask as mask_utils
+ resulting_mask = mask_utils.frPyObjects(
+ rle_uncompressed, *rle_uncompressed['size'])
+ resulting_mask = mask_utils.decode(resulting_mask)
+
+ self.assertTrue(np.array_equal(source_mask, resulting_mask),
+ '%s\n%s\n' % (source_mask, resulting_mask))
+
+ def test_mask_to_rle_multi(self):
+ cases = [
+ np.array([
+ [0, 1, 1, 1, 0, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 0, 1, 0, 1, 0, 0],
+ [0, 0, 0, 1, 0, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ ]),
+
+ np.array([
+ [0]
+ ]),
+ np.array([
+ [1]
+ ]),
+
+ np.array([
+ [1, 0, 0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 0, 1, 0, 1, 1, 1, 0, 0, 0],
+ [1, 1, 0, 1, 0, 1, 1, 1, 1, 0],
+ [1, 0, 1, 0, 1, 0, 0, 0, 0, 0],
+ [1, 0, 0, 1, 0, 0, 0, 1, 0, 1],
+ [1, 1, 0, 0, 1, 1, 0, 0, 0, 1],
+ [0, 0, 1, 0, 0, 0, 1, 1, 1, 1],
+ [1, 1, 0, 0, 0, 0, 0, 1, 0, 0],
+ [1, 1, 1, 1, 1, 0, 1, 0, 1, 0],
+ [0, 1, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 1, 0, 0, 0, 1, 0, 0, 1, 0],
+ [1, 1, 0, 1, 0, 0, 1, 1, 1, 1],
+ ])
+ ]
+
+ for case in cases:
+ self._test_mask_to_rle(case)
+
+class ColormapOperationsTest(TestCase):
+ def test_can_paint_mask(self):
+ mask = np.zeros((1, 3), dtype=np.uint8)
+ mask[:, 0] = 0
+ mask[:, 1] = 1
+ mask[:, 2] = 2
+
+ colormap = mask_tools.generate_colormap(3)
+
+ expected = np.zeros((*mask.shape, 3), dtype=np.uint8)
+ expected[:, 0] = colormap[0][::-1]
+ expected[:, 1] = colormap[1][::-1]
+ expected[:, 2] = colormap[2][::-1]
+
+ actual = mask_tools.paint_mask(mask, colormap)
+
+ self.assertTrue(np.array_equal(expected, actual),
+ '%s\nvs.\n%s' % (expected, actual))
+
+ def test_can_unpaint_mask(self):
+ colormap = mask_tools.generate_colormap(3)
+ inverse_colormap = mask_tools.invert_colormap(colormap)
+
+ mask = np.zeros((1, 3, 3), dtype=np.uint8)
+ mask[:, 0] = colormap[0][::-1]
+ mask[:, 1] = colormap[1][::-1]
+ mask[:, 2] = colormap[2][::-1]
+
+ expected = np.zeros((1, 3), dtype=np.uint8)
+ expected[:, 0] = 0
+ expected[:, 1] = 1
+ expected[:, 2] = 2
+
+ actual = mask_tools.unpaint_mask(mask, inverse_colormap)
+
+ self.assertTrue(np.array_equal(expected, actual),
+ '%s\nvs.\n%s' % (expected, actual))
+
+ def test_can_remap_mask(self):
+ class_count = 10
+ remap_fn = lambda c: class_count - c
+
+ src = np.empty((class_count, class_count), dtype=np.uint8)
+ for c in range(class_count):
+ src[c:, c:] = c
+
+ expected = np.empty_like(src)
+ for c in range(class_count):
+ expected[c:, c:] = remap_fn(c)
+
+ actual = mask_tools.remap_mask(src, remap_fn)
+
+ self.assertTrue(np.array_equal(expected, actual),
+ '%s\nvs.\n%s' % (expected, actual))
+
+ def test_can_merge_masks(self):
+ masks = [
+ np.array([0, 2, 4, 0, 0, 1]),
+ np.array([0, 1, 1, 0, 2, 0]),
+ np.array([0, 0, 2, 3, 0, 0]),
+ ]
+ expected = \
+ np.array([0, 1, 2, 3, 2, 1])
+
+ actual = mask_tools.merge_masks(masks)
+
+ self.assertTrue(np.array_equal(expected, actual),
+ '%s\nvs.\n%s' % (expected, actual))
+
+ def test_can_decode_compiled_mask(self):
+ class_idx = 1000
+ instance_idx = 10000
+ mask = np.array([1])
+ compiled_mask = CompiledMask(mask * class_idx, mask * instance_idx)
+
+ labels = compiled_mask.get_instance_labels()
+
+ self.assertEqual({instance_idx: class_idx}, labels)
\ No newline at end of file
diff --git a/testbed/openvinotoolkit__datumaro/tests/test_mots_format.py b/testbed/openvinotoolkit__datumaro/tests/test_mots_format.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a6ec057e4edfa7040739efcbdd71e0863ad4a7e
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/tests/test_mots_format.py
@@ -0,0 +1,94 @@
+from functools import partial
+import numpy as np
+import os.path as osp
+
+from unittest import TestCase
+
+from datumaro.components.extractor import DatasetItem, Mask
+from datumaro.components.project import Dataset, Project
+from datumaro.plugins.mots_format import MotsPngConverter, MotsImporter
+from datumaro.util.test_utils import (TestDir, compare_datasets,
+ test_save_and_load)
+
+DUMMY_DATASET_DIR = osp.join(osp.dirname(__file__), 'assets', 'mots_dataset')
+
+
+class MotsPngConverterTest(TestCase):
+ def _test_save_and_load(self, source_dataset, converter, test_dir,
+ target_dataset=None, importer_args=None):
+ return test_save_and_load(self, source_dataset, converter, test_dir,
+ importer='mots',
+ target_dataset=target_dataset, importer_args=importer_args)
+
+ def test_can_save_masks(self):
+ source = Dataset.from_iterable([
+ DatasetItem(id=1, subset='a', image=np.ones((5, 1)), annotations=[
+ # overlapping masks, the first should be truncated
+ # the first and third are different instances
+ Mask(np.array([[0, 0, 0, 1, 0]]), label=3, z_order=3,
+ attributes={'track_id': 1}),
+ Mask(np.array([[0, 1, 1, 1, 0]]), label=2, z_order=1,
+ attributes={'track_id': 2}),
+ Mask(np.array([[1, 1, 0, 0, 0]]), label=3, z_order=2,
+ attributes={'track_id': 3}),
+ ]),
+ DatasetItem(id=2, subset='a', image=np.ones((5, 1)), annotations=[
+ Mask(np.array([[1, 0, 0, 0, 0]]), label=3,
+ attributes={'track_id': 2}),
+ ]),
+ DatasetItem(id=3, subset='b', image=np.ones((5, 1)), annotations=[
+ Mask(np.array([[0, 1, 0, 0, 0]]), label=0,
+ attributes={'track_id': 1}),
+ ]),
+ ], categories=['a', 'b', 'c', 'd'])
+
+ target = Dataset.from_iterable([
+ DatasetItem(id=1, subset='a', image=np.ones((5, 1)), annotations=[
+ Mask(np.array([[0, 0, 0, 1, 0]]), label=3,
+ attributes={'track_id': 1}),
+ Mask(np.array([[0, 0, 1, 0, 0]]), label=2,
+ attributes={'track_id': 2}),
+ Mask(np.array([[1, 1, 0, 0, 0]]), label=3,
+ attributes={'track_id': 3}),
+ ]),
+ DatasetItem(id=2, subset='a', image=np.ones((5, 1)), annotations=[
+ Mask(np.array([[1, 0, 0, 0, 0]]), label=3,
+ attributes={'track_id': 2}),
+ ]),
+ DatasetItem(id=3, subset='b', image=np.ones((5, 1)), annotations=[
+ Mask(np.array([[0, 1, 0, 0, 0]]), label=0,
+ attributes={'track_id': 1}),
+ ]),
+ ], categories=['a', 'b', 'c', 'd'])
+
+ with TestDir() as test_dir:
+ self._test_save_and_load(source,
+ partial(MotsPngConverter.convert, save_images=True),
+ test_dir, target_dataset=target)
+
+class MotsImporterTest(TestCase):
+ def test_can_detect(self):
+ self.assertTrue(MotsImporter.detect(DUMMY_DATASET_DIR))
+
+ def test_can_import(self):
+ target = Dataset.from_iterable([
+ DatasetItem(id=1, subset='train', image=np.ones((5, 1)), annotations=[
+ Mask(np.array([[0, 0, 0, 1, 0]]), label=3,
+ attributes={'track_id': 1}),
+ Mask(np.array([[0, 0, 1, 0, 0]]), label=2,
+ attributes={'track_id': 2}),
+ Mask(np.array([[1, 1, 0, 0, 0]]), label=3,
+ attributes={'track_id': 3}),
+ ]),
+ DatasetItem(id=2, subset='train', image=np.ones((5, 1)), annotations=[
+ Mask(np.array([[1, 0, 0, 0, 0]]), label=3,
+ attributes={'track_id': 2}),
+ ]),
+ DatasetItem(id=3, subset='val', image=np.ones((5, 1)), annotations=[
+ Mask(np.array([[0, 1, 0, 0, 0]]), label=0,
+ attributes={'track_id': 1}),
+ ]),
+ ], categories=['a', 'b', 'c', 'd'])
+
+ parsed = Project.import_from(DUMMY_DATASET_DIR, 'mots').make_dataset()
+ compare_datasets(self, expected=target, actual=parsed)
\ No newline at end of file
diff --git a/testbed/openvinotoolkit__datumaro/tests/test_tfrecord_format.py b/testbed/openvinotoolkit__datumaro/tests/test_tfrecord_format.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9491c39effaa8a717325c332e6cddc80386ebc2
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/tests/test_tfrecord_format.py
@@ -0,0 +1,224 @@
+from functools import partial
+import numpy as np
+import os.path as osp
+
+from unittest import TestCase, skipIf
+
+from datumaro.components.project import Dataset
+from datumaro.components.extractor import (DatasetItem,
+ AnnotationType, Bbox, Mask, LabelCategories
+)
+from datumaro.components.project import Project
+from datumaro.util.image import Image, ByteImage, encode_image
+from datumaro.util.test_utils import (TestDir, compare_datasets,
+ test_save_and_load)
+from datumaro.util.tf_util import check_import
+
+try:
+ from datumaro.plugins.tf_detection_api_format.extractor import \
+ TfDetectionApiExtractor, TfDetectionApiImporter
+ from datumaro.plugins.tf_detection_api_format.converter import \
+ TfDetectionApiConverter
+ import_failed = False
+except ImportError:
+ import_failed = True
+
+ import importlib
+ module_found = importlib.util.find_spec('tensorflow') is not None
+
+ @skipIf(not module_found, "Tensorflow package is not found")
+ class TfImportTest(TestCase):
+ def test_raises_when_crashes_on_import(self):
+ # Should fire if import can't be done for any reason except
+ # module unavailability and import crash
+ with self.assertRaisesRegex(ImportError, 'Test process exit code'):
+ check_import()
+
+@skipIf(import_failed, "Failed to import tensorflow")
+class TfrecordConverterTest(TestCase):
+ def _test_save_and_load(self, source_dataset, converter, test_dir,
+ target_dataset=None, importer_args=None):
+ return test_save_and_load(self, source_dataset, converter, test_dir,
+ importer='tf_detection_api',
+ target_dataset=target_dataset, importer_args=importer_args)
+
+ def test_can_save_bboxes(self):
+ test_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, subset='train',
+ image=np.ones((16, 16, 3)),
+ annotations=[
+ Bbox(0, 4, 4, 8, label=2),
+ Bbox(0, 4, 4, 4, label=3),
+ Bbox(2, 4, 4, 4),
+ ], attributes={'source_id': ''}
+ ),
+ ], categories={
+ AnnotationType.label: LabelCategories.from_iterable(
+ 'label_' + str(label) for label in range(10)),
+ })
+
+ with TestDir() as test_dir:
+ self._test_save_and_load(
+ test_dataset,
+ partial(TfDetectionApiConverter.convert, save_images=True),
+ test_dir)
+
+ def test_can_save_masks(self):
+ test_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, subset='train', image=np.ones((4, 5, 3)),
+ annotations=[
+ Mask(image=np.array([
+ [1, 0, 0, 1],
+ [0, 1, 1, 0],
+ [0, 1, 1, 0],
+ [1, 0, 0, 1],
+ ]), label=1),
+ ],
+ attributes={'source_id': ''}
+ ),
+ ], categories={
+ AnnotationType.label: LabelCategories.from_iterable(
+ 'label_' + str(label) for label in range(10)),
+ })
+
+ with TestDir() as test_dir:
+ self._test_save_and_load(
+ test_dataset,
+ partial(TfDetectionApiConverter.convert, save_masks=True),
+ test_dir)
+
+ def test_can_save_dataset_with_no_subsets(self):
+ test_dataset = Dataset.from_iterable([
+ DatasetItem(id=1,
+ image=np.ones((16, 16, 3)),
+ annotations=[
+ Bbox(2, 1, 4, 4, label=2),
+ Bbox(4, 2, 8, 4, label=3),
+ ],
+ attributes={'source_id': ''}
+ ),
+
+ DatasetItem(id=2,
+ image=np.ones((8, 8, 3)) * 2,
+ annotations=[
+ Bbox(4, 4, 4, 4, label=3),
+ ],
+ attributes={'source_id': ''}
+ ),
+
+ DatasetItem(id=3,
+ image=np.ones((8, 4, 3)) * 3,
+ attributes={'source_id': ''}
+ ),
+ ], categories={
+ AnnotationType.label: LabelCategories.from_iterable(
+ 'label_' + str(label) for label in range(10)),
+ })
+
+ with TestDir() as test_dir:
+ self._test_save_and_load(
+ test_dataset,
+ partial(TfDetectionApiConverter.convert, save_images=True),
+ test_dir)
+
+ def test_can_save_dataset_with_image_info(self):
+ test_dataset = Dataset.from_iterable([
+ DatasetItem(id='1/q.e',
+ image=Image(path='1/q.e', size=(10, 15)),
+ attributes={'source_id': ''}
+ )
+ ], categories={
+ AnnotationType.label: LabelCategories(),
+ })
+
+ with TestDir() as test_dir:
+ self._test_save_and_load(test_dataset,
+ TfDetectionApiConverter.convert, test_dir)
+
+ def test_can_save_dataset_with_unknown_image_formats(self):
+ test_dataset = Dataset.from_iterable([
+ DatasetItem(id=1,
+ image=ByteImage(data=encode_image(np.ones((5, 4, 3)), 'png'),
+ path='1/q.e'),
+ attributes={'source_id': ''}
+ ),
+ DatasetItem(id=2,
+ image=ByteImage(data=encode_image(np.ones((6, 4, 3)), 'png'),
+ ext='qwe'),
+ attributes={'source_id': ''}
+ )
+ ], categories={ AnnotationType.label: LabelCategories(), })
+
+ with TestDir() as test_dir:
+ self._test_save_and_load(test_dataset,
+ partial(TfDetectionApiConverter.convert, save_images=True),
+ test_dir)
+
+ def test_labelmap_parsing(self):
+ text = """
+ {
+ id: 4
+ name: 'qw1'
+ }
+ {
+ id: 5 name: 'qw2'
+ }
+
+ {
+ name: 'qw3'
+ id: 6
+ }
+ {name:'qw4' id:7}
+ """
+ expected = {
+ 'qw1': 4,
+ 'qw2': 5,
+ 'qw3': 6,
+ 'qw4': 7,
+ }
+ parsed = TfDetectionApiExtractor._parse_labelmap(text)
+
+ self.assertEqual(expected, parsed)
+
+
+DUMMY_DATASET_DIR = osp.join(osp.dirname(__file__),
+ 'assets', 'tf_detection_api_dataset')
+
+@skipIf(import_failed, "Failed to import tensorflow")
+class TfrecordImporterTest(TestCase):
+ def test_can_detect(self):
+ self.assertTrue(TfDetectionApiImporter.detect(DUMMY_DATASET_DIR))
+
+ def test_can_import(self):
+ target_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, subset='train',
+ image=np.ones((16, 16, 3)),
+ annotations=[
+ Bbox(0, 4, 4, 8, label=2),
+ Bbox(0, 4, 4, 4, label=3),
+ Bbox(2, 4, 4, 4),
+ ],
+ attributes={'source_id': '1'}
+ ),
+
+ DatasetItem(id=2, subset='val',
+ image=np.ones((8, 8, 3)),
+ annotations=[
+ Bbox(1, 2, 4, 2, label=3),
+ ],
+ attributes={'source_id': '2'}
+ ),
+
+ DatasetItem(id=3, subset='test',
+ image=np.ones((5, 4, 3)) * 3,
+ attributes={'source_id': '3'}
+ ),
+ ], categories={
+ AnnotationType.label: LabelCategories.from_iterable(
+ 'label_' + str(label) for label in range(10)),
+ })
+
+ dataset = Project.import_from(DUMMY_DATASET_DIR, 'tf_detection_api') \
+ .make_dataset()
+
+ compare_datasets(self, target_dataset, dataset)
diff --git a/testbed/openvinotoolkit__datumaro/tests/test_transforms.py b/testbed/openvinotoolkit__datumaro/tests/test_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..de3cd66943223b85e816254dc79d4403a1dcf526
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/tests/test_transforms.py
@@ -0,0 +1,414 @@
+import logging as log
+import numpy as np
+
+from unittest import TestCase
+from datumaro.components.project import Dataset
+from datumaro.components.extractor import (Extractor, DatasetItem,
+ Mask, Polygon, PolyLine, Points, Bbox, Label,
+ LabelCategories, MaskCategories, AnnotationType
+)
+import datumaro.util.mask_tools as mask_tools
+import datumaro.plugins.transforms as transforms
+from datumaro.util.test_utils import compare_datasets
+
+
+class TransformsTest(TestCase):
+ def test_reindex(self):
+ source = Dataset.from_iterable([
+ DatasetItem(id=10),
+ DatasetItem(id=10, subset='train'),
+ DatasetItem(id='a', subset='val'),
+ ])
+
+ expected = Dataset.from_iterable([
+ DatasetItem(id=5),
+ DatasetItem(id=6, subset='train'),
+ DatasetItem(id=7, subset='val'),
+ ])
+
+ actual = transforms.Reindex(source, start=5)
+ compare_datasets(self, expected, actual)
+
+ def test_mask_to_polygons(self):
+ source = Dataset.from_iterable([
+ DatasetItem(id=1, image=np.zeros((5, 10, 3)), annotations=[
+ Mask(np.array([
+ [0, 1, 1, 1, 0, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ ]),
+ ),
+ ]),
+ ])
+
+ expected = Dataset.from_iterable([
+ DatasetItem(id=1, image=np.zeros((5, 10, 3)), annotations=[
+ Polygon([3.0, 2.5, 1.0, 0.0, 3.5, 0.0, 3.0, 2.5]),
+ Polygon([5.0, 3.5, 4.5, 0.0, 8.0, 0.0, 5.0, 3.5]),
+ ]),
+ ])
+
+ actual = transforms.MasksToPolygons(source)
+ compare_datasets(self, expected, actual)
+
+ def test_mask_to_polygons_small_polygons_message(self):
+ source_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, image=np.zeros((5, 10, 3)), annotations=[
+ Mask(np.array([
+ [0, 0, 0],
+ [0, 1, 0],
+ [0, 0, 0],
+ ]),
+ ),
+ ]),
+ ])
+
+ target_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, image=np.zeros((5, 10, 3))), ])
+
+ with self.assertLogs(level=log.DEBUG) as logs:
+ actual = transforms.MasksToPolygons(source_dataset)
+
+ compare_datasets(self, target_dataset, actual)
+ self.assertRegex('\n'.join(logs.output), 'too small polygons')
+
+ def test_polygons_to_masks(self):
+ source_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, image=np.zeros((5, 10, 3)), annotations=[
+ Polygon([0, 0, 4, 0, 4, 4]),
+ Polygon([5, 0, 9, 0, 5, 5]),
+ ]),
+ ])
+
+ target_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, image=np.zeros((5, 10, 3)), annotations=[
+ Mask(np.array([
+ [0, 0, 0, 0, 0, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ ]),
+ ),
+ Mask(np.array([
+ [0, 1, 1, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ ]),
+ ),
+ ]),
+ ])
+
+ actual = transforms.PolygonsToMasks(source_dataset)
+ compare_datasets(self, target_dataset, actual)
+
+ def test_crop_covered_segments(self):
+ source_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, image=np.zeros((5, 5, 3)), annotations=[
+ # The mask is partially covered by the polygon
+ Mask(np.array([
+ [0, 0, 1, 1, 1],
+ [0, 0, 1, 1, 1],
+ [1, 1, 1, 1, 1],
+ [1, 1, 1, 0, 0],
+ [1, 1, 1, 0, 0]],
+ ), z_order=0),
+ Polygon([1, 1, 4, 1, 4, 4, 1, 4], z_order=1),
+ ]),
+ ])
+
+ target_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, image=np.zeros((5, 5, 3)), annotations=[
+ Mask(np.array([
+ [0, 0, 1, 1, 1],
+ [0, 0, 0, 0, 1],
+ [1, 0, 0, 0, 1],
+ [1, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0]],
+ ), z_order=0),
+ Polygon([1, 1, 4, 1, 4, 4, 1, 4], z_order=1),
+ ]),
+ ])
+
+ actual = transforms.CropCoveredSegments(source_dataset)
+ compare_datasets(self, target_dataset, actual)
+
+ def test_merge_instance_segments(self):
+ source_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, image=np.zeros((5, 5, 3)),
+ annotations=[
+ Mask(np.array([
+ [0, 0, 1, 1, 1],
+ [0, 0, 0, 0, 1],
+ [1, 0, 0, 0, 1],
+ [1, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0]],
+ ),
+ z_order=0, group=1),
+ Polygon([1, 1, 4, 1, 4, 4, 1, 4],
+ z_order=1, group=1),
+ Polygon([0, 0, 0, 2, 2, 2, 2, 0],
+ z_order=1),
+ ]
+ ),
+ ])
+
+ target_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, image=np.zeros((5, 5, 3)),
+ annotations=[
+ Mask(np.array([
+ [0, 0, 1, 1, 1],
+ [0, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 0],
+ [1, 1, 1, 0, 0]],
+ ),
+ z_order=0, group=1),
+ Mask(np.array([
+ [1, 1, 0, 0, 0],
+ [1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0]],
+ ),
+ z_order=1),
+ ]
+ ),
+ ])
+
+ actual = transforms.MergeInstanceSegments(source_dataset,
+ include_polygons=True)
+ compare_datasets(self, target_dataset, actual)
+
+ def test_map_subsets(self):
+ source_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, subset='a'),
+ DatasetItem(id=2, subset='b'),
+ DatasetItem(id=3, subset='c'),
+ ])
+
+ target_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, subset=''),
+ DatasetItem(id=2, subset='a'),
+ DatasetItem(id=3, subset='c'),
+ ])
+
+ actual = transforms.MapSubsets(source_dataset,
+ { 'a': '', 'b': 'a' })
+ compare_datasets(self, target_dataset, actual)
+
+ def test_shapes_to_boxes(self):
+ source_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, image=np.zeros((5, 5, 3)),
+ annotations=[
+ Mask(np.array([
+ [0, 0, 1, 1, 1],
+ [0, 0, 0, 0, 1],
+ [1, 0, 0, 0, 1],
+ [1, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0]],
+ ), id=1),
+ Polygon([1, 1, 4, 1, 4, 4, 1, 4], id=2),
+ PolyLine([1, 1, 2, 1, 2, 2, 1, 2], id=3),
+ Points([2, 2, 4, 2, 4, 4, 2, 4], id=4),
+ ]
+ ),
+ ])
+
+ target_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, image=np.zeros((5, 5, 3)),
+ annotations=[
+ Bbox(0, 0, 4, 4, id=1),
+ Bbox(1, 1, 3, 3, id=2),
+ Bbox(1, 1, 1, 1, id=3),
+ Bbox(2, 2, 2, 2, id=4),
+ ]
+ ),
+ ])
+
+ actual = transforms.ShapesToBoxes(source_dataset)
+ compare_datasets(self, target_dataset, actual)
+
+ def test_id_from_image(self):
+ source_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, image='path.jpg'),
+ DatasetItem(id=2),
+ ])
+ target_dataset = Dataset.from_iterable([
+ DatasetItem(id='path', image='path.jpg'),
+ DatasetItem(id=2),
+ ])
+
+ actual = transforms.IdFromImageName(source_dataset)
+ compare_datasets(self, target_dataset, actual)
+
+ def test_boxes_to_masks(self):
+ source_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, image=np.zeros((5, 5, 3)),
+ annotations=[
+ Bbox(0, 0, 3, 3, z_order=1),
+ Bbox(0, 0, 3, 1, z_order=2),
+ Bbox(0, 2, 3, 1, z_order=3),
+ ]
+ ),
+ ])
+
+ target_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, image=np.zeros((5, 5, 3)),
+ annotations=[
+ Mask(np.array([
+ [1, 1, 1, 0, 0],
+ [1, 1, 1, 0, 0],
+ [1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0]],
+ ),
+ z_order=1),
+ Mask(np.array([
+ [1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0]],
+ ),
+ z_order=2),
+ Mask(np.array([
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0]],
+ ),
+ z_order=3),
+ ]
+ ),
+ ])
+
+ actual = transforms.BoxesToMasks(source_dataset)
+ compare_datasets(self, target_dataset, actual)
+
+ def test_random_split(self):
+ source_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, subset="a"),
+ DatasetItem(id=2, subset="a"),
+ DatasetItem(id=3, subset="b"),
+ DatasetItem(id=4, subset="b"),
+ DatasetItem(id=5, subset="b"),
+ DatasetItem(id=6, subset=""),
+ DatasetItem(id=7, subset=""),
+ ])
+
+ actual = transforms.RandomSplit(source_dataset, splits=[
+ ('train', 4.0 / 7.0),
+ ('test', 3.0 / 7.0),
+ ])
+
+ self.assertEqual(4, len(actual.get_subset('train')))
+ self.assertEqual(3, len(actual.get_subset('test')))
+
+ def test_random_split_gives_error_on_wrong_ratios(self):
+ source_dataset = Dataset.from_iterable([DatasetItem(id=1)])
+
+ with self.assertRaises(Exception):
+ transforms.RandomSplit(source_dataset, splits=[
+ ('train', 0.5),
+ ('test', 0.7),
+ ])
+
+ with self.assertRaises(Exception):
+ transforms.RandomSplit(source_dataset, splits=[])
+
+ with self.assertRaises(Exception):
+ transforms.RandomSplit(source_dataset, splits=[
+ ('train', -0.5),
+ ('test', 1.5),
+ ])
+
+ def test_remap_labels(self):
+ src_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, annotations=[
+ # Should be remapped
+ Label(1),
+ Bbox(1, 2, 3, 4, label=2),
+ Mask(image=np.array([1]), label=3),
+
+ # Should be kept
+ Polygon([1, 1, 2, 2, 3, 4], label=4),
+ PolyLine([1, 3, 4, 2, 5, 6])
+ ])
+ ], categories={
+ AnnotationType.label: LabelCategories.from_iterable(
+ 'label%s' % i for i in range(5)),
+ AnnotationType.mask: MaskCategories(
+ colormap=mask_tools.generate_colormap(5)),
+ })
+
+ dst_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, annotations=[
+ Label(1),
+ Bbox(1, 2, 3, 4, label=0),
+ Mask(image=np.array([1]), label=1),
+
+ Polygon([1, 1, 2, 2, 3, 4], label=2),
+ PolyLine([1, 3, 4, 2, 5, 6], label=None)
+ ]),
+ ], categories={
+ AnnotationType.label: LabelCategories.from_iterable(
+ ['label0', 'label9', 'label4']),
+ AnnotationType.mask: MaskCategories(colormap={
+ k: v for k, v in mask_tools.generate_colormap(5).items()
+ if k in { 0, 1, 3, 4 }
+ })
+ })
+
+ actual = transforms.RemapLabels(src_dataset, mapping={
+ 'label1': 'label9',
+ 'label2': 'label0',
+ 'label3': 'label9',
+ }, default='keep')
+
+ compare_datasets(self, dst_dataset, actual)
+
+ def test_remap_labels_delete_unspecified(self):
+ source_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, annotations=[ Label(0) ])
+ ], categories=['label0'])
+
+ target_dataset = Dataset.from_iterable([
+ DatasetItem(id=1),
+ ], categories=[])
+
+ actual = transforms.RemapLabels(source_dataset,
+ mapping={}, default='delete')
+
+ compare_datasets(self, target_dataset, actual)
+
+ def test_transform_labels(self):
+ src_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, annotations=[
+ Label(1),
+ Bbox(1, 2, 3, 4, label=2),
+ Bbox(1, 3, 3, 3),
+ Mask(image=np.array([1]), label=3),
+ Polygon([1, 1, 2, 2, 3, 4], label=4),
+ PolyLine([1, 3, 4, 2, 5, 6], label=5)
+ ])
+ ], categories=['label%s' % i for i in range(6)])
+
+ dst_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, annotations=[
+ Label(1),
+ Label(2),
+ Label(3),
+ Label(4),
+ Label(5)
+ ]),
+ ], categories=['label%s' % i for i in range(6)])
+
+ actual = transforms.AnnsToLabels(src_dataset)
+
+ compare_datasets(self, dst_dataset, actual)
diff --git a/testbed/openvinotoolkit__datumaro/tests/test_yolo_format.py b/testbed/openvinotoolkit__datumaro/tests/test_yolo_format.py
new file mode 100644
index 0000000000000000000000000000000000000000..549811fd1ce005a7570f40266bee0f111b107047
--- /dev/null
+++ b/testbed/openvinotoolkit__datumaro/tests/test_yolo_format.py
@@ -0,0 +1,136 @@
+import numpy as np
+import os.path as osp
+
+from unittest import TestCase
+
+from datumaro.components.extractor import (DatasetItem,
+ AnnotationType, Bbox, LabelCategories,
+)
+from datumaro.components.project import Project, Dataset
+from datumaro.plugins.yolo_format.extractor import YoloImporter
+from datumaro.plugins.yolo_format.converter import YoloConverter
+from datumaro.util.image import Image, save_image
+from datumaro.util.test_utils import TestDir, compare_datasets
+
+
+class YoloFormatTest(TestCase):
+ def test_can_save_and_load(self):
+ source_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, subset='train', image=np.ones((8, 8, 3)),
+ annotations=[
+ Bbox(0, 2, 4, 2, label=2),
+ Bbox(0, 1, 2, 3, label=4),
+ ]),
+ DatasetItem(id=2, subset='train', image=np.ones((10, 10, 3)),
+ annotations=[
+ Bbox(0, 2, 4, 2, label=2),
+ Bbox(3, 3, 2, 3, label=4),
+ Bbox(2, 1, 2, 3, label=4),
+ ]),
+
+ DatasetItem(id=3, subset='valid', image=np.ones((8, 8, 3)),
+ annotations=[
+ Bbox(0, 1, 5, 2, label=2),
+ Bbox(0, 2, 3, 2, label=5),
+ Bbox(0, 2, 4, 2, label=6),
+ Bbox(0, 7, 3, 2, label=7),
+ ]),
+ ], categories={
+ AnnotationType.label: LabelCategories.from_iterable(
+ 'label_' + str(i) for i in range(10)),
+ })
+
+ with TestDir() as test_dir:
+ YoloConverter.convert(source_dataset, test_dir, save_images=True)
+ parsed_dataset = YoloImporter()(test_dir).make_dataset()
+
+ compare_datasets(self, source_dataset, parsed_dataset)
+
+ def test_can_save_dataset_with_image_info(self):
+ source_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, subset='train',
+ image=Image(path='1.jpg', size=(10, 15)),
+ annotations=[
+ Bbox(0, 2, 4, 2, label=2),
+ Bbox(3, 3, 2, 3, label=4),
+ ]),
+ ], categories={
+ AnnotationType.label: LabelCategories.from_iterable(
+ 'label_' + str(i) for i in range(10)),
+ })
+
+ with TestDir() as test_dir:
+ YoloConverter.convert(source_dataset, test_dir)
+
+ save_image(osp.join(test_dir, 'obj_train_data', '1.jpg'),
+ np.ones((10, 15, 3))) # put the image for dataset
+ parsed_dataset = YoloImporter()(test_dir).make_dataset()
+
+ compare_datasets(self, source_dataset, parsed_dataset)
+
+ def test_can_load_dataset_with_exact_image_info(self):
+ source_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, subset='train',
+ image=Image(path='1.jpg', size=(10, 15)),
+ annotations=[
+ Bbox(0, 2, 4, 2, label=2),
+ Bbox(3, 3, 2, 3, label=4),
+ ]),
+ ], categories={
+ AnnotationType.label: LabelCategories.from_iterable(
+ 'label_' + str(i) for i in range(10)),
+ })
+
+ with TestDir() as test_dir:
+ YoloConverter.convert(source_dataset, test_dir)
+
+ parsed_dataset = YoloImporter()(test_dir,
+ image_info={'1': (10, 15)}).make_dataset()
+
+ compare_datasets(self, source_dataset, parsed_dataset)
+
+ def test_relative_paths(self):
+ source_dataset = Dataset.from_iterable([
+ DatasetItem(id='1', subset='train',
+ image=np.ones((4, 2, 3))),
+ DatasetItem(id='subdir1/1', subset='train',
+ image=np.ones((2, 6, 3))),
+ DatasetItem(id='subdir2/1', subset='train',
+ image=np.ones((5, 4, 3))),
+ ], categories={
+ AnnotationType.label: LabelCategories(),
+ })
+
+ for save_images in {True, False}:
+ with self.subTest(save_images=save_images):
+ with TestDir() as test_dir:
+ YoloConverter.convert(source_dataset, test_dir,
+ save_images=save_images)
+ parsed_dataset = YoloImporter()(test_dir).make_dataset()
+
+ compare_datasets(self, source_dataset, parsed_dataset)
+
+
+DUMMY_DATASET_DIR = osp.join(osp.dirname(__file__), 'assets', 'yolo_dataset')
+
+class YoloImporterTest(TestCase):
+ def test_can_detect(self):
+ self.assertTrue(YoloImporter.detect(DUMMY_DATASET_DIR))
+
+ def test_can_import(self):
+ expected_dataset = Dataset.from_iterable([
+ DatasetItem(id=1, subset='train',
+ image=np.ones((10, 15, 3)),
+ annotations=[
+ Bbox(0, 2, 4, 2, label=2),
+ Bbox(3, 3, 2, 3, label=4),
+ ]),
+ ], categories={
+ AnnotationType.label: LabelCategories.from_iterable(
+ 'label_' + str(i) for i in range(10)),
+ })
+
+ dataset = Project.import_from(DUMMY_DATASET_DIR, 'yolo') \
+ .make_dataset()
+
+ compare_datasets(self, expected_dataset, dataset)