7. Tuning a policy

In Compare policies with polymorphic functions a store compared inventory policies with hand-picked settings: MinMax with a minimum of 40 and a maximum of 120. Why 40 and 120? They were guesses. This chapter lets Cimba find good values instead. You’ll mark the settings that may change, say what “better” means, and let a search try hundreds of candidates in parallel. Then you’ll check the answer on trials the search never saw.

The script is tutorial/policy_optimization.py and runs in a few seconds:

$ uv run python -m tutorial.policy_optimization

The store

The model comes from tutorial/policy_comparison.py. Each day the store sells what it can from stock; demand it can’t meet is lost. Then it asks its policy how much to order. Orders arrive after a random lead time of two to five days. Three outputs describe a year of trading: mean_stock, orders_per_week and fill_rate, the share of demand served.

The policy we will tune waits until the inventory position (stock on hand plus stock on order) falls to minimum, then orders back up to maximum:

class MinMax(Policy):
    """When the position falls to the minimum, order up to the maximum."""

    minimum: cb.Param[float] = 40.0
    maximum: cb.Param[float] = 120.0

    @cb.function
    def order_quantity(self, on_hand: float, position: float) -> float:
        if position <= self.minimum:
            return self.maximum - position
        return 0.0

Step 1: say what may change

A decision replaces a parameter’s value with a range of allowed values:

def tunable_min_max():
    policy = MinMax()
    policy.minimum = cb.decision(0.0, 100.0, step=1.0)
    policy.maximum = cb.decision(40.0, 250.0, step=1.0)
    return policy

The search may choose any minimum from 0 to 100 and any maximum from 40 to 250, bounds included. step=1.0 keeps both on whole units. The field’s annotation decides the kind of value: these are Param[float] fields, so they stay floats; a Param[int] field would get integers.

Nothing else about the model changes. MinMax is still an ordinary model class, and its compiled code is the same.

Step 2: say what “better” means

More stock protects sales but costs money to hold. Ordering more often keeps stock low but each order costs something. The objective turns that trade-off into one number per trial:

def store_cost(results, store):
    """Cost of one trial: average stock, plus ordering, plus lost sales."""
    outputs = results[store]
    return (outputs.mean_stock
            + 20.0 * outputs.orders_per_week
            + 400.0 * (1.0 - outputs.fill_rate))

Each unit of average stock costs 1, each weekly order costs 20, and losing all demand would cost 400. In a real study these weights come from your business.

The function receives the results of many candidates at once. outputs.mean_stock is shaped (candidates, replications), and the arithmetic keeps that shape, so the function returns a cost for every trial. Don’t average it yourself: Cimba needs the individual trials to compute confidence intervals and compare candidates fairly.

Step 4: read the answer

policy = tunable_min_max()
best = tune(policy)

best[policy.minimum], best[policy.maximum]   # (60.0, 118.0)
best.estimate                                 # cost and its confidence interval

You read the answer through the decision objects you assigned. Here is what main() prints for this study:

MinMax: minimum=60, maximum=118, cost 88.07 (95% CI 87.18 to 88.95)
  searched 254 candidates in 8 generations
  finalists (minimum, maximum, cost, difference from the choice):
      65  120   87.07  +0.38 (-0.54 to +1.29)
      66  121   87.36  +0.67 (-0.23 to +1.57)
      60  129   87.00  +0.31 (-0.79 to +1.40)
      64  119   86.74  +0.05 (-0.85 to +0.95)
      60  118   86.69  chosen

The search stopped on its own after 8 generations, when the population had converged. Three things happened after it stopped:

  1. Finalists. The five best candidates were run again, on 128 fresh replications they all share, and the cheapest was chosen.

  2. Comparison. Every other finalist was compared with the choice, trial by trial. All five intervals contain zero: on these trials, the five settings are statistically tied. Any of them is a good answer, and that is worth knowing before arguing about 60 versus 66.

  3. Estimate. The chosen settings were run once more, on another 128 fresh replications. That gives the cost you can quote: 88.07, with a 95% confidence interval from 87.18 to 88.95.

Why not just report 86.69, the choice’s cost among the finalists? Because picking the lowest of several noisy numbers favors the ones that were lucky. The estimate comes from trials that played no part in the choice, so it isn’t flattered by that luck. Here it’s about 1.4 higher.

