Portability, Imports & Definitions#
Hypster requires all of your configuration code to be encapsulated within the function itself to ensure portability. This means you must include any necessary imports and class definitions inside the function.
from hypster import HP, config
@config
def portable_config(hp: HP):
import torch
device = hp.select(["cpu", "cuda"], default="cuda" if torch.cuda.is_available() else "cpu")
# Rest of your configuration...
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In[1], line 1
----> 1 from hypster import HP, config
4 @config
5 def portable_config(hp: HP):
6 import torch
ModuleNotFoundError: No module named 'hypster'
This approach ensures that the configuration function can be easily shared or saved without dependency issues.
Examples of What Works and What Doesn’t#
❌ This will not work:#
import os
from hypster import HP, config
@config
def non_portable_config(hp: HP):
device = hp.select(["cpu", "cuda"], default="cuda" if os.environ.get("USE_CUDA", "0") == "1" else "cpu")
import logging
# Disable logging to prevent verbose output
logging.disable(logging.CRITICAL)
try:
non_portable_config()
print("If you see this, the error didn't occur as expected.")
except NameError as e:
assert "name 'os' is not defined" in str(e)
print("NameError occurred as expected: 'os' is not defined")
NameError occurred as expected: 'os' is not defined
✅ This will work:#
from hypster import HP, config
@config
def portable_config(hp: HP):
import torch
device = hp.select(["cpu", "cuda"], default="cuda" if torch.cuda.is_available() else "cpu")
# Rest of your configuration...
The same principle applies to class definitions and function definitions:
from hypster import HP, config
@config
def class_kwargs_naming(hp: HP):
# Note: New class definitions (or imports) need to be inside the config function
class ModelConfig:
def __init__(self, model_type, learning_rate):
self.model_type = model_type
self.learning_rate = learning_rate
def func(param):
return param
model = ModelConfig(
model_type=hp.select(["cnn", "rnn"]), # Automatically named 'model.model_type'
learning_rate=hp.number(0.001),
) # Automatically named 'model.learning_rate'
var = func(param=hp.select(["option1", "option2"])) # Automatically named 'var.param'