MCPcopy Create free account
hub / github.com/TransluceAI/observatory / pad_sequence

Function pad_sequence

project/user_modeling/user_modeling/padding_util.py:4–35  ·  view source on GitHub ↗

Pad a list of sequences to the same length and return input_ids and attention_mask tensors. If `max_length` is provided, AND if the `max_length` is longer than the longest sequence, pad the sequences to the same length up to `max_length`.

(
    sequences: list[list[int]] | list[list[bool]],
    pad_token_id: int | bool,
    padding_side: str = "right",
    max_length: int | None = None,
)

Source from the content-addressed store, hash-verified

2
3
4def pad_sequence(
5 sequences: list[list[int]] | list[list[bool]],
6 pad_token_id: int | bool,
7 padding_side: str = "right",
8 max_length: int | None = None,
9) -> tuple[torch.Tensor, torch.Tensor]:
10 """
11 Pad a list of sequences to the same length and return input_ids and attention_mask tensors.
12
13 If `max_length` is provided, AND if the `max_length` is longer than the longest sequence,
14 pad the sequences to the same length up to `max_length`.
15 """
16 seq_tensors = [torch.tensor(seq) for seq in sequences]
17 ones_tensors = [torch.ones_like(seq, dtype=torch.int32) for seq in seq_tensors]
18 input_ids = torch.nn.utils.rnn.pad_sequence(
19 seq_tensors, batch_first=True, padding_value=pad_token_id, padding_side=padding_side
20 )
21 attention_mask = torch.nn.utils.rnn.pad_sequence(
22 ones_tensors, batch_first=True, padding_value=0, padding_side=padding_side
23 )
24 if max_length is not None:
25 cur_len = input_ids.shape[1]
26 if cur_len < max_length:
27 pad_len = max_length - cur_len
28 if padding_side == "right":
29 input_ids = torch.nn.functional.pad(input_ids, (0, pad_len), value=pad_token_id)
30 attention_mask = torch.nn.functional.pad(attention_mask, (0, pad_len), value=0)
31 else:
32 input_ids = torch.nn.functional.pad(input_ids, (pad_len, 0), value=pad_token_id)
33 attention_mask = torch.nn.functional.pad(attention_mask, (pad_len, 0), value=0)
34
35 return input_ids, attention_mask
36
37
38def strip_padding(token_ids: list[int], pad_token_id: int, padding_side: str = "left") -> list[int]:

Callers 4

collate_fnMethod · 0.90
collate_fnMethod · 0.90
collate_examplesMethod · 0.90
evaluate_controlFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected