import torch


def reparametrize(
    x_min, x_max, y_min, y_max, reparametrization_h, reparametrization_w,
    inplace=False, inverse=False):
    """
        If `inverse is False`, scale module's parameters so that their range becomes
        approximately [-1; 1]. Otherwise, do the inverse operation.

        This hack is unfortunately needed for the parameters to work with variants of SGD.
        Without this "reparametrization", box sizes' gradients will be extremely small.

        If `not inplace`, returns 4 new tensors, otherwise modifies the given ones.
    """
    scalar_h = reparametrization_h if inverse else (1 / reparametrization_h)
    scalar_w = reparametrization_w if inverse else (1 / reparametrization_w)

    with torch.no_grad():
        if inplace:
            x_min *= scalar_h
            x_max *= scalar_h
            y_min *= scalar_w
            y_max *= scalar_w
        else:
            return x_min * scalar_h, x_max * scalar_h, y_min * scalar_w, y_max * scalar_w