instantiate¶
- torchtune.config.instantiate(config: DictConfig, *args: Any, **kwargs: Any) Any [源代码]¶
给定一个 DictConfig,其中包含指定要实例化的对象的 _component_ 字段以及关键字参数的附加字段,此函数会创建指定对象的实例。您可以使用此函数根据配置中的规范,创建您要在 recipe 中使用的 torchtune 对象的精确实例。
此函数还支持在函数调用中传入位置参数和关键字参数。这些参数会自动与提供的配置合并,其中关键字参数优先。
基于 Facebook Research 的 Hydra 的 instantiate 工具:https://github.com/facebookresearch/hydra/blob/main/hydra/_internal/instantiate/_instantiate2.py#L148
- 参数:
config (DictConfig) – 从 yaml 文件解析的 OmegaConf 对象中的单个字段。该字段应包含一个 _component_ 字段,指定要实例化的对象的路径。
*args (Any) – 要传递给要实例化的对象的位置参数。
**kwargs (Any) – 要传递给要实例化的对象的关键字参数。
示例
>>> config.yaml: >>> model: >>> _component_: torchtune.models.llama2 >>> num_layers: 32 >>> num_heads: 32 >>> num_kv_heads: 32
>>> from torchtune import config >>> vocab_size = 32000 >>> # Pass in vocab size as positional argument. Since it is positioned first >>> # in llama2(), it must be specified first. Pass in other arguments as kwargs. >>> # This will return an nn.Module directly for llama2 with specified args. >>> model = config.instantiate(parsed_yaml.model, vocab_size, max_seq_len=4096, embed_dim=4096)
- 返回值:
实例化的对象。
- 返回值类型:
Any
- 抛出异常:
ValueError – 如果 config 不是 DictConfig。