Blog
megaconf
Mass generating configs.
tldr:
megaconfgenerates config files from declarative YAML, with random sampling for large config spaces. This post covers the problem, the solution and what I learned publishing my first Python package.
I recently published my first Python package which was a pretty fun learning experience. I wanted to write a little post to share my experiences as well as explain what problem I was trying to solve.
The issue I was facing
I was working on a project where I needed to create config files for trading strategies. A simple example of this would look like the following:
strategy: momentum
indicator: price
moving_avg_type: sma
moving_avg_period: 30
Such a strategy means that a trading system will rank stocks based on the momentum of their price. If a company’s price has been rising faster than others, it will be ranked higher.
We were training a system where we wanted a lot of these configs with varied parameters. The first approach I had was to make a very nested for loop:
for strategy in strategies:
for indicator in indicators:
...
But here we see the first problem. The keys moving_avg_type and moving_avg_period rely on the strategy being momentum. That is not too complicated, we can add this:
for indicator in indicators: # moved to outer loop to reduce duplicating logic
for strategy in strategies:
if strategy == "momentum":
for moving_avg_type in moving_avg_types:
for moving_avg_period in moving_avg_periods:
...
I don’t think I need to convince you that this is ugly. There are better solutions, where we describe the possible values each variable can take and make a grid search / cartesian product to get all the config files. This can work but what about that if statement. How do we encode a dependency inside a grid search.
I thought this would be a nice opportunity to write a Python package. It is a small enough problem that allows me to over-engineer it to my heart’s content.
What I really wanted was some declarative solution. One that doesn’t involve writing code but simply states the possible values something can take and encode a dependency.
An overview of the tool
To generate configs with this tool, you require a base config and a list of overwrites. This looks like this:
# Base config
strategy: momentum
indicator: price
# overwrites
- fixed:
strategy: momentum
product:
moving_avg_type: [sma, ema]
moving_avg_period: [30, 60, 90, 180]
- fixed:
strategy: mean_reversion
joint:
indicator: [rsi, macd]
drawdown_threshold: [0.05, 0.10]
product:
lookback_period: [10, 20, 30]
Each overwrite has three fields that allow the user to vary the config. The first and most simple is fixed which simply changes the variable to the given value for every config generated by this overwrite. The second is joint which pairs values at the same position in each list. Here, rsi is always paired with a drawdown_threshold of 0.05, and macd with 0.10. Lastly, product simply produces a cartesian product over the choices provided.
The momentum overwrite generates 8 configs: one for each combination of moving average type and period. The mean reversion overwrite generates 6 configs: each of the two indicator/threshold pairs is combined with all three lookback periods. Together, these overwrites generate 14 configs, each starting from the base config.
When the config space is too large
Another obvious problem I ran into was what about if the config space was too large to actually generate all the configs. This happens surprisingly fast. With just 6 keys that each take on 10 values, you already have 1,000,000 configs. The naive idea would be to iterate through the values and once you’ve reached your desired number of configs you stop the system. But this doesn’t work so well.
If we look at the for loop example from before:
for strategy in ["momentum", "mean_reversion"]:
for indicator in big_list_of_indicators:
... # lots of variables iterated down here
If we were to generate values sequentially and just stop when there is enough, there is a good chance that all the configs will have the momentum strategy. A nicer idea is to sample over this space of values randomly.
To see how this works, consider three lists:
l1 = [1, 2]
l2 = ["x", "y", "z"]
l3 = ["a", "b"]
Their Cartesian product contains different configurations. We can retrieve any configuration directly using an index, without first constructing the full Cartesian product.
Suppose idx = 0. Starting with the last list, we calculate:
idx % len(l3) # 0
Since this evaluates to 0, we select the first element of l3 (“a”). We then use integer division to determine the index to carry over to the next list:
idx // len(l3) # 0
This too is zero so we also select the first element and continue this process for l2 and l1 giving us the following configuration:
[1, "x", "a"]
The process is easier to see with idx = 3. Beginning again with l3:
3 % len(l3) # 1
Since it is 1, we select "b". The index carried into the next step is:
3 // len(l3) # 1
For l2, we calculate:
1 % len(l2) # 1
This selects "y". Dividing once more gives 0, so we select the first element of l1, which is 1. The
configuration at index 3 is therefore:
[1, "y", "b"]
This algorithm allows us to index into the product space which is very important if we want to be able to randomly sample from this space. To generate a list of of random configurations we simply need a list of random integers in where is the size of the product space. This can be done as follows: random.choices(range(n), k=n). This will provide a random list of integers with replacement, that is, we may see the same value twice. If we wanted to do so without replace we can instead use random.sample.
Experience deploying this as a package
Packaging everything so it can be put on PyPI was particular interesting. I wasn’t too familiar with build tools, so I went through some documentation of UV. The first step is to make sure the project is in the right structure. That is, rather than having a flat layout where you have you src code living in the root directory, you configure it to the following layout:
root_directory/
src/
megaconf/
src files
tests/
test files
pyproject.toml
...
Then you can configure a build system in pyproject.toml. I chose uv_build since I am a fanboy of everything Astral puts out. Then it is as simple as running uv build and it generates a source map as well as a wheel file.
With these build artifacts, you can already import the package into other projects. The next step was to upload it to PyPI so it would be publically available. This wasn’t too complicated. I made use of Github Actions which provides a nice solution to this. When I push a tagged commit to the main branch, the workflow runs which involves building the project and then running uv publish which uploads the build artifacts to PyPI. All relevant permissions are handled by OpenID (check this). It took a bit of reading to understand how to set this up but is actually quite easy, and once it is up, deploying new versions is trivial.
Conclusion
Building packages for the PyPI ecosystem is quite rewarding. Even if the solution is not that useful, I think going through the process of structuring a project like a library, building it and publishing it is quite informative and I’d recommend it to people who would like to have a deeper understanding of this part of Python. In terms of the solution I created, I am not entirely sure of the value. I find it a somewhat simple answer to a problem. I found existing solutions to be a bit to bloated and required too much configuration to get things working. There are however many shortcomings with my solution. The main one is that dependencies are encoded via fixed and joint. This is restricted and doesn’t allow more advanced logic. An example is, a variable can be defined to take on a set of variables, but if another variable is larger than 10, then only a subset of these values is valid. I think this would be an interesting idea to implement for the next version.
If you are interesting in this package and/or want to provide some feedback, here are the links: