File size: 3,021 Bytes
3e334a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
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