instantiate¶
- torchtune.config.instantiate(config: DictConfig, *args: Any, **kwargs: Any) Any [源代码]¶
给定一个 DictConfig,其中 _component_ 字段指定要实例化的对象,以及用于关键字参数的附加字段,创建指定对象的实例。您可以使用此函数,通过配置中的规范,创建您想在配方中使用的 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。