Repeated calls to the same _target_ with different parameter combinations using hydra

42 Views Asked by At

I have the following python class:

class MyClass:

    @classmethod
    def from_config(cls, configs: dict):
        calculation = hydra.utils.instantiate(configs)
        return calculation

    def __call__(self, a, b): 
        return a + b

I want to create objects of the class and call with different a and b values.

The current solution is as follows:

calculation.yaml:

- _target_: mymodule.MyClass
  a: 1
  b: 2
- _target_: mymodule.MyClass
  a: 3
  b: 4

main.py:

    calc_cfgs = cfg.calculation
    for calc_cfg in calc_cfgs:
        calculation =  mymodule.MyClass.from_config(configs=calc_cfg)
        calculated_output = calculation(
                                a=calcs_cfg['a'],
                                b=calcs_cfg['b']
                             )

This approach works fine, but the downside is that the calculation.yaml file gets too long when the user wants to experiment with a lot of combinations of a and b.

Is there a better way to do it?

PS: Maybe something like this:

- _target_: mymodule.MyClass
  a: SOME_KEYWORD[1, 2]
  b: SOME_KEYWORD[3, 4]
1

There are 1 best solutions below

2
Omry Yadan On

You can create a vectorized calc class that takes two lists.

- _target_: mymodule.MyVecClass
  a: [1, 2]
  b: [3, 4]