In the first post, “From Forecasts to Decisions: Inventory Planning with Probabilistic Programming”, we studied the following situation: selling a single product and deciding today how many units to order for each of the next \(15\) days. The basis for decisions was a probabilistic demand model. However, that was not enough information to make a decision. The reason was that under-forecasting has a different cost from over-forecasting. Hence, we had to account for that asymmetry. To do so, we had to work out the explicit form of the loss function we wanted to use for our decision-making process. The main idea was to choose the orders that minimize a loss with two unit costs: a holding cost per unit left over and a lost margin per unit of demand that we cannot serve. Once the loss function was defined, we passed all the posterior predictive samples of the demand model to an inventory simulator and chose the orders that minimize the loss. This allowed us to also use the uncertainty of the demand model to make a decision.
That problem had three simplifications, which the first post lists among its limitations. In this notebook we remove them:
Lead time. In the first post every order arrived on the day for which we planned it. Here an order placed on day \(t\) arrives at the start of day \(t + L\), where \(L\) is the lead time in days.
Policies. In the first post we fixed all \(15\) orders on day one. That is, the decision output was a vector of orders fixed in advance. We call such a fixed decision a plan. Here the order of each day is a function of what we have observed up to that day. We call such a function a policy (observe that a plan is a policy too, one that ignores what it observes).
Weekly forecast. In the first post we ran the forecast once, on day one. Here we run it again after the first week: on day \(8\) we update it with the demand of days \(1\) to \(7\). In general, the cadence of the forecast update depends on the compute power and the expected fluctuations of the demand. We choose weekly updates, as this is a common approach. Moreover, we do not fit the forecasting model again for this update. A filter that processes the new demand one day at a time is much cheaper. In principle, we could re-train from scratch. Nevertheless, we want to showcase the use of a filter to update the forecast. In a final appendix we compare the forecast update against a refit of the forecasting model.
These changes bring the problem closer to practice, where a delivery takes time and a retailer looks at the stock before it orders. How often a retailer orders and runs its forecast depends on the product and the supplier. Some stores order every day, and many order once or twice a week, since every order and every delivery takes some effort. For example, in the VN2 challenge described by Szabłowski (2026), which motivated the first post, a delivery takes two weeks and the decisions follow a weekly cycle. In this notebook we place an order every day and we run the forecast every week. It is easy to adapt the techniques below to a longer order cycle.
In this simulation study, we compare five ways of placing the orders. The first one is the plan of the first post, a vector of orders that we fix on day one, our baseline. Each of the other four starts from the one before it and makes one of its assumptions more flexible. The policies we compare are:
Fixed plan. This is the expected cost plan of the first post, now with a lead time. It cannot react to the demand. For example, after a strong first week, as it sends the same orders, the shelf might run empty. On the other hand, after a slow first week, the same orders might pile up.
Base-stock (day-one forecast). It looks at the stock every day. It compares the units that we have, on the shelf and on their way, with a target level, and it orders the difference. The target level of a day is a high quantile of the demand that the order has to cover (based on the forecasted demand). In the previous post, this target level was the newsvendor level (we will recall the definition below).
Base-stock (day-one forecast, trained). It uses the same target levels plus one number per day, an offset. Why do we need an offset? The quantile from the base-stock policy is the best target level when the customers wait for the next delivery. That is, the customer can wait for another day if we were not able to serve the demand. This is not the case in, for example, food delivery apps where the customer expects a food delivery to have dinner and cannot wait until the next day. In such cases, when the sale is lost and the order takes time to arrive, this quantile is not the best one. So we look for the offsets with the lowest average loss in the simulator to account for this fact. Searching for the offsets is a training process.
Base-stock (weekly forecast, trained). It is the same rule with the target levels of the weekly forecast, so from day \(8\) on the levels use the demand of the first week. It has its own trained offsets.
Neural. It adds to the offset a correction, a trained function of what we observe on the day, such as the stock and the demand of the last days. A small neural network computes it.
We compare the five policies at the same lead time \(L\), and we repeat the comparison for lead times of \(0\) to \(3\) days. The Policies section defines each policy and works an example.
Recall that the simulator of the first post is implemented as a jax.lax.scan over the days. This is convenient as JAX can differentiate through it. As a consequence, we can train a policy in the same way we solved for the plan: we write the order of each day as policy(params, observation) inside the scan and run gradient descent on the parameters over the demand scenarios. Alvo et al. (2023) call this approach hindsight differentiable policy optimization and test it on a range of inventory problems.
We are mainly interested in answering four questions (for lead times of \(0\) to \(3\) days):
How much of the expected loss of the fixed plan do we remove when the order of each day depends on the stock that we observe?
Does training the target levels through the simulator lower the loss further?
How much does the update of the forecast after the first week lower the loss?
Does a correction that depends on what we observe, computed by a neural network, lower the loss of
Base-stock (weekly forecast, trained)further?
We answer them in the Out of Sample Evaluation section.
We build on top of the first post: we keep the data generating process, the forecasting model with its priors, the costs, and the initial stock.
Here is the outline of the notebook:
Prepare Notebook. Imports and plotting defaults.
The Decision Problem. The lead time and the days on which we count the cost.
Policies. What a policy observes, what training means, and the five policies with a worked example.
Demand Scenarios. The demand model of the first post written as components, the data, the fit, and the scenario sets for training, validation and testing.
Forecast Updates. An update of the forecast with a filter in place of a new fit of the model, and the weekly forecast of every scenario.
Inventory Simulator. The simulator with a lead time, in which a policy places the order of each day.
Policy Training. The fixed plan, the base-stock policies and the neural policy, which we train by gradient descent through the simulator.
Out of Sample Evaluation. The expected loss by lead time and the paired differences, which answer the four questions, then the gain by expected demand, the stock and the stockouts, the cost ratio and the tail risk.
Conclusion. What we learned.
Next Steps. Extensions.
Appendix. The forecast update against a refit of the forecasting model.
Prepare Notebook
import numpyro
# `dynestyx` starts JAX when we import it, so we set the number of devices first
numpyro.set_host_device_count(4)
from collections.abc import Callable
from enum import StrEnum
from itertools import pairwise
from typing import Final, NamedTuple
import arviz as az
import graphviz as gr
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpyro.distributions as dist
import optax
import polars as pl
import preliz as pz
import seaborn as sns
import xarray as xr
from dynestyx import DiscreteTimeSimulator, DynamicalModel, Filter
from dynestyx.configs import EKFConfig
from flax import nnx
from jax import random
from jax.scipy.stats import norm
from jaxtyping import (
Array,
Bool,
Float,
Int,
PRNGKeyArray,
PyTree,
ScalarLike,
UInt32,
)
from matplotlib.patches import Patch
from matplotlib.ticker import MultipleLocator, PercentFormatter
from numpyro import handlers
from numpyro.handlers import do
from numpyro.infer import MCMC, NUTS, Predictive
from numpyro.infer.reparam import LocScaleReparam
from numpyro_forecast import Horizon, forecast, innovations, predict, to_datatree
from numpyro_forecast.contrib.dynestyx import end_state, start_state, state_space
from numpyro_forecast.features import fourier_features
from numpyro_forecast.metrics import crps_empirical
from numpyro_forecast.typing import ForecastModel
seed: int = 42
rng_key: PRNGKeyArray = random.PRNGKey(seed)
CI_PROB = 0.94
az.style.use("arviz-darkgrid")
az.rcParams["stats.ci_kind"] = "eti"
az.rcParams["stats.ci_prob"] = CI_PROB
plt.rcParams["figure.figsize"] = [10.0, 6.0]
plt.rcParams["figure.dpi"] = 100
plt.rcParams["figure.facecolor"] = "white"
pl.Config(float_precision=1, tbl_width_chars=160)
%load_ext autoreload
%autoreload 2
%load_ext jaxtyping
%jaxtyping.typechecker beartype.beartype
%config InlineBackend.figure_format = "retina"
The Decision Problem
Let’s start with the setting of the first post. Let \(H = 15\) be the number of days on which we order and let \(D_t\) be the demand on day \(t\). We start with \(I_0\) units on the shelf. We assume customers buy what is there and go elsewhere for the rest, so the demand that we cannot serve is lost.
Two unit costs define the loss. A unit that sits on the shelf at the end of a day costs the holding cost \(h\), and a unit of demand that we cannot serve costs the lost margin \(p\). We take \(h = 0.1\), \(p = 2\) and \(I_0 = 50\).
Lead Time
Let \(L \geq 0\) be the lead time in days and let \(a_t \geq 0\) be the order placed on day \(t\). The order arrives at the start of day \(t + L\). The orders that we have placed and that have not arrived yet are the pipeline.
Notation: Note that in the first post the letter \(L\) was the loss. Here \(L\) is the lead time, as is usual in inventory theory. We write \(C\) for the loss and \(J\) for the expected loss.
On day \(t\) we have a sequence of five steps:
Receive. For \(L \geq 1\) the order placed on day \(t - L\) arrives.
Observe. We look at the stock, the pipeline, the demand of the last days and the latest forecast.
Order. If \(t \leq H\) we place the order \(a_t\).
Sell. The demand \(D_t\) arrives and we sell what the shelf allows.
Pay. We pay the holding cost on the units left over and the lost margin on the demand that we could not serve.
Let’s visualize the five steps with a diagram.
day = gr.Digraph(graph_attr={"rankdir": "LR"})
day.attr(
label="<<b>The Five Steps of Day t</b>>",
labelloc="t",
fontsize="18",
nodesep="0.35",
ranksep="0.6",
)
day.node("receive", label="Receive", color="#2a2eec80", style="filled")
day.node("observe", label="Observe", shape="box", color="#fa7c1780", style="filled")
day.node("order", label="Order", color="#2a2eec80", style="filled")
day.node("sell", label="Sell", color="#2a2eec80", style="filled")
day.node("pay", label="Pay", color="#328c0680", style="filled")
day.edge("receive", "observe")
day.edge("observe", "order")
day.edge("order", "sell")
day.edge("sell", "pay")
day.edge("pay", "receive", label="next day", style="dashed", constraint="false")
day
Let \(I_{t-1}\) be the stock on hand at the end of day \(t - 1\). The stock available for sale on day \(t\) is \(y_t = I_{t-1} + a_{t-L}\), the stock on hand plus the order that arrives. With \(L = 0\) this is \(y_t = I_{t-1} + a_t\), the setting of the first post. The lost sales \(U_t\) and the stock on hand at the end of the day are
\[U_t = (D_t - y_t)^{+}, \qquad I_t = (y_t - D_t)^{+},\]
where \((u)^{+} = \max(u, 0)\). The cost of the day is \(h \, I_t + p \, U_t\).
For \(L \geq 1\) the orders \(a_{1-L}, \dots, a_0\) were placed before day one. They are the initial pipeline. We fix each of them at the median forecast of the demand of the day on which it arrives, and we use the same initial pipeline for every policy.
The inventory position is the stock on hand plus the pipeline when we decide the order of day \(t\), after the arrival of step \(1\):
\[\text{IP}_t = I_{t-1} + \sum_{s=t-L}^{t-1} a_s.\]
With \(L = 0\) the sum is empty and the inventory position is the stock on hand. With \(L \geq 1\) the order \(a_{t-L}\) arrives in step \(1\) of day \(t\), so the inventory position is the stock available \(y_t\) plus the \(L - 1\) orders that are still on their way.
The inventory position is the right quantity to compare with a target, for two reasons:
No double orders. The orders in the pipeline are stock that we have already bought. A rule that looks only at the shelf would order the same missing units again on every day until they arrive.
Coverage. The inventory position after the order of day \(t\), \(\text{IP}_t + a_t\), is all the stock that can serve the demand of the \(L + 1\) days \(t, \dots, t + L\).
Let’s look at a concrete example to illustrate the second reason with \(L = 2\). The next diagram shows the days \(t\) to \(t + 3\) and the order that arrives at the start of each day.
DAYS = ["t", "t + 1", "t + 2", "t + 3"]
ARRIVING_ORDERS = ["t - 2", "t - 1", "t", "t + 1"] # the order that arrives on each day
# with L = 2 the stock after the order of day t serves the days t, t + 1 and t + 2
NUM_COVERED = 3
# the fill of each order box: the orders already placed, the order of day t, and the
# order of day t + 1, which arrives too late for these days
ORDER_FILLS = ["#b16b5780", "#b16b5780", "#fa7c1780", "lightgray"]
timeline = gr.Digraph()
timeline.attr(
newrank="true",
label="<<b>Orders and Days at Lead Time L = 2</b>>",
labelloc="t",
fontsize="18",
)
with timeline.subgraph(name="cluster_covered") as covered:
covered.attr(
label="the days that the stock after the order of day t has to serve",
labelloc="b",
style="dashed",
fontsize="14",
)
for day in DAYS[:NUM_COVERED]:
covered.node(f"day {day}")
with timeline.subgraph() as row:
# the days in one row, from left to right
row.attr(rank="same")
for day in DAYS:
row.node(f"day {day}")
for day, order, fill in zip(DAYS, ARRIVING_ORDERS, ORDER_FILLS, strict=True):
timeline.node(f"order of day {order}", shape="box", color=fill, style="filled")
timeline.edge(f"order of day {order}", f"day {day}", label=" arrives")
for day, next_day in pairwise(DAYS):
timeline.edge(f"day {day}", f"day {next_day}", label=" stock left over")
timeline
Each box is an order, and its arrow points to the day on which the order arrives. The brown boxes are orders that we placed before day \(t\), the orange box is the order of day \(t\), and the gray box arrives too late for the days in the dashed frame.
On day \(t\) the order of day \(t - 2\) arrives, and then we place the order of day \(t\), which arrives on day \(t + 2\). The order of the next day, day \(t + 1\), arrives only on day \(t + 3\). So for the demand of the days \(t\), \(t + 1\) and \(t + 2\) we have three sources of stock:
Stock on the shelf. The stock available \(y_t\) on day \(t\), which includes the order of day \(t - 2\) that arrived in the morning.
Order on its way. The order of day \(t - 1\), which arrives on day \(t + 1\).
Order of the day. The order of day \(t\), which arrives on day \(t + 2\).
No order that we place after day \(t\) arrives in time for these three days. The three sources add up to the inventory position after the order of day \(t\), \(\text{IP}_t + a_t\). For a lead time \(L\), the same argument gives the \(L + 1\) days \(t, \dots, t + L\).
Cost Window
An order placed on day \(t\) cannot change anything before day \(t + L\). This has two consequences.
First days. The stock of days \(1\) to \(L\) depends only on the initial stock, the initial pipeline and the demand. No order can change it, so the cost of these days is the same for every policy.
Last orders. The orders of the last \(L\) ordering days arrive after day \(H\). If we stopped counting on day \(H\), these orders would cost nothing and serve nothing.
Hence, for this analysis, we count the cost on the days \(L + 1, \dots, H + L\), the cost window. It has \(H\) days for every lead time, and every order arrives inside it. The loss \(C\) of a demand path is the sum of the daily costs over the cost window,
\[C = \sum_{t=L+1}^{H+L} \left[ h \, I_t + p \, U_t \right].\]
We report the loss as a plain number, in the currency of \(h\) and \(p\).
We store the lengths, the lead times and the day of the forecast update in the Setup tuple, and the costs and the initial stock in the InventoryConfig tuple.
class Setup(NamedTuple):
"""Lengths of the history and the horizon, promotion settings and lead times."""
t_obs: int = 364 # one year of daily history
horizon: int = 15 # days on which we place an order
discount: float = 0.3 # price cut in a promotion week
promo_prob: float = 0.1 # chance that a given week of the history is a promotion
lead_times: tuple[int, ...] = (0, 1, 2, 3) # days between an order and its arrival
history_window: int = 7 # days of past demand that a policy observes
update_after: int = 7 # days of demand that the forecast update on day 8 uses
@property
def max_days(self) -> int:
"""Days that we simulate for the longest lead time."""
return self.horizon + max(self.lead_times)
@property
def num_future(self) -> int:
"""Days after the history with covariates.
The forecast of the last simulated day covers its own lead time.
"""
return self.max_days + max(self.lead_times)
class InventoryConfig(NamedTuple):
"""Costs and initial stock of the inventory problem."""
holding_cost: float
lost_sales_cost: float
initial_inventory: float
setup = Setup()
config = InventoryConfig(holding_cost=0.1, lost_sales_cost=2.0, initial_inventory=50.0)
The next figure shows, for each lead time, the days on which we order and the days on which we count the cost.
horizon_days = jnp.arange(1, setup.max_days + 1)
lead_times = jnp.asarray(setup.lead_times)[:, None]
is_ordering_day = jnp.broadcast_to(
horizon_days <= setup.horizon, (lead_times.shape[0], setup.max_days)
)
is_cost_day = (horizon_days > lead_times) & (horizon_days <= setup.horizon + lead_times)
DAY_KINDS = {
"order, cost not counted": is_ordering_day & ~is_cost_day,
"order, cost counted": is_ordering_day & is_cost_day,
"no order, cost counted": ~is_ordering_day & is_cost_day,
}
# one code per kind of day, and the days that we do not simulate stay empty
day_kind = jnp.select(
list(DAY_KINDS.values()),
[float(code) for code in range(len(DAY_KINDS))],
default=jnp.nan,
)
kind_colors = ["C1", "C0", "C2"]
fig, ax = plt.subplots(figsize=(12, 4.5))
sns.heatmap(
day_kind,
cmap=kind_colors,
cbar=False,
linewidths=1,
linecolor="white",
xticklabels=horizon_days.tolist(),
yticklabels=setup.lead_times,
ax=ax,
)
ax.tick_params(axis="y", rotation=0)
ax.set(xlabel="day", ylabel="lead time $L$ (days)")
fig.legend(
handles=[
Patch(color=color, label=label)
for color, label in zip(kind_colors, DAY_KINDS, strict=True)
],
loc="outside lower center",
ncol=3,
)
fig.suptitle("Ordering Days and Cost Window", fontsize=18, fontweight="bold");
Every row has \(15\) ordering days and \(15\) days in the cost window, and the cost window starts \(L\) days after the first order. The empty cells are days that we do not simulate.
The cost window moves with the lead time, so it covers different days for different lead times. For this reason the loss of a policy is not comparable across lead times, and we compare the policies within a lead time. A difference between two policies can change with the lead time, and the shift of the window is then part of that change. We check the trends that our answers use on the days that all the windows share.
Now that we know when an order arrives and which days we pay for, let’s define the policies that place the orders.
Policies
On day \(t\) a policy sees the observation \(o_t\), which collects what we know when we order:
Day. The day \(t\) of the horizon.
Stock available. The units on the shelf after the arrival of step \(1\), \(y_t\).
Pipeline. Each order that is still on its way.
Recent demand. The demand of the last \(K\) days. We fix the window of the recent demand at \(K = 7\) days since we assume one forecast update per week.
Forecast. The latest forecast of the demand of the next days.
A policy is a function \(\pi_\theta\) that maps the observation to the order of the day,
\[a_t = \pi_\theta(o_t),\]
where \(\theta\) collects the parameters of the policy (not of the demand model). The observation contains only what we know when we order. In particular, it does not contain the demand \(D_t\) of the day or of any later day.
The loss now depends on the policy and on the demand path \(D = (D_1, \dots, D_{H+L})\), so we write it as \(C(\theta, D)\). As in the first post, we estimate its expected value with scenarios. Let \(D^{(1)}, \dots, D^{(N)}\) be \(N\) scenarios, joint posterior predictive draws of the demand path from the forecast. The expected loss of a policy is
\[J(\theta) = \text{E}[C(\theta, D)] \approx \frac{1}{N} \sum_{n=1}^{N} C(\theta, D^{(n)}).\]
Training a policy means looking for the parameters \(\theta\) with the lowest expected loss. Again, training leaves the demand model and the forecast as they are. It fits the parameters of the policy to the scenarios of the forecast, with the simulated loss in place of a likelihood. A common training method, to find these parameters, is gradient descent.
Avoid Overfitting: We do not want a policy to overfit its training scenarios. For this reason we score every policy on test scenarios that the training does not use. For the neural policy, which has the most parameters, we also use a validation set to make sure that we do not overfit during the training.
Now that we have the notation in place, let’s define the five policies that we want to compare.
Fixed Plan
The first policy is Fixed plan. It sets all the \(H\) orders on day one, and they cannot change afterwards. As a policy, it reads only the day from the observation, so the order of day \(t\) is one number,
\[\pi_\theta(o_t) = \theta_t, \qquad \theta_t \geq 0,\]
and the parameters are the \(H\) orders. For \(L = 0\) this is the expected cost plan of the first post.
The plan is our baseline because it just shows what the forecast of day one induces when the orders do not react to the stock or to the demand. We choose its \(H\) orders on day one: the training looks for the orders with the lowest expected loss over the scenarios of the forecast of day one.
This is a static policy, meaning that after day one we cannot change these orders, whatever the demand of the first days is.
Base-Stock (Day-One Forecast)
The second policy is Base-stock (day-one forecast). It looks at the stock every day and orders up to a target level that comes from the forecast of day one. We define the level first and then work an example.
Target Level
A base-stock policy answers one question on every day: how much stock, on the shelf and on its way, do we want to have after the order of today? This number is the target level of the day, and the policy orders the difference between the level and the inventory position. If the position is already above the level, it orders nothing.
The quality of a base-stock policy depends on its (target) levels. To choose them, recall the newsvendor problem of the first post. For a single day, the stock that minimizes the expected cost is the \(p / (p + h)\) quantile of the demand. The ratio \(p / (p + h)\) is the critical fractile, \(0.952\) for our costs. The quantile is high because a lost sale costs \(20\) times as much as a unit left over.
With a lead time the level has to cover more than one day. Recall the diagram of the Lead Time section. With \(L = 2\), the stock on the shelf on day \(t\), the order of day \(t - 1\) on its way and the order of day \(t\) are all the stock that can serve the days \(t\), \(t + 1\) and \(t + 2\). Together they are the inventory position after the order, \(\text{IP}_t + a_t\). So the level of day \(t\) has to cover the total demand of these three days, and for a lead time \(L\) the total demand of the \(L + 1\) days \(t, \dots, t + L\).
Let the newsvendor level \(\hat{q}_t\) be the \(p / (p + h)\) quantile of the total demand \(D_t + \dots + D_{t+L}\) under a forecast. Base-stock (day-one forecast) orders up to the newsvendor level of the forecast of day one,
\[\pi(o_t) = (\hat{q}_t - \text{IP}_t)^{+}.\]
It has no parameters, so it needs no training.
How does this policy react to the demand? The inventory position of day \(t\) is the position after the order of the day before, minus what we sold on that day,
\[\text{IP}_t = \text{IP}_{t-1} + a_{t-1} - (D_{t-1} - U_{t-1}).\]
If the order of the day before reached its level, \(\text{IP}_{t-1} + a_{t-1} = \hat{q}_{t-1}\), the order of day \(t\) is
\[a_t = \left( (D_{t-1} - U_{t-1}) + (\hat{q}_t - \hat{q}_{t-1}) \right)^{+}.\]
In other words, the policy orders what we sold the day before, plus the change of the level from one day to the next.
Worked Example
Let’s work a simple example with made-up numbers. We take \(L = 2\), so an order has to cover three days. As the forecast of the total demand of these three days we take a Gamma distribution with a mean of \(160\) units and a standard deviation of \(23\) units. The next figure shows its density and its newsvendor level.
class PolicyName(StrEnum):
"""Names of the ways of placing the orders."""
FIXED_PLAN = "Fixed plan"
DAY_ONE = "Base-stock (day-one forecast)"
DAY_ONE_TRAINED = "Base-stock (day-one forecast, trained)"
WEEKLY_TRAINED = "Base-stock (weekly forecast, trained)"
NEURAL = "Neural"
# one color per policy in every figure that follows
POLICY_COLORS = {
PolicyName.FIXED_PLAN: "C0",
PolicyName.DAY_ONE: "C1",
PolicyName.DAY_ONE_TRAINED: "C2",
PolicyName.WEEKLY_TRAINED: "C3",
PolicyName.NEURAL: "C4",
}
def critical_fractile(config: InventoryConfig) -> float:
"""The quantile of the newsvendor problem, p / (p + h)."""
return config.lost_sales_cost / (config.lost_sales_cost + config.holding_cost)
class ExampleForecast(NamedTuple):
"""A made-up forecast of the total demand of the days that an order covers."""
label: str
total_demand: pz.distributions.distributions.Continuous
color: str
linestyle: str = "-"
def newsvendor_level(self, config: InventoryConfig) -> float:
"""The p / (p + h) quantile of the total demand, for the costs of `config`."""
return float(self.total_demand.ppf(critical_fractile(config)))
def plot_levels(examples: list[ExampleForecast], config: InventoryConfig) -> plt.Figure:
"""Densities of made-up forecasts and the newsvendor level of each one."""
fig, ax = plt.subplots()
for example in examples:
example.total_demand.plot_pdf(ax=ax, legend=None, color=example.color)
ax.get_lines()[-1].set(label=example.label, linestyle=example.linestyle)
for example in examples:
level = example.newsvendor_level(config)
ax.axvline(
level,
color=example.color,
linestyle=example.linestyle,
label=f"its newsvendor level ({level:,.0f} units)",
)
ax.set(xlabel="total demand of the days $t$, $t + 1$ and $t + 2$ (units)")
fig.legend(loc="outside lower center", ncol=2)
return fig
day_one_example = ExampleForecast(
"forecast of day one",
pz.Gamma(mu=160, sigma=23),
POLICY_COLORS[PolicyName.DAY_ONE],
)
fig = plot_levels([day_one_example], config)
fig.suptitle("Newsvendor Level of an Example Forecast", fontsize=18, fontweight="bold");
The newsvendor level is \(200\) units. The critical fractile leaves a share \(1 - p / (p + h) = h / (p + h) = 0.1 / 2.1 \approx 4.8\%\) of the probability above the level. So under this forecast the demand of the three days is above the level with a probability of \(4.8\%\).
Now we look at one ordering day in two cases, one after slow sales and one after strong sales. In both cases the order of day \(t - 1\), \(60\) units, is on its way and arrives tomorrow. After slow sales the shelf holds \(105\) units, the arrival of this morning included, and after strong sales it holds \(60\) units. Let’s compare the order of Base-stock (day-one forecast) in each case with a fixed plan that chose an order of \(55\) units for this day on day one.
class ExampleDay(NamedTuple):
"""Stock on a made-up ordering day with a lead time of two days."""
title: str
on_hand: float # after the arrival of the day
on_the_way: float # the order that arrives tomorrow
@property
def position(self) -> float:
"""Inventory position: the stock on hand plus the order on its way."""
return self.on_hand + self.on_the_way
def plot_orders(ax: plt.Axes, day: ExampleDay, orders: dict[PolicyName, float]) -> None:
"""Stacked bars of the stock of a day and the order of each policy."""
stock = {
"stock on hand": (day.on_hand, 1.0),
"order of day $t - 1$, on its way": (day.on_the_way, 0.5),
}
for row, (name, order) in enumerate(orders.items()):
left = 0.0
for label, (units, alpha) in stock.items():
ax.barh(
row,
units,
left=left,
color="C9",
alpha=alpha,
edgecolor="white",
label=label if row == 0 else None,
)
left += units
bars = ax.barh(
row,
order,
left=left,
color=POLICY_COLORS[name],
edgecolor="white",
label=f"order of the day: {name}",
)
ax.bar_label(bars, fmt="{:,.0f}", padding=4)
ax.set(
title=f"{day.title} (inventory position {day.position:,.0f})",
yticks=range(len(orders)),
yticklabels=list(orders),
)
ax.invert_yaxis()
PLAN_ORDER_EXAMPLE = 55.0 # the order of this day that the plan chose on day one
example_days = [
ExampleDay("After slow sales", on_hand=105.0, on_the_way=60.0),
ExampleDay("After strong sales", on_hand=60.0, on_the_way=60.0),
]
level_example = day_one_example.newsvendor_level(config)
example_orders = {
day.title: {
PolicyName.FIXED_PLAN: PLAN_ORDER_EXAMPLE,
PolicyName.DAY_ONE: max(level_example - day.position, 0.0),
}
for day in example_days
}
fig, axes = plt.subplots(nrows=2, figsize=(11, 6.5), sharex=True, layout="constrained")
for ax, day in zip(axes, example_days, strict=True):
plot_orders(ax, day, example_orders[day.title])
ax.axvline(
level_example,
color=POLICY_COLORS[PolicyName.DAY_ONE],
label="newsvendor level",
)
axes[-1].set(xlabel="units")
fig.legend(*axes[0].get_legend_handles_labels(), loc="outside lower center", ncol=3)
fig.suptitle(
"Orders of the Fixed Plan and of the Base-Stock Policy",
fontsize=18,
fontweight="bold",
);
The base-stock policy fills the gap to the level. It orders \(35\) units after slow sales and \(80\) units after strong sales, and in both cases it ends at the level of \(200\) units. The fixed plan places the same order of \(55\) units in both cases, so it ends above the level after slow sales and below it after strong sales.
Base-Stock (Day-One Forecast, Trained)
The third policy is Base-stock (day-one forecast, trained). It is the base-stock policy above with one trained offset per day added to the newsvendor level. It answers the following question: is the newsvendor level the best target level when a sale that we cannot serve is lost and an order takes \(L\) days to arrive?
The short answer is no: The newsvendor level aims to run out about \(4.8\%\) of the time (in this example), the point where holding one more unit costs as much as missing a sale. With a lead time, a missed sale leaves that unit on the shelf, so you run out less often and hold it too often. Ordering a bit less can save more in holding cost than it adds in lost sales.
This might be hard to grasp at first. So we expand on it step by step. First, we follow the example for three days and see that a lost sale leaves more stock than the newsvendor level assumes. Next, we define the offset and say what it can fix and what it cannot. Finally, we recall what the literature says about its size.
Stock After Lost Sales
Let’s expand the example from the previous section. In both cases (slow and strong sales), the inventory position after the order is the level of \(200\) units. We let the three covered days, \(t\), \(t + 1\) and \(t + 2\), have a demand of \(80\), \(70\) and \(60\) units. Their total of \((80 + 70 + 60) = 210\) units is above the level, which happens with probability \(h / (p + h) = 4.8\%\) under the forecast. We plot the stock available and the demand on each of the three days, for both cases, with the arrivals of the diagram of the Lead Time section.
DEMAND_EXAMPLE = (80.0, 70.0, 60.0) # demand of the days t, t + 1 and t + 2
DAY_LABELS = ("$t$", "$t + 1$", "$t + 2$")
class ExampleStep(NamedTuple):
"""One day after an order: stock carried over, arrival and lost sales."""
carried: float
arrival: float
lost_sales: float
def follow_order(day: ExampleDay, order: float) -> list[ExampleStep]:
"""The days t, t + 1 and t + 2 after the order of day t, with lost sales."""
carried, steps = day.on_hand, []
# the stock on hand of day t already contains the arrival of that day
arrivals = (0.0, day.on_the_way, order)
for arrival, demand in zip(arrivals, DEMAND_EXAMPLE, strict=True):
available = carried + arrival
steps.append(ExampleStep(carried, arrival, max(demand - available, 0.0)))
carried = max(available - demand, 0.0)
return steps
def plot_stock(ax: plt.Axes, steps: list[ExampleStep]) -> None:
"""
Stacked bars of the stock available on each day,
the units sold, and the demand.
"""
arrival_styles = [
("C9", 0.5, None),
("C9", 0.5, "arrival of the order of day $t - 1$"),
(POLICY_COLORS[PolicyName.DAY_ONE], 1.0, "arrival of the order of day $t$"),
]
bar_width = 0.36
for x, (step, (color, alpha, label)) in enumerate(
zip(steps, arrival_styles, strict=True)
):
ax.bar(
x - bar_width / 2,
step.carried,
width=bar_width,
color="C9",
label="stock already on the shelf" if x == 0 else None,
)
ax.bar(
x - bar_width / 2,
step.arrival,
width=bar_width,
bottom=step.carried,
color=color,
alpha=alpha,
label=label,
)
if step.lost_sales > 0:
available = step.carried + step.arrival
ax.annotate(
f"{step.lost_sales:,.0f} lost",
(x - bar_width / 2, max(available, DEMAND_EXAMPLE[x])),
textcoords="offset points",
xytext=(0, 6),
ha="center",
)
sold = DEMAND_EXAMPLE[x] - step.lost_sales
sold_bars = ax.bar(
x + bar_width / 2,
sold,
width=bar_width,
color="C0",
label="units sold" if x == 0 else None,
)
ax.bar_label(sold_bars, fmt="{:,.0f}", padding=2)
ax.hlines(
DEMAND_EXAMPLE,
[x - 0.45 for x in range(len(DEMAND_EXAMPLE))],
[x + 0.45 for x in range(len(DEMAND_EXAMPLE))],
color="black",
linewidth=3,
label="demand of the day",
)
ax.set(xlabel="day", xticks=range(len(DAY_LABELS)), xticklabels=DAY_LABELS)
fig, axes = plt.subplots(
ncols=2, figsize=(12, 6), sharex=True, sharey=True, layout="constrained"
)
for ax, day in zip(axes, example_days, strict=True):
plot_stock(ax, follow_order(day, example_orders[day.title][PolicyName.DAY_ONE]))
ax.set(title=day.title)
# room for the labels above the bars
axes[0].set(ylabel="units", ylim=(0, 125))
fig.legend(*axes[1].get_legend_handles_labels(), loc="outside lower center", ncol=3)
fig.suptitle(
"Three Days After an Order up to the Level", fontsize=18, fontweight="bold"
);
The black line is the demand of the day, and the bar beside each stock bar is the units sold. A label above a stock bar, such as \(10\) lost, is the demand we did not serve. The dark part of a stock bar is the stock already on the shelf. On day \(t\) it includes the order of day \(t - 2\), and on the next days it is the stock left over from the day before. The part on top is the order that arrives that morning.
Both cases start from the same inventory position of \(200\) units after the order of day \(t\), and in both the order of day \(t\) arrives on day \(t + 2\). They differ in what happens on the two days before.
After slow sales. The shelf does not run empty on days \(t\) and \(t + 1\). We sell the whole demand of these days, \(80 + 70 = 150\) units, so \(200 - 150 = 50\) units are available on day \(t + 2\). This is what the newsvendor level assumes: the \(200\) units serve the whole demand of the days before the order arrives.
After strong sales. The shelf is empty on days \(t\) and \(t + 1\), and we lose \(20 + 10 = 30\) units of demand. A lost sale is demand that we do not serve, so it takes no unit off the shelf. We sell only \(60 + 60 = 120\) units, while the orders on their way arrive in full. So \(200 - 120 = 80\) units are available on day \(t + 2\), which is \(30\) units more than the level assumes. These \(30\) units are the sales that we lost on the two days before.
We can write this for any lead time. After the order, the inventory position is at least the level, \(\text{IP}_t + a_t \geq \hat{q}_t\), with equality when the order is positive. All of this stock has arrived by day \(t + L\), and no later order has. What we sell on a day \(s\) is \(D_s - U_s\), the demand minus the lost sales. So for a positive order the stock available on day \(t + L\) is
\[y_{t+L} = \hat{q}_t - \sum_{s=t}^{t+L-1} (D_s - U_s).\]
The newsvendor level counts the whole demand of the days before \(t + L\) against the stock, and every sale that we lose on those days leaves one more unit for day \(t + L\). For \(L = 0\) the sum is empty, and nothing is left out.
So with a lead time, a base-stock policy at the newsvendor level has at least as much stock on the day on which its order arrives as the level assumes, and more after a stockout. That extra stock is why a lower level can then be cheaper.
Take the strong sales in the example. The order of day \(t\) arrives on day \(t + 2\), so it cannot serve the \(30\) units already lost, and those units are still on the shelf. The demand of day \(t + 2\) is \(60\). The level assumed \(50\) units, which is \(10\) short of that demand. We have \(80\) units, so we sell all \(60\) and \(20\) are left over.
The demand of the three days is \(210\), which is above the level of \(200\). The critical fractile counts this path as a miss. On the shelf it is not a miss, and we pay the holding cost on the \(20\) units left over.
The critical fractile chooses the level so that the total demand exceeds it with probability \(h / (p + h)\), about \(4.8\%\) for our costs. At that rate the lost margin a marginal unit saves equals the holding cost it adds. With a lead time the arrival day runs out less often than that. A path can sit above the level on total demand and still keep the unsold units from the earlier stockout, as in the example. On that path the marginal unit saves no lost margin, and we pay \(h\) to hold it.
A lower level takes these units away. We give up some cover on the paths with no stockout before the arrival, where the shelf matches what the level assumed. We hold less on the paths with a stockout. The holding cost we save can exceed the lost margin we give up, so the expected cost can fall. For \(L = 0\) the order arrives before we sell, so a lost sale leaves no extra unit behind and the stockout rate is the one the fractile set.
Offset Definition
There is no simple formula for the best level, so we look for it with the simulator. Base-stock (day-one forecast, trained) adds an offset \(\theta_t\) to the newsvendor level of every ordering day,
\[\pi_\theta(o_t) = (\hat{q}_t + \theta_t - \text{IP}_t)^{+}.\]
The parameters are the \(H\) offsets, and the training starts them at zero, that is, at the newsvendor level. The day-one levels are the same in every scenario, so this policy has one free level per day.
A positive offset raises the level and a negative one lowers it. With a lead time we expect the offsets to be negative. A lost sale before the arrival leaves that unit on the shelf, so the newsvendor level holds more stock than it counted on, and a lower level can be cheaper.
For \(L = 0\) the order arrives before we sell, and a lost sale leaves no extra unit. We expect the offsets to stay near zero.
Here is an important observation. The offsets do not change the forecast. We train them on scenarios drawn from the forecast that gives the levels, so the levels are the right quantiles of these scenarios. The offsets correct the rule that turns a quantile into an order. We check this in the Base-Stock Training section: the demand is above the level about as often as the forecast says, at every lead time, and with a lead time the policy still runs out less often.
For the same reason the offsets cannot see where the forecast is wrong. They move the levels in one direction, which helps when the true demand lies on that side of the forecast and costs when it lies on the other. We see both cases in the Gain by Expected Demand section.
Evidence From the Literature
Whether the newsvendor level is the best level when the sales are lost is a classical question of inventory theory. Huh et al. (2009) provide an analysis of it for a demand that is independent from day to day and has the same distribution on every day. They compare two cases and recall the classical result for each:
Backlogged demand. When the shelf is empty, the customers wait for the next delivery, and we pay a cost per unit and day of waiting. Then a base-stock policy is the optimal policy, and its best level is the newsvendor level.
Lost sales. When the shelf is empty, the customers buy elsewhere. If in addition an order takes at least one day to arrive, no base-stock policy is optimal.
So with lost sales two gaps remain. The first is how much more the newsvendor level costs than the best level. The second is how much more the best base-stock policy costs than the optimal policy.
Zipkin (2008) computes the optimal policy for small problems, with lead times of \(1\) to \(4\) periods, and compares several simple rules with it. He reports in the abstract:
We find that several perform reasonably well, although none is perfect. However, the standard base-stock policy (a direct analogue of the optimal policy for a backlog system) performs badly.
For more details, see the review of Bijvank and Vis (2011).
Base-Stock (Weekly Forecast, Trained)
The fourth policy is Base-stock (weekly forecast, trained). This policy takes its levels from the weekly forecast: the forecast of day one up to day \(7\), and from day \(8\) on the forecast updated with the demand of the first week. We do not fit the forecasting model again on day \(8\). The update uses a filter, which we explain in the Forecast Updates section. The rule is the same as the one of the previous policy,
\[\pi_\theta(o_t) = (\hat{q}_t + \theta_t - \text{IP}_t)^{+},\]
where \(\hat{q}_t\) is now the newsvendor level of the weekly forecast in the observation, and the policy has its own \(H\) offsets.
Let’s go back to the example and suppose that its three days come after the update. The next figure shows the forecast of day one next to two weekly forecasts of the same three days, one after a slow first week and one after a strong first week, each with its newsvendor level. We made up the sizes of the changes. Relative to the level, they are close to the largest changes of the Weekly Forecast section, at the edges of its \(94\%\) interval. For half of the paths the level moves less than half as much.
weekly_examples = [
ExampleForecast(
"weekly forecast after a slow first week",
pz.Gamma(mu=146, sigma=22),
POLICY_COLORS[PolicyName.WEEKLY_TRAINED],
),
ExampleForecast(
"weekly forecast after a strong first week",
pz.Gamma(mu=174, sigma=22),
POLICY_COLORS[PolicyName.WEEKLY_TRAINED],
linestyle="--",
),
]
fig = plot_levels([day_one_example, *weekly_examples], config)
fig.suptitle(
"Newsvendor Levels of the Example Forecasts", fontsize=18, fontweight="bold"
);
After a slow first week the weekly forecast moves down and its level is \(185\) units. After a strong first week it moves up and its level is \(212\) units. The weekly forecast gives every demand path its own level, while the forecast of day one has one level of \(200\) units for all of them.
The updated forecast has seen one more week of demand, so it is less uncertain about how high demand is now. Its upper tail is thinner, and the high quantile can fall even when the mean demand does not.
With lost sales the newsvendor level can be too high, and the offset lowers it. If neither forecast has an offset, the weekly quantile can be lower only because the forecast is tighter. Part of the gain is then that lower level, and we would count it as a gain of the update.
So Base-stock (weekly forecast, trained) has its own trained offsets, as Base-stock (day-one forecast, trained) does. Both can lower their levels, and what remains between them is the update. In the Paired Differences section we look at the update with and without trained offsets.
The weekly offsets can also absorb part of the error in the update. We do not fit the forecasting model again. A filter, built in the Forecast Updates section, passes the new demand through the forecast of day one, and it only approximates a new fit. The offsets are one number per day, trained on these approximate levels, so they can shift a level to make up for part of that error.
Neural
The fifth policy is Neural. It starts from two limitations of a base-stock policy that no level and no offset removes:
Stock seen only through the inventory position. The inventory position is the sum of the stock on hand and the pipeline. In the example of the Stock After Lost Sales section both cases are ordered up to \(200\). On the day the order arrives, the slow case has \(50\) units and the strong case has \(80\). An offset of \(-10\) sends both cases to \(190\). It cannot send the slow case higher and the strong case lower.
Levels that do not see the latest sales. The levels change only when the forecast is updated, on day \(8\), and then they stay fixed. On day \(14\) the forecast has not seen the demand of days \(8\) to \(13\). If those days were strong, demand is higher than this forecast thinks and we would want a higher level. If they were slow, we would want a lower one. The level stays the same either way. The offset of day \(14\) is one number for every scenario, so it moves both cases the same way.
To overcome these limitations, we let the offset of a day depend on the observation. Neural adds a correction \(\bar{d} \, g_\theta(o_t)\) to the level of Base-stock (weekly forecast, trained),
\[\pi_\theta(o_t) = (\hat{q}_t + \theta_t + \bar{d} \, g_\theta(o_t) - \text{IP}_t)^{+},\]
where \(\bar{d}\) is the mean daily demand of the history. So the offset of day \(t\) is now \(\theta_t + \bar{d} \, g_\theta(o_t)\), the trained offset of the day plus a correction that changes with what we observe.
The function \(g_\theta\) reads each part of the observation separately: the stock available, each order of the pipeline, the demand of each of the last \(7\) days, the day and the forecast. Recall from the first post that the product has price promotions, which the retailer plans in advance, so \(g_\theta\) also reads which of the days that the order covers are promotion days.
The base-stock rule reads only the day, the newsvendor level of the forecast and the inventory position. So \(g_\theta\) can tell the two cases of the example apart, and it can react to the sales since the last forecast update.
We use a small neural network for \(g_\theta\). It is differentiable, so jax.grad gives its gradient through the simulator and we train it in the same way as the offsets. The last layer of the network starts at zero, so the training starts at Base-stock (weekly forecast, trained).
The factor \(\bar{d}\) sets the scale. The stock, the forecast and the demand are tens to hundreds of units. We divide these inputs by \(\bar{d}\) and multiply the output by \(\bar{d}\), so that the network reads and returns numbers of order one, which is the usual practice for training a network. An output of \(1\) moves the level by one day of mean demand. As a consequence, the policy does not depend on the unit in which we count the product.
The neural policy tells us how much a correction that reads the whole observation gains over the base-stock policy in our problem. We do not expect a large gain. In the stationary experiments of Huh et al. (2009), at a cost ratio like ours, the best base-stock policy is within a few percent of the optimal policy. Our demand is not stationary, so this is only a guide.
Remark (Reinforcement Learning). Gijsbrechts et al. (2022) train neural policies for this lost-sales problem with a model-free method of reinforcement learning (A3C), which estimates the gradient of the loss from the outcomes of sampled orders. We take the exact gradient through the simulator instead, and Alvo et al. (2023) report that this is more reliable than variants of the REINFORCE algorithm. Three properties of our problem allow it:
Joint paths. The forecast is a generative model, so it gives joint demand paths. A forecast that gives only a quantile per day does not.
Exogenous demand. The demand does not depend on our orders, so we can replay a path under any policy.
Known dynamics. The five steps of a day are a known and differentiable function of the order.
The next table summarizes the five policies.
| Policy | Order of day \(t\) | Reads | Parameters |
|---|---|---|---|
Fixed plan |
\(\theta_t\) | the day | \(H\) orders |
Base-stock (day-one forecast) |
\((\hat{q}_t - \text{IP}_t)^{+}\) | the day, the inventory position, the forecast of day one | none |
Base-stock (day-one forecast, trained) |
\((\hat{q}_t + \theta_t - \text{IP}_t)^{+}\) | the same as the policy above | \(H\) offsets |
Base-stock (weekly forecast, trained) |
\((\hat{q}_t + \theta_t - \text{IP}_t)^{+}\) | the day, the inventory position, the weekly forecast | \(H\) offsets |
Neural |
\((\hat{q}_t + \theta_t + \bar{d} \, g_\theta(o_t) - \text{IP}_t)^{+}\) | the whole observation and the promotion calendar | \(H\) offsets and the weights of the network |
Now that we have the five policies, let’s build the demand scenarios that all of them use.
Demand Scenarios
Demand Model
We use the data generating process and the forecasting model of the first post. The demand has a level that drifts as a random walk on the log scale, a weekly pattern, a price promotion with an elasticity, and negative binomial noise. We assume that a promotion cuts the price by \(30\%\) for a week, and the second week of the horizon (evaluation), days \(8\) to \(14\), is a promotion week. The first post explains the model, the prior elicitation with PreliZ and the diagnostics in its sections Generate Data to Model Fitting.
Here we write the model from small components, and we use the same model to generate the data, to fit it and to draw the demand scenarios. Let’s start with the priors, which are the priors of the first post. We elicit three of them with PreliZ: pz.maxent returns the member of a family with the largest entropy among those with \(94\%\) of their mass between two bounds. We state the other two directly.
intercept: a Normal on the log of the demand per day at the start of the history at the list price, with \(94\%\) of its mass between \(\log 10\) and \(\log 300\).drift_scale: a LogNormal on the standard deviation of the daily increments of the log level, with \(94\%\) of its mass between \(\log(1.04) / \sqrt{T}\) and \(\log(2) / \sqrt{T}\), where \(T = 364\) is the length of the history. So over one year the level moves by a factor between \(1.04\) and \(2\).concentration: a Gamma on the concentration \(\phi\) of the negative binomial, with \(94\%\) of its mass between \(4\) and \(100\). So the extra noise is between a tenth and a half of the level.beta: a \(\text{Normal}(0, 0.3)\) for each Fourier coefficient of the weekly pattern.elasticity: a \(\text{Normal}(-1, 1)\) for the price elasticity.
The model and the checks refer to the sample sites by name, so we keep the names in the Site class. Every model component gets its own small tuple of priors, and the Priors tuple collects them.
class Site:
"""Names of the sample sites of the demand model."""
INTERCEPT: Final = "intercept"
DRIFT_SCALE: Final = "drift_scale"
DRIFT: Final = "drift"
BETA: Final = "beta"
ELASTICITY: Final = "elasticity"
CONCENTRATION: Final = "concentration"
# the expected demand of every day, a deterministic site
MEAN: Final = "mean"
# the demand, the site that `predict` registers
OBS: Final = "obs"
# the increments and the demand of the days after the history, the sites that
# `innovations` and `predict` add when the covariates are longer than the data
DRIFT_FUTURE: Final = "drift_future"
FORECAST: Final = "forecast"
# the global parameters of the model
PARAMETERS: Final = (INTERCEPT, DRIFT_SCALE, BETA, ELASTICITY, CONCENTRATION)
class LevelPriors(NamedTuple):
"""Priors of the random walk level."""
intercept: dist.Distribution
drift_scale: dist.Distribution
class SeasonalityPriors(NamedTuple):
"""Prior of the weekly seasonality."""
beta: dist.Distribution
class PricePriors(NamedTuple):
"""Prior of the price effect."""
elasticity: dist.Distribution
class DispersionPriors(NamedTuple):
"""Prior of the dispersion of the likelihood."""
concentration: dist.Distribution
class Priors(NamedTuple):
"""Priors of the demand model, one tuple per component."""
level: LevelPriors
seasonality: SeasonalityPriors
price: PricePriors
dispersion: DispersionPriors
intercept_bounds = (jnp.log(10.0), jnp.log(300.0))
drift_bounds = (
jnp.log(1.04) / jnp.sqrt(setup.t_obs),
jnp.log(2.0) / jnp.sqrt(setup.t_obs),
)
concentration_bounds = (4.0, 100.0)
def elicit(
family: pz.distributions.distributions.Continuous,
bounds: tuple[ScalarLike, ScalarLike],
mass: float = 0.94,
) -> pz.distributions.distributions.Continuous:
"""Maximum entropy member of `family` with `mass` between the bounds."""
return pz.maxent(family, *bounds, mass=mass, plot=False)
# the three elicited priors and the two that we state directly
intercept_prior = elicit(pz.Normal(), intercept_bounds)
drift_prior = elicit(pz.LogNormal(), drift_bounds)
concentration_prior = elicit(pz.Gamma(), concentration_bounds)
beta_prior = pz.Normal(0.0, 0.3)
elasticity_prior = pz.Normal(-1.0, 1.0)
priors = Priors(
level=LevelPriors(
intercept=dist.Normal(intercept_prior.mu, intercept_prior.sigma),
drift_scale=dist.LogNormal(drift_prior.mu, drift_prior.sigma),
),
seasonality=SeasonalityPriors(beta=dist.Normal(beta_prior.mu, beta_prior.sigma)),
price=PricePriors(
elasticity=dist.Normal(elasticity_prior.mu, elasticity_prior.sigma)
),
dispersion=DispersionPriors(
concentration=dist.Gamma(concentration_prior.alpha, concentration_prior.beta)
),
)
Next, we write the components of the model. Each of the first four samples its own sites. The first three return a term of the log of the expected demand with shape (days, 1), one column because we have one series, and the fourth returns the concentration of the likelihood.
local_level: the log level \(\ell_t\), the initial levelinterceptplus the summed daily incrementsdrift.weekly_seasonality: the Fourier term with the coefficientsbeta.price_effect: theelasticitytimes the log of the price relative to the list price.dispersion: theconcentrationof the negative binomial.
Two more functions combine these parts:
covariate_effects: the weekly term plus the price term, the effect of the covariates on the log of the expected demand of a day.negative_binomial: the likelihood, a negative binomial distribution of the demand with a log link, given the log of the expected demand and theconcentration.
The function make_demand_model adds the level and the effect of the covariates, records the expected demand of every day in the deterministic site mean, and registers the likelihood with predict of numpyro_forecast. The model has the signature (covariates, data=None) of numpyro_forecast. The covariates are the Fourier features of the weekly cycle and the log price of every day, so the model runs on any window of consecutive days.
def local_level(h: Horizon, priors: LevelPriors) -> Float[Array, "days 1"]:
"""Random walk level: the initial level plus the summed daily increments."""
intercept = numpyro.sample(Site.INTERCEPT, priors.intercept)
drift_scale = numpyro.sample(Site.DRIFT_SCALE, priors.drift_scale)
drift = innovations(h, Site.DRIFT, dist.Normal(0.0, drift_scale))
return intercept + jnp.cumsum(drift, axis=-2)
def weekly_seasonality(
fourier: Float[Array, "days n_fourier"], priors: SeasonalityPriors
) -> Float[Array, "days 1"]:
"""Weekly Fourier seasonality."""
beta = numpyro.sample(
Site.BETA, priors.beta.expand([fourier.shape[-1]]).to_event(1)
)
return (fourier @ beta)[:, None]
def price_effect(
log_price: Float[Array, " days"], priors: PricePriors
) -> Float[Array, "days 1"]:
"""Price elasticity times the log price relative to the list price."""
elasticity = numpyro.sample(Site.ELASTICITY, priors.elasticity)
return (elasticity * log_price)[:, None]
def dispersion(priors: DispersionPriors) -> Float[Array, ""]:
"""Concentration of the negative binomial."""
return numpyro.sample(Site.CONCENTRATION, priors.concentration)
def covariate_effects(
covariates: Float[Array, "days features"], priors: Priors
) -> Float[Array, "days 1"]:
"""The weekly term plus the price term of the log of the expected demand."""
# the Fourier features in the first columns and the log price in the last one
fourier, log_price = covariates[:, :-1], covariates[:, -1]
return weekly_seasonality(fourier, priors.seasonality) + price_effect(
log_price, priors.price
)
def negative_binomial(
log_mean: Float[Array, "*shape"], concentration: Float[Array, ""]
) -> dist.Distribution:
"""Negative binomial with a log link."""
return dist.NegativeBinomial2(jnp.exp(log_mean), concentration)
def make_demand_model(priors: Priors) -> ForecastModel:
"""Build the demand model as a plain `(covariates, data=None)` function."""
def demand_model(
covariates: Float[Array, "days features"],
data: Int[Array, "t_obs 1"] | None = None,
) -> None:
h = Horizon.from_data(covariates, data)
log_mean = local_level(h, priors.level) + covariate_effects(covariates, priors)
concentration = dispersion(priors.dispersion)
numpyro.deterministic(Site.MEAN, jnp.exp(log_mean))
def likelihood(log_mean: Float[Array, "days 1"]) -> dist.Distribution:
"""The negative binomial with the concentration of this draw."""
return negative_binomial(log_mean, concentration)
predict(h, likelihood, log_mean)
return demand_model
demand_model = make_demand_model(priors)
Before we fit the model, we generate the data. Besides the parameters and the demand, the calendar of the promotions is the only random input. We draw it from a small generative model: one Bernoulli per week of the history, repeated over its seven days, followed by the plan of the retailer for the days after the history. The deterministic log_price site is the log of the price relative to the list price, \(\log(1 - 0.3)\) in a promotion week and zero otherwise.
We need covariates for more days than the horizon. The longest lead time adds \(3\) days to the \(15\) ordering days, and the forecast of each of these \(18\) days covers its own lead time, up to \(3\) more days. So the calendar covers the \(364\) days of the history and \(21\) days after it. The forecasts of the days after day \(15\) never reach an order, but the simulator reads one on every day. Only the second week of the horizon is a promotion week.
Then we fix the true parameters of the first post with the do handler and draw the history from the demand model. We keep the daily increments of the level, because the true process test set continues the level from them.
def calendar_generator(setup: Setup, promo_future: Float[Array, " num_future"]) -> None:
"""Promotion weeks of the history, followed by the planned future days."""
# one Bernoulli per week of history, repeated over its seven days
with numpyro.plate("week", setup.t_obs // 7):
promo_week = numpyro.sample("promo_week", dist.Bernoulli(setup.promo_prob))
promo = jnp.concatenate([jnp.repeat(promo_week, 7), promo_future])
numpyro.deterministic("log_price", promo * jnp.log(1.0 - setup.discount))
# the retailer's plan: a promotion in the second week of the horizon and none after it
promo_future = jnp.zeros(setup.num_future).at[7:14].set(1.0)
rng_key, key_calendar = random.split(rng_key)
calendar = Predictive(calendar_generator, num_samples=1)(
key_calendar, setup, promo_future
)
# three harmonics of the weekly cycle, and the log price in the last column
fourier = fourier_features(setup.t_obs + setup.num_future, period=7.0, num_terms=3)
covariates = jnp.concatenate([fourier, calendar["log_price"][0][:, None]], axis=1)
covariates_history = covariates[: setup.t_obs]
true_params: dict[str, Array] = {
Site.INTERCEPT: jnp.log(60.0),
Site.DRIFT_SCALE: jnp.array(0.01),
Site.BETA: jnp.array([0.15, 0.05, -0.08, 0.10, 0.03, -0.02]),
Site.ELASTICITY: jnp.array(-1.5),
Site.CONCENTRATION: jnp.array(30.0),
}
rng_key, key_data = random.split(rng_key)
history = Predictive(
do(demand_model, data=true_params),
num_samples=1,
return_sites=[Site.OBS, Site.DRIFT],
)(key_data, covariates_history)
data = history[Site.OBS][0].astype(jnp.int32)
assert data.shape == (setup.t_obs, 1)
# the daily increments of the true level over the history
true_increments = history[Site.DRIFT][0]
Now we fit the model to the history with NUTS. As in the first post, the sampler works with standardized increments of the level, the non-centered parameterization. The handlers.reparam handler applies it from the outside, so the data generator and the scenarios below use the model as it is. Let’s look at the graph of the model that the sampler works with.
non_centered_model = handlers.reparam(
demand_model, config={Site.DRIFT: LocScaleReparam(0)}
)
graph = numpyro.render_model(
non_centered_model,
model_args=(covariates_history, data),
render_distributions=True,
)
graph.attr(label="<<b>Non-Centered Demand Model</b>>", labelloc="t", fontsize="18")
graph
The plate time holds the daily increments of the history. The sampler draws the standardized increments drift_decentered, and drift is their product with drift_scale. Together with the intercept, the weekly coefficients beta and the elasticity, the increments give the expected demand mean, and the concentration sets the noise of the observed demand obs around it.
Now we run the sampler.
%%time
TARGET_ACCEPT_PROB = 0.95
rng_key, key_fit = random.split(rng_key)
mcmc = MCMC(
NUTS(non_centered_model, target_accept_prob=TARGET_ACCEPT_PROB),
num_warmup=1_000,
num_samples=1_000,
num_chains=4,
)
mcmc.run(key_fit, covariates_history, data)
posterior = mcmc.get_samples()
rng_key, key_tree = random.split(rng_key)
idata = to_datatree(
key_tree,
non_centered_model,
posterior,
data,
covariates_history,
num_chains=4,
)
CPU times: user 1min 17s, sys: 1min 51s, total: 3min 9s
Wall time: 20.6 s
Next, we look at the \(\hat{R}\) values and the effective sample sizes of the global parameters. The assertion checks the \(\hat{R}\) values, because the scenario sets and the forecast updates come from this fit.
summary = az.summary(idata, var_names=list(Site.PARAMETERS))
assert float(summary["r_hat"].max()) <= 1.01
summary
| mean | sd | eti94_lb | eti94_ub | ess_bulk | ess_tail | r_hat | mcse_mean | mcse_sd | |
|---|---|---|---|---|---|---|---|---|---|
| intercept | 4.017 | 0.054 | 3.9 | 4.1 | 5015 | 3019 | 1.00 | 0.00076 | 0.00091 |
| drift_scale | 0.0125 | 0.0045 | 0.0054 | 0.022 | 1478 | 2321 | 1.00 | 0.00012 | 7e-05 |
| beta[0] | 0.1208 | 0.0171 | 0.089 | 0.15 | 6882 | 2831 | 1.00 | 0.00021 | 0.00032 |
| beta[1] | 0.0248 | 0.0168 | -0.0078 | 0.057 | 7468 | 2515 | 1.00 | 0.00019 | 0.0003 |
| beta[2] | -0.1226 | 0.0172 | -0.15 | -0.09 | 8746 | 2697 | 1.00 | 0.00018 | 0.0003 |
| beta[3] | 0.1329 | 0.0171 | 0.1 | 0.16 | 7319 | 2912 | 1.00 | 0.0002 | 0.00032 |
| beta[4] | 0.046 | 0.0171 | 0.014 | 0.078 | 8199 | 2531 | 1.00 | 0.00019 | 0.00032 |
| beta[5] | -0.048 | 0.0171 | -0.08 | -0.015 | 7970 | 2591 | 1.00 | 0.00019 | 0.00035 |
| elasticity | -1.685 | 0.103 | -1.9 | -1.5 | 5698 | 2817 | 1.00 | 0.0014 | 0.0018 |
| concentration | 27.75 | 3.1 | 22 | 34 | 5063 | 3150 | 1.00 | 0.044 | 0.052 |
The \(\hat{R}\) values are at most \(1.01\) and the effective sample sizes are above \(1{,}000\) for every parameter, which is good!
Next, let’s compare the posterior of each parameter with the true value.
true_values = xr.Dataset(
{
Site.INTERCEPT: float(true_params[Site.INTERCEPT]),
Site.BETA: (idata["posterior"][Site.BETA].dims[-1], true_params[Site.BETA]),
Site.ELASTICITY: float(true_params[Site.ELASTICITY]),
Site.DRIFT_SCALE: float(true_params[Site.DRIFT_SCALE]),
Site.CONCENTRATION: float(true_params[Site.CONCENTRATION]),
}
)
pc = az.plot_dist(
idata,
var_names=list(Site.PARAMETERS),
kind="kde",
visuals={
"point_estimate": False,
"point_estimate_text": False,
"credible_interval": False,
},
col_wrap=3,
figure_kwargs={
"figsize": (14, 11),
"layout": "constrained",
},
)
az.add_lines(
pc,
values=true_values,
aes_by_visuals={"ref_line": []},
visuals={
"ref_line": {"color": "C3", "linestyle": "-", "linewidth": 2, "zorder": 2}
},
)
pc.viz["figure"].item().suptitle(
"Posterior Against True Parameters", fontsize=18, fontweight="bold"
);
The lines are the true values. The posterior is not centered on every true parameter. For example, the posterior mean of the elasticity is \(-1.69\) with a standard deviation of \(0.10\), against a true value of \(-1.5\). Some of the weekly coefficients beta are also about two standard deviations away from their true values. So the forecast expects more demand than the true process in the promotion week, and on some days of the week. Keep this in mind for the evaluation.
Scenario Sets
In the first post a scenario was a posterior predictive draw of the \(15\) days. We shuffled the \(4{,}000\) draws and used \(1{,}000\) of them to build the plans, the optimization set, and the other \(3{,}000\) to score them, the test set. Here we keep this split and make three changes.
Longer paths. The longest lead time needs \(15 + 3 = 18\) days of demand. The \(3\) extra days have no promotion.
A validation set. The neural policy has many parameters, so we choose its parameters on scenarios that it does not train on.
A split by posterior draw. Every scenario comes from one posterior draw of the parameters and the level, and we split the draws. The training set, the validation set and the forecast updates use the \(1{,}000\) optimization draws, and the test scenarios come from the other \(3{,}000\) draws. So no policy sees the parameters behind a test scenario.
A scenario is still a posterior predictive draw. We take the parameters and the daily increments of a posterior draw, and we run the demand model on the history and the next \(18\) days with these values fixed. The model then draws the increments and the demand of the new days, so every scenario continues the level of its own posterior draw. The function forecast of numpyro_forecast does this for a batch of posterior draws. It runs Predictive, which fixes the sites of each draw with the effect handlers of NumPyro and records what the model samples.
First, we shuffle the posterior draws and split them as above. Of the \(1{,}000\) optimization draws, \(800\) go to the training set and \(200\) to the validation set.
How many scenarios do we draw from each of these draws? A scenario has two sources of randomness: the posterior draw, which fixes the parameters and the level of the history, and the demand of the new days, which forecast draws on top of it. One scenario per draw would give only \(800\) training scenarios and \(200\) validation scenarios. This is few for the neural policy, which has many parameters, and for levels close to the \(95\%\) quantile of the demand.
So we draw \(5\) scenarios from every training and validation draw, which gives \(4{,}000\) and \(1{,}000\) scenarios. The \(5\) scenarios of a draw share its parameters and its level, and they differ in the demand of the new days. The test set needs no repetition, because it has \(3{,}000\) draws of its own.
Here is an important remark: the \(5\) scenarios of a draw are not independent, because they share the parameters. More scenarios per draw reduce the noise of the demand, and they do not add new parameter values. We come back to this in Paired Differences, where we average the scenarios of a draw before we compute a standard error.
The assertions in the code below check two things.
First, no test draw is an optimization draw.
Second, the training scenarios are \(5\) blocks of \(800\) with the same order of the draws in every block, so the scenarios \(i\) and \(i + 800\) come from the same draw.
class ScenarioSet(StrEnum):
"""Names of the scenario sets."""
TRAINING = "training set"
VALIDATION = "validation set"
FORECAST = "forecast test set"
TRUE_PROCESS = "true process test set"
NUM_DRAWS_OPT = 1_000
NUM_DRAWS_TRAIN = 800
PATHS_PER_DRAW = 5
rng_key, key_split = random.split(rng_key)
draw_order = random.permutation(key_split, posterior[Site.INTERCEPT].shape[0])
draws_opt, draws_test = draw_order[:NUM_DRAWS_OPT], draw_order[NUM_DRAWS_OPT:]
assert not jnp.isin(draws_opt, draws_test).any()
# the posterior draw behind every scenario, with 5 scenarios for each training and
# validation draw
draws_by_set: dict[ScenarioSet, Int[Array, " scenarios"]] = {
ScenarioSet.TRAINING: jnp.tile(draws_opt[:NUM_DRAWS_TRAIN], PATHS_PER_DRAW),
ScenarioSet.VALIDATION: jnp.tile(draws_opt[NUM_DRAWS_TRAIN:], PATHS_PER_DRAW),
ScenarioSet.FORECAST: draws_test,
}
# the training scenarios are 5 blocks with the same order of the draws
draw_blocks = draws_by_set[ScenarioSet.TRAINING].reshape(PATHS_PER_DRAW, -1)
assert (draw_blocks == draws_opt[:NUM_DRAWS_TRAIN]).all()
pl.DataFrame(
{
"scenario set": [str(name) for name in draws_by_set],
"posterior draws": [
jnp.unique(draws).shape[0] for draws in draws_by_set.values()
],
"scenarios": [draws.shape[0] for draws in draws_by_set.values()],
}
)
| scenario set | posterior draws | scenarios |
|---|---|---|
| str | i64 | i64 |
| "training set" | 800 | 4000 |
| "validation set" | 200 | 1000 |
| "forecast test set" | 3000 | 3000 |
The training set has \(4{,}000\) scenarios, the validation set \(1{,}000\) and the forecast test set \(3{,}000\), one from each test draw. The split is by draw, so the validation set also has parameter values that the training set does not have.
Next, we draw the scenarios: \(18\) days for every entry of the three sets. The function posterior_of returns the posterior samples of a batch of draws, and draw_scenarios passes them to forecast.
# the history and the days that we simulate for the longest lead time
covariates_sim = covariates[: setup.t_obs + setup.max_days]
def posterior_of(draws: Int[Array, " num"]) -> dict[str, Array]:
"""The posterior samples of the draws `draws`, one row per draw."""
return jax.tree.map(lambda site: site[draws], posterior)
def draw_scenarios(
key: PRNGKeyArray, draws: Int[Array, " scenarios"]
) -> Float[Array, "scenarios days"]:
"""One demand path of the simulated days for every posterior draw in `draws`."""
paths = forecast(key, demand_model, posterior_of(draws), data, covariates_sim)
return paths[..., 0].astype(jnp.float32)
rng_key, key_sets = random.split(rng_key)
demand_by_set: dict[ScenarioSet, Float[Array, "scenarios days"]] = {
scenario_set: draw_scenarios(key, draws)
for key, (scenario_set, draws) in zip(
random.split(key_sets, len(draws_by_set)), draws_by_set.items(), strict=True
)
}
Because the data are synthetic, we can also draw paths from the process that generated them. As in the data generation, the do handler fixes the true parameters, and now also the true increments of the history, so the model continues the true level. The true process test set has \(3{,}000\) such paths. These scenarios tell us how a policy that was trained on the forecast does when the demand comes from the true process.
true_process = do(demand_model, data={**true_params, Site.DRIFT: true_increments})
rng_key, key_true = random.split(rng_key)
demand_true = Predictive(
true_process, num_samples=draws_test.shape[0], return_sites=[Site.FORECAST]
)(key_true, covariates_sim, data)[Site.FORECAST]
demand_by_set[ScenarioSet.TRUE_PROCESS] = demand_true[..., 0].astype(jnp.float32)
Let’s look at the forecast test set over the \(18\) days, next to the last \(4\) weeks of the history. We want to see whether the \(3\) extra days look reasonable and where the true process lies inside the forecast. The bands are the \(50\%\) and \(94\%\) equal-tailed intervals (ETI) of the forecast test set, that is, the ranges between two percentiles.
def lighten_bands(pc: az.PlotCollection, x: str) -> None:
"""Set the alpha of the 50% and 94% credible bands of a `plot_lm` collection."""
bands = pc.viz["ci_band"][x]
for prob, alpha in [(0.5, 0.5), (CI_PROB, 0.25)]:
for band in bands.sel(prob=prob).values.flat:
band.set_alpha(alpha)
def shade_promotion(ax: plt.Axes) -> None:
"""Shade the promotion week of the horizon."""
promoted = jnp.flatnonzero(promo_future) + 1
ax.axvspan(
promoted[0] - 0.5,
promoted[-1] + 0.5,
color="C5",
alpha=0.25,
label="Promotion week",
)
forecast_tree = az.from_dict(
{
"posterior_predictive": {"demand": demand_by_set[ScenarioSet.FORECAST][None]},
"observed_data": {
"demand": demand_by_set[ScenarioSet.TRUE_PROCESS].mean(axis=0)
},
# ArviZ sorts the x values in place, which a JAX array does not allow
"constant_data": {"day": jax.device_get(horizon_days)},
},
coords={"time": horizon_days.tolist()},
dims={"demand": ["time"], "day": ["time"]},
)
pc = az.plot_lm(
forecast_tree,
x="day",
y="demand",
y_obs="demand",
smooth=False,
ci_prob=(0.5, CI_PROB),
point_estimate="mean",
# the forecast of day one in the color of the first policy that reads it
visuals={
"ci_band": {"color": POLICY_COLORS[PolicyName.DAY_ONE]},
"pe_line": {
"color": POLICY_COLORS[PolicyName.DAY_ONE],
"alpha": 1.0,
"linewidth": 2,
},
"observed_scatter": False,
},
figure_kwargs={"figsize": (12, 6)},
)
lighten_bands(pc, "day")
ax = pc.viz["plot"]["day"].item()
pc.viz["ci_band"]["day"].sel(prob=CI_PROB).item().set_label(f"{CI_PROB:.0%} ETI")
pc.viz["ci_band"]["day"].sel(prob=0.5).item().set_label("50% ETI")
pc.viz["pe_line"]["day"].item().set_label(f"Mean of the {ScenarioSet.FORECAST}")
ax.plot(
horizon_days,
demand_by_set[ScenarioSet.TRUE_PROCESS].mean(axis=0),
"o-",
markersize=3,
color="C7",
label=f"Mean of the {ScenarioSet.TRUE_PROCESS}",
)
# the two means are within 20% of each other on every day
assert jnp.allclose(
demand_by_set[ScenarioSet.TRUE_PROCESS].mean(axis=0),
demand_by_set[ScenarioSet.FORECAST].mean(axis=0),
rtol=0.2,
)
history_days = jnp.arange(-27, 1)
ax.plot(
history_days,
data[-len(history_days) :, 0],
"o-",
markersize=3,
color="black",
label="Observed history",
)
ax.axvline(0.5, color="black", linestyle="--", linewidth=1)
shade_promotion(ax)
ax.set(xlabel="day (the horizon starts on day $1$)", ylabel="units", title="")
fig = pc.viz["figure"].item()
fig.legend(loc="outside lower center", ncol=3)
fig.suptitle("Forecast and True Process Test Sets", fontsize=18, fontweight="bold");
The forecast follows the weekly pattern and rises in the promotion week (the shaded days), and the \(3\) extra days look like the first days of the horizon. The mean of the true process test set stays close to the mean of the forecast test set before and after the promotion week, except on day \(7\). In the promotion week it is below it.
Forecast Updates
In practice we do not keep the forecast of day one for the whole horizon. When new demand comes in, we run the forecasting model again. A retailer that runs its forecast every week updates it after the first week, and so do we: on day \(8\) we update the forecast with the demand of the first week.
The direct way to update the forecast is to fit the model again with NUTS, on the history plus the first week. For a retailer this is fine. Our fit took about \(20\) seconds, and a forecasting job that runs once per week usually runs overnight.
In this notebook the situation is different, because we train and test the policies on simulated scenarios. Each of the \(11{,}000\) scenarios (\(4{,}000 + 1{,}000 + 3{,}000 + 3{,}000\)) has its own first week and needs its own update, and \(11{,}000\) refits of \(20\) seconds take about \(60\) hours. So we look for an alternative that is much cheaper than a refit.
The alternative is also useful in practice. When a fit is expensive, for example for many products, a retailer can fit the model once a month and update the forecast every week with the method of this section.
State Space Model
The alternative uses the structure of the demand model. Recall its components from the Demand Model section. Let \(\ell_t\) be the log level of the demand on day \(t\), where \(t\) now runs over the days of the history and of the horizon. The level moves from one day to the next by an increment \(\varepsilon_t\) with scale \(\sigma\) (drift_scale). Let \(z_t\) be the covariates of day \(t\) (the Fourier features and the log price), \(\gamma\) their coefficients (beta and elasticity) and \(\phi\) the concentration. Then the model of the demand \(D_t\) is
\[\begin{align*} \ell_t &= \ell_{t-1} + \varepsilon_t, \qquad \varepsilon_t \sim \text{Normal}(0, \sigma), \\ D_t \mid \ell_t &\sim \text{NegativeBinomial}\left(\exp(\ell_t + z_t^{\top} \gamma), \phi\right), \end{align*}\]
where \(\exp(\ell_t + z_t^{\top} \gamma)\) is the mean of the negative binomial, and the level before the first day of the history is the intercept. The level is a hidden state that moves as a random walk, and the demand of a day depends on the past only through the level of that day. A model with this structure is a state space model.
For a state space model with fixed parameters, a filter computes the distribution of the state of a day given the demand up to that day. It works one day at a time: the distribution of day \(t\) follows from the distribution of day \(t - 1\) and the demand of day \(t\). So an update with one more week takes \(7\) steps of the filter, and not a new fit. See Särkkä and Svensson (2023) for an introduction to filtering.
We do not write the filter ourselves. We use dynestyx and a module of numpyro_forecast that connects it with our model functions:
dynestyx. It is a library for state space models built on NumPyro. We describe the model as aDynamicalModel, with an initial condition, a state evolution and an observation model, and the library provides the filters and a simulator.numpyro_forecast.contrib.dynestyx. The blockstate_spaceruns aDynamicalModelinside a model function with the signature(covariates, data=None), soPredictiveandforecastwork with it as with the demand model. The functionsend_stateandstart_statecarry the filtered level from one window of days to the next, so we filter the history only once.
For more details, see the section “Reusing a Filtered History” of the getting started example and the example “State Space Models with dynestyx and numpyro_forecast”.
The best-known filter is the Kalman filter, which is exact for a linear model with Normal noise. Our demand is a count with a negative binomial distribution, so we use the extended Kalman filter of dynestyx, which is an approximation. It keeps a Normal approximation of the distribution of the level.
Let \(m_t\) and \(P_t\) be the mean and the variance of this Normal approximation for the level of day \(t\), given the demand up to day \(t\). Before we see the demand of day \(t + 1\), its level is one step of the random walk away:
\[\ell_{t+1} \mid D_1, \dots, D_t \sim \text{Normal}\left(m_t, \sqrt{P_t + \sigma^2}\right).\]
The demand of day \(t + 1\) then updates this distribution to the mean \(m_{t+1}\) and the variance \(P_{t+1}\).
A filter needs fixed parameters, and the fit gives us posterior draws of them. So we run one filter for every parameter draw, and the update has three steps:
History. For every posterior draw of the parameters, we filter the \(364\) days of the history. This gives the distribution of the level on the last day of the history. We do this only once, and
end_statereturns the result as two sites.First week. For a scenario, we continue the filter of every draw with the demand of days \(1\) to \(7\), from the level on the last day of the history.
Simulation. From the level of day \(7\), we simulate the demand of the remaining days, one path for every draw.
Here is an important remark. The update keeps the parameter draws of the fit with equal weights and moves only the level, so it ignores what the first week tells us about the parameters. We expect one week to add little to what a year of history says about them.
In the Appendix we compare the update with a NUTS refit on \(6\) scenarios. The two forecasts are close, except after the highest first week of the test set. There the refit moves the forecast further up, and weights of the draws, which the filter can compute, recover most of the difference.
Let’s write the model. The function make_state_space_model writes the demand model in the form above, with the log level as the state. It has four parts:
Control. The effect of the covariates \(z_t^{\top} \gamma\) is the control of day \(t\), an input that the observation model adds to the level. The function
covariate_effectsof the Demand Model section computes it.Parameters. The model reuses the component
dispersionand the prior ofdrift_scalefrom the same section.Start. In place of the
intercept,start_statereads two sites, the mean and the variance of the level on the day before the first day. The initial condition is one step of the random walk from there, as in the formula above.Demand. The observation model is the likelihood
negative_binomialof the Demand Model section, and the blockstate_spacereads the observed demand fromdata.
So the two models share every component except the level. A change of the covariate effects, of the likelihood or of any prior other than the one of the intercept applies to both. The level is the one part that we write twice, because the two models use it in different ways. The demand model samples the whole path of the level, while the filter needs the step of the level from one day to the next. The check after step \(1\) compares the levels of the two models.
LEVEL: Final = "level" # the name of the state space block
def make_state_space_model(priors: Priors) -> ForecastModel:
"""The demand model as a state space model, with the log level as the state."""
def state_space_model(
covariates: Float[Array, "days features"],
data: Float[Array, "t_obs 1"] | None = None,
) -> None:
h = Horizon.from_data(covariates, data)
drift_scale = numpyro.sample(Site.DRIFT_SCALE, priors.level.drift_scale)
control = covariate_effects(covariates, priors)
concentration = dispersion(priors.dispersion)
# the mean and the variance of the level on the day before the first day
mean, cov = start_state(LEVEL, 1)
# dynestyx calls the next two functions by keyword, so the argument names
# are fixed
def random_walk_step(
x: Float[Array, " state"],
u: Float[Array, " control"] | None,
t_now: ScalarLike,
t_next: ScalarLike,
) -> dist.Distribution:
"""The log level of the next day, one step of the random walk away."""
return dist.Normal(x, drift_scale).to_event(1)
def demand_given_level(
x: Float[Array, " state"], u: Float[Array, " control"], t: ScalarLike
) -> dist.Distribution:
"""The demand of a day given its log level and its control."""
return negative_binomial(x + u, concentration).to_event(1)
dynamics = DynamicalModel(
# the level of the first day is one step of the random walk away
initial_condition=dist.MultivariateNormal(
mean, cov + drift_scale**2 * jnp.eye(1)
),
state_evolution=random_walk_step,
observation_model=demand_given_level,
control_dim=1,
)
state_space(h, LEVEL, data, dynamics, controls=control)
return state_space_model
state_space_model = make_state_space_model(priors)
Now we run the first step. Before the history starts, the level of a draw is its intercept, a known number, so its variance is zero. We give these values to the two sites of start_state, together with the \(1{,}000\) optimization draws, and run Predictive under the extended Kalman filter extended_kalman. Recall from the Scenario Sets section that Predictive fixes the sites of each draw.
dynestyx records the mean and the variance of the filtered level of every day. The function end_state takes those of the last day of the history and returns them under the names of the two sites. So posterior_resumed holds, for every draw, the parameters and the mean and the variance of the level at the end of the history.
The fit gives us a check of the filter. For every draw it has a level on the last day of the history, the intercept plus the sum of the daily increments, and this level should be a draw from the Normal distribution that the filter gives for the same parameters. So we standardize the levels of the fit with the mean and the standard deviation of their filter, and the assertions check that the result has mean zero and standard deviation one within \(0.1\).
posterior_opt = posterior_of(draws_opt)
# the parameters of the optimization draws, without the increments of the level
params_opt = {site: posterior_opt[site] for site in Site.PARAMETERS}
START_MEAN: Final = f"{LEVEL}_start_mean"
START_COV: Final = f"{LEVEL}_start_cov"
# before the history the level of a draw is its intercept, a known number
start_history: dict[str, Float[Array, " draws 1 1"]] = {
START_MEAN: params_opt[Site.INTERCEPT][:, None],
START_COV: jnp.zeros((NUM_DRAWS_OPT, 1, 1)),
}
rng_key, key_history = random.split(rng_key)
extended_kalman = Filter(filter_config=EKFConfig())
with extended_kalman:
filtered_history = Predictive(
state_space_model, posterior_samples=params_opt | start_history
)(key_history, covariates_history, data.astype(jnp.float32))
posterior_resumed = params_opt | end_state(filtered_history, LEVEL)
# the level of every draw on the last day of the history, from the fit
def last_level(samples: dict[str, Array]) -> Float[Array, " draws"]:
"""Log level on the last day of the history: the intercept plus the increments."""
return samples[Site.INTERCEPT] + samples[Site.DRIFT].sum(axis=(1, 2))
level_fit = last_level(posterior_opt)
filtered_mean = posterior_resumed[START_MEAN][:, 0]
filtered_scale = jnp.sqrt(posterior_resumed[START_COV][:, 0, 0])
standardized = (level_fit - filtered_mean) / filtered_scale
assert jnp.allclose(standardized.mean(), 0.0, atol=0.1, rtol=0.0)
assert jnp.allclose(standardized.std(), 1.0, atol=0.1, rtol=0.0)
The assertions pass, which is good! Next, we write steps \(2\) and \(3\) for one scenario. The function update_forecast calls forecast with posterior_resumed and the demand of the observed days, so the model of every draw starts from its level at the end of the history.
The handlers around the call decide what the block does with the days. Under extended_kalman it filters the observed days, and under DiscreteTimeSimulator it simulates the remaining days from the last filtered level, one path for every draw. So update_forecast returns \(1{,}000\) paths.
covariates_future = covariates[setup.t_obs :]
def update_forecast(
key: PRNGKeyArray, observed: Float[Array, " observed"]
) -> Float[Array, "draws days"]:
"""Forecast paths of the days after `observed`, one for every parameter draw."""
with DiscreteTimeSimulator(n_simulations=1), extended_kalman:
paths = forecast(
key,
state_space_model,
posterior_resumed,
observed[:, None],
covariates_future,
)
return paths[..., 0].astype(jnp.float32)
Now that we have the update, we can compute the forecast that the policies read.
Weekly Forecast
In this section we compute the forecast that the policies read. Recall that a base-stock policy does not read the whole forecast. On day \(t\) it only reads the newsvendor level \(\hat{q}_t\). On the other hand, the neural policy also reads the mean of the total demand \(D_t + \dots + D_{t+L}\) of the days that the order of day \(t\) has to cover. So for every scenario we reduce the forecast paths to these two numbers, for every day and every lead time.
We do this in three steps. First, we compute the levels of the forecast of day one, which are the same for every scenario. Next, we compute the weekly forecast of one scenario: the day-one levels up to day \(7\), and from day \(8\) on the levels of the update with the first week of that scenario. Finally, we repeat this for all \(11{,}000\) scenarios.
The rest of the section checks the result. Why do we need these checks? Recall we are using an approximation and not a refit, and every policy after this section takes its levels as an input. A level that is too high or too low would look like a loss of the weekly forecast in the evaluation, and a level that uses the demand of its own day would look like a gain. We could not see these errors in the loss later, so we check the levels now:
Consistency with day one. Averaged over the scenarios, the weekly forecast should give back the forecast of day one.
Coverage after the update. The demand should be above the weekly level on about \(h / (p + h) = 4.8\%\) of the days, after a slow first week and after a strong one.
No look-ahead. The forecast of a day should not change when we change the demand of that day or of a later day.
Now that we have a clear path, let’s work out the details. We start by implementing the function summarize_forecast that turns the paths into the level and the mean of one total: the demand \(D_t + \dots + D_{t+L}\) over the days that the order of day \(t\) has to cover. The level is the quantile of that total, and the mean is its average over the paths. For the forecast of day one no new demand has arrived, so we draw the paths from the posterior of the fit and we do not run the filter.
class Forecast(NamedTuple):
"""Newsvendor level and mean of the total demand of the days t, ..., t + L."""
level: Float[Array, "*batch"]
mean: Float[Array, "*batch"]
def covered_demand(
paths: Float[Array, "paths days"], num_days: int
) -> Float[Array, "paths num_days lead_times"]:
"""Total demand of the days t, ..., t + L, for every path, day t and lead time."""
cumulative = jnp.cumsum(jnp.pad(paths, ((0, 0), (1, 0))), axis=1)
first = jnp.arange(num_days)[:, None]
last = first + jnp.asarray(setup.lead_times)[None, :]
return cumulative[:, last + 1] - cumulative[:, first]
def summarize_forecast(
paths: Float[Array, "paths days_ahead"], num_days: int, fractile: float
) -> Forecast:
"""Levels and means of the totals over the days t, ..., t + L of the paths.
Both have shape `(num_days, lead_times)`, one column per lead time.
"""
totals = covered_demand(paths, num_days)
return Forecast(jnp.quantile(totals, fractile, axis=0), totals.mean(axis=0))
DAY_ONE_PATHS_PER_DRAW = 4
rng_key, key_day_one = random.split(rng_key)
# on all the days with covariates: the simulated days and the lead time of the last one
paths_day_one = forecast(
key_day_one,
demand_model,
posterior_of(jnp.tile(draws_opt, DAY_ONE_PATHS_PER_DRAW)),
data,
covariates,
)[..., 0].astype(jnp.float32)
assert paths_day_one.shape[1] == setup.num_future
forecast_day_one = summarize_forecast(
paths_day_one, setup.max_days, critical_fractile(config)
)
pl.DataFrame(
{
"day": [1, 2, 3],
**{
f"L = {lead_time}": forecast_day_one.level[:3, k].tolist()
for k, lead_time in enumerate(setup.lead_times)
},
}
)
| day | L = 0 | L = 1 | L = 2 | L = 3 |
|---|---|---|---|---|
| i64 | f64 | f64 | f64 | f64 |
| 1 | 98.0 | 184.0 | 263.0 | 321.0 |
| 2 | 105.0 | 182.0 | 242.0 | 312.0 |
| 3 | 96.0 | 156.0 | 227.0 | 277.0 |
The level grows with the lead time, since the order of day \(t\) covers \(L + 1\) days.
Now we compute the weekly forecast of a path with the function weekly_forecast. Up to day \(7\) it is the forecast of day one. From day \(8\) on it summarizes the \(1{,}000\) paths of update_forecast. These paths cover days \(8\) to \(18\), the rest of the simulated days, plus \(3\) days for the lead time of the last day. Let’s compare the levels of the first test scenario at \(L = 2\) with the levels of day one.
NUM_OBSERVED = setup.update_after # the days that the update sees, the first week
num_remaining = setup.max_days - NUM_OBSERVED
def weekly_forecast(
key: PRNGKeyArray, path: Float[Array, " days"], fractile: float
) -> Forecast:
"""The forecast of day one for the first week and the update for the other days."""
paths = update_forecast(key, path[:NUM_OBSERVED])
first_week = jax.tree.map(lambda leaf: leaf[:NUM_OBSERVED], forecast_day_one)
return jax.tree.map(
lambda before, after: jnp.concatenate([before, after]),
first_week,
summarize_forecast(paths, num_remaining, fractile),
)
LEAD_TIME_DETAIL = 2 # the lead time that we look at in detail
lead_index_detail = setup.lead_times.index(LEAD_TIME_DETAIL)
path_example = demand_by_set[ScenarioSet.FORECAST][0]
days_example = jnp.array([0, 6, 7, 13, 14])
rng_key, key_example = random.split(rng_key)
forecast_example = jax.jit(
lambda key, path: weekly_forecast(key, path, critical_fractile(config))
)(key_example, path_example)
pl.DataFrame(
{
"day": (days_example + 1).tolist(),
"day-one level": forecast_day_one.level[
days_example, lead_index_detail
].tolist(),
"weekly level": forecast_example.level[
days_example, lead_index_detail
].tolist(),
}
)
| day | day-one level | weekly level |
|---|---|---|
| i64 | f64 | f64 |
| 1 | 263.0 | 263.0 |
| 7 | 406.0 | 406.0 |
| 8 | 481.0 | 465.0 |
| 14 | 328.6 | 311.4 |
| 15 | 267.0 | 255.0 |
Up to day \(7\) the two levels are the same, since the weekly forecast is the forecast of day one. On days \(8\), \(14\) and \(15\) the levels of this scenario are lower, by \(16\), \(17\) and \(12\) units.
Here is an important observation. We observe the demand and not the sales, so the forecast of a day depends on the demand of the earlier days and not on the orders. The orders cannot change it. So we can compute the weekly forecast of every scenario once, before we train any policy, and give it to the simulator as an input.
We do this for the four scenario sets, in batches of \(500\) scenarios. We keep the random key of every scenario, so that we can repeat the computation with the same random numbers.
First, we check the consistency with day one. The scenarios of the forecast test set have the same distribution as the paths of the forecast of day one, so the mean of their weekly forecasts over the scenarios should give back the mean of the forecast of day one, up to the approximation of the update and the Monte Carlo error. The assertion checks this within \(2\%\) for every day from day \(8\) on and every lead time.
%%time
forecast_scenarios = jax.jit(
lambda keys, paths: jax.lax.map(
lambda inputs: weekly_forecast(*inputs, critical_fractile(config)),
(keys, paths),
batch_size=500,
)
)
forecast_keys: dict[ScenarioSet, UInt32[Array, "scenarios 2"]] = {}
forecast_by_set: dict[ScenarioSet, Forecast] = {}
for scenario_set, paths in demand_by_set.items():
rng_key, key_set = random.split(rng_key)
forecast_keys[scenario_set] = random.split(key_set, paths.shape[0])
forecast_by_set[scenario_set] = forecast_scenarios(
forecast_keys[scenario_set], paths
)
forecast_by_set = jax.block_until_ready(forecast_by_set)
# the weekly forecasts of the forecast test set average to the forecast of day one
assert jnp.allclose(
forecast_by_set[ScenarioSet.FORECAST].mean[:, NUM_OBSERVED:].mean(axis=0),
forecast_day_one.mean[NUM_OBSERVED:],
rtol=0.02,
)
{str(name): forecast.level.shape for name, forecast in forecast_by_set.items()}
CPU times: user 25min 27s, sys: 35.3 s, total: 26min 2s
Wall time: 2min 9s
{'training set': (4000, 18, 4),
'validation set': (1000, 18, 4),
'forecast test set': (3000, 18, 4),
'true process test set': (3000, 18, 4)}
Every set now has a level and a mean for every scenario, day and lead time.
Before the second check, let’s look at how the update moves the levels. We plot the weekly levels at \(L = 2\) on the two test sets: the median and the \(50\%\) and \(94\%\) intervals over the scenarios, next to the levels of day one. On the panel of the true process test set we add the newsvendor level of the true process itself, the same quantile of the demand of that set.
TEST_SETS = [ScenarioSet.FORECAST, ScenarioSet.TRUE_PROCESS]
ordering_days = jnp.arange(1, setup.horizon + 1)
set_names = [str(scenario_set).capitalize() for scenario_set in TEST_SETS]
levels_by_set = {
scenario_set: forecast_by_set[scenario_set].level[
:, : setup.horizon, lead_index_detail
]
for scenario_set in TEST_SETS
}
# (chain, draw, scenario set, day): plot_lm reduces the sample dimensions and
# facets on the extra dimension of the day coordinate
weekly_levels = jnp.moveaxis(
jnp.stack([levels_by_set[scenario_set] for scenario_set in TEST_SETS]), 0, 1
)
level_tree = az.from_dict(
{
"posterior_predictive": {"level": weekly_levels[None]},
"observed_data": {"level": jnp.zeros((len(TEST_SETS), setup.horizon))},
"constant_data": {
"day": jax.device_get(ordering_days)[None, :].repeat(len(TEST_SETS), axis=0)
},
},
coords={"scenario_set": set_names, "time": ordering_days.tolist()},
dims={"level": ["scenario_set", "time"], "day": ["scenario_set", "time"]},
)
pc = az.plot_lm(
level_tree,
x="day",
y="level",
y_obs="level",
smooth=False,
ci_prob=(0.5, CI_PROB),
point_estimate="median",
visuals={
"ci_band": {"color": "C3"},
"pe_line": {"color": "C3", "marker": "o", "markersize": 3},
"observed_scatter": False,
},
figure_kwargs={"figsize": (13, 5.5)},
)
lighten_bands(pc, "day")
axes = [pc.viz["plot"]["day"].sel(scenario_set=name).item() for name in set_names]
axes[0].sharex(axes[1])
axes[0].sharey(axes[1])
day_one_levels = forecast_day_one.level[: setup.horizon, lead_index_detail]
legend_set = set_names[-1]
pc.viz["ci_band"]["day"].sel(prob=CI_PROB, scenario_set=legend_set).item().set_label(
f"{CI_PROB:.0%} interval of the weekly level"
)
pc.viz["ci_band"]["day"].sel(prob=0.5, scenario_set=legend_set).item().set_label(
"50% interval of the weekly level"
)
pc.viz["pe_line"]["day"].sel(scenario_set=legend_set).item().set_label(
"median of the weekly level"
)
for ax, scenario_set, name in zip(axes, TEST_SETS, set_names, strict=True):
levels = levels_by_set[scenario_set]
# after the update the median of the weekly levels is below the day-one level
shift = jnp.median(levels, axis=0) - day_one_levels
assert (shift[setup.update_after :] < 0).all()
ax.plot(
ordering_days,
day_one_levels,
color=POLICY_COLORS[PolicyName.DAY_ONE],
label="day-one level" if name == legend_set else None,
)
if scenario_set == ScenarioSet.TRUE_PROCESS:
level_true_process = summarize_forecast(
demand_by_set[scenario_set], setup.horizon, critical_fractile(config)
).level[:, lead_index_detail]
ax.plot(
ordering_days,
level_true_process,
color="C7",
label="newsvendor level of the true process",
)
# on the ordering days of the promotion week the level of the true process
# is below the 94% interval of the weekly levels
lower_edge = jnp.quantile(levels, (1 - CI_PROB) / 2, axis=0)
is_promotion_day = promo_future[: setup.horizon] == 1.0
assert (level_true_process < lower_edge)[is_promotion_day].all()
shade_promotion(ax)
ax.set(title=name, xlabel="ordering day", ylabel="")
axes[0].set(ylabel=f"newsvendor level at $L = {LEAD_TIME_DETAIL}$ (units)")
fig = pc.viz["figure"].item()
fig.legend(*axes[-1].get_legend_handles_labels(), loc="outside lower center", ncol=3)
fig.suptitle(
"Newsvendor Levels of the Weekly Forecast", fontsize=18, fontweight="bold"
);
From day \(8\) on the median weekly level is below the day-one level on both test sets. The updated forecast is less uncertain, so its high quantile can fall.
Next, we check the coverage. If the update works, the covered demand is above the weekly level on about \(h / (p + h) = 4.8\%\) of days \(8\) to \(15\), after a slow first week and after a strong one. We split the forecast test set into \(5\) groups by the demand of the first week, and we compare this share for the day-one levels and the weekly levels.
def equal_groups(
values: Float[Array, " scenarios"], num_groups: int
) -> Int[Array, " scenarios"]:
"""Group of every scenario when we cut the ranks of `values` into equal groups."""
return jnp.argsort(jnp.argsort(values)) * num_groups // values.shape[0]
NUM_WEEK_GROUPS = 5
demand_test = demand_by_set[ScenarioSet.FORECAST]
week_group = equal_groups(demand_test[:, :NUM_OBSERVED].sum(axis=1), NUM_WEEK_GROUPS)
# the demand that the orders of the days 8 to 15 cover: (scenarios, days, lead_times)
covered_test = covered_demand(demand_test, setup.horizon)[:, NUM_OBSERVED:]
levels_after_update = {
"day-one level": forecast_day_one.level[NUM_OBSERVED : setup.horizon],
"weekly level": forecast_by_set[ScenarioSet.FORECAST].level[
:, NUM_OBSERVED : setup.horizon
],
}
# share of the days with demand above the level: (groups, lead_times)
share_above = {
name: jnp.stack(
[
(covered_test > level)[week_group == g].mean(axis=(0, 1))
for g in range(NUM_WEEK_GROUPS)
]
)
for name, level in levels_after_update.items()
}
# at every lead time the weekly levels leave about the share of the fractile above
# them in every group, and the day-one levels leave less in the lowest group and
# more in the highest one
target_share = 1 - critical_fractile(config)
assert jnp.abs(share_above["weekly level"] - target_share).max() < 0.015
assert (share_above["day-one level"][0] < target_share).all()
assert (share_above["day-one level"][-1] > target_share).all()
fig, ax = plt.subplots(figsize=(10, 5.5))
week_groups = jnp.arange(1, NUM_WEEK_GROUPS + 1)
for (name, share), color in zip(
share_above.items(), [POLICY_COLORS[PolicyName.DAY_ONE], "C3"], strict=True
):
ax.plot(week_groups, share[:, lead_index_detail], "o-", color=color, label=name)
ax.axhline(target_share, color="black", linestyle="--", label="$h / (p + h)$")
ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))
ax.set(
xticks=week_groups,
xlabel="group of the scenario by the demand of its first week ($1$ is the lowest)",
ylabel="share of the days with demand above the level",
)
fig.legend(loc="outside lower center", ncol=3)
fig.suptitle(
f"Demand Above the Level After the Update at Lead Time $L = {LEAD_TIME_DETAIL}$",
fontsize=18,
fontweight="bold",
);
The day-one level ignores the first week, so after a slow week the demand is above it less often than \(4.8\%\), and after a strong week more often. The weekly level stays near \(4.8\%\) in every group. The update gives a level that is about right at both ends of the first week.
Finally, we check that there is no look-ahead. We take the first \(100\) validation scenarios and compute their weekly forecast again with the same keys, once as they are and once with \(50\) more units of demand from day \(8\) on. The update uses the first week only, so no level should change. Adding \(50\) units on day \(7\) alone should move the levels from day \(8\) on and leave the first week unchanged.
CHANGED_FROM = setup.update_after # index of the first day whose demand we change
NUM_CHECKED = 100 # the validation scenarios whose forecast we compute again
keys_val = forecast_keys[ScenarioSet.VALIDATION][:NUM_CHECKED]
demand_val = demand_by_set[ScenarioSet.VALIDATION][:NUM_CHECKED]
forecast_original, forecast_changed, forecast_day_7 = (
forecast_scenarios(keys_val, paths)
for paths in (
demand_val,
demand_val.at[:, CHANGED_FROM:].add(50.0),
demand_val.at[:, CHANGED_FROM - 1].add(50.0),
)
)
level_original = forecast_original.level
assert all(
jnp.array_equal(changed, original)
for changed, original in zip(forecast_changed, forecast_original, strict=True)
)
assert jnp.array_equal(
forecast_day_7.level[:, :CHANGED_FROM], level_original[:, :CHANGED_FROM]
)
# every day from the update on changes in at least one scenario
assert (
(forecast_day_7.level[:, CHANGED_FROM:] != level_original[:, CHANGED_FROM:])
.any(axis=0)
.all()
)
The three assertions pass: the forecast of a day only depends on the demand before the day of its update.
Now that every scenario has its weekly forecast, we can build the simulator in which the policies place their orders.
Inventory Simulator
The simulator of the first post took a vector of orders and a demand path and returned the loss. The new simulator takes a policy and its parameters in place of the orders, and the forecast of every day as a second input. It is again a jax.lax.scan over the days, and every iteration runs the five steps of a day from the Lead Time section. We start with the state and the observation.
State. The scan carries the
InventoryStatefrom one day to the next: the stock on hand, the pipeline as a vector of length \(L\), and the last \(K\) demands. The functioninitial_statereturns the state before day one, the same for every policy: the initial stock, the initial pipeline and the demand of the last \(7\) days of the history.Observation. The function
observereceives the order that arrives and builds theObservationfrom the state, the day and the forecast of the day. It does not take the demand as an argument, so no policy can see the demand of the day on which it orders. A policy that reads no forecast getsNone.
Let’s look at the observation of day one for \(L = 2\), without a forecast.
class InventoryState(NamedTuple):
"""What the simulator carries from one day to the next."""
inventory: Float[Array, ""] # stock on hand at the end of the day
pipeline: Float[Array, " lead_time"] # orders on their way, the first arrives next
demand_history: Float[Array, " window"] # the last demands, most recent last
class Observation(NamedTuple):
"""What a policy sees on a day, before the demand of that day."""
day: Int[Array, ""]
inventory: Float[Array, ""] # stock on hand after the arrival of the day
pipeline: Float[Array, " in_transit"] # orders that arrive on later days
position: Float[Array, ""] # stock on hand plus pipeline
demand_history: Float[Array, " window"]
forecast: Forecast | None # the latest forecast of the days t, ..., t + L
def initial_state(lead_time: int) -> InventoryState:
"""The state before day one, the same for every policy."""
return InventoryState(
inventory=jnp.asarray(config.initial_inventory),
# each order in the pipeline is the median demand of the day on which it arrives
pipeline=jnp.median(demand_by_set[ScenarioSet.TRAINING][:, :lead_time], axis=0),
demand_history=data[-setup.history_window :, 0].astype(jnp.float32),
)
def observe(
state: InventoryState,
day: Int[Array, ""],
forecast: Forecast | None,
lead_time: int,
) -> Observation:
"""Receive the order that arrives today and collect what a policy may see."""
# an empty pipeline, the case of lead time zero, contributes an arrival of zero
assert state.pipeline.shape[0] == lead_time
inventory = state.inventory + jnp.pad(state.pipeline, (0, 1))[0]
in_transit = state.pipeline[1:]
return Observation(
day=day,
inventory=inventory,
pipeline=in_transit,
position=inventory + in_transit.sum(),
demand_history=state.demand_history,
forecast=forecast,
)
observe(initial_state(LEAD_TIME_DETAIL), jnp.asarray(0), None, LEAD_TIME_DETAIL)
Observation(day=Array(0, dtype=int32, weak_type=True), inventory=Array(119., dtype=float32), pipeline=Array([72.], dtype=float32), position=Array(191., dtype=float32), demand_history=Array([57., 56., 95., 48., 64., 48., 59.], dtype=float32), forecast=None)
On day one the first order of the initial pipeline has arrived, so the stock on hand is the initial stock of \(50\) units plus that order. The second order of the initial pipeline arrives on day two, and the inventory position adds it.
Next, the function inventory_step asks the policy for the order, appends it to the pipeline, sells, and charges the cost if the day is in the cost window. It returns a DayResult: the state at the end of the day and the record of the day, a Simulation with the cost, the order, the stock and the lost sales.
The simplest policy is the fixed plan. Its order on day \(t\) is the entry \(\theta_t\) of a vector of orders, whatever the observation. As a plan we take the mean demand of the training scenarios on the day on which each order arrives, which the function mean_demand_plan computes. Let’s follow the first scenario of the training set through its first five days at \(L = 2\).
class Simulation(NamedTuple):
"""Daily cost, orders, stock and lost sales of a policy on demand paths."""
daily_cost: Float[Array, "*scenarios days"]
orders: Float[Array, "*scenarios days"]
inventory: Float[Array, "*scenarios days"]
lost_sales: Float[Array, "*scenarios days"]
@property
def loss(self) -> Float[Array, "*scenarios"]:
"""Sum of the daily costs, which are zero outside the cost window."""
return self.daily_cost.sum(axis=-1)
class DayResult(NamedTuple):
"""The state at the end of a day and the record of that day."""
state: InventoryState
record: Simulation
type Policy = Callable[[PyTree, Observation], Float[Array, ""]]
def inventory_step(
policy: Policy,
params: PyTree,
state: InventoryState,
demand_t: Float[Array, ""],
forecast_t: Forecast | None,
day: Int[Array, ""],
config: InventoryConfig,
lead_time: int,
) -> DayResult:
"""One day of the inventory dynamics: receive, observe, order, sell, pay."""
observation = observe(state, day, forecast_t, lead_time)
# no orders after day H
order = jnp.where(day < setup.horizon, policy(params, observation), 0.0)
# the order arrives today only when the lead time is zero,
# and then it leaves the pipeline
pipeline = jnp.concatenate([observation.pipeline, order[None]])
arrives_today = int(lead_time == 0)
inventory = observation.inventory + arrives_today * pipeline[0]
pipeline = pipeline[arrives_today:]
sales = jnp.minimum(inventory, demand_t)
lost_sales = demand_t - sales
inventory = inventory - sales
in_cost_window = (day >= lead_time) & (day < setup.horizon + lead_time)
daily_cost = jnp.where(
in_cost_window,
config.holding_cost * inventory + config.lost_sales_cost * lost_sales,
0.0,
)
demand_history = jnp.concatenate([state.demand_history[1:], demand_t[None]])
return DayResult(
state=InventoryState(inventory, pipeline, demand_history),
record=Simulation(daily_cost, order, inventory, lost_sales),
)
def fixed_plan(params: Float[Array, " horizon"], obs: Observation) -> Float[Array, ""]:
"""The order of a day is one number per ordering day."""
return params[obs.day]
def mean_demand_plan(lead_time: int) -> Float[Array, " horizon"]:
"""Mean demand of the training scenarios on the day on which each order arrives."""
demand = demand_by_set[ScenarioSet.TRAINING]
return demand[:, lead_time : lead_time + setup.horizon].mean(axis=0)
NUM_DEMO_DAYS = 5
plan = mean_demand_plan(LEAD_TIME_DETAIL)
path = demand_by_set[ScenarioSet.TRAINING][0]
def demo_day(
state: InventoryState, day: Int[Array, ""]
) -> tuple[InventoryState, tuple[Float[Array, ""], ...]]:
"""One demo day and its row of the table.
The row has the arrival, order, demand, lost sales, stock and cost of the day.
"""
# an empty pipeline, the case of lead time zero, contributes an arrival of zero
arrival = jnp.pad(state.pipeline, (0, 1))[0]
result = inventory_step(
fixed_plan, plan, state, path[day], None, day, config, LEAD_TIME_DETAIL
)
record = result.record
return result.state, (
arrival,
record.orders,
path[day],
record.lost_sales,
record.inventory,
record.daily_cost,
)
_, columns = jax.lax.scan(
demo_day, initial_state(LEAD_TIME_DETAIL), jnp.arange(NUM_DEMO_DAYS)
)
arrival, order, demand, lost_sales, stock, cost = columns
pl.DataFrame(
{
"day": (jnp.arange(NUM_DEMO_DAYS) + 1).tolist(),
"arrival": arrival.tolist(),
"order": order.tolist(),
"demand": demand.tolist(),
"lost sales": lost_sales.tolist(),
"stock at the end": stock.tolist(),
"cost": cost.tolist(),
}
)
| day | arrival | order | demand | lost sales | stock at the end | cost |
|---|---|---|---|---|---|---|
| i64 | f64 | f64 | f64 | f64 | f64 | f64 |
| 1 | 69.0 | 67.8 | 84.0 | 0.0 | 35.0 | 0.0 |
| 2 | 72.0 | 51.5 | 58.0 | 0.0 | 49.0 | 0.0 |
| 3 | 67.8 | 61.3 | 58.0 | 0.0 | 58.8 | 5.9 |
| 4 | 51.5 | 44.8 | 61.0 | 0.0 | 49.3 | 4.9 |
| 5 | 61.3 | 64.1 | 34.0 | 0.0 | 76.7 | 7.7 |
Let’s understand how to read this table by following the first scenario.
The order of day \(1\), \(67.8\) units, arrives on day \(3\), and the order of day \(2\) arrives on day \(4\).
On days \(1\) and \(2\) the arrivals come from the initial pipeline, and the cost is zero because these days are not in the cost window.
From day \(3\) on we pay the holding cost of \(0.1\) per unit left on the shelf at the end of the day. In this scenario no demand is lost in the first five days.
Next, the function simulate scans inventory_step over a demand path, and simulate_scenarios vectorizes it over the scenarios with jax.vmap. Both take a Scenarios tuple: the demand paths and the forecast of every day, or None. The function scenarios_for builds this tuple for a scenario set, a lead time and the forecast that a policy reads, which the ForecastSource enumeration names: none, the forecast of day one or the weekly forecast. It keeps the \(H + L\) days that we simulate for the lead time, and the forecast of that lead time.
class ForecastSource(StrEnum):
"""The forecast that a policy reads."""
NONE = "no forecast"
DAY_ONE = "day-one forecast"
WEEKLY = "weekly forecast"
class Scenarios(NamedTuple):
"""Demand paths and the forecast of every day of every path."""
demand: Float[Array, "*scenarios days"]
forecast: Forecast | None
def scenarios_for(
scenario_set: ScenarioSet,
lead_time: int,
source: ForecastSource,
day_one: Forecast = forecast_day_one,
) -> Scenarios:
"""The days that we simulate for a lead time, with the forecast of a source."""
num_days = setup.horizon + lead_time
demand = demand_by_set[scenario_set][:, :num_days]
# a fixed plan reads no forecast, and None is not an array a mask can select
if source == ForecastSource.NONE:
return Scenarios(demand, None)
column = setup.lead_times.index(lead_time)
# the day-one forecast is one path of levels, repeated for every scenario
shared = jax.tree.map(
lambda leaf: jnp.broadcast_to(
leaf[:num_days, column], (demand.shape[0], num_days)
),
day_one,
)
weekly = jax.tree.map(
lambda leaf: leaf[:, :num_days, column], forecast_by_set[scenario_set]
)
use_day_one = source == ForecastSource.DAY_ONE
forecast = jax.tree.map(lambda a, b: jnp.where(use_day_one, a, b), shared, weekly)
return Scenarios(demand, forecast)
def simulate(
policy: Policy,
params: PyTree,
scenario: Scenarios,
state: InventoryState,
config: InventoryConfig,
lead_time: int,
) -> Simulation:
"""Run a policy against one demand path from day one on."""
def step(
state: InventoryState,
inputs: tuple[Float[Array, ""], Forecast | None, Int[Array, ""]],
) -> tuple[InventoryState, Simulation]:
demand_t, forecast_t, day = inputs
# `jax.lax.scan` needs a pair: the carry and the output of the day
day_result = inventory_step(
policy, params, state, demand_t, forecast_t, day, config, lead_time
)
return day_result.state, day_result.record
days = jnp.arange(scenario.demand.shape[0])
_, simulation = jax.lax.scan(
step, state, (scenario.demand, scenario.forecast, days)
)
return simulation
def simulate_scenarios(
policy: Policy,
params: PyTree,
scenarios: Scenarios,
state: InventoryState,
config: InventoryConfig,
lead_time: int,
) -> Simulation:
"""Run a policy against a batch of demand paths from the same initial state."""
return jax.vmap(
lambda scenario: simulate(policy, params, scenario, state, config, lead_time)
)(scenarios)
simulate_scenarios_jit = jax.jit(
simulate_scenarios, static_argnames=("policy", "lead_time")
)
simulations_mean_plan = {
lead_time: simulate_scenarios_jit(
fixed_plan,
mean_demand_plan(lead_time),
scenarios_for(ScenarioSet.TRAINING, lead_time, ForecastSource.NONE),
initial_state(lead_time),
config,
lead_time,
)
for lead_time in setup.lead_times
}
{lead_time: sim.loss.shape for lead_time, sim in simulations_mean_plan.items()}
{0: (4000,), 1: (4000,), 2: (4000,), 3: (4000,)}
Every lead time has one loss for each of the \(4{,}000\) training scenarios. Given the orders that come out of the scan, we can write the dynamics of a whole path at once and compare them with the scan:
Arrivals. The order that arrives on day \(t\) is the initial pipeline for \(t \leq L\) and the order of day \(t - L\) afterwards.
Stock and lost sales. The stock available on day \(t\) is \(y_t = I_{t-1}\) plus the arrival, and the scan has to return \(I_t = (y_t - D_t)^{+}\) and \(U_t = (D_t - y_t)^{+}\).
We write small and scoped functions to better follow the process and dynamics.
def arriving_orders(
initial_pipeline: Float[Array, " lead_time"],
orders: Float[Array, "scenarios days"],
) -> Float[Array, "scenarios days"]:
"""The arrival of each day: the initial pipeline, then the order of day t - L."""
num_scenarios, num_days = orders.shape
pipeline = jnp.broadcast_to(
initial_pipeline, (num_scenarios, initial_pipeline.shape[0])
)
return jnp.concatenate([pipeline, orders], axis=1)[:, :num_days]
def carried_stock(
initial_inventory: float, ending_stock: Float[Array, "scenarios days"]
) -> Float[Array, "scenarios days"]:
"""Stock at the end of the previous day, with the initial stock on day one."""
opening = jnp.full((ending_stock.shape[0], 1), initial_inventory)
return jnp.concatenate([opening, ending_stock[:, :-1]], axis=1)
def stock_available(
carried: Float[Array, "scenarios days"], arrivals: Float[Array, "scenarios days"]
) -> Float[Array, "scenarios days"]:
"""Stock on hand after the arrival, before the demand."""
return carried + arrivals
def on_hand(
available: Float[Array, "scenarios days"], demand: Float[Array, "scenarios days"]
) -> Float[Array, "scenarios days"]:
"""Stock left after the sales, (y - D)+."""
return jnp.maximum(available - demand, 0.0)
def unmet_demand(
demand: Float[Array, "scenarios days"], available: Float[Array, "scenarios days"]
) -> Float[Array, "scenarios days"]:
"""Demand we do not serve, (D - y)+."""
return jnp.maximum(demand - available, 0.0)
for lead_time, simulation in simulations_mean_plan.items():
demand = scenarios_for(ScenarioSet.TRAINING, lead_time, ForecastSource.NONE).demand
available = stock_available(
carried_stock(config.initial_inventory, simulation.inventory),
arriving_orders(initial_state(lead_time).pipeline, simulation.orders),
)
assert jnp.allclose(simulation.inventory, on_hand(available, demand), atol=1e-3)
assert jnp.allclose(
simulation.lost_sales, unmet_demand(demand, available), atol=1e-3
)
The stock and the lost sales match for every lead time. Two more checks concern the days:
Cost window. The daily cost is \(h \, I_t + p \, U_t\) on the days \(L + 1, \dots, H + L\) and zero on the others.
Orders. There are no orders after day \(H\).
def cost_window(num_days: int, lead_time: int, horizon: int) -> Bool[Array, " days"]:
"""The indices of the days L + 1 through H + L."""
days = jnp.arange(num_days)
return (days >= lead_time) & (days < horizon + lead_time)
def inventory_cost(
inventory: Float[Array, "scenarios days"],
lost_sales: Float[Array, "scenarios days"],
holding_cost: float,
lost_sales_cost: float,
) -> Float[Array, "scenarios days"]:
"""Holding cost plus lost-sales cost on every day, before the window."""
return holding_cost * inventory + lost_sales_cost * lost_sales
def cost_inside_window(
cost: Float[Array, "scenarios days"], inside: Bool[Array, " days"]
) -> Float[Array, "scenarios days"]:
"""The cost on the days inside the window, and zero outside it."""
return jnp.where(inside, cost, 0.0)
def has_no_late_orders(
orders: Float[Array, "scenarios days"], horizon: int
) -> Bool[Array, ""]:
"""True when no scenario places an order after day H."""
return jnp.all(orders[:, horizon:] == 0.0)
for lead_time, simulation in simulations_mean_plan.items():
counted = cost_inside_window(
inventory_cost(
simulation.inventory,
simulation.lost_sales,
config.holding_cost,
config.lost_sales_cost,
),
cost_window(simulation.daily_cost.shape[-1], lead_time, setup.horizon),
)
assert jnp.allclose(simulation.daily_cost, counted, atol=1e-3)
assert has_no_late_orders(simulation.orders, setup.horizon)
The four checks pass for every lead time, which is good!
Policy Training
We train the fixed plan, the base-stock offsets and the neural policy with one function. First, we need its objective. As in the first post, we summarize the loss of a policy over the scenarios with two quantities:
Expected loss. The mean of the loss over the scenarios, the estimate of \(J(\theta)\).
Conditional value at risk (CVaR). The mean of the worst \(\alpha = 5\%\) of the scenario losses, the tail average. With \(N\) scenarios it is the mean of the \(k = \alpha N\) largest losses.
As an example, we compute both for the mean demand plans of the simulator checks. The training of the fixed plan starts from these plans.
ALPHA = 0.05 # tail probability of the CVaR
def tail_size(num_scenarios: int) -> int:
"""The integer k = ALPHA * N, static because top_k needs a Python integer."""
return max(1, round(ALPHA * num_scenarios))
def cvar(losses: Float[Array, " scenarios"]) -> Float[Array, ""]:
"""Mean of the k largest losses."""
worst, _ = jax.lax.top_k(losses, tail_size(losses.shape[0]))
return worst.mean()
# the expected loss and the CVaR of the mean demand plan of every lead time
mean_plan_scores = {
"expected loss": [
float(simulation.loss.mean()) for simulation in simulations_mean_plan.values()
],
f"CVaR of loss (worst {ALPHA:.0%})": [
float(cvar(simulation.loss)) for simulation in simulations_mean_plan.values()
],
}
fig, axes = plt.subplots(ncols=2, figsize=(12, 5), layout="constrained")
for ax, (score, values) in zip(axes, mean_plan_scores.items(), strict=True):
sns.barplot(
x=list(setup.lead_times),
y=values,
color=POLICY_COLORS[PolicyName.FIXED_PLAN],
errorbar=None,
ax=ax,
)
ax.bar_label(ax.containers[0], fmt="{:.0f}", padding=2)
ax.set(title=score, xlabel="lead time $L$ (days)")
fig.suptitle(
f"Mean Demand Plans ({ScenarioSet.TRAINING.title()})",
fontsize=18,
fontweight="bold",
);
At every lead time the CVaR of the mean demand plan is about \(2.8\) times its expected loss, so the worst \(5\%\) of the scenarios cost much more than the average one.
Before we train, we set up the bookkeeping, with the names and the colors of the Policies section. A TrainedPolicy holds a policy, its parameters and the forecast that it reads, and the function evaluate simulates it on a scenario set with that forecast. We keep the trained policies in a dictionary indexed by the lead time and the name of the policy. As a check, evaluate gives back the losses of the mean demand plans that we simulated above.
class TrainedPolicy(NamedTuple):
"""A policy with its parameters and the forecast that it reads."""
policy: Policy
params: PyTree
source: ForecastSource
def evaluate(
trained: TrainedPolicy,
scenario_set: ScenarioSet,
lead_time: int,
config: InventoryConfig = config,
) -> Simulation:
"""Simulate a trained policy on a scenario set with the forecast that it reads."""
return simulate_scenarios_jit(
trained.policy,
trained.params,
scenarios_for(scenario_set, lead_time, trained.source),
initial_state(lead_time),
config,
lead_time,
)
for lead_time, simulation in simulations_mean_plan.items():
mean_plan = TrainedPolicy(
fixed_plan, mean_demand_plan(lead_time), ForecastSource.NONE
)
assert jnp.allclose(
evaluate(mean_plan, ScenarioSet.TRAINING, lead_time).loss, simulation.loss
)
The objective of the training is the expected loss plus a tail weight \(\lambda \geq 0\) times the CVaR,
\[\min_\theta \; J(\theta) + \lambda \, \text{CVaR}_\alpha(C(\theta, D)).\]
We train with \(\lambda = 0\), the expected loss, everywhere except in the Tail Risk section.
The function train runs Adam from Optax on this objective, and the gradient with respect to the parameters of the policy comes from jax.grad through the simulator. Here are four remarks about this function:
Batches. The fixed plan and the base-stock offsets have \(15\) parameters each, and we train them on the full training set. The neural policy trains on random batches of scenarios.
Validation. Every \(100\) steps we evaluate the objective on a second set of scenarios, and we return the parameters with the lowest value on that set. For the neural policy this is the validation set, and for the other two we pass the training set again. The initial parameters are the first candidate, so the training cannot return a policy that is worse on that set than its starting point. The scan carries the current and the best parameters in a
TrainState.Projection. The orders of the fixed plan cannot be negative, so after every step we clip them at zero. The base-stock and neural policies clip the order inside the policy.
Seeds. The function is pure, so we can vectorize it over random keys with
jax.vmapand train from several seeds at once.
def objective(
losses: Float[Array, " scenarios"], tail_weight: ScalarLike
) -> Float[Array, ""]:
"""Expected loss plus the tail weight times the CVaR of the loss."""
return losses.mean() + tail_weight * cvar(losses)
class TrainConfig(NamedTuple):
"""Settings of one training run."""
num_steps: int
batch_size: int # a value at or above the number of scenarios means the full batch
learning_rate: float
eval_every: int = 100 # steps between two evaluations on the validation set
class TrainResult(NamedTuple):
"""Best parameters on the validation set and the validation objective."""
params: PyTree
validation: Float[Array, "*seeds evaluations"] # the first value is at the start
class TrainState(NamedTuple):
"""What the training carries from one step to the next."""
params: PyTree
opt_state: optax.OptState
best_params: PyTree # the parameters with the lowest validation objective so far
best_value: Float[Array, ""]
def train(
key: PRNGKeyArray,
policy: Policy,
params: PyTree,
scenarios_train: Scenarios,
scenarios_val: Scenarios,
state: InventoryState,
config: InventoryConfig,
lead_time: int,
tail_weight: ScalarLike,
train_config: TrainConfig,
project: Callable[[PyTree], PyTree] | None = None,
) -> TrainResult:
"""Adam on the objective through the simulator, best parameters on validation."""
schedule = optax.cosine_decay_schedule(
train_config.learning_rate, train_config.num_steps
)
optimizer = optax.adam(schedule)
num_train = scenarios_train.demand.shape[0]
def loss(params: PyTree, scenarios: Scenarios) -> Float[Array, ""]:
simulation = simulate_scenarios(
policy, params, scenarios, state, config, lead_time
)
return objective(simulation.loss, tail_weight)
def step(carry: TrainState, key_step: PRNGKeyArray) -> tuple[TrainState, None]:
"""One step of Adam on a batch, followed by the projection."""
# a batch at least as large as the training set uses every scenario, in order
size = min(train_config.batch_size, num_train)
index = (
jnp.arange(num_train)
if size == num_train
else random.choice(key_step, num_train, (size,), replace=False)
)
batch = jax.tree.map(lambda leaf: leaf[index], scenarios_train)
grads = jax.grad(loss)(carry.params, batch)
updates, opt_state = optimizer.update(grads, carry.opt_state, carry.params)
params = optax.apply_updates(carry.params, updates)
if project is not None:
params = project(params)
return carry._replace(params=params, opt_state=opt_state), None
def train_round(
carry: TrainState, keys: UInt32[Array, "steps 2"]
) -> tuple[TrainState, Float[Array, ""]]:
"""`eval_every` steps, then one evaluation on the validation set."""
carry, _ = jax.lax.scan(step, carry, keys)
value = loss(carry.params, scenarios_val)
improved = value < carry.best_value
best_params = jax.tree.map(
lambda new, old: jnp.where(improved, new, old),
carry.params,
carry.best_params,
)
carry = carry._replace(
best_params=best_params, best_value=jnp.minimum(value, carry.best_value)
)
return carry, value
num_evaluations = train_config.num_steps // train_config.eval_every
keys = random.split(key, (num_evaluations, train_config.eval_every))
value_start = loss(params, scenarios_val)
carry = TrainState(params, optimizer.init(params), params, value_start)
carry, values = jax.lax.scan(train_round, carry, keys)
return TrainResult(carry.best_params, jnp.concatenate([value_start[None], values]))
train_jit = jax.jit(
train, static_argnames=("policy", "lead_time", "train_config", "project")
)
# the settings of the first post: the full batch, 1,500 steps and a learning rate of 1
FULL_BATCH = TrainConfig(
num_steps=1_500,
batch_size=demand_by_set[ScenarioSet.TRAINING].shape[0],
learning_rate=1.0,
)
NO_KEY = random.PRNGKey(0) # a full batch uses no random numbers
Fixed Plan Training
Now we train the fixed plan for every lead time on the training set, from the mean demand plans. The figure shows how much the training lowers the expected loss on the training set: the expected loss of the mean demand plan minus the expected loss of the trained plan.
def clip_at_zero(params: Float[Array, " horizon"]) -> Float[Array, " horizon"]:
"""Projection of a plan onto the non-negative orders."""
return jnp.maximum(params, 0.0)
def train_fixed_plan(
lead_time: int, config: InventoryConfig, tail_weight: float = 0.0
) -> TrainedPolicy:
"""Train the fixed plan from the mean demand plan."""
scenarios = scenarios_for(ScenarioSet.TRAINING, lead_time, ForecastSource.NONE)
result = train_jit(
NO_KEY,
fixed_plan,
mean_demand_plan(lead_time),
scenarios,
scenarios, # 15 parameters: we keep the best iterate on the training set
initial_state(lead_time),
config,
lead_time=lead_time,
tail_weight=tail_weight,
train_config=FULL_BATCH,
project=clip_at_zero,
)
return TrainedPolicy(fixed_plan, result.params, ForecastSource.NONE)
policies: dict[tuple[int, PolicyName], TrainedPolicy] = {
(lead_time, PolicyName.FIXED_PLAN): train_fixed_plan(lead_time, config)
for lead_time in setup.lead_times
}
# the expected loss on the training set before minus after the training
training_gain = [
float(
simulations_mean_plan[lead_time].loss.mean()
- evaluate(
policies[lead_time, PolicyName.FIXED_PLAN], ScenarioSet.TRAINING, lead_time
).loss.mean()
)
for lead_time in setup.lead_times
]
fig, ax = plt.subplots(figsize=(10, 5))
sns.barplot(
x=list(setup.lead_times),
y=training_gain,
color=POLICY_COLORS[PolicyName.FIXED_PLAN],
errorbar=None,
ax=ax,
)
ax.bar_label(ax.containers[0], fmt="{:.1f}", padding=2)
ax.set(xlabel="lead time $L$ (days)", ylabel="decrease of the expected loss")
fig.suptitle(
f"Training of the Fixed Plan ({ScenarioSet.TRAINING.title()})",
fontsize=18,
fontweight="bold",
);
The training lowers the expected loss of the mean demand plan at every lead time, by \(12.4\) for \(L = 0\) and by \(4.7\) for \(L = 3\).
Base-Stock Training
The three base-stock policies share one function, base_stock: order up to the newsvendor level of the forecast in the observation plus the offset of the day. Base-stock (day-one forecast) has zero offsets, so we can build it without training.
def base_stock(params: Float[Array, " horizon"], obs: Observation) -> Float[Array, ""]:
"""Order up to the newsvendor level plus the offset of the day."""
return jax.nn.relu(obs.forecast.level + params[obs.day] - obs.position)
no_offsets = jnp.zeros(setup.horizon)
for lead_time in setup.lead_times:
policies[lead_time, PolicyName.DAY_ONE] = TrainedPolicy(
base_stock, no_offsets, ForecastSource.DAY_ONE
)
Recall from the Stock After Lost Sales section why the newsvendor levels are not the best levels when there is a lead time. For a positive order the stock available on day \(t + L\) is
\[y_{t+L} = \hat{q}_t - \sum_{s=t}^{t+L-1} (D_s - U_s),\]
so every sale that we lose before day \(t + L\) leaves one more unit for that day. For \(L = 0\) the sum is empty.
Let’s check this on the training set with Base-stock (day-one forecast). For every lead time we compare the shares of the days with two events: the demand of the covered days is above the level, and the policy runs out. We count a stockout only when the lost sales exceed \(10^{-3}\) units, since the orders of the solver are not whole numbers.
STOCKOUT_TOL = 1e-3 # lost sales below this are rounding noise of the solver
def stockouts(simulation: Simulation, lead_time: int) -> Bool[Array, "scenarios days"]:
"""The days of the cost window with lost sales above the tolerance."""
return simulation.lost_sales[:, lead_time:] > STOCKOUT_TOL
class Event(StrEnum):
"""Names of the two events of a day whose shares we compare."""
DEMAND_ABOVE = "demand of the covered days above the level"
RUNS_OUT = "the policy runs out"
def demand_exceeds_level(
covered: Float[Array, "scenarios days lead_times"],
level: Float[Array, "days lead_times"],
) -> Bool[Array, "scenarios days lead_times"]:
"""Whether the demand of days t through t + L is above the level of day t."""
return covered > level
def runs_out_only_if(
demand_above: Bool[Array, "scenarios days"],
runs_out: Bool[Array, "scenarios days"],
) -> Bool[Array, ""]:
"""A stockout happens only where the covered demand is above the level."""
return jnp.all(demand_above | ~runs_out)
def event_share(
lead_time: int, event: Event, happened: Bool[Array, "scenarios days"]
) -> dict[str, int | str | float]:
"""One bar: the share of days on which the event happens."""
return {
"lead time": lead_time,
"event": str(event),
"share": float(happened.mean()),
}
rows = []
# the stockouts of `Base-stock (day-one forecast)`, by lead time
runs_out_day_one: dict[int, Bool[Array, "scenarios days"]] = {}
covered_training = covered_demand(demand_by_set[ScenarioSet.TRAINING], setup.horizon)
above_level = demand_exceeds_level(
covered_training, forecast_day_one.level[: setup.horizon]
)
for column, lead_time in enumerate(setup.lead_times):
demand_above = above_level[..., column]
runs_out = stockouts(
evaluate(
policies[lead_time, PolicyName.DAY_ONE], ScenarioSet.TRAINING, lead_time
),
lead_time,
)
runs_out_day_one[lead_time] = runs_out
assert runs_out_only_if(demand_above, runs_out)
rows += [
event_share(lead_time, Event.DEMAND_ABOVE, demand_above),
event_share(lead_time, Event.RUNS_OUT, runs_out),
]
Let’s visualize the results.
fig, ax = plt.subplots(figsize=(10, 6))
sns.barplot(
data=pl.DataFrame(rows),
x="lead time",
y="share",
hue="event",
hue_order=list(Event),
palette={
Event.DEMAND_ABOVE: "black",
Event.RUNS_OUT: POLICY_COLORS[PolicyName.DAY_ONE],
},
errorbar=None,
ax=ax,
)
for container in ax.containers:
ax.bar_label(container, fmt="{:.1%}", fontsize=11, padding=2)
ax.get_legend().remove()
ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=1))
ax.set(xlabel="lead time $L$ (days)", ylabel="share of the days")
fig.legend(*ax.get_legend_handles_labels(), loc="outside lower center", ncol=2)
fig.suptitle(
f"Stockouts at the Newsvendor Levels ({ScenarioSet.TRAINING.title()})",
fontsize=18,
fontweight="bold",
);
For \(L = 0\) the two shares are the same, \(4.5\%\) of the days. This is a little below \(h / (p + h) = 4.8\%\), the share of the days that the fractile leaves above the level. The level is a quantile of \(4{,}000\) forecast paths and the training scenarios are another sample, so the coverage is not exact.
With a lead time the demand of the covered days is above the level about as often, on \(4.5\%\) to \(4.6\%\) of the days. The policy runs out less often than that, and the gap grows with the lead time: on \(4.0\%\), \(3.4\%\) and \(3.1\%\) of the days for \(L = 1, 2, 3\).
The two bars count different events. The black bar is the share of ordering days on which the demand of days \(t\) through \(t + L\) is above the level of day \(t\). The colored bar is the share of those days on which the shelf runs out on day \(t + L\), when the order of day \(t\) arrives.
With a lead time the black bar stays near \(4.5\%\). The colored bar is lower, and it falls as the lead time grows: \(4.0\%\), \(3.4\%\) and \(3.1\%\) for \(L = 1, 2, 3\).
A stockout on the arrival day can happen only when the covered demand is above the level. The assertion assert runs_out_only_if(demand_above, runs_out) confirms this on every day of the training set. The other way around does not hold. On some days the covered demand is above the level and the shelf still does not run out. Sales were lost before the order arrived, and a lost sale takes no unit off the shelf. Those units are still there on day \(t + L\). The level had counted them as sold. The shelf holds more than the level counted on, so it runs out less often than the \(4.8\%\) the costs call for. A lower level can cost less.
There is a second reason to lower the level. Take a day \(t + L\) on which we run out, and suppose that one more unit had been on the shelf. We would have sold it and saved the margin \(p\). The rule orders this unit again on day \(t + L + 1\), so it is back on the shelf on day \(t + 2L + 1\), and on the \(L\) days in between it is missing. Call such a unit a missing unit.
On a later day a missing unit does one of two things. If we run out again, the unit would have saved a sale, worth the margin \(p\). If stock is left over, the unit would have sat on the shelf and cost the holding cost \(h\). Let \(\omega\) be the share of these days on which we run out again. The expected cost of the missing unit on that day is
\[p \, \omega - h \, (1 - \omega).\]
This cost is positive when \(\omega\) is above \(h / (p + h) = 4.8\%\). The sale that the extra unit saves is worth \(p\) minus the sum of this cost over the \(L\) days. So when \(\omega\) is above \(4.8\%\), a lost sale costs less than the margin the newsvendor level uses, and the best level is lower than that level.
Let’s measure how often Base-stock (day-one forecast) runs out on each of the \(L\) days after a stockout.
def sequential_colors(num: int) -> list[tuple[float, ...]]:
"""`num` colors of the viridis palette for an ordered variable, light to dark."""
return [plt.colormaps["viridis_r"](0.9 * k / max(num - 1, 1)) for k in range(num)]
# one color per lead time
LEAD_TIME_COLORS = dict(
zip(setup.lead_times, sequential_colors(len(setup.lead_times)), strict=True)
)
fig, ax = plt.subplots(figsize=(10, 5.5))
positive_lead_times = [lead_time for lead_time in setup.lead_times if lead_time > 0]
for lead_time in positive_lead_times:
runs_out = runs_out_day_one[lead_time]
days_after = list(range(1, lead_time + 1))
# the share of the stockouts with another stockout `lag` days later
runs_out_again = [
float((runs_out[:, :-lag] & runs_out[:, lag:]).sum() / runs_out[:, :-lag].sum())
for lag in days_after
]
assert all(share > target_share for share in runs_out_again)
ax.plot(
days_after,
runs_out_again,
"o-",
color=LEAD_TIME_COLORS[lead_time],
label=f"lead time $L = {lead_time}$",
)
ax.axhline(target_share, color="black", linestyle="--", label="$h / (p + h)$")
ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))
ax.set(
xticks=range(1, max(setup.lead_times) + 1),
xlabel="days after a stockout",
ylabel="share of the days with a stockout",
ylim=(0, None),
)
fig.legend(loc="outside lower center", ncol=4)
fig.suptitle(
f"Stockouts After a Stockout ({ScenarioSet.TRAINING.title()})",
fontsize=18,
fontweight="bold",
);
The day after a stockout the policy runs out again in \(17\%\), \(23\%\) and \(29\%\) of the cases for \(L = 1, 2, 3\). The share falls on the days after it and stays above \(4.8\%\) on each of the next \(L\) days.
In other words, the stockouts come in runs. This is consistent with two causes: a day on which we sell everything leaves less stock for the next days, and a scenario with high demand keeps its high demand for the whole horizon.
So the net cost of a lost sale is below \(p\), and the best level runs out more often than \(h / (p + h)\). We see in the Stock and Stockouts section that the trained policies do. Both effects can lower the best level below the newsvendor level, as in the experiments of Huh et al. (2009).
Next, we train one offset per day for the levels of each forecast. Before each training, the assertion checks that with zero offsets every ordering day has a positive order in more than half of the training scenarios, so every offset has a gradient at the start.
def train_base_stock(
lead_time: int,
config: InventoryConfig,
source: ForecastSource,
tail_weight: float = 0.0,
day_one: Forecast = forecast_day_one,
) -> TrainedPolicy:
"""Train the offsets of the base-stock policy from zero."""
scenarios = scenarios_for(ScenarioSet.TRAINING, lead_time, source, day_one)
result = train_jit(
NO_KEY,
base_stock,
jnp.zeros(setup.horizon),
scenarios,
scenarios, # 15 parameters: we keep the best iterate on the training set
initial_state(lead_time),
config,
lead_time=lead_time,
tail_weight=tail_weight,
train_config=FULL_BATCH,
)
return TrainedPolicy(base_stock, result.params, source)
# the forecast that each trained base-stock policy reads
TRAINED_BASE_STOCK = {
PolicyName.DAY_ONE_TRAINED: ForecastSource.DAY_ONE,
PolicyName.WEEKLY_TRAINED: ForecastSource.WEEKLY,
}
for lead_time in setup.lead_times:
for name, source in TRAINED_BASE_STOCK.items():
# with zero offsets every ordering day has a positive order in more than half
# of the training scenarios, so every offset has a gradient at the start
orders_start = evaluate(
TrainedPolicy(base_stock, no_offsets, source),
ScenarioSet.TRAINING,
lead_time,
).orders[:, : setup.horizon]
assert float((orders_start > 0).mean(axis=0).min()) > 0.5
policies[lead_time, name] = train_base_stock(lead_time, config, source)
Next, we look at the trained offsets. The figure shows the offset of every ordering day for the two trained base-stock policies, with one line per lead time.
fig, axes = plt.subplots(
nrows=2, figsize=(12, 9), sharex=True, sharey=True, layout="constrained"
)
for ax, name in zip(axes, TRAINED_BASE_STOCK, strict=True):
for lead_time, color in LEAD_TIME_COLORS.items():
ax.plot(
ordering_days,
policies[lead_time, name].params,
"o-",
color=color,
label=f"lead time $L = {lead_time}$",
)
ax.axhline(0.0, color="black", linestyle="--")
shade_promotion(ax)
ax.set(title=name, ylabel="trained offset (units)", xticks=ordering_days)
axes[-1].set(xlabel="ordering day")
fig.legend(*axes[0].get_legend_handles_labels(), loc="outside lower center", ncol=5)
fig.suptitle(
"Trained Offsets of the Base-Stock Policies", fontsize=18, fontweight="bold"
);
The offsets stay near zero without a lead time and are at or below zero with one, for both forecasts.
No lead time. For \(L = 0\) the offsets stay within \(3\) units of zero. Without a lead time we can order up to the level of the day on every day. As long as the stock left over is below that level, the days are separate single-day problems, and the newsvendor levels already solve them. Recall that in the first post the myopic newsvendor plan cost \(11\%\) more than the expected cost plan. A plan cannot react to the stock left over and a policy can, which is why the same rule works here.
Positive lead time. For \(L \geq 1\) the offsets are at or below zero on every ordering day, and their size grows with the lead time. With the day-one levels the lowest offsets are \(-11\), \(-24\) and \(-38\) units for \(L = 1, 2, 3\), on days whose orders cover promotion days.
Weekly forecast. The two trained policies share the levels of the first week, and up to day \(3\) they have the same offsets. From day \(8\) on the offsets of the weekly levels are smaller in size on most days. Their lowest values are \(-9\), \(-22\) and \(-31\) units, on days \(8\) to \(10\). The updated forecast is less uncertain, so its high quantile is already lower, and the offset has less to subtract.
This supports the observation of the Offset Definition section. The levels cover the demand about as often as the forecast says at every lead time, the offsets stay near zero without a lead time, and they are at or below zero with one. So the offsets do not repair the forecast. They correct what the base-stock rule does with its levels when the sales are lost and the orders take time.
Neural Training
Recall from the Neural section why we let the offset depend on the observation. The base-stock policy sees the stock on hand and the pipeline only through their sum, and its levels change only when the forecast is updated, on day \(8\).
The neural policy adds a correction to the level of Base-stock (weekly forecast, trained). A multilayer perceptron with two hidden layers of \(32\) units computes the correction. We build it with Flax NNX as the module MLP. Its last layer starts with zero weights and a zero bias, so a new network returns a correction of zero. Let’s check this on a network with five inputs.
DEMAND_SCALE = float(data.mean()) # mean daily demand of the history
HIDDEN_UNITS = 32
class MLP(nnx.Module):
"""Multilayer perceptron with two hidden layers and GELU activations."""
def __init__(self, num_features: int, rngs: nnx.Rngs) -> None:
self.hidden_1 = nnx.Linear(num_features, HIDDEN_UNITS, rngs=rngs)
self.hidden_2 = nnx.Linear(HIDDEN_UNITS, HIDDEN_UNITS, rngs=rngs)
# zero weights and bias: the network starts with no correction
self.output = nnx.Linear(
HIDDEN_UNITS, 1, kernel_init=nnx.initializers.zeros, rngs=rngs
)
def __call__(self, x: Float[Array, " features"]) -> Float[Array, "1"]:
x = nnx.gelu(self.hidden_1(x))
x = nnx.gelu(self.hidden_2(x))
return self.output(x)
N_FEATURES = 5
network_example = MLP(N_FEATURES, nnx.Rngs(0))
rng_key, key_example = random.split(rng_key)
{
"parameters": sum(
leaf.size for leaf in jax.tree.leaves(nnx.state(network_example, nnx.Param))
),
"output": network_example(random.normal(key_example, (N_FEATURES,)))[0],
}
{'parameters': 1281, 'output': Array(0., dtype=float32)}
A network with \(5\) inputs has \(1{,}281\) weights and biases, and it returns zero, as it should. The network of the policy reads the following features of the observation:
Stock. The stock on hand and each order in the pipeline, divided by the mean daily demand \(\bar{d}\) of the history. Recall that \(\bar{d}\) brings the inputs and the output of the network to numbers of order one.
Promotion. The promotion flags of the days \(t, \dots, t + L\).
Day. The day index \(t - 1\) divided by \(H\).
Forecast. The newsvendor level and the mean of the total demand of the days \(t, \dots, t + L\) under the latest weekly forecast, divided by \(\bar{d}\).
Demand history. The demand of the last \(K = 7\) days, divided by \(\bar{d}\). On days \(1\) and \(8\) all of these days are in the forecast, and on the other days some of them are not.
The policy keeps its own copy of the offsets, in units of \(\bar{d}\), and trains them together with the network. The function nnx.split separates a network into its graph definition, the structure of the layers, and its state, the weights and the biases. The state is a PyTree, so the trainer updates it like the offsets, and the policy puts it back into the network with nnx.merge.
The function make_neural_policy returns the policy, the correction, and a function init that returns the state of a new network for a random key. Let’s build the policy for \(L = 2\) and check that the correction of a new network is zero on the first day of a test scenario.
class NeuralPolicy(NamedTuple):
"""A neural base-stock policy for one lead time."""
policy: Policy
# what the network adds to the base-stock level of the day, in units
correction: Callable[[PyTree, Observation], Float[Array, ""]]
# the state of a new network, its weights and biases, for a random key
init: Callable[[PRNGKeyArray], nnx.State]
num_features: int
def make_neural_policy(lead_time: int) -> NeuralPolicy:
"""Trained base-stock levels plus a network that reads the observation."""
def features(obs: Observation) -> Float[Array, " features"]:
stock = jnp.concatenate(
[obs.inventory[None] / DEMAND_SCALE, obs.pipeline / DEMAND_SCALE]
)
# promotion flags of the days t, ..., t + lead_time
promotions = jax.lax.dynamic_slice(promo_future, (obs.day,), (lead_time + 1,))
day = (obs.day / setup.horizon)[None]
forecast = jnp.stack([obs.forecast.level, obs.forecast.mean])
return jnp.concatenate(
[
stock,
promotions,
day,
forecast / DEMAND_SCALE,
obs.demand_history / DEMAND_SCALE,
]
)
# the number of features, from the observation of day one with any forecast
forecast_shape = Forecast(jnp.asarray(0.0), jnp.asarray(0.0))
observation = observe(
initial_state(lead_time), jnp.asarray(0), forecast_shape, lead_time
)
num_features = features(observation).shape[0]
# the structure of the network, without its weights and biases
graphdef, _ = nnx.split(MLP(num_features, nnx.Rngs(0)))
def init(key: PRNGKeyArray) -> nnx.State:
_, state = nnx.split(MLP(num_features, nnx.Rngs(key)))
return state
def correction(params: PyTree, obs: Observation) -> Float[Array, ""]:
network = nnx.merge(graphdef, params["net"])
return DEMAND_SCALE * network(features(obs))[0]
def policy(params: PyTree, obs: Observation) -> Float[Array, ""]:
offset = DEMAND_SCALE * params["offsets"][obs.day]
level = obs.forecast.level + offset + correction(params, obs)
return jax.nn.relu(level - obs.position)
return NeuralPolicy(policy, correction, init, num_features)
neural_example = make_neural_policy(LEAD_TIME_DETAIL)
scenarios_example = scenarios_for(
ScenarioSet.FORECAST, LEAD_TIME_DETAIL, ForecastSource.WEEKLY
)
observation_example = observe(
initial_state(LEAD_TIME_DETAIL),
jnp.asarray(0),
jax.tree.map(lambda leaf: leaf[0, 0], scenarios_example.forecast),
LEAD_TIME_DETAIL,
)
rng_key, key_example = random.split(rng_key)
params_example = {
"offsets": jnp.zeros(setup.horizon),
"net": neural_example.init(key_example),
}
{
"features": neural_example.num_features,
"correction": float(neural_example.correction(params_example, observation_example)),
}
{'features': 15, 'correction': 0.0}
For \(L = 2\) the network reads \(15\) features, \(1 + 1 + 3 + 1 + 2 + 7\) in the order of the list above, and a new network adds nothing to the level.
The function train_neural trains the neural policy of one lead time from three seeds at once, with jax.vmap over the seeds. Every seed starts from the trained offsets of Base-stock (weekly forecast, trained) and from a new network. It trains on random batches and keeps the seed with the lowest validation loss.
MINIBATCH = TrainConfig(num_steps=3_000, batch_size=256, learning_rate=3e-3)
NUM_SEEDS = 3
class NeuralTraining(NamedTuple):
"""The neural policy of the best seed and the validation loss of every seed."""
trained: TrainedPolicy
validation: Float[Array, "seeds evaluations"]
def train_neural(
key: PRNGKeyArray,
lead_time: int,
config: InventoryConfig,
offsets: Float[Array, " horizon"],
) -> NeuralTraining:
"""Train the neural policy from several seeds and keep the best on validation."""
neural = make_neural_policy(lead_time)
scenarios = (
scenarios_for(ScenarioSet.TRAINING, lead_time, ForecastSource.WEEKLY),
scenarios_for(ScenarioSet.VALIDATION, lead_time, ForecastSource.WEEKLY),
)
state = initial_state(lead_time)
key_init, key_train = random.split(key)
# one new network per seed, all with the same offsets
params = jax.vmap(
lambda key_seed: {
"offsets": offsets / DEMAND_SCALE,
"net": neural.init(key_seed),
}
)(random.split(key_init, NUM_SEEDS))
train_seeds = jax.jit(
jax.vmap(
lambda key_seed, params_seed: train(
key_seed,
neural.policy,
params_seed,
*scenarios,
state,
config,
lead_time,
0.0, # tail weight: we train the network for the expected loss
MINIBATCH,
)
)
)
result = train_seeds(random.split(key_train, NUM_SEEDS), params)
best_seed = int(result.validation.min(axis=1).argmin())
best_params = jax.tree.map(lambda leaf: leaf[best_seed], result.params)
return NeuralTraining(
TrainedPolicy(neural.policy, best_params, ForecastSource.WEEKLY),
result.validation,
)
We train the neural policy for every lead time. The assertions check that before the first step every seed is Base-stock (weekly forecast, trained): its validation loss is the validation loss of that policy.
%%time
validation: dict[int, Float[Array, "seeds evaluations"]] = {}
for lead_time in setup.lead_times:
rng_key, key_neural = random.split(rng_key)
policies[lead_time, PolicyName.NEURAL], validation[lead_time] = train_neural(
key_neural,
lead_time,
config,
policies[lead_time, PolicyName.WEEKLY_TRAINED].params,
)
loss_base_stock = evaluate(
policies[lead_time, PolicyName.WEEKLY_TRAINED],
ScenarioSet.VALIDATION,
lead_time,
).loss.mean()
assert jnp.allclose(validation[lead_time][:, 0], loss_base_stock, atol=0.01)
CPU times: user 5min 29s, sys: 2min 51s, total: 8min 20s
Wall time: 1min 13s
Let’s look at the expected loss on the validation set during the training. Every line is one seed, and the dashed line is the validation loss of Base-stock (weekly forecast, trained), where every seed starts.
evaluation_steps = MINIBATCH.eval_every * jnp.arange(
MINIBATCH.num_steps // MINIBATCH.eval_every + 1
)
fig, axes = plt.subplots(
nrows=2, ncols=2, figsize=(13, 8), sharex=True, layout="constrained"
)
for ax, lead_time in zip(axes.flat, setup.lead_times, strict=True):
lines = ax.plot(
evaluation_steps,
validation[lead_time].T,
color=POLICY_COLORS[PolicyName.NEURAL],
)
lines[0].set_label(PolicyName.NEURAL)
ax.axhline(
float(validation[lead_time][0, 0]),
color=POLICY_COLORS[PolicyName.WEEKLY_TRAINED],
linestyle="--",
label=PolicyName.WEEKLY_TRAINED,
)
ax.set(title=f"lead time $L = {lead_time}$")
for ax in axes[-1]:
ax.set(xlabel="training step")
fig.supylabel(
"expected loss on the validation set", fontsize=plt.rcParams["axes.labelsize"]
)
fig.legend(*axes[0, 0].get_legend_handles_labels(), loc="outside lower center", ncol=2)
fig.suptitle("Validation Loss of the Neural Policy", fontsize=18, fontweight="bold");
Let’s look at the curves by lead time.
No lead time. For \(L = 0\) the validation loss stays within \(0.7\) of its start, and the three seeds end a little below it. The base-stock policy leaves little to correct here.
Positive lead time. For \(L \geq 1\) more than half of the fall comes in the first \(500\) steps, and the curves are noisy after that. For example, one seed for \(L = 2\) jumps up by about \(0.7\) at step \(1{,}300\) and is back down at step \(1{,}400\). The best values are about \(0.9\), \(2.8\) and \(3.8\) below the start for \(L = 1, 2, 3\), and the three seeds end within about \(0.2\) of each other.
These gains are small next to the losses themselves, which are between \(68\) and \(125\). We measure them on the test sets in the Out of Sample Evaluation section.
Before we move on, we check on a trained policy that it does not use the demand of the day on which it orders. Recall from the forecast check that \(50\) more units of demand from day \(8\) on leave the weekly forecast of a scenario as it is. We add these units to every validation scenario. The orders of the neural policy for \(L = 2\) must be the same up to and including day \(8\), and differ on day \(9\).
scenarios_original = scenarios_for(
ScenarioSet.VALIDATION, LEAD_TIME_DETAIL, ForecastSource.WEEKLY
)
scenarios_changed = scenarios_original._replace(
demand=scenarios_original.demand.at[:, CHANGED_FROM:].add(50.0)
)
orders_original = evaluate(
policies[LEAD_TIME_DETAIL, PolicyName.NEURAL],
ScenarioSet.VALIDATION,
LEAD_TIME_DETAIL,
).orders
orders_changed = simulate_scenarios_jit(
*policies[LEAD_TIME_DETAIL, PolicyName.NEURAL][:2],
scenarios_changed,
initial_state(LEAD_TIME_DETAIL),
config,
LEAD_TIME_DETAIL,
).orders
assert jnp.array_equal(
orders_original[:, : CHANGED_FROM + 1], orders_changed[:, : CHANGED_FROM + 1]
)
assert not jnp.array_equal(
orders_original[:, CHANGED_FROM + 1], orders_changed[:, CHANGED_FROM + 1]
)
The orders are the same up to the day of the change and differ on the day after it, as expected.
Now that we have trained all the policies, let’s score them on the test sets.
Out of Sample Evaluation
We score every policy on the two test sets, on all \(3{,}000\) scenarios of each. We also simulate the policies on the training set, to see how much of a gain is left on new scenarios. We record five scores. The stockout scores count only the days of the cost window, with the tolerance of the Base-Stock Training section.
Expected loss. The mean of the loss over the scenarios.
CVaR of the loss. The mean of the worst \(5\%\) of the scenario losses. We look at it in the Tail Risk section.
Stockout probability per day. The fraction of scenario and day pairs with a lost sale.
Probability of a stockout in the cost window. The fraction of scenarios with at least one lost sale.
Units ordered. The mean over the scenarios of the sum of the orders.
The function summarize computes them for one policy on one scenario set. We run every policy on the three sets and collect the scores in the data frame results.
class Metric(StrEnum):
"""Names of the scores."""
EXPECTED_LOSS = "expected loss"
CVAR = f"CVaR of loss (worst {ALPHA:.0%})"
STOCKOUT = "stockout probability per day"
WINDOW = "probability of a stockout in the cost window"
ORDERED = "units ordered"
def summarize(simulation: Simulation, lead_time: int) -> dict[Metric, float]:
"""Scores of one policy over a set of scenarios."""
stockout = stockouts(simulation, lead_time)
return {
Metric.EXPECTED_LOSS: float(simulation.loss.mean()),
Metric.CVAR: float(cvar(simulation.loss)),
Metric.STOCKOUT: float(stockout.mean()),
Metric.WINDOW: float(stockout.any(axis=1).mean()),
Metric.ORDERED: float(simulation.orders.sum(axis=1).mean()),
}
EVALUATION_SETS = [ScenarioSet.TRAINING, *TEST_SETS]
simulations: dict[tuple[ScenarioSet, int, PolicyName], Simulation] = {
(scenario_set, lead_time, name): evaluate(trained, scenario_set, lead_time)
for scenario_set in EVALUATION_SETS
for (lead_time, name), trained in policies.items()
}
results = pl.DataFrame(
[
{
"scenario set": str(scenario_set),
"lead time": lead_time,
"policy": str(name),
**summarize(simulation, lead_time),
}
for (scenario_set, lead_time, name), simulation in simulations.items()
]
)
Expected Loss
Let’s start with the first question: how much of the expected loss of the fixed plan do we remove when the order of each day depends on the stock? The next figure shows the expected loss of the five policies on each test set, by lead time.
fig, axes = plt.subplots(
nrows=2, figsize=(13, 10), sharex=True, sharey=True, layout="constrained"
)
for ax, test_set in zip(axes, TEST_SETS, strict=True):
sns.barplot(
data=results.filter(pl.col("scenario set") == test_set),
x="lead time",
y=Metric.EXPECTED_LOSS,
hue="policy",
hue_order=list(PolicyName),
palette=POLICY_COLORS,
ax=ax,
)
for container in ax.containers:
ax.bar_label(container, fmt="{:.0f}", fontsize=11, padding=2)
ax.get_legend().remove()
ax.set(title=test_set.capitalize(), xlabel="", ylabel=Metric.EXPECTED_LOSS)
axes[-1].set(xlabel="lead time $L$ (days)")
fig.legend(*axes[0].get_legend_handles_labels(), loc="outside lower center", ncol=3)
fig.suptitle("Expected Loss by Policy and Lead Time", fontsize=18, fontweight="bold");
On the forecast test set, at every lead time the expected loss falls, or stays about the same, from one policy to the next, in the order in which we introduced them. The largest step is the first one: with no lead time the base-stock policy at the newsvendor levels has about half of the loss of the fixed plan, and it needs no optimizer. On the true process test set the order is the same, except at \(L = 3\), where Base-stock (weekly forecast, trained) is about \(1\) above Base-stock (day-one forecast, trained).
Here is the answer to question \(1\) from the introduction. How much of the expected loss of the fixed plan do we remove when the order of each day depends on the stock that we observe? With no lead time, a policy that looks at the stock removes about half of the expected loss of the fixed plan, on both test sets. With a lead time it removes less, and less with every extra day. With trained day-one levels the reduction is \(51\%\), \(37\%\), \(29\%\) and \(23\%\) for \(L = 0, 1, 2, 3\) on the forecast test set, and about \(49\%\), \(34\%\), \(26\%\) and \(21\%\) on the true process test set. These numbers are for our costs, and the Cost Ratio section repeats the comparison for other costs.
Recall from the Cost Window section that the cost window moves with the lead time. So we check that this trend is not an effect of the window. On the days \(4\) to \(15\), which are in the cost window of every lead time, the reduction must also fall with every extra day of lead time, on both test sets.
# the days that are in the cost window of every lead time
COMMON_DAYS = slice(max(setup.lead_times), setup.horizon)
def common_loss(
scenario_set: ScenarioSet, lead_time: int, name: PolicyName
) -> Float[Array, ""]:
"""Expected cost of a policy on the days in the cost window of every lead time."""
daily_cost = simulations[scenario_set, lead_time, name].daily_cost
return daily_cost[:, COMMON_DAYS].sum(axis=1).mean()
for test_set in TEST_SETS:
reduction = [
1
- common_loss(test_set, lead_time, PolicyName.DAY_ONE_TRAINED)
/ common_loss(test_set, lead_time, PolicyName.FIXED_PLAN)
for lead_time in setup.lead_times
]
assert all(shorter > longer for shorter, longer in pairwise(reduction))
The assertion passes, so the trend holds on a common set of days.
With the newsvendor levels the reduction falls faster, to \(18\%\) on the forecast test set and \(3\%\) on the true process test set at \(L = 3\). Recall from the Base-Stock Training section that with a lead time the policy has more stock than these levels assume, and the true process, which has less demand than the center of the forecast, makes this worse. So the trained policy on the forecast test set is the better measure of what the lead time costs.
The lead time matters because an order answers to what we observe today and arrives \(L\) days later. The longer the lead time, the more days of demand an order has to cover without seeing them. Goldberg et al. (2016) study the limit of a very long lead time with stationary demand, and show that a constant order is then close to optimal:
The main insight of our work is that when the lead time is very large, such a significant amount of randomness is injected into the system between when an order for more inventory is placed and when that order is received, that “being smart” algorithmically provides almost no benefit.
Our lead times are short and our demand has a promotion, so we are far from that limit. Still, the reduction moves in the same direction.
Paired Differences
The three trained policies have expected losses within a few percent of each other, and each loss is an average over \(3{,}000\) scenarios with its own Monte Carlo error. The policies run on the same scenarios, so for each pair of policies we take the difference of the two losses in every scenario. The mean of these differences, the expected gain of a step, equals the difference of the two expected losses. Its Monte Carlo error is much smaller than if the policies ran on separate scenarios, because the two losses of a scenario move together.
We show each expected gain with its \(50\%\) and \(94\%\) equal-tailed intervals, the same interval kinds as in the rest of the notebook. They come from a normal approximation of the Monte Carlo error of the mean, which is accurate for a mean over thousands of scenarios. These intervals are about the mean. The gain in a single scenario varies much more. The training set has \(5\) scenarios per posterior draw, which are not independent, so there we average the scenarios of a draw before we compute the error.
The function mean_difference computes the mean of a difference over the scenarios and its standard error, and it returns them as an Estimate.
class Estimate(NamedTuple):
"""Mean of a paired difference and its Monte Carlo standard error."""
mean: float
std_error: float
def interval(self, prob: float) -> tuple[float, float]:
"""Equal-tailed interval of the mean, from a normal approximation."""
half_width = float(norm.ppf((1 + prob) / 2)) * self.std_error
return self.mean - half_width, self.mean + half_width
def sign(self) -> int:
"""Sign of the mean, or zero when its 94% interval includes zero."""
lower, upper = self.interval(CI_PROB)
return int(lower > 0) - int(upper < 0)
def mean_difference(
difference: Float[Array, " scenarios"], num_paths: int = 1
) -> Estimate:
"""Mean and Monte Carlo standard error of a difference over scenarios.
With `num_paths` scenarios per posterior draw we average the scenarios of a
draw first, since they are not independent.
"""
by_draw = difference.reshape(num_paths, -1).mean(axis=0)
return Estimate(
float(by_draw.mean()), float(by_draw.std() / jnp.sqrt(by_draw.shape[0]))
)
Next, we define the steps that we compare. A step goes from one of the five policies to the next one. Its expected gain is the expected loss before the step minus the expected loss after it, so a positive value means that the step lowers the expected loss. We look at three steps:
Trained offsets. From
Base-stock (day-one forecast)toBase-stock (day-one forecast, trained).Weekly forecast. From
Base-stock (day-one forecast, trained)toBase-stock (weekly forecast, trained).Network. From
Base-stock (weekly forecast, trained)toNeural.
The function expected_gains computes the expected gain of a step on the three scenario sets, for every lead time. Let’s start with the trained offsets.
class Step(StrEnum):
"""Names of the steps that we compare."""
OFFSETS = "Trained offsets"
WEEKLY = "Weekly forecast"
WEEKLY_NO_OFFSETS = "Weekly forecast without offsets"
NETWORK = "Network"
# the two policies of each of the three steps
STEP_PAIRS = {
Step.OFFSETS: (PolicyName.DAY_ONE, PolicyName.DAY_ONE_TRAINED),
Step.WEEKLY: (PolicyName.DAY_ONE_TRAINED, PolicyName.WEEKLY_TRAINED),
Step.NETWORK: (PolicyName.WEEKLY_TRAINED, PolicyName.NEURAL),
}
type Losses = dict[ScenarioSet, list[Float[Array, " scenarios"]]]
type Gains = dict[ScenarioSet, list[Estimate]]
def policy_losses(name: PolicyName) -> Losses:
"""Scenario losses of a policy, by scenario set and lead time."""
return {
scenario_set: [
simulations[scenario_set, lead_time, name].loss
for lead_time in setup.lead_times
]
for scenario_set in EVALUATION_SETS
}
def expected_gains(before: Losses, after: Losses) -> Gains:
"""Expected loss of `before` minus `after`, by scenario set and lead time."""
return {
scenario_set: [
mean_difference(
first - second,
PATHS_PER_DRAW if scenario_set == ScenarioSet.TRAINING else 1,
)
for first, second in zip(
before[scenario_set], after[scenario_set], strict=True
)
]
for scenario_set in EVALUATION_SETS
}
first, second = STEP_PAIRS[Step.OFFSETS]
gains_offsets = expected_gains(policy_losses(first), policy_losses(second))
For every step the assertions check the signs that the answers below rest on. The function signs returns the sign of every expected gain, with zero when its \(94\%\) interval includes zero. The function common_gains computes the gain of a step on the days that are in the cost window of every lead time, so that we can check a trend over the lead times on the same days.
def signs(estimates: list[Estimate]) -> list[int]:
"""Sign of every expected gain, zero when its 94% interval includes zero."""
return [estimate.sign() for estimate in estimates]
def common_gains(step: Step) -> list[Float[Array, ""]]:
"""Gain of a step on the forecast test set, on the days of every cost window."""
first, second = STEP_PAIRS[step]
return [
common_loss(ScenarioSet.FORECAST, lead_time, first)
- common_loss(ScenarioSet.FORECAST, lead_time, second)
for lead_time in setup.lead_times
]
ALL_POSITIVE = [1] * len(setup.lead_times)
# on the forecast test set the interval includes zero without a lead time and lies
# above zero with one
assert signs(gains_offsets[ScenarioSet.FORECAST]) == [0, *ALL_POSITIVE[1:]]
# the gain grows with the lead time, also on the days in every cost window
assert all(shorter < longer for shorter, longer in pairwise(common_gains(Step.OFFSETS)))
The function plot_expected_gains draws the expected gains of a step as a forest plot, with one row per lead time and one color per scenario set.
# the forecast test set in the color of its forecast, and the true process as before
SET_COLORS = {
ScenarioSet.TRAINING: "C8",
ScenarioSet.FORECAST: POLICY_COLORS[PolicyName.DAY_ONE],
ScenarioSet.TRUE_PROCESS: "C7",
}
GAIN = "gain"
LEAD_TIME = "lead time"
LEAD_TIMES = [f"L = {lead_time}" for lead_time in setup.lead_times]
def plot_expected_gains(step: Step, gains: Gains) -> None:
"""Forest plot of the expected gains of a step with their 50% and 94% intervals.
One row per lead time and one color per scenario set.
"""
def intervals(prob: float) -> xr.Dataset:
bounds = [
[estimate.interval(prob) for estimate in estimates]
for estimates in gains.values()
]
return xr.Dataset(
{GAIN: (("model", LEAD_TIME, "ci_bound"), bounds)},
coords={
"model": list(gains),
LEAD_TIME: LEAD_TIMES,
"ci_bound": ["lower", "upper"],
},
)
# the mean as the only draw of each scenario set, and the intervals as statistics
means = {
str(scenario_set): xr.Dataset(
{
GAIN: (
("sample", LEAD_TIME),
[[estimate.mean for estimate in estimates]],
)
},
coords={LEAD_TIME: LEAD_TIMES},
)
for scenario_set, estimates in gains.items()
}
pc = az.plot_forest(
means,
sample_dims=["sample"],
labels=[LEAD_TIME],
stats={"trunk": intervals(0.5), "twig": intervals(CI_PROB)},
color=[SET_COLORS[scenario_set] for scenario_set in gains],
figure_kwargs={"figsize": (10, 5.5)},
)
ax = pc.viz["plot"].sel(column="forest").item()
ax.axvline(0.0, color="black", linestyle="--")
ax.set(xlabel="expected loss before the step minus expected loss after it")
pc.add_legend("model", title="", loc="outside lower center", ncol=len(gains))
pc.viz["figure"].item().suptitle(
f"Expected Gain of the {step.title()} (50% and 94% ETI)",
fontsize=18,
fontweight="bold",
)
plot_expected_gains(Step.OFFSETS, gains_offsets);
On the forecast test set the trained offsets lower the expected loss when there is a lead time, and they gain more with every extra day of it. Without a lead time the interval includes zero, as we expected in the Offset Definition section.
The gain is much larger on the true process test set. The true process has less demand than the center of the forecast, so it favors the trained offsets, which lower the levels.
Next, we look at the weekly forecast, between the two policies with trained offsets.
first, second = STEP_PAIRS[Step.WEEKLY]
gains_weekly = expected_gains(policy_losses(first), policy_losses(second))
assert signs(gains_weekly[ScenarioSet.FORECAST]) == ALL_POSITIVE
# on the true process test set the update loses at the longest lead time
assert gains_weekly[ScenarioSet.TRUE_PROCESS][-1].sign() == -1
plot_expected_gains(Step.WEEKLY, gains_weekly);
On the forecast test set the update lowers the expected loss at every lead time. On the true process test set it gains for \(L \leq 2\) and loses at \(L = 3\).
Recall from the Base-Stock (Weekly Forecast, Trained) section that each of the two policies has its own offsets, so this step changes the levels and the offsets at once. For a second view we repeat the step without offsets: from Base-stock (day-one forecast) to the same rule at the newsvendor levels of the weekly forecast. This rule is not one of the five policies.
# the base-stock rule at the newsvendor levels of the weekly forecast, without offsets
weekly_no_offsets = TrainedPolicy(base_stock, no_offsets, ForecastSource.WEEKLY)
losses_no_offsets: Losses = {
scenario_set: [
evaluate(weekly_no_offsets, scenario_set, lead_time).loss
for lead_time in setup.lead_times
]
for scenario_set in EVALUATION_SETS
}
gains_no_offsets = expected_gains(policy_losses(PolicyName.DAY_ONE), losses_no_offsets)
# without offsets the update gains at every lead time on both test sets
for test_set in TEST_SETS:
assert signs(gains_no_offsets[test_set]) == ALL_POSITIVE
plot_expected_gains(Step.WEEKLY_NO_OFFSETS, gains_no_offsets);
Without offsets the update gains at every lead time on both test sets. On the forecast test set it gains a little more than between the two trained policies, and on the true process test set much more.
Neither comparison isolates what the first week tells us. Recall from the Weekly Forecast section that the median weekly level is a few units below the day-one level. Without offsets the update also gets the credit for these lower levels, which is consistent with its larger gain there. With trained offsets the two policies have different offsets. So we do not read the loss at \(L = 3\) as a cost of the update alone.
Finally, we look at the network.
first, second = STEP_PAIRS[Step.NETWORK]
gains_network = expected_gains(policy_losses(first), policy_losses(second))
assert signs(gains_network[ScenarioSet.FORECAST]) == ALL_POSITIVE
# the network gains more at L = 2 and L = 3 than at the shorter lead times, also on
# the days in every cost window
network_common = common_gains(Step.NETWORK)
assert max(network_common[:2]) < min(network_common[2:])
plot_expected_gains(Step.NETWORK, gains_network);
The network lowers the expected loss at every lead time on both test sets, and it gains more at \(L = 2\) and \(L = 3\) than at the shorter lead times.
Now we can answer questions \(2\) to \(4\) on the forecast test set:
Does training the target levels through the simulator lower the loss further? Yes, when there is a lead time. The gain grows with every extra day of lead time, and without a lead time the training changes nothing.
How much does the update of the forecast after the first week lower the loss? Between the two trained policies, the update after the first week lowers the expected loss by about \(1\%\) for \(L \geq 1\), and without offsets by a little more. This is much less than what the stock gives, and for \(L \geq 2\) less than what the training gives.
Does a correction that depends on what we observe, computed by a neural network, lower the loss of
Base-stock (weekly forecast, trained)further? Yes. The correction of the network lowers the expected loss by \(0.6\%\) to \(2.5\%\).
Here are two remarks about the sizes of these gains.
Weekly forecast. The level of our data generating process moves slowly. Its daily increments have a standard deviation of about \(1\%\), so in one week the level moves by about \(2.6\%\), while the demand of a single day has a noise of about \(20\%\) around its mean. We expect a larger gain of the update when the level moves faster.
Network. In the stationary experiments of Huh et al. (2009), at a cost ratio like ours, the best base-stock policy costs \(0.7\%\) to \(3.0\%\) more than the optimal policy. The network is not the optimal policy and our demand has a promotion, so this is only a guide.
Gain by Expected Demand
Where does each of the three steps (the trained offsets, the weekly forecast and the network) lower the loss? We take the lead time \(L = 2\) and group the scenarios of the forecast test set by the expected demand behind them: the expected total demand of the ordering days under the parameters and the level of the scenario, with the level held at its value on the last day of the history. We read it from the deterministic site mean of the demand model, with the increments of the days after the history fixed at zero. The function log_expected_demand sums this site over the ordering days.
We write it on the log scale and in standard deviations from its mean over the test draws, so zero is the center of the forecast. The output shows where the true process is on this scale.
def log_expected_demand(mean: Float[Array, "draws days 1"]) -> Float[Array, " draws"]:
"""Log of the expected total demand of the ordering days, from the `mean` site."""
return jnp.log(mean[:, setup.t_obs :].sum(axis=(1, 2)))
covariates_horizon = covariates[: setup.t_obs + setup.horizon]
# no increments after the history: the level stays at its value on the last day
no_increments = jnp.zeros((setup.horizon, 1))
rng_key, key_mean_test, key_mean_true = random.split(rng_key, 3)
mean_test = Predictive(
demand_model,
posterior_samples={
**posterior_of(draws_test),
Site.DRIFT_FUTURE: jnp.broadcast_to(
no_increments, (draws_test.shape[0], *no_increments.shape)
),
},
return_sites=[Site.MEAN],
parallel=True,
)(key_mean_test, covariates_horizon, data)[Site.MEAN]
mean_true = Predictive(
do(true_process, data={Site.DRIFT_FUTURE: no_increments}),
num_samples=1,
return_sites=[Site.MEAN],
)(key_mean_true, covariates_horizon, data)[Site.MEAN]
log_demand_test = log_expected_demand(mean_test)
log_demand_true = log_expected_demand(mean_true)
# in standard deviations from the center of the forecast
center, spread = log_demand_test.mean(), log_demand_test.std()
expected_demand_test = (log_demand_test - center) / spread
expected_demand_true = float((log_demand_true[0] - center) / spread)
expected_demand_true
-1.0370898246765137
The true process is about one standard deviation below the center of the forecast, so it has less demand than the typical test scenario. Recall from the Demand Model section that the posterior mean of the elasticity is about two standard deviations below the true value. A more negative elasticity means a larger effect of the promotion, so the forecast expects more demand in the promotion week than the true process has. Recall from the State Space Model section that the update moves only the level, so it cannot correct this.
Next, we cut the test scenarios into \(8\) groups of equal size by their expected demand. For each group the function gain_by_group computes the expected gain of a step, the loss of the first policy of a pair minus the loss of the second one, with its \(50\%\) and \(94\%\) intervals as in the Paired Differences section. We plot the expected gain of the three steps, one panel per step, in the color of the policy that the step leads to. The thick and thin bars are the \(50\%\) and \(94\%\) intervals, and the vertical line is the position of the true process.
NUM_GROUPS = 8
group = equal_groups(expected_demand_test, NUM_GROUPS)
# the mean expected demand of every group, in standard deviations
group_centers = [
float(expected_demand_test[group == g].mean()) for g in range(NUM_GROUPS)
]
def gain_by_group(first: PolicyName, second: PolicyName) -> list[Estimate]:
"""Expected gain by group of expected demand.
The loss of `first` minus the loss of `second` on the forecast test set, at the
lead time that we look at in detail.
"""
gain = (
simulations[ScenarioSet.FORECAST, LEAD_TIME_DETAIL, first].loss
- simulations[ScenarioSet.FORECAST, LEAD_TIME_DETAIL, second].loss
)
return [mean_difference(gain[group == g]) for g in range(NUM_GROUPS)]
gains = {step: gain_by_group(*pair) for step, pair in STEP_PAIRS.items()}
fig, axes = plt.subplots(
nrows=len(gains), figsize=(10, 3.6 * len(gains)), sharex=True, layout="constrained"
)
for ax, (step, group_estimates) in zip(axes, gains.items(), strict=True):
color = POLICY_COLORS[STEP_PAIRS[step][1]]
# thin 94% and thick 50% intervals, as in a forest plot
for prob, linewidth in [(CI_PROB, 1.5), (0.5, 4.0)]:
lower, upper = jnp.asarray(
[estimate.interval(prob) for estimate in group_estimates]
).T
ax.vlines(group_centers, lower, upper, color=color, linewidth=linewidth)
ax.plot(
group_centers,
[estimate.mean for estimate in group_estimates],
"o-",
color=color,
label=f"gain of the {step.lower()}",
)
ax.axvline(
expected_demand_true,
color="C7",
label="true process" if ax is axes[0] else None,
)
ax.axhline(0.0, color="black", linestyle="--")
ax.set(title=step)
axes[-1].set(xlabel="expected demand of the scenario (standard deviations)")
fig.supylabel("expected gain", fontsize=plt.rcParams["axes.labelsize"])
fig.legend(loc="outside lower center", ncol=2)
fig.suptitle(
f"Gain by Expected Demand at Lead Time $L = {LEAD_TIME_DETAIL}$ (50% and 94% ETI)",
fontsize=18,
fontweight="bold",
);
The three panels have different shapes:
Trained offsets. The gain falls from the lowest group to the highest one. The trained offsets lower the levels in every scenario. This saves holding cost when the demand is at or below the center of the forecast, and it costs lost sales in the top quarter of the scenarios.
Weekly forecast. The update gains when the demand of a path is far from the center of the forecast, on either side, and near the center it gains nothing or costs a little. At the two ends the demand of a path is far from what the day-one levels assume, and the update moves the levels toward it. Near the center the day-one levels are already about right, and the weekly levels add the Monte Carlo error of their \(1{,}000\) paths, which is consistent with the small cost there.
Network. The mean gain is positive in every group. It is largest in the lowest group and in the highest one.
In the first panel the true process lies where the trained offsets gain the most, which is consistent with their large gain on the true process test set. For a truth in the top quarter of the scenarios the same offsets would raise the loss.
Stock and Stockouts
To see why the policies beat the fixed plan, we look at what each of them does with the stock. We stay with the lead time \(L = 2\) and the forecast test set. The next figure shows four of the scores.
results_detail = results.filter(
(pl.col("scenario set") == ScenarioSet.FORECAST)
& (pl.col("lead time") == LEAD_TIME_DETAIL)
)
fig, axes = plt.subplots(
nrows=2, ncols=2, figsize=(14, 10), sharex=True, layout="constrained"
)
for ax, metric in zip(
axes.flat,
[Metric.EXPECTED_LOSS, Metric.STOCKOUT, Metric.WINDOW, Metric.ORDERED],
strict=True,
):
is_probability = metric in {Metric.STOCKOUT, Metric.WINDOW}
sns.barplot(
data=results_detail,
x="policy",
y=metric,
order=list(PolicyName),
hue="policy",
palette=POLICY_COLORS,
legend=False,
ax=ax,
)
for container in ax.containers:
ax.bar_label(
container,
fmt="{:.1%}" if is_probability else "{:.0f}",
fontsize=12,
padding=2,
)
if is_probability:
ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))
ax.margins(y=0.12)
ax.set(title=metric, xlabel="", ylabel="")
for ax in axes[-1]:
# the names of the policies on three lines
ax.set_xticks(
range(len(PolicyName)),
[
name.replace(" (", "\n(")
.replace(" forecast", "\nforecast")
.replace(", ", ",\n")
for name in PolicyName
],
)
fig.suptitle(
f"Scores at Lead Time $L = {LEAD_TIME_DETAIL}$ ({ScenarioSet.FORECAST.title()})",
fontsize=18,
fontweight="bold",
);
The fixed plan orders more than every policy and still runs out about three times as often as Base-stock (day-one forecast). Its orders are the same in every scenario. So in the scenarios with low demand the units stay on the shelf, and in the scenarios with high demand they are missing.
The trained offsets lower the levels: the trained policies hold less stock and run out more often, and this is cheaper under our costs. Recall the two observations of the Base-Stock Training section. With a lead time Base-stock (day-one forecast) runs out less often than \(h / (p + h) = 4.8\%\), and a unit that we sell is missing on the next days. The trained policies end up above \(4.8\%\), which is consistent with the second observation.
Next, we look at the same five policies day by day: the mean order, the mean stock on hand at the end of the day and the stockout probability. The black lines mark the cost window, and the shaded days are the promotion week.
simulations_detail = {
name: simulations[ScenarioSet.FORECAST, LEAD_TIME_DETAIL, name]
for name in PolicyName
}
days_detail = jnp.arange(1, setup.horizon + LEAD_TIME_DETAIL + 1)
fig, axes = plt.subplots(nrows=3, figsize=(12, 11), sharex=True, layout="constrained")
for name, simulation in simulations_detail.items():
for ax, values in zip(
axes,
[
simulation.orders.mean(axis=0),
simulation.inventory.mean(axis=0),
(simulation.lost_sales > STOCKOUT_TOL).mean(axis=0),
],
strict=True,
):
ax.plot(days_detail, values, "o-", color=POLICY_COLORS[name], label=name)
for ax in axes:
ax.axvline(LEAD_TIME_DETAIL + 0.5, color="black", label="Cost window")
ax.axvline(days_detail[-1] + 0.5, color="black")
shade_promotion(ax)
axes[0].set(ylabel="mean order (units)")
axes[1].set(ylabel="mean stock on hand (units)")
axes[2].yaxis.set_major_locator(MultipleLocator(0.05))
axes[2].yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))
axes[2].set(xlabel="day", ylabel="stockout probability", xticks=days_detail)
fig.legend(*axes[0].get_legend_handles_labels(), loc="outside lower center", ncol=3)
fig.suptitle(
f"Orders, Stock and Stockouts by Day at Lead Time $L = {LEAD_TIME_DETAIL}$",
fontsize=18,
fontweight="bold",
);
Let’s go through the five policies.
Fixed plan. The mean stock grows through the whole cost window. The leftovers of the scenarios with low demand pile up, and the plan cannot lower a later order to use them.
Base-stock (day-one forecast). Its mean stock rises in the promotion week and comes back afterwards, and its stockout probability stays between about \(3\%\) and \(4.5\%\) on every day of the cost window.
Trained base-stock policies and neural. They hold less stock than
Base-stock (day-one forecast)and run out more often. The two trained base-stock policies hold about the same stock and run out about as often on every day.
So the fixed plan ends with the most stock and still runs out most often, while the trained policies hold less stock than Base-stock (day-one forecast) and accept more stockouts.
Cost Ratio
Next, we check how much the answer to the first question depends on the costs. That question asks how much of the expected loss of the fixed plan we remove when the order of each day depends on the stock that we observe. The lost margin \(p = 2\) is \(20\) times the holding cost. We repeat the comparison for five cost ratios, \(p / h = 0.5\), \(1\), \(5\), \(20\) and \(80\), with the same holding cost, initial stock and initial pipeline. The critical fractile \(p / (p + h)\) of these ratios is \(0.33\), \(0.5\), \(0.83\), \(0.95\) and \(0.99\). For the two smallest ratios a lost sale costs at most as much as one day of holding, and the newsvendor level is at or below the median of the demand that an order covers.
For each ratio we train the fixed plan again, compute the newsvendor levels of the forecast of day one at the critical fractile of that ratio from the same paths as before, and train the offsets of these levels. The comparison isolates the first question, since the plan and the two policies use only the forecast of day one. For every policy, ratio and lead time we keep the reduction of the expected loss relative to the fixed plan, and the sign of the paired difference with the fixed plan as in the Paired Differences section. The assertions check that for \(p / h = 20\) the sweep gives the two base-stock policies of the main results, and the signs that the text below uses.
COST_RATIOS = [0.5, 1.0, 5.0, 20.0, 80.0] # lost margin over holding cost, p / h
SWEEP_POLICIES = [PolicyName.DAY_ONE, PolicyName.DAY_ONE_TRAINED]
rows = []
for cost_ratio in COST_RATIOS:
config_sweep = config._replace(lost_sales_cost=cost_ratio * config.holding_cost)
# the day-one forecast at the critical fractile of this cost ratio
day_one_sweep = summarize_forecast(
paths_day_one, setup.max_days, critical_fractile(config_sweep)
)
for lead_time in setup.lead_times:
losses_plan = evaluate(
train_fixed_plan(lead_time, config_sweep),
ScenarioSet.FORECAST,
lead_time,
config_sweep,
).loss
# the test scenarios with the levels of this cost ratio
scenarios_sweep = scenarios_for(
ScenarioSet.FORECAST,
lead_time,
ForecastSource.DAY_ONE,
day_one=day_one_sweep,
)
offsets_sweep = {
PolicyName.DAY_ONE: no_offsets,
PolicyName.DAY_ONE_TRAINED: train_base_stock(
lead_time, config_sweep, ForecastSource.DAY_ONE, day_one=day_one_sweep
).params,
}
for name in SWEEP_POLICIES:
losses = simulate_scenarios_jit(
base_stock,
offsets_sweep[name],
scenarios_sweep,
initial_state(lead_time),
config_sweep,
lead_time,
).loss
rows.append(
{
"policy": str(name),
"cost ratio": cost_ratio,
"lead time": lead_time,
Metric.EXPECTED_LOSS: float(losses.mean()),
"reduction": float(1 - losses.mean() / losses_plan.mean()),
# the sign of the paired difference with the fixed plan
"sign": mean_difference(losses_plan - losses).sign(),
}
)
cost_sweep = pl.DataFrame(rows)
def sweep_values(
name: PolicyName, cost_ratio: float, column: str
) -> list[float] | list[int]:
"""A column of the sweep for one policy and one cost ratio, by lead time."""
return cost_sweep.filter(
(pl.col("policy") == name) & (pl.col("cost ratio") == cost_ratio)
)[column].to_list()
# for our costs the sweep gives the two policies of the main results
main_ratio = config.lost_sales_cost / config.holding_cost
for name in SWEEP_POLICIES:
loss_main = [
float(simulations[ScenarioSet.FORECAST, lead_time, name].loss.mean())
for lead_time in setup.lead_times
]
assert jnp.allclose(
jnp.asarray(sweep_values(name, main_ratio, Metric.EXPECTED_LOSS)),
jnp.asarray(loss_main),
)
# the signs that the text below uses
for cost_ratio in COST_RATIOS:
newsvendor, trained = (
sweep_values(name, cost_ratio, "sign") for name in SWEEP_POLICIES
)
# without a lead time both policies beat the fixed plan
assert newsvendor[0] == trained[0] == 1
if cost_ratio >= 5:
# with an expensive lost sale the trained policy beats it at every lead time
assert trained == ALL_POSITIVE
else:
# with a cheap lost sale and a lead time the newsvendor levels lose to it
assert newsvendor[1:] == [-1] * (len(setup.lead_times) - 1)
The next figure shows the reduction of the expected loss of the two policies relative to the fixed plan on the forecast test set, one panel per policy. The lines go from light to dark as the cost ratio grows. Below the dashed line a policy has a higher expected loss than the fixed plan.
fig, axes = plt.subplots(
ncols=2, figsize=(14, 6), sharex=True, sharey=True, layout="constrained"
)
for ax, name in zip(axes, SWEEP_POLICIES, strict=True):
for ((cost_ratio,), frame), color in zip(
cost_sweep.filter(pl.col("policy") == name).group_by(
"cost ratio", maintain_order=True
),
sequential_colors(len(COST_RATIOS)),
strict=True,
):
ax.plot(
frame["lead time"],
frame["reduction"],
"o-",
color=color,
label=f"$p / h = {cost_ratio:g}$",
)
ax.axhline(0.0, color="black", linestyle="--")
ax.yaxis.set_major_formatter(PercentFormatter(xmax=1, decimals=0))
ax.set(title=name, xlabel="lead time $L$ (days)", xticks=setup.lead_times)
axes[0].set(ylabel="reduction of the expected loss")
fig.legend(
*axes[0].get_legend_handles_labels(),
loc="outside lower center",
ncol=len(COST_RATIOS),
)
fig.suptitle(
"Base-Stock Policies Against the Fixed Plan by Cost Ratio",
fontsize=18,
fontweight="bold",
);
Let’s read the figure in three parts.
No lead time. For \(L = 0\) both policies have a lower expected loss than the fixed plan at every ratio. The reduction grows with the ratio, from \(11\%\) for the smallest one to \(57\%\) for the largest, and the trained offsets change nothing.
Expensive lost sale. For \(p / h \geq 5\) the reduction shrinks with the lead time, and with trained levels it stays positive: for \(L = 3\) it is \(10\%\), \(23\%\) and \(29\%\). The training matters more when the ratio is smaller. For \(L = 3\) it moves the reduction from about zero to \(10\%\) for \(p / h = 5\), and from \(27\%\) to \(29\%\) for \(p / h = 80\).
Cheap lost sale. For \(p / h \leq 1\) and a lead time the base-stock policy at the newsvendor levels has a higher expected loss than the fixed plan, by \(3\%\) to \(51\%\). The trained offsets close most of this gap. Still, in five of these six cases the trained policy has a higher expected loss than the fixed plan, by \(2\%\) to \(10\%\).
Why can the fixed plan be better when a lost sale is cheap? A plausible reason is the identity of the Stock After Lost Sales section: for a positive order, the stock on the day on which the order arrives is the level minus the sales of the \(L\) days before. So the noise of these sales goes into the stock, while the fixed plan adds the same order in every scenario. With a high level the policy rarely runs out, and reacting to the stock that is left over is worth more than this noise costs. With a low level the shelf is empty on most days, and there is little stock left over to react to.
Both ends agree with the literature. Huh et al. (2009) show that the best base-stock policy comes close to the optimal policy when the lost margin is large compared to the holding cost. Recall from the Expected Loss section that Goldberg et al. (2016) find a constant order close to optimal when the lead time is long.
So the answer to the first question depends on the costs. With an expensive lost sale, as in our example, a policy that looks at the stock removes a large part of the expected loss of the fixed plan at every lead time. When a lost sale costs about as much as one day of holding, it does so only without a lead time.
Tail Risk
Finally, we look at the tail of the loss. Recall that the CVaR is the mean of the worst \(5\%\) of the scenario losses, here \(150\) of \(3{,}000\). We trained four of the five policies for the expected loss, and Base-stock (day-one forecast) has no offsets to train. Let’s first look at their CVaR by lead time on the forecast test set.
fig, ax = plt.subplots(figsize=(13, 6))
sns.barplot(
data=results.filter(pl.col("scenario set") == ScenarioSet.FORECAST),
x="lead time",
y=Metric.CVAR,
hue="policy",
hue_order=list(PolicyName),
palette=POLICY_COLORS,
errorbar=None,
ax=ax,
)
for container in ax.containers:
ax.bar_label(container, fmt="{:.0f}", fontsize=11, padding=2)
ax.get_legend().remove()
ax.set(xlabel="lead time $L$ (days)", ylabel=Metric.CVAR)
fig.legend(*ax.get_legend_handles_labels(), loc="outside lower center", ncol=3)
fig.suptitle(
f"CVaR by Policy and Lead Time ({ScenarioSet.FORECAST.title()})",
fontsize=18,
fontweight="bold",
);
The four policies that look at the stock have a much lower CVaR than the fixed plan at every lead time. Among them the order is not the order of the expected loss.
No lead time. For \(L = 0\) the four are close to each other.
Positive lead time. For \(L \geq 1\)
Base-stock (day-one forecast)has the lowest CVaR. Training its offsets raises the CVaR by about \(11\%\) to \(24\%\), while it lowers the expected loss.Weekly forecast and network. The weekly forecast lowers the CVaR for \(L \geq 1\), and the network hardly changes it. The CVaR is a mean of \(150\) losses, so small differences are uncertain.
So the training lowers the expected loss and raises the loss in the worst scenarios. This is consistent with the Gain by Expected Demand section, where the trained offsets cost in the scenarios with high demand.
Next, we check whether we can give up some expected loss for a lower CVaR. In the first post the CVaR plan did this, and the tail weight \(\lambda\) traced a frontier: the plans for which we cannot lower one of the two without raising the other. We can train a policy with the same objective.
We train the fixed plan and Base-stock (day-one forecast, trained) for \(6\) tail weights at \(L = 2\) and score them on the forecast test set. Both use only the forecast of day one, which keeps the comparison about the stock. We show Base-stock (day-one forecast), which has no offsets, as a single point. The assertion checks that with \(\lambda = 0\) we get the two policies of the main results.
TAIL_WEIGHTS = [0.0, 0.25, 0.5, 1.0, 2.0, 8.0]
# the training function of each frontier
FRONTIER_POLICIES = {
PolicyName.FIXED_PLAN: lambda tail_weight: train_fixed_plan(
LEAD_TIME_DETAIL, config, tail_weight
),
PolicyName.DAY_ONE_TRAINED: lambda tail_weight: train_base_stock(
LEAD_TIME_DETAIL, config, ForecastSource.DAY_ONE, tail_weight
),
}
frontier = pl.DataFrame(
[
{
"policy": str(name),
"tail weight": tail_weight,
**summarize(
evaluate(
train_policy(tail_weight), ScenarioSet.FORECAST, LEAD_TIME_DETAIL
),
LEAD_TIME_DETAIL,
),
}
for name, train_policy in FRONTIER_POLICIES.items()
for tail_weight in TAIL_WEIGHTS
]
)
fig, ax = plt.subplots(figsize=(10, 6.5))
for name, frame in zip(
FRONTIER_POLICIES, frontier.partition_by("policy", maintain_order=True), strict=True
):
# with a tail weight of zero we get the policy of the main results
assert jnp.isclose(
frame[Metric.EXPECTED_LOSS][0],
float(simulations[ScenarioSet.FORECAST, LEAD_TIME_DETAIL, name].loss.mean()),
rtol=1e-6,
)
ax.plot(
frame[Metric.EXPECTED_LOSS],
frame[Metric.CVAR],
"o-",
color=POLICY_COLORS[name],
label=name,
)
for row in frame.filter(pl.col("tail weight").is_in([0.0, 1.0, 8.0])).iter_rows(
named=True
):
ax.annotate(
rf"$\lambda={row['tail weight']:g}$",
(row[Metric.EXPECTED_LOSS], row[Metric.CVAR]),
textcoords="offset points",
xytext=(8, 6),
fontsize=12,
)
# the base-stock policy with the day-one levels and no offsets
day_one_scores = summarize(
simulations[ScenarioSet.FORECAST, LEAD_TIME_DETAIL, PolicyName.DAY_ONE],
LEAD_TIME_DETAIL,
)
ax.scatter(
day_one_scores[Metric.EXPECTED_LOSS],
day_one_scores[Metric.CVAR],
marker="X",
s=120,
color=POLICY_COLORS[PolicyName.DAY_ONE],
label=PolicyName.DAY_ONE,
zorder=3,
)
ax.set(xlabel=Metric.EXPECTED_LOSS, ylabel=Metric.CVAR)
ax.margins(x=0.1)
# the legend in the order of the policies
handles, labels = ax.get_legend_handles_labels()
order = [labels.index(name) for name in PolicyName if name in labels]
fig.legend(
[handles[k] for k in order],
[labels[k] for k in order],
loc="outside lower center",
ncol=2,
)
fig.suptitle(
f"Cost Against Tail Risk at Lead Time $L = {LEAD_TIME_DETAIL}$ "
f"({ScenarioSet.FORECAST.title()})",
fontsize=18,
fontweight="bold",
);
Let’s compare the two frontiers. They have the same shape: most of the reduction of the CVaR comes with the first tail weights.
Trained for the expected loss alone, the offsets lower the expected loss by about \(4\) and raise the CVaR by about \(48\). With the first tail weight, \(\lambda = 0.25\), the trained policy has an expected loss of about \(120\) and a CVaR of about \(231\), close to the \(120\) and \(226\) of Base-stock (day-one forecast), whose levels are higher.
The whole frontier of Base-stock (day-one forecast, trained) lies below and to the left of the frontier of the fixed plan. Trained for the expected loss alone, it has a CVaR of about \(274\), and the lowest CVaR of the fixed plan over the \(6\) tail weights is about \(364\). This is what we expect. A fixed plan loses the most when the demand moves away from the plan, and the base-stock policy changes its orders when that happens.
Conclusion
Key Findings
Orders that depend on the stock. A base-stock policy at the newsvendor levels of the forecast needs a quantile of the scenarios and no optimizer. Without a lead time it removed about half of the expected loss of the fixed plan, and at every lead time it had a much lower tail risk.
Lead time. The gain over the fixed plan was smaller for every extra day of lead time, because each order covers more demand that we have not seen.
Cost ratio. These gains need an expensive lost sale. When a lost sale costs about as much as one day of holding and there is a lead time, the base-stock policies gave little or no gain over the fixed plan, and in most cases a higher expected loss.
Trained levels. With lost sales and a lead time the policy has more stock than its newsvendor levels assume, so training the levels through the simulator lowered them and the expected loss. The training corrects the base-stock rule and not the forecast. It lowers the expected loss at the price of a higher tail risk, and the tail weight in the objective sets this trade.
Forecast updates. A filter updated the forecast of every scenario without a new fit. One update after the first week gave a small gain on the forecast test set, and we expect a larger one when the level of the demand moves faster.
Flexible corrections. A small network on top of the trained base-stock policy lowered the expected loss a little further. This is consistent with the stationary experiments of Huh et al. (2009), where at a cost ratio like ours the best base-stock policy is within a few percent of the optimal policy.
One simulator and one trainer. One function trained the fixed plan, the offsets and the network, with the gradient from
jax.gradthrough thejax.lax.scanof the simulator.
Model Limitations
Daily orders. We place an order every day, and an order has no fixed cost. A retailer that orders once or twice a week needs levels that cover the days until the next order arrives.
Observed demand. We observe the demand of a day even when the shelf was empty. In practice the history is sales, which are censored on those days, see Caron (2023) and the censored demand example of
numpyro_forecast. With censored sales the forecast depends on the orders, and we cannot compute the weekly forecast before the training.One synthetic series. The results come from one series, one forecast origin and one set of true parameters, and the forecasting model has the structure of the generator. For a truth above the center of the forecast the trained offsets would gain less or raise the loss, as the Gain by Expected Demand section shows.
Forecast update. The update keeps the parameter draws of the fit with equal weights and moves only the level. After the highest first week of the test set it moves the forecast less than a refit, as the Appendix shows.
Costs and lead time. The lead time is known, the costs are linear, and a lost sale costs the margin \(p\) and nothing else. Order minimums, fixed ordering costs, uncertain lead times and stockouts that cost future demand change the simulator or the loss.
Recommendations
Start with a base-stock policy. Order up to the \(p / (p + h)\) quantile of the total demand of the next \(L + 1\) days under the forecast, from the stock on hand plus the pipeline. If a lost sale is cheap and there is a lead time, compare it with a fixed plan first, as in the Cost Ratio section.
Train the levels when there is a lead time. With lost sales the newsvendor levels are too high, and more so when a lost sale is cheap. If the worst scenarios matter, train with a tail weight, which trades expected loss for a lower CVaR.
Update the forecast with a filter when a fit is expensive. Fit the model once a month, for example, and update the forecast every week with the new demand.
Measure before you add a flexible correction. Compare the candidates on the same held-out scenarios, and look at the paired differences with their Monte Carlo error.
Next Steps
Rolling horizon. Solve the fixed plan again every day with the latest forecast and place only its first order, the practical version of the problem of the first post.
Daily forecast update. Run the filter every day, so that the target levels use the demand of the day before.
Censored demand. Train the policies on sales, with a censored likelihood in the forecasting model and in the filter, which then has to run inside the simulator.
Many forecast origins. Train one policy on the scenarios of the forecast origins of a rolling backtest, so that it can be used every day.
Many products. Share a capacity between the products of a store, as in the cannibalization post, and let the policy return the orders of all the products.
Appendix
In the Forecast Updates section we replaced the refit of the forecasting model with a filter that keeps the parameter draws of the fit with equal weights. Here we compare the two on \(6\) scenarios of the forecast test set, and we look at what the equal weights cost.
We suppose that we have observed the first week of each scenario, and we compute the forecast of the total demand of the remaining \(11\) days, which contain the promotion week, in three ways:
Filter. We update the forecast with
update_forecast, as in the main text.Filter, weighted draws. We give every parameter draw a weight and resample the paths of the filter with these weights.
NUTS refit. We fit the forecasting model again on the history plus the first week, with the sampler settings of the fit on the history. We keep one of every four posterior draws, so that the three forecasts have \(1{,}000\) paths.
We write every forecast as the forecast minus the realized total, so that zero is a perfect forecast.
First, we choose the scenarios. We sort the scenarios of the forecast test set by the total demand of their first week and take the lowest, the highest and the \(5\%\), \(25\%\), \(75\%\) and \(95\%\) quantiles, so that the comparison includes first weeks that are far from the forecast. The function scenario_keys splits the random key of a scenario into one key for each of its four random steps.
# the lowest and the highest first week of the test set, and four quantiles between
CHECK_QUANTILES = (0.0, 0.05, 0.25, 0.75, 0.95, 1.0)
NUM_CHECK_SCENARIOS = len(CHECK_QUANTILES)
first_week_total = demand_test[:, :NUM_OBSERVED].sum(axis=1)
check_index = jnp.argsort(first_week_total)[
(jnp.asarray(CHECK_QUANTILES) * (first_week_total.shape[0] - 1)).astype(int)
]
first_weeks = demand_test[check_index, :NUM_OBSERVED]
# the total demand of the remaining days, which every forecast has to predict
realized_check = demand_test[check_index, NUM_OBSERVED:].sum(axis=1)
def scenario_keys(key: PRNGKeyArray) -> tuple[PRNGKeyArray, ...]:
"""Keys of the four random steps of a scenario.
The paths of the filter, the resampling, the refit and the paths of the refit.
"""
key_filter, key_refit, key_predict = random.split(key, 3)
key_paths, key_resample = random.split(key_filter)
return key_paths, key_resample, key_refit, key_predict
rng_key, key_check = random.split(rng_key)
keys_paths, keys_resample, keys_refit, keys_predict = jax.vmap(scenario_keys)(
random.split(key_check, NUM_CHECK_SCENARIOS)
)
Next, we compute the forecast of the filter for each scenario with update_forecast. The function remaining_total sums the paths of a forecast over the remaining days.
def remaining_total(paths: Float[Array, "draws days"]) -> Float[Array, " draws"]:
"""Total demand of the remaining days of the horizon, for every path."""
return paths[:, :num_remaining].sum(axis=1)
update_forecast_jit = jax.jit(update_forecast)
errors_filter = [
remaining_total(update_forecast_jit(key, first_week)) - realized
for key, first_week, realized in zip(
keys_paths, first_weeks, realized_check, strict=True
)
]
Now we compute the weights, which come from the filter itself. The first week also tells us something about the parameters. For every draw the filter computes its approximation of the probability of the demand of the first week under the parameters of that draw, and dynestyx records its logarithm in a site. Let \(w_i\) be the weight of the posterior draw \(i\) after the first week. By Bayes’ rule it is proportional to this probability,
\[w_i \propto \text{P}(D_1, \dots, D_7 \mid \text{history}, \text{draw } i), \qquad \sum_i w_i = 1.\]
The function draw_weights returns the weights. The function systematic_resample returns the index of the draw \(i\) about \(1{,}000 \, w_i\) times, so a draw with a large weight appears several times and a draw with a small weight drops out. The assertion checks these counts. See Särkkä and Svensson (2023) for resampling.
We also keep the effective number of draws, \(1 / \sum_i w_i^2\). It is \(1{,}000\) for equal weights, and it is smaller when few draws carry the weight.
# the site in which the filter records the log likelihood of the observed days
LOG_LIKELIHOOD: Final = f"{LEVEL}_marginal_loglik"
def draw_weights(observed: Float[Array, " observed"]) -> Float[Array, " draws"]:
"""Weight of every parameter draw after the observed days, from the filter."""
with extended_kalman:
# the filter uses no random numbers
filtered = Predictive(
state_space_model,
posterior_samples=posterior_resumed,
return_sites=[LOG_LIKELIHOOD],
)(NO_KEY, covariates_future[: observed.shape[0]], observed[:, None])
return jax.nn.softmax(filtered[LOG_LIKELIHOOD])
def systematic_resample(
key: PRNGKeyArray, weights: Float[Array, " draws"]
) -> Int[Array, " draws"]:
"""Indices of the draws, each one about `weights * draws` times."""
num_draws = weights.shape[0]
positions = (random.uniform(key) + jnp.arange(num_draws)) / num_draws
cumulative = jnp.cumsum(weights)
return jnp.searchsorted(cumulative / cumulative[-1], positions)
weights_check = [draw_weights(first_week) for first_week in first_weeks]
resampled = [
systematic_resample(key, weights)
for key, weights in zip(keys_resample, weights_check, strict=True)
]
# every draw appears about as many times as its weight says
for index, weights in zip(resampled, weights_check, strict=True):
counts = jnp.bincount(index, length=NUM_DRAWS_OPT)
assert jnp.abs(counts - NUM_DRAWS_OPT * weights).max() <= 1
errors_weighted = [
errors[index] for errors, index in zip(errors_filter, resampled, strict=True)
]
effective_draws = [round(float(1 / (weights**2).sum())) for weights in weights_check]
Finally, we fit the model again for each scenario. The function refit_forecast runs NUTS on the history plus the first week of a scenario. It returns the forecast paths of the remaining days and the posterior mean of the elasticity.
%%time
mcmc_refit = MCMC(
NUTS(non_centered_model, target_accept_prob=TARGET_ACCEPT_PROB),
num_warmup=1_000,
num_samples=1_000,
num_chains=4,
thinning=4, # one of every four draws, as many paths as the filter gives
progress_bar=False,
)
class Refit(NamedTuple):
"""Forecast of a NUTS fit on the history plus the first week of a scenario."""
paths: Float[Array, "draws days"] # the remaining days of the horizon
elasticity: float # posterior mean
def refit_forecast(
key_fit: PRNGKeyArray,
key_predict: PRNGKeyArray,
first_week: Float[Array, " observed"],
) -> Refit:
"""Fit the demand model on the history plus a first week and forecast the rest."""
# the first week as integers, like the history
data_long = jnp.concatenate([data, first_week[:, None].astype(data.dtype)])
mcmc_refit.run(key_fit, covariates[: data_long.shape[0]], data_long)
posterior_refit = mcmc_refit.get_samples()
paths = forecast(
key_predict, demand_model, posterior_refit, data_long, covariates_sim
)
return Refit(
paths[..., 0].astype(jnp.float32),
float(posterior_refit[Site.ELASTICITY].mean()),
)
refits = [
refit_forecast(key_fit, key_predict, first_week)
for key_fit, key_predict, first_week in zip(
keys_refit, keys_predict, first_weeks, strict=True
)
]
errors_refit = [
remaining_total(refit.paths) - realized
for refit, realized in zip(refits, realized_check, strict=True)
]
CPU times: user 8min 18s, sys: 10min 58s, total: 19min 16s
Wall time: 2min 12s
The table shows the mean error of the three forecasts for each scenario, the effective number of draws and the elasticity of the refit.
forecast_errors: dict[str, Float[Array, "draws scenarios"]] = {
"Filter": jnp.stack(errors_filter, axis=1),
"Filter, weighted draws": jnp.stack(errors_weighted, axis=1),
"NUTS refit": jnp.stack(errors_refit, axis=1),
}
assert len({errors.shape for errors in forecast_errors.values()}) == 1
pl.DataFrame(
{
"scenario": list(range(1, NUM_CHECK_SCENARIOS + 1)),
"quantile of the first week": [f"{q:.0%}" for q in CHECK_QUANTILES],
"total demand of the first week": first_week_total[check_index].tolist(),
**{
f"mean error: {name}": errors.mean(axis=0).tolist()
for name, errors in forecast_errors.items()
},
"effective draws": effective_draws,
"elasticity of the refit": [f"{refit.elasticity:.2f}" for refit in refits],
}
)
| scenario | quantile of the first week | total demand of the first week | mean error: Filter | mean error: Filter, weighted draws | mean error: NUTS refit | effective draws | elasticity of the refit |
|---|---|---|---|---|---|---|---|
| i64 | str | f64 | f64 | f64 | f64 | i64 | str |
| 1 | "0%" | 311.0 | -5.4 | -6.3 | -15.7 | 751 | "-1.70" |
| 2 | "5%" | 364.0 | 164.0 | 165.0 | 165.7 | 917 | "-1.70" |
| 3 | "25%" | 404.0 | -14.1 | -15.6 | -15.5 | 869 | "-1.69" |
| 4 | "75%" | 465.0 | -119.3 | -120.8 | -114.5 | 857 | "-1.69" |
| 5 | "95%" | 512.0 | 179.6 | 184.0 | 195.8 | 873 | "-1.69" |
| 6 | "100%" | 653.0 | -5.3 | 47.2 | 63.5 | 326 | "-1.66" |
The first weeks go from \(311\) to \(653\) units. In the first \(5\) scenarios, including the lowest first week, the mean errors of the three forecasts are less than \(17\) units apart. The effective number of draws is between \(751\) and \(917\), and the weights move the forecast of the filter by less than \(5\) units.
After the highest first week the filter is about \(69\) units below the refit. Here the effective number of draws falls to \(326\), and the weighted draws are about \(16\) units below the refit. So most of what the filter misses after this extreme first week is what the week tells us about the parameters, and the weights of the filter recover most of it.
Between the \(5\%\) and the \(95\%\) quantiles of the first week the weights move the forecast little. Recall from the Weekly Forecast section that the levels of the update with equal weights leave about the right share of the demand above them in every group of the first week. For this reason the main text keeps the simpler update with equal weights.
The elasticity hardly moves: its posterior mean stays between \(-1.70\) and \(-1.66\) in the \(6\) refits, against \(-1.69\) in the fit on the history.
Next, we look at the three forecasts for every scenario. We also compute the continuous ranked probability score (CRPS) of each one. The CRPS generalizes the absolute error to a predictive distribution. It is in the units of the data, and lower is better.
ERROR = "forecast minus realized demand"
error_draws = {
name: xr.Dataset(
{ERROR: (("sample", "scenario"), errors)},
coords={"scenario": list(range(1, NUM_CHECK_SCENARIOS + 1))},
)
for name, errors in forecast_errors.items()
}
# the CRPS of the forecast error against zero, averaged over the scenarios
crps = {
name: float(crps_empirical(errors, jnp.zeros(NUM_CHECK_SCENARIOS)).mean())
for name, errors in forecast_errors.items()
}
pc = az.plot_forest(
{
f"{name} (mean CRPS {crps[name]:.1f} units)": dataset
for name, dataset in error_draws.items()
},
sample_dims=["sample"],
labels=["scenario"],
color=["C0", "C2", "C1"],
figure_kwargs={"figsize": (10, 7)},
)
ax = pc.viz["plot"].sel(column="forest").item()
ax.axvline(0.0, color="black", linestyle="--")
ax.set(
xlabel=f"forecast minus realized total demand of days {NUM_OBSERVED + 1} "
f"to {setup.max_days} (units)"
)
pc.add_legend("model", title="", loc="outside lower center", ncol=1)
pc.viz["figure"].item().suptitle(
"Filter Against a NUTS Refit", fontsize=18, fontweight="bold"
);
The dots are the means and the thick and thin bars the \(50\%\) and \(94\%\) intervals. The intervals of the three forecasts are about as wide, except in scenario \(6\), where the interval of the refit is the widest. The mean CRPS is \(64.5\) units for the filter, \(66.7\) units for the weighted draws and \(68.3\) units for the refit, and six scenarios are too few to rank them by it.
So the filter is close to a refit at a small fraction of its cost. It reacts less than a refit to the highest first week, and its weights remove most of that difference.
References
Orduz, J. (2026). From Forecasts to Decisions: Inventory Planning with Probabilistic Programming. Personal blog.
Orduz, J. (2026). From Forecasts to Decisions: Cannibalization and Shared Capacity. Personal blog.
Alvo, M., Russo, D., Kanoria, Y. and Lee, M. (2023). Deep Reinforcement Learning for Inventory Networks: Toward Reliable Policy Optimization. arXiv:2306.11246.
Zipkin, P. (2008). Old and New Methods for Lost-Sales Inventory Systems. Operations Research, 56(5), 1256-1263.
Bijvank, M. and Vis, I. F. A. (2011). Lost-sales inventory theory: A review. European Journal of Operational Research, 215(1), 1-13.
Huh, W. T., Janakiraman, G., Muckstadt, J. A. and Rusmevichientong, P. (2009). Asymptotic Optimality of Order-Up-To Policies in Lost Sales Inventory Systems. Management Science, 55(3), 404-420.
Goldberg, D. A., Katz-Rogozhnikov, D. A., Lu, Y., Sharma, M. and Squillante, M. S. (2016). Asymptotic Optimality of Constant-Order Policies for Lost Sales Inventory Models with Large Lead Times. Mathematics of Operations Research, 41(3), 898-913.
Gijsbrechts, J., Boute, R. N., Van Mieghem, J. A. and Zhang, D. J. (2022). Can Deep Reinforcement Learning Improve Inventory Management? Performance on Lost Sales, Dual-Sourcing, and Multi-Echelon Problems. Manufacturing & Service Operations Management, 24(3), 1349-1368.
Särkkä, S. and Svensson, L. (2023). Bayesian Filtering and Smoothing. Second edition. Cambridge University Press.
Szabłowski, B. (2026). One Global Model, Many Behaviors: Stockout-Aware Feature Engineering and Dynamic Scaling for Multi-Horizon Retail Demand Forecasting with a Cost-Aware Ordering Policy (VN2 Winner Report). arXiv:2601.18919.
Caron, K. (2023). Modeling Anything With First Principles: Demand under extreme stockouts. Personal blog.
Orduz, J. NumPyro Forecast documentation.
Orduz, J. Getting Started with
dynestyxState Space Models. NumPyro Forecast documentation, development version.Orduz, J. State Space Models with
dynestyxandnumpyro_forecast. NumPyro Forecast documentation, development version.Basis Research.
dynestyxdocumentation.NumPyro team. Effect Handlers in NumPyro: A Practical Guide. NumPyro documentation.
DeepMind. Optax documentation.
Flax team. Flax NNX basics.