facebookresearch / hydra

Hydra is a framework for elegantly configuring complex applications
https://hydra.cc
MIT License
8.82k stars 636 forks source link

[Bug] tab completion slow with slow imports #934

Open greaber opened 4 years ago

greaber commented 4 years ago

🐛 Bug

Description

Bash tab completion is slow for me (over two seconds even with a trivial config and a moderately complex config adds another 600ms). It seems that the reason is that it is loading my whole script, and some imports are slow.

Checklist

To reproduce

Minimal Code/Config snippet to reproduce

import hydra
import torch

@hydra.main(config_path="conf", config_name="config")
def main():
    pass

if __name__ == '__main__':
    main()

import torch here is just an example of a slow import.

System information

I'm running on a fast machine with ssd, no NFS or anything.

omry commented 4 years ago

Thanks for the report @greaber. As you have identified this as caused by your imports, what you can do to improve things is to delay those imports.

original:

main.py

import hydra
import torch

@hydra.main(config_path="conf", config_name="config")
def main():
    pass

if __name__ == '__main__':
    main()

modified:

main.py

import hydra

@hydra.main(config_path="conf", config_name="config")
def main(cfg):
    import train # delay the importing of train to after we have composed the configuraiton
    train.train(cfg)

if __name__ == '__main__':
    main()

train.py

import torch

def train(cfg):
  pass
greaber commented 4 years ago

I see. I guess it could be pretty nice if the completion could use some kind of cache so it doesn't have to do this analysis on every completion, but I understand that would take a significant effort to implement, and it's not something I have time to do.

omry commented 4 years ago

Yup, running some kind of daemon would be perfect to cache the resulting config object, but as you pointed out this is a major effort and I am not sure it's worth it as this time.

Closing for now.

addisonklinke commented 2 years ago

@Jasha10 There's a new PEP for lazy imports which might be of interest if this gets revisited

Jasha10 commented 2 years ago

Awesome, thanks for the link @addisonklinke. We can experiment with having our CLI completion hook set the PYTHONLAZYIMPORTS environment variable or the -L if the PEP is implemented. It might also be possible for users to opt into faster completion by setting that env variable manually. I'll reopen this issue so it stays on our radar.