import torch


def decode_box_outputs(rel_codes, anchors):
    """Transforms relative regression coordinates to absolute positions.
    Args:
        rel_codes: batched box regression targets.
        anchors: batched anchors on all feature levels.
    Returns:
        outputs: batched bounding boxes.
    """
    y_center_a = (anchors[:, :, 0] + anchors[:, :, 2]) / 2
    x_center_a = (anchors[:, :, 1] + anchors[:, :, 3]) / 2
    ha = anchors[:, :, 2] - anchors[:, :, 0]
    wa = anchors[:, :, 3] - anchors[:, :, 1]
    ty, tx = rel_codes[:, :, 0], rel_codes[:, :, 1]
    th, tw = rel_codes[:, :, 2], rel_codes[:, :, 3]

    w = torch.exp(tw) * wa
    h = torch.exp(th) * ha
    y_center = ty * ha + y_center_a
    x_center = tx * wa + x_center_a
    y_min = y_center - h / 2.
    x_min = x_center - w / 2.
    y_max = y_center + h / 2.
    x_max = x_center + w / 2.
    outputs = torch.stack([y_min, x_min, y_max, x_max], dim=-1)

    return outputs