3

How can I use OmegaConf custom interpolation with Hydra?

Some background: One can define a custom interpolation for square root:

from omegaconf import OmegaConf
import math
OmegaConf.register_resolver("sqrt", lambda x: math.sqrt(float(x)))

And use it with this config.yaml:

foo: ${sqrt:9}

Loading and printing foo:

cfg = OmegaConf.load('config.yaml')
print(cfg.foo)

Outputs 3.0

When trying this with Hydra:

import hydra

@hydra.main(config_path="config.yaml")
def main(cfg):
  print(cfg.foo)

if __name__ == "__main__":
  main()

I get the following error:

Unsupported interpolation type sqrt
    full_key: foo
    reference_type=Optional[Dict[Any, Any]]
    object_type=dict

How can I register my resolver when using Hydra?

Omry Yadan
  • 31,280
  • 18
  • 64
  • 87
anthonytec2
  • 49
  • 1
  • 2

1 Answers1

10

You can register your custom resolver ahead of time:

config.yaml:

foo: ${sqrt:9}

main.py:

from omegaconf import OmegaConf
import math
import hydra

OmegaConf.register_new_resolver("sqrt", lambda x: math.sqrt(float(x)))

@hydra.main(config_path=".", config_name="config")
def main(cfg):
  print(cfg.foo)

if __name__ == "__main__":
  main()

This will print 3.0.

This approach will work just as well with the Compose API. The evaluation of the custom resolver is happening when you access the node (lazily). You just need to register the resolver before you access it.

Omry Yadan
  • 31,280
  • 18
  • 64
  • 87