Skip to content

Bin packing MDP formulation

The bin packing problem is an example of an infinite horizon MDP. Weights arrive sequentially and must be assigned to one of several bins. Each bin has a maximum capacity (max_bin_size). When a bin's total weight exceeds this capacity, the overflow weight incurs a cost, and the bin is emptied. The goal is to minimize the total overflow cost over an infinite horizon.

In this problem, weights are revealed one by one according to a probability distribution. Each weight must be immediately assigned to one of the available bins. When a bin exceeds its maximum capacity, any overflow weight incurs a cost proportional to the overflow amount, and the bin is reset to empty. The process continues indefinitely.

Note

This is an infinite horizon MDP, meaning the process continues indefinitely rather than terminating after a fixed number of steps. This contrasts with finite horizon MDPs like the airplane MDP, which has a fixed termination time (day 26).

In infinite horizon MDPs, it is especially important to explicitly track time progression. DynaPlex requires you to manually update context.time_elapsed to track the passage of time. In this bin packing problem, time progresses by one unit each time a new random weight arrives (in the modify_state_with_event function).

The components of the MDP

  1. States (S): The state consists of:

    • weight_vector: a list holding the current weight in each bin
    • upcoming_weight: the weight that has just arrived and must be assigned
    • category: the state category (AWAIT_EVENT or AWAIT_ACTION)
  2. Actions (A): The action is to select which bin (0 to number_of_bins - 1) to assign the upcoming weight to. All bins are always valid actions. (This is unlike the airplane ticket selling MDP, where the action space was constrained.)

  3. Randomness / events: A new item arrives that will need to be added to a bin. The weight of the item is sampled from a distribution — in the implementation, a DiscreteDist held by the MDP, drawn via an AliasSampler for fast repeated sampling.

  4. Transitions:

    • When a new weight arrives (event), it is sampled from the weight distribution and stored in upcoming_weight. The state transitions to AWAIT_ACTION, and context.time_elapsed is incremented.
    • When an action is taken, the weight is added to the selected bin. If the bin overflows, the overflow cost is added to context.cumulative_cost, and the bin is reset to empty. The state transitions back to AWAIT_EVENT.
  5. Costs (C): The cost is the overflow amount when a bin exceeds its capacity.

Time tracking in infinite horizon MDPs

Unlike finite horizon MDPs where time is naturally bounded, infinite horizon MDPs require explicit time tracking. In DynaPlex, you must manually increment context.time_elapsed to track the progression of time. This is essential for:

  • algorithms that need to know how many steps have elapsed;
  • stopping criteria for training or evaluation.

In this bin packing problem, time advances by one unit each time a new weight arrives, which happens in the modify_state_with_event function: context.time_elapsed += 1.

Policy

This MDP example includes two simple heuristic policies:

  1. LowestWeightPolicy: always assigns the incoming weight to the bin with the lowest current weight. This is a greedy strategy that tries to balance the load across bins.

  2. FirstFitPolicy: assigns the weight to the first bin that can accommodate it without overflow. If no bin can accommodate it without overflow, it assigns to the first bin. This is a common heuristic in bin packing problems.

Python code

You can download a complete Python implementation of this MDP example: binpacking.py.

Below is the full code for reference; note that other files could import from this and use the MDP, e.g. for training policies:

binpacking.py
"""
Bin Packing MDP example in DynaML - the dynamic modelling language for DynaPlex.
Includes:
- BinPackingMDP: The MDP class
- LowestWeightPolicy: A simple heuristic policy that assigns the incoming weight to the bin with the lowest current weight
- FirstFitPolicy: A simple heuristic policy that assigns the incoming weight to the first bin that can accommodate it without overflow
- State: The state class
"""
from dataclasses import dataclass
from typing import Final

from dynaplex.modelling import (
    Featurizer,
    AliasSampler,
    DiscreteDist,
    GlobalStateCounter,
    GlobalStateWriter,
    HorizonType,
    StateCategory,
    TrajectoryContext,
    Validity,
    const_dataclass,
    featurizer,
    probe_state,
)
from dynaplex.validation import mdp, policy


@dataclass(slots=True)
class State:
    """
    State representation for the bin packing MDP.
    """
    weight_vector: list[int]  # Current weight in each bin
    upcoming_weight: int      # Weight to be assigned
    # This member must always be defined on any dynaplex MDP state:
    category: StateCategory = StateCategory.AWAIT_EVENT


