freeze_from_config
freeze_from_config(model, config_path)
根据配置文件中freeze关键词下的include和exclude列表冻结网络指定模块。需在定义优化器之前调用。
参数
- model(nn.Cell) - 需要冻结的模型实例。
- config_path(str) - 配置文件路径。
配置文件必须是yaml格式,内容示例: freeze: include: ['*', '*dense*','*.dense.*', '*.dense.*.bias'] exclude: ['*', '*dense*','*.dense.*', '*.dense.*.bias']
- include(Optional[List[str]]) - 需要冻结的模块名列表,默认值为None。
- 模糊匹配列表中所有模块名,挨个将匹配到的模块的“requires_grad”设置为“False”。
- 列表项支持配置符号*,代表任意字符串,格式如 ['*', '*dense*','*.dense.*', '*.dense.*.bias']。
- 如果不配置符号*,仅传字符串,表示精确匹配。
- exclude(Optional[List[str]]) - 不冻结的模块名列表,默认值为None。
- 模糊匹配列表中所有模块名,挨个将匹配到的模块的“requires_grad”设置为“True”。
- 列表项支持配置符号*,代表任意字符串,格式如 ['*', '*dense*','*.dense.*', '*.dense.*.bias']。
- 如果不配置符号*,仅传字符串,表示精确匹配。
- 当“include”和“exclude”列表项冲突时,对该项匹配到的模块不做任何处理。
- include(Optional[List[str]]) - 需要冻结的模块名列表,默认值为None。
异常
- TypeError - “model”参数类型不是nn.Cell。
- TypeError - “config_path”参数不是字符串。
- TypeError - “include”或“exclude”参数不是非空列表。
- ValueError - “include”和“exclude”参数同时为空。
- ValueError - “config_path”参数是空值。
- ReadYamlFileError - “config_path”参数对应文件不存在,或是软链接,或读取文件时报错。
- ModelConfigFreezeInfoError - 配置文件中没有内容、没有freeze关键词、freeze值不是字典或freeze值中没有“include”/“exclude”关键词。
样例
from tk.graph.freeze_utils import freeze_from_config # 初始化网络结构 model = Network() # 根据配置文件冻结指定模块 freeze_from_config(model, config_path='test_freeze_config_file.yaml') # 定义优化器 ...
父主题: API接口