Skip to content

BatchReward reward

Bases: Reward

Batch reward base; use when a sample's score depends on the rest of the batch.

Subclasses receive the entire batch at once and must return one reward per sample. Use this when the reward needs cross-sample context (e.g. group-relative scores, batch normalization, paired comparisons).

To be implemented by subclasses:

  • call(y_true, y_pred): y_true and y_pred are lists of length batch_size. MUST return a list[float] of the same length, one reward per sample. Declare an x argument to also get the batch's inputs (a list) during fit / evaluate.

Parameters:

Name Type Description Default
name str

Optional name for the reward instance.

None
reduction str

Optional. One of "mean", "sum", "min", "max", "none" or None. Applied by __call__ when called on a batch directly. The trainer consumes the unreduced per-sample list via compute_batch, but propagates this value to control the scalar shown in progress logs and used for candidate scoring ("none"/None falls back to "mean" for those).

'mean'
in_mask list

Optional. List of exact field names to keep before computing the reward.

None
out_mask list

Optional. List of exact field names to drop before computing the reward.

None
in_mask_pattern str

Optional. Regex pattern; fields whose names match are kept (combined with in_mask).

None
out_mask_pattern str

Optional. Regex pattern; fields whose names match are dropped (combined with out_mask).

None
Source code in synalinks/src/rewards/batch_reward.py
@synalinks_export(["synalinks.BatchReward", "synalinks.rewards.BatchReward"])
class BatchReward(Reward):
    """Batch reward base; use when a sample's score depends on the rest of the batch.

    Subclasses receive the entire batch at once and must return one reward
    per sample. Use this when the reward needs cross-sample context (e.g.
    group-relative scores, batch normalization, paired comparisons).

    To be implemented by subclasses:

    * ``call(y_true, y_pred)``: ``y_true`` and ``y_pred`` are lists of
      length ``batch_size``. MUST return a ``list[float]`` of the same
      length, one reward per sample. Declare an ``x`` argument to also get
      the batch's inputs (a list) during ``fit`` / ``evaluate``.

    Args:
        name (str): Optional name for the reward instance.
        reduction (str): Optional. One of ``"mean"``, ``"sum"``, ``"min"``,
            ``"max"``, ``"none"`` or ``None``. Applied by ``__call__`` when
            called on a batch directly. The trainer consumes the unreduced
            per-sample list via ``compute_batch``, but propagates this
            value to control the scalar shown in progress logs and used
            for candidate scoring (``"none"``/``None`` falls back to
            ``"mean"`` for those).
        in_mask (list): Optional. List of exact field names to keep before
            computing the reward.
        out_mask (list): Optional. List of exact field names to drop before
            computing the reward.
        in_mask_pattern (str): Optional. Regex pattern; fields whose names
            match are kept (combined with ``in_mask``).
        out_mask_pattern (str): Optional. Regex pattern; fields whose names
            match are dropped (combined with ``out_mask``).
    """

    async def __call__(self, y_true, y_pred, x=None):
        rewards = await self.compute_batch(y_true, y_pred, x=x)
        return reduce_values(rewards, reduction=self.reduction)

    async def compute_batch(self, y_true, y_pred, x=None):
        """Apply masks and return the per-sample reward list (unreduced).

        This is what the trainer calls: it expects the raw ``list[float]``
        of length ``batch_size`` so it can treat each entry as that
        sample's reward. A ``call`` that declares ``x`` also gets the
        batch's inputs (a list, unmasked).
        """
        with ops.name_scope(self.name):
            y_true, y_pred, x = self.mask(y_true, y_pred, x)
            if accepts_argument(self.call, "x"):
                rewards = await self.call(y_true, y_pred, x=x)
            else:
                rewards = await self.call(y_true, y_pred)
            cls_name = type(self).__name__
            if isinstance(rewards, (list, tuple)):
                pass
            elif hasattr(rewards, "__iter__") and not isinstance(
                rewards, (str, bytes, dict)
            ):
                # Accept numpy arrays / generators / other iterables of floats.
                rewards = list(rewards)
            else:
                raise TypeError(
                    f"`{cls_name}.call` must return a list of per-sample floats. "
                    f"Got {type(rewards).__name__}."
                )
            if hasattr(y_pred, "__len__") and len(rewards) != len(y_pred):
                raise ValueError(
                    f"`{cls_name}.call` returned {len(rewards)} rewards but the "
                    f"batch has {len(y_pred)} samples; they must match."
                )
            return [0.0 if r is None else float(r) for r in rewards]

    async def call(self, y_true, y_pred):
        raise NotImplementedError

compute_batch(y_true, y_pred, x=None) async

Apply masks and return the per-sample reward list (unreduced).

This is what the trainer calls: it expects the raw list[float] of length batch_size so it can treat each entry as that sample's reward. A call that declares x also gets the batch's inputs (a list, unmasked).

Source code in synalinks/src/rewards/batch_reward.py
async def compute_batch(self, y_true, y_pred, x=None):
    """Apply masks and return the per-sample reward list (unreduced).

    This is what the trainer calls: it expects the raw ``list[float]``
    of length ``batch_size`` so it can treat each entry as that
    sample's reward. A ``call`` that declares ``x`` also gets the
    batch's inputs (a list, unmasked).
    """
    with ops.name_scope(self.name):
        y_true, y_pred, x = self.mask(y_true, y_pred, x)
        if accepts_argument(self.call, "x"):
            rewards = await self.call(y_true, y_pred, x=x)
        else:
            rewards = await self.call(y_true, y_pred)
        cls_name = type(self).__name__
        if isinstance(rewards, (list, tuple)):
            pass
        elif hasattr(rewards, "__iter__") and not isinstance(
            rewards, (str, bytes, dict)
        ):
            # Accept numpy arrays / generators / other iterables of floats.
            rewards = list(rewards)
        else:
            raise TypeError(
                f"`{cls_name}.call` must return a list of per-sample floats. "
                f"Got {type(rewards).__name__}."
            )
        if hasattr(y_pred, "__len__") and len(rewards) != len(y_pred):
            raise ValueError(
                f"`{cls_name}.call` returned {len(rewards)} rewards but the "
                f"batch has {len(y_pred)} samples; they must match."
            )
        return [0.0 if r is None else float(r) for r in rewards]