@mdp
@const_dataclass(init=False, slots=True)
class BinPackingMDP:
    """
    Bin Packing MDP is an infinite horizon online bin packing problem. 

    In this problem, weights are revealed one by one and must be assigned to one of several bins.
    When a bin exceeds max_bin_size, any overflow weight incurs a cost.
    The goal is to minimize total overflow cost across the episode.

    Actions:
        0 to number_of_bins-1: Assign weight to the corresponding bin
    """
    max_bin_size: int
    number_of_bins: int
    weight_dist: DiscreteDist         # Distribution of arriving weights
    weight_sampler: AliasSampler      # O(1) repeated-draw sampler over weight_dist
    num_actions: int
    horizon_type: HorizonType


    def __init__(
        self,
        max_bin_size: int,
        number_of_bins: int,
        weight_dist: DiscreteDist,
    ):
        """
        Initialize the Bin Packing MDP with validation.

        Args:
            max_bin_size: Maximum weight a bin can hold before overflow (must be > 0)
            number_of_bins: Number of bins available (must be > 0)
            weight_dist: Distribution of the arriving weights (non-negative support);
                         non-consecutive weight values are expressed as zero-probability
                         gaps in the PMF (e.g. DiscreteDist.custom(probs, offset=10))

        Raises:
            AssertionError: If any validation checks fail
        """
        # NOTE: __init__ on the MDP class itself is never called by the dynaplex compiler,
        # so we can use any valid cpython code here, but the class must be a dataclass,
        # and other functions need to be valid DynaML code.

        # Validating parameters
        assert max_bin_size > 0, "max_bin_size must be positive"
        assert number_of_bins > 0, "number_of_bins must be positive"
        assert weight_dist.min() >= 0, "weights must be non-negative"

        # Set attributes
        # NOTE: only set attributes that are part of the annotation.
        self.max_bin_size = max_bin_size
        self.number_of_bins = number_of_bins
        self.weight_dist = weight_dist
        self.weight_sampler = weight_dist.alias_sampler()
        # Number of actions in the MDP that are potentially valid
        self.num_actions = number_of_bins
        # Horizon type for this MDP
        self.horizon_type = HorizonType.INFINITE


    def get_initial_state(self, context: TrajectoryContext) -> State:
        """
        Generates and returns an initial state of the MDP.
        """
        return State(
            weight_vector=[0] * self.number_of_bins,
            upcoming_weight=0,
            category=StateCategory.AWAIT_EVENT,
        )


    def modify_state_with_event(self, state: State, context: TrajectoryContext) -> None:
        """
        Generate a weight arrival event and modify state in place.

        Args:
            state: Current state (modified in place)
            context: Trajectory context containing rng and cumulative_cost
        """
        # Sample a weight from the distribution
        state.upcoming_weight = self.weight_sampler.sample(context.rng)


        # Next, the agent must decide which bin to assign the weight to
        state.category = StateCategory.AWAIT_ACTION
        # time elapsed increases by 1
        context.time_elapsed += 1


    def modify_state_with_action(self, state: State, context: TrajectoryContext, action: int) -> None:
        """
        Apply an action to the state (modify in place).

        Args:
            state: Current state (modified in place)
            context: Trajectory context containing cumulative_cost (updated in place)
            action: Bin index to assign the weight to (0 to number_of_bins-1)
        """
        # NOTE: do _not_ attempt to generate random numbers here; that is what modify_state_with_event is for.       

        assert action >= 0 and action < self.number_of_bins, f"Invalid action: {action}"
        # Assign weight to the selected bin
        state.weight_vector[action] += state.upcoming_weight

        # Calculate overflow amount
        diff = state.weight_vector[action] - self.max_bin_size

        if diff >= 0:
            # Bin overflows: incur cost and dispatch (empty) the bin
            context.cumulative_cost += float(diff)
            state.weight_vector[action] = 0

        # Reset upcoming weight
        state.upcoming_weight = 0

        # Transition back to await next event (infinite horizon - never reaches FINAL)
        state.category = StateCategory.AWAIT_EVENT


    def write_action_validity(self, state: State, valid: Validity) -> None:
        """
        Write action validity: valid[i] = True if action i is allowed in the current state
                               valid[i] = False otherwise.

        Args:
            state: Current state
            valid: Boolean array of length num_actions to write the validity mask to
        """
        # All bins are always valid actions in this problem. write_action_validity must write EVERY
        # entry (the contract is "valid[i] = True if allowed, False otherwise" — the caller's buffer
        # is not pre-initialised), so set them all explicitly rather than relying on a default.
        for i in range(self.number_of_bins):
            valid.set(i, True)


