import torch


def _tblr_pred_to_delta_xywh_pred(bbox_pred: torch.Tensor,
                                  normalizer: torch.Tensor) -> torch.Tensor:
    """Transform tblr format bbox prediction to delta_xywh format for ncnn.

    An internal function for transforming tblr format bbox prediction to
    delta_xywh format. NCNN DetectionOutput layer needs delta_xywh format
    bbox_pred as input.

    Args:
        bbox_pred (Tensor): The bbox prediction of tblr format, has shape
            (N, num_det, 4).
        normalizer (Tensor): The normalizer scale of bbox horizon and
            vertical coordinates, has shape (2,).

    Returns:
        Tensor: The delta_xywh format bbox predictions.
    """
    top = bbox_pred[:, :, 0:1]
    bottom = bbox_pred[:, :, 1:2]
    left = bbox_pred[:, :, 2:3]
    right = bbox_pred[:, :, 3:4]
    h = (top + bottom) * normalizer[0]
    w = (left + right) * normalizer[1]

    _dwh = torch.cat([w, h], dim=2)
    assert torch.all(_dwh >= 0), 'wh must be positive before log.'
    dwh = torch.log(_dwh)

    return torch.cat([(right - left) / 2, (bottom - top) / 2, dwh], dim=2)