import torch
from typing import Optional


def calc_mse(
    x: torch.Tensor,
    y: torch.Tensor,
    mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
    """
    Calculates the mean square error between tensors `x` and `y`.
    """
    if mask is None:
        return torch.mean((x - y) ** 2)
    else:
        return (((x - y) ** 2) * mask).sum() / mask.expand_as(x).sum().clamp(1e-5)