Skip to content
ML Academy

Neural networks, deep learning, NLP · insight-1461

Check mask polarity at every library boundary, because True can mean attend or ignore

Evidence type
documented fact
Difficulty
medium
Roles
ML engineer, Applied AI
Industries
cross-industry

Summary: situation, action, reason, boundary

  1. Situation

    Custom transformer code combines a Hugging Face attention_mask with nn.MultiheadAttention or scaled_dot_product_attention.

  2. Action

    Convert once with a named helper, assert the convention at the boundary, and test that a short sequence gives the same output alone and padded inside a batch.

  3. Reason

    Hugging Face uses 1 for tokens to attend and 0 for padding; MultiheadAttention's boolean key_padding_mask marks positions to ignore with True, whereas scaled_dot_product_attention's boolean mask uses True for positions that take part.

  4. Boundary

    Any code mixing masks from tokenizers, nn.MultiheadAttention and fused attention functions.

Symptom or risk

An inverted mask attends to padding and ignores real tokens; shapes match, the loss still falls, and the model is just mediocre.

Exceptions

Using one library end to end with its own mask helper.

Trade-offs

One extra unit test and helper.

Pitfalls

Fixing the symptom by inverting in one place and double-inverting elsewhere; float masks that are added, not selected.

Lessons and concepts

Claims and their sources