Shortcuts

instantiate

torchtune.config.instantiate(config: Union[dict[str, Any], DictConfig], *args: Any, caller_globals: Optional[dict[str, Any]] = None, **kwargs: Any) Any[source]

Instantiate a component from a configuration, recursively handling nested components.

Given a dict with a ‘_component_’ field specifying the object to instantiate and additional fields as keyword arguments, create an instance of the specified object. Positional and keyword arguments passed in the call are merged with the config, with keyword arguments taking precedence.

Based on Hydra’s instantiate utility.

Parameters:
  • config (Union[dict[str, Any], DictConfig]) – Configuration with ‘_component_’ and optional arguments.

  • *args (Any) – Positional arguments for the component.

  • caller_globals (Optional[dict[str, Any]]) – Enable instantiating objects from caller’s globals.

  • **kwargs (Any) – Keyword arguments to override or add to the config.

Returns:

The instantiated object, or None if config is None.

Return type:

Any

Examples

>>> class Spice:
>>>     def __init__(self, heat_level):
>>>         self.heat_level = heat_level
>>> class Food:
>>>     def __init__(self, seed, ingredient):
>>>         self.seed = seed
>>>         self.ingredient = ingredient
>>> config = OmegaConf.create({
>>>     '_component_': 'Food',
>>>     'seed': 0,
>>>     'ingredient': {'_component_': 'Spice', 'heat_level': 5}
>>> })
>>> food = instantiate(config, seed=42)
>>> print(food.seed)  # 42
>>> print(food.ingredient.heat_level)  # 5
>>> new_spice = {'_component_': 'Spice', 'heat_level': 10}
>>> food = instantiate(config, ingredient=new_spice)
>>> print(food.ingredient.heat_level)  # 10
Raises:
  • ValueError – If config is not a DictConfig.

  • InstantiationError – If the object to instantiate misses the ‘_component_’ key.

Docs

Access comprehensive developer documentation for PyTorch

View Docs

Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

Resources

Find development resources and get your questions answered

View Resources