1 注冊器(Registry)
為了管理功能相似的模塊,MMEngine實現了注冊器。注冊器可以被視作這些類或函數的抽象。例如注冊器 MODELS 可以被視作所有模型的抽象。
1.1 什么是注冊器
MMEngine 實現的注冊器可以看作一個映射表和模塊構建方法(build function)的組合。
映射表:維護了一個字符串到類或者函數的映射,使得用戶可以借助字符串查找到相應的類或函數,例如維護字符串 “ResNet” 到 ResNet 類或函數的映射,使得用戶可以通過 “ResNet” 找到 ResNet 類;
模塊構建方法:定義了如何根據字符串查找到對應的類或函數以及如何實例化這個類或者調用這個函數。
MMEngine 中的注冊器默認使用 build_from_cfg 函數來查找并實例化字符串對應的類或者函數。
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, orcall 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 callits 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 keyin ``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 ofthe 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 initializationarguments.
函數 build_from_cfg 是設計用來從配置字典(配置實例)創建一個類實例或調用一個函數。這個函數是框架(如 MMDetection, MMClassification 等)中一個核心組件,它通過解耦配置和對象的實例化增加了系統的靈活性和可擴展性。具體來說,它從一個注冊表中獲取類或函數的類型,并使用提供的參數初始化它。
參數解釋
cfg: 這是一個包含配置信息的字典(或 ConfigDict/Config 類型),至少需要包含一個 type 鍵,該鍵指定了要構建或調用的類或函數的名稱。
registry: 這是一個 Registry 對象,build_from_cfg 函數會在這個注冊表中查找 type 指定的名稱,以獲取對應的類或函數。
default_args: 這是可選參數,提供一些默認的初始化參數,如果在 cfg 中沒有提供相應的值,則會使用這里的默認值。
功能詳解
類型和有效性檢查:函數開始會檢查 cfg 是否為字典或 ConfigDict/Config 類型。同時也會檢查 registry 是否為 Registry 類型,以及 default_args 是否為字典、ConfigDict、Config 或者 None。
合并參數:default_args 中的參數將與 cfg 合并。如果同一個鍵在兩者中都存在,cfg 中的值將會覆蓋 default_args 中的值。
處理注冊表和作用域:如果 cfg 中提供了特定的 scope,則函數將嘗試在該作用域下從注冊表中獲取相應的類或函數。
獲取并實例化類/調用函數:
如果 type 是字符串,會在注