import torch


def quaternion_inv(q):
    """
    inverse quaternion(s) q
    The quaternion should be in (x, y, z, w) format.
    Expects  tensors of shape (*, 4), where * denotes any number of dimensions.
    Returns q*r as a tensor of shape (*, 4).
    """
    assert q.shape[-1] == 4

    q_conj = q[..., :3] * -1.0
    q_conj = torch.cat((q_conj, q[..., 3:]), dim=-1)
    q_norm = torch.norm(q, dim=-1, keepdim=True)
    return q_conj / q_norm