import torch


def huber_loss(x):
    """The classical robust Huber loss, with first and second derivatives."""
    mask = x <= 1
    sx = torch.sqrt(x)
    isx = torch.max(sx.new_tensor(torch.finfo(torch.float).eps), 1/sx)
    loss = torch.where(mask, x, 2*sx-1)
    loss_d1 = torch.where(mask, torch.ones_like(x), isx)
    loss_d2 = torch.where(mask, torch.zeros_like(x), -isx/(2*x))
    return loss, loss_d1, loss_d2