Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

configurator.py 1.7 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
  1. """
  2. Poor Man's Configurator. Probably a terrible idea. Example usage:
  3. $ python train.py config/override_file.py --batch_size=32
  4. this will first run config/override_file.py, then override batch_size to 32
  5. The code in this file will be run as follows from e.g. train.py:
  6. >>> exec(open('configurator.py').read())
  7. So it's not a Python module, it's just shuttling this code away from train.py
  8. The code in this script then overrides the globals()
  9. I know people are not going to love this, I just really dislike configuration
  10. complexity and having to prepend config. to every single variable. If someone
  11. comes up with a better simple Python solution I am all ears.
  12. """
  13. import sys
  14. from ast import literal_eval
  15. for arg in sys.argv[1:]:
  16. if '=' not in arg:
  17. # assume it's the name of a config file
  18. assert not arg.startswith('--')
  19. config_file = arg
  20. print(f"Overriding config with {config_file}:")
  21. with open(config_file) as f:
  22. print(f.read())
  23. exec(open(config_file).read())
  24. else:
  25. # assume it's a --key=value argument
  26. assert arg.startswith('--')
  27. key, val = arg.split('=')
  28. key = key[2:]
  29. if key in globals():
  30. try:
  31. # attempt to eval it it (e.g. if bool, number, or etc)
  32. attempt = literal_eval(val)
  33. except (SyntaxError, ValueError):
  34. # if that goes wrong, just use the string
  35. attempt = val
  36. # ensure the types match ok
  37. assert type(attempt) == type(globals()[key])
  38. # cross fingers
  39. print(f"Overriding: {key} = {attempt}")
  40. globals()[key] = attempt
  41. else:
  42. raise ValueError(f"Unknown config key: {key}")
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...