Brute-forcing parameter combinations one at a time becomes impractical as their number grows. Optuna uses previous trial results to select the next values and find a good configuration with fewer trials than exhaustive search. I installed it and tested optimization after disconnecting the network.
After each trial, Optuna uses the objective value and a statistical model to choose the next parameter values. The Optuna project publishes its source under the MIT License (*1).
1. Install Optuna
FROM docker.io/library/python:3.12.13-slim
RUN pip install --no-cache-dir --quiet 'optuna==4.9.0'
WORKDIR /work
podman build -t optuna-sandbox .
2. Optimize a resource-allocation objective
I prepared a synthetic objective function with memory size and CPU count as variables. Increasing either variable raises throughput, while the cost penalty grows faster. The function performs calculations and does not run a real container. I disconnected the network before running it.
import optuna
def objective(trial):
memory_mb = trial.suggest_int("memory_mb", 512, 4096, step=256)
cpus = trial.suggest_int("cpus", 1, 4)
throughput = (memory_mb**0.5) * (cpus**0.7)
cost_penalty = 0.001 * memory_mb**1.6 + 3 * cpus**2
return throughput - cost_penalty
study = optuna.create_study(direction="maximize")
study.optimize(objective, n_trials=50)
print(f"best value: {study.best_value:.2f}")
print(f"best params: {study.best_params}")
podman run --rm --network none --memory 2g --cpus 2 --pids-limit 512 \
-v "$(pwd)":/work -w /work optuna-sandbox \
python optimize_demo.py
The -v option makes the specified directory readable and writable from the container. Use an empty directory dedicated to the experiment.
This objective function has 15 possible memory_mb values (512 to 4096 in increments of 256) and 4 possible cpus values, for 60 combinations. I computed all combinations and found memory_mb=512, cpus=2 as the optimum, with a value of 3.14. I ran 50 trials with Optuna, and it produced the following result.
number of trials: 50
best value: 3.14
best params: {'memory_mb': 512, 'cpus': 2}
Optuna found the same combination as exhaustive search after 50 trials out of 60 possible combinations. Adding memory or CPU count does not keep increasing the objective value. Optuna identified an optimum in the middle of the range, a setting that intuition alone can miss.
Narrow the search instead of trying every combination
Trying every parameter combination becomes impractical as the number of combinations grows. An optimization library such as Optuna can reduce the number of trials needed to find a good configuration. The approach suits settings where a larger parameter value can hurt the objective.
Sources
*1 Optuna (GitHub), https://github.com/optuna/optuna, MIT License