@policy
@const_dataclass(slots=True)
class LowestWeightPolicy:
    """
    Simple heuristic policy for the bin packing MDP.

    This policy always assigns the incoming weight to the bin with the lowest current weight.
    """
    mdp: BinPackingMDP

    def get_action(self, state: State) -> int:
        """
        Assigns weight to the bin with the lowest current weight.

        Args:
            state: Current state

        Returns:
            Action (bin index to assign weight to)
        """
        # NOTE: this function must be valid DynaML code.

        # Find bin with minimum weight
        min_weight = state.weight_vector[0]
        min_index = 0

        for i in range(1, len(state.weight_vector)):
            if state.weight_vector[i] < min_weight:
                min_weight = state.weight_vector[i]
                min_index = i

        return min_index


@policy
@const_dataclass(slots=True)
class FirstFitPolicy:
    """
    First-fit heuristic policy.

    Assigns weight to the first bin that can accommodate it without overflow.
    If no bin can accommodate it, assigns to the first bin.
    """
    mdp: BinPackingMDP

    def get_action(self, state: State) -> int:
        for i in range(len(state.weight_vector)):
            if state.weight_vector[i] + state.upcoming_weight <= self.mdp.max_bin_size:
                return i        
        # If no bin can accommodate, use first bin
        return 0

@featurizer
@dataclass(slots=True)
class BinPackingFeaturizer(Featurizer):
    """Default featurizer for BinPackingMDP (@featurizer derives the holder and
    synthesizes bind/reset/finish — featurizers.md section 13)."""
    mdp: Final[BinPackingMDP]
    v: Final[GlobalStateWriter]

    def write_features(self, state: State) -> None:
        self.v.extend(state.weight_vector)
        self.v.append(state.upcoming_weight)

    # Optional — this is exactly the body @featurizer synthesizes when spec() is
    # omitted: sizing-by-counting on a probe state. Edit the return to declare
    # sizes explicitly instead (here:
    # {"v": TensorSpec(Dtype.float32, (self.mdp.number_of_bins + 1,))}).
    def spec(self) -> dict:
        state = probe_state(self.mdp)
        v = GlobalStateCounter()
        twin = BinPackingFeaturizer(mdp=self.mdp, v=v)
        twin.write_features(state)
        return {"v": v.spec()}

Training a DCL agent

With the model and the two heuristic policies in place, we can train a neural network policy with Deep Controlled Learning and see whether it beats the heuristics. Download binpacking_dcl.py, place it next to binpacking.py, and run it:

binpacking_dcl.py
"""
Training a DCL agent on the bin packing MDP, and comparing it against the
FirstFit and LowestWeight heuristics on common random numbers.

Place this file next to binpacking.py (the model file from the tutorial) and
run it directly. Artifacts (samples, trained agents) land in dynaplex_runs/;
rerunning resumes rather than recomputes.
"""
import numpy as np

import dynaplex as dp
from dynaplex.modelling import DiscreteDist, assert_mdp, assert_policy_for_mdp

try:
    # If you author your own models, you can import them from another file 
    # as you would any other Python module:
    from binpacking import (  # pyright: ignore[reportMissingImports]  # local-file form; falls back to dynaplex.models below
        BinPackingMDP,
        BinPackingFeaturizer,
        FirstFitPolicy,
        LowestWeightPolicy,
    )
except ImportError:
    # Since binpacking is also one of the built-in models that ships with 
    # DynaPlex, we can also import it directly from the dynaplex.models.binpacking module.. 
    from dynaplex.models.binpacking import (
        BinPackingMDP,
        BinPackingFeaturizer,
        FirstFitPolicy,
        LowestWeightPolicy,
    )


