def one_hot(val: torch.LongTensor, num: int) -> torch.FloatTensor:
    """
    **Overview**:
        Convert a ``torch.LongTensor`` to one hot encoding with scatter API.
        This implementation can be slightly faster than ``torch.nn.functional.one_hot`` .
    """
    # Remember original shape of ``val`` .
    old_shape = val.shape
    # Reshape ``val`` into 2D tensor.
    val_reshape = val.reshape(-1, 1)
    # Initialize return tensor with float32 dtype and the same device as val.
    ret = torch.zeros(val_reshape.shape[0], num, device=val.device)
    # Fill value 1 into tensor ``ret`` , according to the index stored in ``val_reshape`` . It is an inplace operation.
    ret.scatter_(1, val_reshape, 1)
    # Return the reshaped result with the same prefix shape as original shape of val.
    return ret.reshape(*old_shape, num)

    **Overview**:
        Convert a ``torch.LongTensor`` to one hot encoding with scatter API.
        This implementation can be slightly faster than ``torch.nn.functional.one_hot`` .
    
chapter3_obs/encoding.py