keras/src/metrics/reduction_metrics.py/reduce_to_samplewise_values
def reduce_to_samplewise_values(values, sample_weight, reduce_fn, dtype):
    dtype = dtype or backend.floatx()
    mask = getattr(values, "_keras_mask", None)
    values = ops.cast(values, dtype=dtype)
    if sample_weight is not None:
        sample_weight = ops.convert_to_tensor(sample_weight, dtype=dtype)

        if mask is not None:
            sample_weight = losses.loss.apply_mask(
                sample_weight, mask, dtype=dtype, reduction="sum"
            )
        # Update dimensions of weights to match with values if possible.
        values, sample_weight = losses.loss.squeeze_or_expand_to_same_rank(
            values, sample_weight
        )
        # Reduce values to same ndim as weight array.
        weight_ndim = len(sample_weight.shape)
        values_ndim = len(values.shape)
        if values_ndim > weight_ndim:
            values = reduce_fn(
                values, axis=list(range(weight_ndim, values_ndim))
            )
        # Broadcast sample_weight. It doesn't change the multiplication below
        # but changes the sample_weight reduction applied later.
        sample_weight = ops.broadcast_to(sample_weight, ops.shape(values))
        values = values * sample_weight
        if weight_ndim > 1:
            sample_weight = reduce_fn(
                sample_weight, axis=list(range(1, weight_ndim))
            )

    values_ndim = len(values.shape)
    if values_ndim > 1:
        values = reduce_fn(values, axis=list(range(1, values_ndim)))
    return values, sample_weight