from typing import List, Tuple, Optional import numpy as np def batch_sort(S: np.ndarray[int], START: int, END: int, reverse: bool = True) -> List[np.ndarray]: """ Extracts subsequences between START/END tokens and sorts by length. Args: S: Input array of tokens. START: Token marking sequence start. END: Token marking sequence end. reverse: If True, sorts descending (longest first). Returns: List of subsequences as numpy arrays. """ sequences: List[np.ndarray] = [] current_seq = [] in_sequence = False for token in S: if token == START: current_seq = [token] in_sequence = True elif token == END and in_sequence: current_seq.append(token) sequences.append(np.array(current_seq, dtype=S.dtype)) in_sequence = False elif in_sequence: current_seq.append(token) sequences.sort(key=lambda x: len(x), reverse=reverse) return sequences def pack_sequences( S: np.ndarray[int], N: int, START: int, END: int, PAD: Optional[int] = None, reverse: bool = True, ) -> Tuple[np.ndarray, np.ndarray]: """ Packs subsequences into batches of size N, respecting START/END boundaries. Args: S: Input array of tokens. N: Batch size (must be >= longest sequence). START: Start token. END: End token. PAD: Padding token. If None, uses max_token + 1. reverse: Sort sequences by length descending if True. Returns: BATCH: Padded array of shape (num_batches, N). attention_mask: Boolean mask where True = non-PAD. Example: >>> S = np.array([0, 5, 1, 0, 3, 1]) >>> BATCH, mask = pack_sequences(S, N=4, START=0, END=1) >>> BATCH array([[0, 5, 1, 0], [3, 1, 102, 102]]) """ sequences = batch_sort(S, START, END, reverse=reverse) # Input validation assert len(S) > 0, "Input array is empty" max_len = max(len(seq) for seq in sequences) assert N >= max_len, f"Batch size {N} < longest sequence ({max_len})" # Auto-select PAD if PAD is None: PAD_candidate = max(np.max(seq) for seq in sequences) + 1 PAD = PAD_candidate # Pack sequences batches: List[np.ndarray] = [] for seq in sequences: placed = False for i, batch in enumerate(batches): if len(batch) + len(seq) <= N: batches[i] = np.concatenate([batch, seq]) placed = True break if not placed: batches.append(seq) # Pad batches BATCH = np.full((len(batches), N), PAD, dtype=sequences[0].dtype) for i, batch in enumerate(batches): BATCH[i, :len(batch)] = batch return BATCH, (BATCH != PAD) def packing_efficiency(BATCH: np.ndarray, PAD: int) -> float: """Returns % of non-PAD tokens in batches.""" return np.mean(BATCH != PAD) * 100