def main() -> None:
    # Weights 10/20/30/40/50: a PMF over 10..50 with zero-probability gaps.
    weight_probs = np.zeros(41)
    weight_probs[[0, 10, 20, 30, 40]] = [0.2, 0.3, 0.25, 0.15, 0.1]
    mdp = BinPackingMDP(
        max_bin_size=100,
        number_of_bins=3,
        weight_dist=DiscreteDist.custom(weight_probs, offset=10),
    )

    lowest_weight = LowestWeightPolicy(mdp=mdp)
    first_fit = FirstFitPolicy(mdp=mdp)

    # No-ops at runtime; they make pyright statically verify that the MDP and
    # policies satisfy the interfaces DynaPlex expects.
    assert_mdp(mdp)
    assert_policy_for_mdp(mdp, lowest_weight)
    assert_policy_for_mdp(mdp, first_fit)

    # What is collected: no featurizer and no network here. Generation 0 stores the
    # state of every sample, so other featurizers and networks can be tried on it
    # later without collecting again.
    d = dp.DCL(
        mdp, lowest_weight,                # generation-0 rollout policy
        n=8000,                            # labeled samples per generation
        m=200,                             # rollouts per candidate action
        h=100,                             # rollout horizon (periods)
    )
    # What is trained on it: a featurizer, a network and the training settings.
    agents = d.run(
        3,                                 # generations
        features=BinPackingFeaturizer,
        # NOTE: a plain MLP over the raw (unsorted) weight vector ignores the
        # symmetry between bins — see the warning in the tutorial.
        network=dp.MLP(hidden=[128, 128]),
        train=dict(loss="soft_ce", epochs=50, batch_size=64, lr=1e-3,   # soft_ce is the default
                   patience=10, val_fraction=0.1),
    )

    # Evaluate all policies on common random numbers: each sees the same
    # weight streams, so the delta columns are paired differences.
    comparer = dp.PolicyComparer(
        mdp,
        number_of_trajectories=100,
        warmup_time=100,
        horizon=1000,
        seed=0,
    )
    to_compare = {
        "LowestWeight": lowest_weight,
        "FirstFit": first_fit,
    }
    for agent in agents:
        to_compare[f"DCL_gen{agent.info['generation']}"] = agent
    print(comparer.compare(to_compare))


if __name__ == "__main__":
    main()

The script calls assert_mdp and assert_policy_for_mdp — no-ops at runtime that make pyright binpacking_dcl.py statically verify that the MDP and policies satisfy the interfaces DynaPlex expects (see the airplane tutorial for details).

The script trains three DCL generations, starting from LowestWeightPolicy as the generation-0 rollout policy, and then evaluates everything with the PolicyComparer on common random numbers.

Unexploited symmetry may hamper performance

This model is deliberately kept simple, and that leaves DRL performance on the table. The bins are interchangeable — any permutation of weight_vector describes an equivalent state — but the model does not sort the weights after adding each weight, and the featurizer feeds the raw vector to a plain MLP. Equivalent states therefore look different to the network, which must spend training data and capacity learning the symmetry instead of having it built in. A canonical state — e.g. keeping weight_vector sorted after every assignment, so that action i means "assign to the i-th fullest bin" — exploits the symmetry and typically learns faster and reaches better policies.

It takes a few minutes on a laptop; training artifacts land in dynaplex_runs/, and rerunning the script resumes from what is already here instead of recomputing.

On our machine the comparison comes out as follows (network training is seeded but follows torch's determinism caveats, so your numbers may differ slightly — the ordering should not):

policy                  mean       error    delta_mean  delta_error
LowestWeight *        2.6381     0.01583             0            0
FirstFit              2.6298     0.01543       -0.0083     0.004839
DCL_gen1              2.5504      0.0164       -0.0877      0.02135
DCL_gen2              2.3791     0.01584        -0.259      0.01681
DCL_gen3              2.0206     0.01277       -0.6175      0.01875
(* = benchmark; delta = policy - benchmark, paired on common random numbers)

The two heuristics are nearly tied at about 2.63 overflow cost per period. Each DCL generation improves on the previous one, and the generation-3 agent reaches 2.02 — beating the heuristics by roughly 23%, with the paired delta column showing the improvement is far outside the noise.

Solving it exactly

This instance is small enough to solve exactly: three bins holding a multiple of 10 each and five possible arriving weights make 5000 decision states. The exact solver enumerates them, computes the heuristics' costs exactly (both 2.6546 per period) and finds the optimal policy, at 0.069 per period — a policy that fills bins to exactly 100, where emptying costs nothing. The DCL agent above improves on the heuristics but is still far from that optimum; the exact solver page walks through the instance and reads the optimal decisions state by state.