Skip to content

ComposableReward reward

ComposableReward

Bases: Reward

Weighted mix of rewards; use to trade off objectives, not with BatchRewards.

ComposableReward evaluates each child reward and combines them according to reduction. The child rewards keep their own masks, while this reward owns the reduction across child rewards.

Parameters:

Name Type Description Default
rewards list

List of Reward instances or async reward functions. A BatchReward is not accepted: it needs the whole batch, while this reward combines its children one sample at a time.

required
weights list

Optional positive weights, one per reward, used by the "mean" and "sum" reductions. Defaults to equal weights.

None
name str

Optional name for the reward instance.

'composable_reward'
reduction str

Optional. How child rewards are combined. One of "mean" (weighted mean), "sum" (weighted sum), "min", "max", "none" or None (both combine like "mean", so each sample keeps a single reward). Defaults to "mean". It only combines the child rewards of each sample: the scores over a batch or a dataset (progress logs, candidate scoring) are always their mean.

'mean'
in_mask list

Optional outer fields to keep before computing rewards.

None
out_mask list

Optional outer fields to remove before computing rewards.

None
in_mask_pattern str

Optional regex of outer fields to keep.

None
out_mask_pattern str

Optional regex of outer fields to remove.

None
Source code in synalinks/src/rewards/composable_reward.py
@synalinks_export(
    [
        "synalinks.ComposableReward",
        "synalinks.rewards.ComposableReward",
    ]
)
class ComposableReward(Reward):
    """Weighted mix of rewards; use to trade off objectives, not with BatchRewards.

    `ComposableReward` evaluates each child reward and combines them according to
    `reduction`. The child rewards keep their own masks, while this reward owns
    the reduction across child rewards.

    Args:
        rewards (list): List of `Reward` instances or async reward functions.
            A `BatchReward` is not accepted: it needs the whole batch, while
            this reward combines its children one sample at a time.
        weights (list): Optional positive weights, one per reward, used by the
            `"mean"` and `"sum"` reductions. Defaults to equal weights.
        name (str): Optional name for the reward instance.
        reduction (str): Optional. How child rewards are combined. One of
            `"mean"` (weighted mean), `"sum"` (weighted sum), `"min"`, `"max"`,
            `"none"` or `None` (both combine like `"mean"`, so each sample
            keeps a single reward). Defaults to `"mean"`. It only combines the
            child rewards of each sample: the scores over a batch or a dataset
            (progress logs, candidate scoring) are always their mean.
        in_mask (list): Optional outer fields to keep before computing rewards.
        out_mask (list): Optional outer fields to remove before computing rewards.
        in_mask_pattern (str): Optional regex of outer fields to keep.
        out_mask_pattern (str): Optional regex of outer fields to remove.
    """

    def __init__(
        self,
        rewards,
        weights=None,
        name="composable_reward",
        description=None,
        reduction="mean",
        in_mask=None,
        out_mask=None,
        in_mask_pattern=None,
        out_mask_pattern=None,
    ):
        # `reduction` combines the children; the batch is always averaged.
        self.combine = standardize_reduction(reduction)
        super().__init__(
            name=name,
            reduction="mean",
            in_mask=in_mask,
            out_mask=out_mask,
            in_mask_pattern=in_mask_pattern,
            out_mask_pattern=out_mask_pattern,
            description=description,
        )
        if not rewards:
            raise ValueError("`rewards` is required and must not be empty.")
        batch_rewards = [r.name for r in rewards if isinstance(r, BatchReward)]
        if batch_rewards:
            raise ValueError(
                f"`ComposableReward` scores one sample at a time, so it cannot "
                f"combine the `BatchReward`s {batch_rewards}. Pass them to "
                "`compile(reward=[...])` instead, which feeds each one the batch."
            )
        self.rewards = [self.standardize_reward(reward) for reward in rewards]
        if weights is None:
            weights = [1.0] * len(self.rewards)
        if len(weights) != len(self.rewards):
            raise ValueError(
                "`weights` must have the same length as `rewards`. "
                f"Received {len(weights)} weights for {len(self.rewards)} rewards."
            )
        self.weights = [float(weight) for weight in weights]
        if any(weight <= 0 for weight in self.weights):
            raise ValueError("All `weights` values must be positive.")

    def standardize_reward(self, reward):
        if isinstance(reward, Reward):
            return reward
        return RewardFunctionWrapper(reward)

    async def __call__(self, y_true, y_pred, x=None):
        return await self.call(*self.mask(y_true, y_pred, x))

    async def call(self, y_true, y_pred, x=None):
        values = [await self.call_reward(r, y_true, y_pred, x) for r in self.rewards]
        if self.combine == "min":
            return tree.map_structure(lambda *v: min(map(float, v)), *values)
        if self.combine == "max":
            return tree.map_structure(lambda *v: max(map(float, v)), *values)
        total = tree.map_structure(
            lambda *v: sum(float(x) * w for x, w in zip(v, self.weights)), *values
        )
        if self.combine == "sum":
            return total
        weight_sum = sum(self.weights)
        return tree.map_structure(lambda value: value / weight_sum, total)

    async def call_reward(self, reward, y_true, y_pred, x=None):
        y_true, y_pred, x = reward.mask(y_true, y_pred, x)
        if accepts_argument(reward.call, "x"):
            value = await reward.call(y_true, y_pred, x=x)
        else:
            value = await reward.call(y_true, y_pred)
        return 0.0 if value is None else value  # A failed reward scores 0.0.

    async def close(self):
        """Close each reward this one combines. Idempotent."""
        for reward in self.rewards:
            await reward.close()

    def get_config(self):
        config = super().get_config()
        config.update(
            {
                "rewards": serialization_lib.serialize_synalinks_object(self.rewards),
                "weights": self.weights,
                "reduction": self.combine,
            }
        )
        return config

    @classmethod
    def from_config(cls, config):
        config = dict(config)
        config["rewards"] = serialization_lib.deserialize_synalinks_object(
            config["rewards"]
        )
        return cls(**config)

close() async

Close each reward this one combines. Idempotent.

Source code in synalinks/src/rewards/composable_reward.py
async def close(self):
    """Close each reward this one combines. Idempotent."""
    for reward in self.rewards:
        await reward.close()