| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | """Sequence and its related classes.""" |
| 4 | |
| 5 | from dataclasses import dataclass |
| 6 | |
| 7 | import torch |
| 8 | |
| 9 | |
| 10 | # cannot use msgspec.Struct here because Dynamo does not support it |
| 11 | @dataclass |
| 12 | class IntermediateTensors: |
| 13 | """For all pipeline stages except the last, we need to return the hidden |
| 14 | states and residuals to be sent to the next stage. This data structure |
| 15 | contains the hidden states and residuals for a request. |
| 16 | """ |
| 17 | |
| 18 | tensors: dict[str, torch.Tensor] |
| 19 | |
| 20 | def __init__( |
| 21 | self, |
| 22 | tensors: dict[str, torch.Tensor], |
| 23 | ) -> None: |
| 24 | # manually define this function, so that |
| 25 | # Dynamo knows `IntermediateTensors()` comes from this file. |
| 26 | # Otherwise, dataclass will generate this function by evaluating |
| 27 | # a string, and we will lose the information about the source file. |
| 28 | self.tensors = tensors |
| 29 | |
| 30 | def __getitem__(self, key: str | slice): |
| 31 | if isinstance(key, str): |
| 32 | return self.tensors[key] |
| 33 | elif isinstance(key, slice): |
| 34 | return self.__class__({k: v[key] for k, v in self.tensors.items()}) |
| 35 | |
| 36 | def __setitem__(self, key: str, value: torch.Tensor): |
| 37 | self.tensors[key] = value |
| 38 | |
| 39 | def items(self): |
| 40 | return self.tensors.items() |
| 41 | |
| 42 | def __len__(self): |
| 43 | return len(self.tensors) |
| 44 | |
| 45 | def __eq__(self, other: object): |
| 46 | if not isinstance(other, self.__class__): |
| 47 | return False |
| 48 | if self.tensors.keys() != other.tensors.keys(): |
| 49 | return False |
| 50 | return all(torch.equal(self.tensors[k], other.tensors[k]) for k in self.tensors) |
| 51 | |
| 52 | def __repr__(self) -> str: |
| 53 | return f"IntermediateTensors(tensors={self.tensors})" |
| 54 | |
| 55 | @staticmethod |
| 56 | def empty_like( |
| 57 | intermediate_tensors: "IntermediateTensors", |
| 58 | ) -> "IntermediateTensors": |
| 59 | tensors = { |
| 60 | k: torch.empty_like(v) for k, v in intermediate_tensors.tensors.items() |
| 61 | } |
| 62 | return IntermediateTensors(tensors) |