use object.__setattr__ in DualModule and DeployableModule to avoid unexpected key in self._modules #468
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
之前直接赋值
self.xxx = some_nn_Module
的写法,会在self._modules
中写入一个key='xxx'
的键值对,这是由于 torch.nn.Module 的__setattr__
决定的,导致遍历、取 state_dict 等行为得到的结果与期望值不符,会多一层不必要的 _torch_module 或者 _deployable_module_model,比如下列场景:修改之后不用直接赋值语句,而是调用
object.__setattr__
,避免在 self._modules 中增加不必要的键值对,然后把子 module 中的 _modules、_parameters、_buffers 都浅拷贝一份,这样遍历、state_dict、get_submodule 等行为都正常了