MCPcopy Create free account
hub / github.com/AnswerDotAI/ModernBERT / unpad_input

Function unpad_input

src/bert_padding.py:79–105  ·  view source on GitHub ↗

Remove padding from input sequences. Arguments: hidden_states: (batch, seqlen, ...) attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid. Returns: hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attentio

(
    hidden_states: torch.Tensor,
    attention_mask: torch.Tensor,
)

Source from the content-addressed store, hash-verified

77
78
79def unpad_input(
80 hidden_states: torch.Tensor,
81 attention_mask: torch.Tensor,
82) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, int]:
83 """Remove padding from input sequences.
84
85 Arguments:
86 hidden_states: (batch, seqlen, ...)
87 attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
88
89 Returns:
90 hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
91 indices: (total_nnz)
92 cu_seqlens: (batch + 1), the cumulative sequence lengths, used to index into hidden_states.
93 max_seqlen_in_batch: int ()
94 """
95 seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
96 indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
97 max_seqlen_in_batch = int(seqlens_in_batch.max().item())
98 cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
99 # TD [2022-03-04] We don't want to index with a bool mask, because Pytorch will expand the
100 # bool mask, then call nonzero to get the indices, then index with those. The indices is @dim
101 # times larger than it needs to be, wasting memory. It's faster and more memory-efficient to
102 # index with integer indices. Moreover, torch's index is a bit slower than it needs to be,
103 # so we write custom forward and backward to make it a bit faster.
104 hidden_states = cast(torch.Tensor, index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices))
105 return hidden_states, indices, cu_seqlens, max_seqlen_in_batch
106
107
108def unpad_input_only(

Callers 7

test_unpad_inputFunction · 0.90
test_pad_inputFunction · 0.90
test_roundtripFunction · 0.90
test_token_inputFunction · 0.90
test_2d_inputFunction · 0.90
test_rotary_emb_unpadFunction · 0.90
test_rotaryFunction · 0.90

Calls

no outgoing calls

Tested by 7

test_unpad_inputFunction · 0.72
test_pad_inputFunction · 0.72
test_roundtripFunction · 0.72
test_token_inputFunction · 0.72
test_2d_inputFunction · 0.72
test_rotary_emb_unpadFunction · 0.72
test_rotaryFunction · 0.72