Skip to content

[Feature Request] instantiate support for ListConfig at top level #1950

Closed

Description

@Jasha10

The below text is copied directly from a post by a user of the internal Meta Hydra users group:


It seems that Hydra doesn't support recursive instantiation for list objects yet. For example, I would expect the following code to work, but it's raising an InstantiationException: Top level config has to be OmegaConf DictConfig, plain dict, or a Structured Config class or instance.

hydra.utils.instantiate([
    {"_target_": "torch.nn.Linear", "in_features": 3, "out_features": 4},
    {"_target_": "torch.nn.Linear", "in_features": 4, "out_features": 5},
])
# hydra.errors.InstantiationException: Top level config has to be OmegaConf DictConfig, plain dict, or a Structured Config class or instance

As another example, we often instantiate a list of callbacks and pass them to a trainer. Although the same thing can be done with a list comprehension, you can probably imagine its usefulness when composed with other structures. This looks like a simple and intuitive feature, so I'm curious if we plan to support it, if it hasn't been done already.

Activity

  1. added this to the Hydra 1.2.0 milestone on Jan 11, 2022
  2. Jasha10 commented on Jan 11, 2022

    @Jasha10
    ContributorAuthor

    Workaround 1: wrapping in a toplevel dict:

    A workaround is to wrap the top-level list in a dictionary before calling instantiate:

    >>> cfg = OmegaConf.create([
    ...     {"_target_": "torch.nn.Linear", "in_features": 3, "out_features": 4},
    ...     {"_target_": "torch.nn.Linear", "in_features": 4, "out_features": 5},
    ... ])
    >>> hydra.utils.instantiate({"foo": cfg}).foo
    [Linear(in_features=3, out_features=4, bias=True), Linear(in_features=4, out_features=5, bias=True)]

    Workaround 2: list comprehension

    >>> [hydra.utils.instantiate(elt) for elt in cfg]
    [Linear(in_features=3, out_features=4, bias=True), Linear(in_features=4, out_features=5, bias=True)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions