import torch


def generate_anchor(
    grid_height: int, grid_width: int, anchor_wh: torch.Tensor, device: torch.device
) -> torch.Tensor:
    """Generates grid anchors for a single level.

    Args:
        grid_height (int): Height of feature map.
        grid_width (int): Width of feature map.
        anchor_wh (torch.Tensor): Width and height of the anchor boxes.
        device (torch.device): The device which a `torch.Tensor` is on or
            will be allocated.

    Returns:
        (torch.Tensor): Anchors of a feature map in a single level.
    """
    num_anchors = len(anchor_wh)
    y_vec, x_vec = torch.meshgrid(torch.arange(grid_height), torch.arange(grid_width))
    x_vec, y_vec = x_vec.to(device), y_vec.to(device)

    # Shape 2 x grid_height x grid_width
    mesh = torch.stack([x_vec, y_vec], dim=0)
    # Shape num_anchors x 2 x grid_height x grid_width
    mesh = mesh.unsqueeze(0).repeat(num_anchors, 1, 1, 1).float()
    # Shape num_anchors x 2 x grid_height x grid_width
    anchor_offset_mesh = (
        anchor_wh.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, grid_height, grid_width)
    )
    # Shape num_anchors x 4 x grid_height x grid_width
    anchor_mesh = torch.cat([mesh, anchor_offset_mesh], dim=1)
    return anchor_mesh