| 
 | 1 | +import enum  | 
 | 2 | +from dataclasses import dataclass  | 
 | 3 | +from typing import Dict, List, Set  | 
 | 4 | + | 
 | 5 | + | 
 | 6 | +class RequsetStatus(enum.Enum):  | 
 | 7 | +    """The status of Sentences"""  | 
 | 8 | + | 
 | 9 | +    WAITING = enum.auto()  | 
 | 10 | +    RUNNING = enum.auto()  | 
 | 11 | +    ABORTED = enum.auto()  | 
 | 12 | +    OVERLENGTH = enum.auto()  | 
 | 13 | +    COMPLETED = enum.auto()  | 
 | 14 | +    LENGTH_CAPPED = enum.auto()  | 
 | 15 | + | 
 | 16 | +    @staticmethod  | 
 | 17 | +    def is_finished(status: "RequsetStatus") -> bool:  | 
 | 18 | +        return status in [  | 
 | 19 | +            RequsetStatus.OVERLENGTH,  | 
 | 20 | +            RequsetStatus.COMPLETED,  | 
 | 21 | +            RequsetStatus.LENGTH_CAPPED,  | 
 | 22 | +        ]  | 
 | 23 | + | 
 | 24 | +    @staticmethod  | 
 | 25 | +    def is_running(status: "RequsetStatus") -> bool:  | 
 | 26 | +        return status == RequsetStatus.RUNNING  | 
 | 27 | + | 
 | 28 | +    @staticmethod  | 
 | 29 | +    def is_waiting(status: "RequsetStatus") -> bool:  | 
 | 30 | +        return status == RequsetStatus.WAITING  | 
 | 31 | + | 
 | 32 | + | 
 | 33 | +class Sequence:  | 
 | 34 | +    """Store information of input sequence.  | 
 | 35 | +
  | 
 | 36 | +    Args:  | 
 | 37 | +        request_id: The ID of input sequence.  | 
 | 38 | +        prompt: The prompt of input sequence.  | 
 | 39 | +        token_id: The tokens ID of input sequence.  | 
 | 40 | +        block_size: The block size of input sequence.  | 
 | 41 | +        sample_params: The sample_params of input sequence.  | 
 | 42 | +        block_table_index: The index of input sequence in block_table.  | 
 | 43 | +    """  | 
 | 44 | + | 
 | 45 | +    def __init__(  | 
 | 46 | +        self,  | 
 | 47 | +        request_id: int,  | 
 | 48 | +        prompt: str,  | 
 | 49 | +        token_id: List[int],  | 
 | 50 | +        block_size: int,  | 
 | 51 | +        sample_params,  # SampleParams needs to be imported later.  | 
 | 52 | +        block_table_index: int,  | 
 | 53 | +    ):  | 
 | 54 | +        self.request_id = request_id  | 
 | 55 | +        self.prompt = prompt  | 
 | 56 | +        self.input_token_id = token_id  | 
 | 57 | +        self.blokc_size = block_size  | 
 | 58 | +        self.sample_params = sample_params  | 
 | 59 | +        self.output_token_id = []  | 
 | 60 | +        self.status = RequsetStatus.WAITING  | 
 | 61 | +        self.block_table_index = block_table_index  | 
 | 62 | + | 
 | 63 | +    def get_sentence_len(self) -> None:  | 
 | 64 | +        """  | 
 | 65 | +        Get length of current sentence.  | 
 | 66 | +        """  | 
 | 67 | +        return len(self.input_token_id) + len(self.output_token_id)  | 
 | 68 | + | 
 | 69 | +    def get_input_len(self) -> None:  | 
 | 70 | +        """  | 
 | 71 | +        Get length of input sentence.  | 
 | 72 | +        """  | 
 | 73 | +        return len(self.input_token_id)  | 
 | 74 | + | 
 | 75 | +    def get_output_len(self) -> None:  | 
 | 76 | +        """  | 
 | 77 | +        Get output length of current sentence.  | 
 | 78 | +        """  | 
 | 79 | +        return len(self.output_token_id)  | 
 | 80 | + | 
 | 81 | +    def check_finish(self) -> bool:  | 
 | 82 | +        """  | 
 | 83 | +        Check whether inference is over.  | 
 | 84 | +        """  | 
 | 85 | +        return RequsetStatus.is_finished(self.status)  | 
 | 86 | + | 
 | 87 | +    def __repr__(self) -> str:  | 
 | 88 | +        return (  | 
 | 89 | +            f"Request ID(request_id={self.request_id}, "  | 
 | 90 | +            f"prompt={self.prompt}, "  | 
 | 91 | +            f"status={self.status.name}, "  | 
 | 92 | +            f"sample_params={self.sample_params}, "  | 
 | 93 | +            f"logical block number={len(self._logical_blocks)}"  | 
 | 94 | +        )  | 
 | 95 | + | 
 | 96 | + | 
 | 97 | +@dataclass  | 
 | 98 | +class BatchHandler:  | 
 | 99 | +    """  | 
 | 100 | +    Information to be passed and used for a batch of sequences.  | 
 | 101 | +    """  | 
 | 102 | + | 
 | 103 | +    sequences_set: Set[Sequence]  | 
 | 104 | +    block_table: Dict[int, int]  | 
 | 105 | + | 
 | 106 | +    @classmethod  | 
 | 107 | +    def init_batch(cls, seqs: List[Sequence]) -> "BatchHandler":  | 
 | 108 | +        """  | 
 | 109 | +        Initializes inference batches by input sentence list.  | 
 | 110 | +
  | 
 | 111 | +        Args:  | 
 | 112 | +            seqs (List[Sequence]): List of input sequence.  | 
 | 113 | +        """  | 
 | 114 | +        sequences_set = set()  | 
 | 115 | +        block_table = {}  | 
 | 116 | +        for seq in seqs:  | 
 | 117 | +            if seq in sequences_set:  | 
 | 118 | +                print("The sequence is already in sequences_set.")  | 
 | 119 | +                assert (  | 
 | 120 | +                    seq.request_id in block_table  | 
 | 121 | +                ), "The sequence has been added to sequences_set, but it has not been added to block_table."  | 
 | 122 | +                continue  | 
 | 123 | +            assert (  | 
 | 124 | +                seq.request_id not in block_table  | 
 | 125 | +            ), "The sequence has not been added to sequences_set, but it is already in block_table."  | 
 | 126 | + | 
 | 127 | +            sequences_set.add(seq)  | 
 | 128 | +            block_table[seq.request_id] = seq.block_table_index  | 
 | 129 | + | 
 | 130 | +        return cls(sequences_set=sequences_set, block_table=block_table)  | 
 | 131 | + | 
 | 132 | +    def clear_batch(self) -> None:  | 
 | 133 | +        """  | 
 | 134 | +        Clear sequence set and block table.  | 
 | 135 | +        """  | 
 | 136 | +        for seq in self.sequences_set:  | 
 | 137 | +            if not seq.check_finish():  | 
 | 138 | +                seq.status = RequsetStatus.ABORTED  | 
 | 139 | +        self.sequences_set.clear()  | 
 | 140 | +        self.block_table.clear()  | 
 | 141 | + | 
 | 142 | +    def fliter_batch(self) -> None:  | 
 | 143 | +        """  | 
 | 144 | +        Remove completed sentences from a batch.  | 
 | 145 | +        """  | 
 | 146 | +        for seq in self.sequences_set:  | 
 | 147 | +            if seq.check_finish():  | 
 | 148 | +                self.sequences_set.reomve(seq)  | 
 | 149 | +                del self.block_table[seq.request_id]  | 
 | 150 | + | 
 | 151 | +    def add_seqs(self, seqs: List[Sequence]) -> None:  | 
 | 152 | +        """  | 
 | 153 | +        Add new sequence to batch  | 
 | 154 | +
  | 
 | 155 | +        Args:  | 
 | 156 | +            seqs (List[Sequence]): The list of new sequences.  | 
 | 157 | +        """  | 
 | 158 | +        for seq in seqs:  | 
 | 159 | +            if seq in self.sequences_set:  | 
 | 160 | +                print("The sequence is already in sequences_set.")  | 
 | 161 | +                assert (  | 
 | 162 | +                    seq.request_id in self.block_table  | 
 | 163 | +                ), "The sequence has been added to sequences_set, but it has not been added to block_table."  | 
 | 164 | +                continue  | 
 | 165 | +            assert (  | 
 | 166 | +                seq.request_id not in self.block_table  | 
 | 167 | +            ), "The sequence has not been added to sequences_set, but it is already in block_table."  | 
 | 168 | +            self.sequences_set.add(seq)  | 
 | 169 | +            self.block_table[seq.request_id] = seq.block_table_index  | 
0 commit comments