Implement a custom PyTorch module for a multi-head self-attention mechanism, ensuring proper tensor dimension handling and masking.