To use the answer, write it back into the model:

best.apply()
policy.minimum, policy.maximum               # (60.0, 118.0): plain values again

The policy is now an ordinary configured model, ready for any experiment.

Step 5: was MinMax the right policy?

The search tuned one policy. To choose between policies, tune each one, then compare the tuned versions on fresh trials. OrderUpTo orders every day, back up to a single level:

def tunable_order_up_to():
    policy = OrderUpTo()
    policy.level = cb.decision(40.0, 250.0, step=1.0)
    return policy
def tune_policies(*, replications=32, evaluations=300, validation=None, workers=None):
    """Tune both policies, apply the answers, and compare them on fresh trials."""
    policies = (tunable_min_max(), tunable_order_up_to())
    optima = []
    for policy in policies:
        best = tune(policy, replications=replications, evaluations=evaluations,
                    validation=validation, workers=workers)
        best.apply()
        optima.append(best)
    store, results = compare(policies, replications=validation or 128, workers=workers)
    return store, results, tuple(optima)

After apply(), both policies hold their chosen values. compare puts them in a model sweep and runs a plain experiment with a new seed:

def compare(policies, *, replications=128, workers=None):
    store = Store()
    store.policy = cb.sweep(*policies)
    results = cb.Experiment(store, replications=replications, window=WINDOW,
                            seed=12).run(workers=workers)
    return store, results
Tuned policies on fresh trials:
  MinMax     cost 87.52
  OrderUpTo  cost 185.87
  OrderUpTo - MinMax: +98.36 (95% CI +97.65 to +99.06)

Even at its best level, OrderUpTo places an order every day, and seven orders a week cost 140 on their own. Tuned MinMax is far cheaper, and the paired interval leaves no doubt. Tuning first and comparing second is the fair way to judge policies: an untuned policy can lose just because of bad settings.

Step 6: an integer decision

Decisions work the same way for whole numbers. A call centre pays 20 per agent and 400 per unit of average waiting time. How many agents should it employ?

class CallCentre(cb.Model):
    staff: cb.Param[int] = 3
    gaps: cb.Input[float] = inputs.dist.exponential(mean=0.25)
    handling: cb.Input[float] = inputs.dist.exponential(mean=1.0)
    agents: cb.Container                        # one token per free agent
    waits: cb.Dataset
    cost: cb.Output[float]

    @cb.on_start
    def open(self):
        self.agents.put(self.staff)

    @cb.process
    def calls(self):
        while True:
            cb.hold(self.gaps.next())
            cb.spawn(Caller, centre=self)

    @cb.on_end
    def measure(self):
        self.cost = 20.0 * self.staff + 400.0 * self.waits.sample_mean()

The agents are tokens in a Container: a call takes one while it is being handled and puts it back afterwards (see Caller in the script). The start hook adds staff tokens, so the number of agents is an ordinary Param[int] and can be a decision. The cost is computed inside the model, as an output, so the objective just returns it:

def tune_staff(*, replications=40, validation=None, workers=None):
    centre = CallCentre()
    centre.staff = cb.decision(1, 20)
    best = cb.Optimization(
        centre,
        minimize=lambda results: results[centre].cost,
        replications=replications,
        window=cb.Window(warmup=50.0, duration=500.0),
        seed=5,
    ).run(validation=validation, workers=workers)
    return centre, best
Call centre: 7 agents, cost 157.85 (95% CI 156.82 to 158.88)

staff is a Param[int], so the search only proposes whole numbers of agents. Six agents leave callers waiting too long; eight cost more in wages than they save.

What you learned

  • cb.decision(low, high) makes a Param searchable. The field’s type decides whether values are real, integer or boolean.

  • The objective returns a value per trial, built from outputs with ordinary arithmetic.

  • cb.Optimization(...).run() searches with differential evolution. Every candidate shares the same seeds, and each generation runs as one parallel batch.

  • The reported best.estimate comes from fresh trials, so it is honest. best.finalists tells you which alternatives are statistically tied.

  • best.apply() writes the answer back. Tune each policy, then compare the tuned policies on fresh trials.

Where next

  • Find the best parameters covers the practical choices: replications, budgets, using every core, failed trials and reproducing a candidate.

  • Optimization explains why the search and the estimate use different seeds.

  • Optimization API lists every option and report field.