main
py 253 lines 8.69 KB
Raw
1 # SPDX-License-Identifier: Apache-2.0
2 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3 import dataclasses
4 from collections.abc import Mapping, Set
5 from itertools import groupby
6
7 import torch
8
9 from vllm.config import PoolerConfig
10 from vllm.model_executor.layers.pooler import PoolingParamsUpdate
11 from vllm.tasks import PoolingTask
12 from vllm.v1.pool.metadata import PoolingMetadata
13
14 from .abstract import Pooler, PoolerOutput
15 from .common import ClassifierFn
16 from .seqwise import (
17 SequencePoolingFn,
18 SequencePoolingMethod,
19 pooler_for_classify,
20 pooler_for_embed,
21 )
22 from .tokwise import pooler_for_token_classify, pooler_for_token_embed
23
24
25 class DispatchPooler(Pooler):
26 """Dispatches calls to a sub-pooler based on the pooling task."""
27
28 @classmethod
29 def for_embedding(cls, pooler_config: PoolerConfig):
30 return cls(
31 {
32 "token_embed": pooler_for_token_embed(pooler_config),
33 "embed": pooler_for_embed(pooler_config),
34 },
35 )
36
37 @classmethod
38 def for_seq_cls(
39 cls,
40 pooler_config: PoolerConfig,
41 *,
42 pooling: SequencePoolingMethod | SequencePoolingFn | None = None,
43 classifier: ClassifierFn | None = None,
44 ):
45 return cls(
46 {
47 "token_classify": pooler_for_token_classify(
48 pooler_config,
49 classifier=classifier,
50 ),
51 "classify": pooler_for_classify(
52 pooler_config,
53 pooling=pooling,
54 classifier=classifier,
55 ),
56 }
57 )
58
59 def __init__(self, poolers_by_task: Mapping[PoolingTask, Pooler]) -> None:
60 super().__init__()
61
62 for task, pooler in poolers_by_task.items():
63 if task not in pooler.get_supported_tasks():
64 raise ValueError(
65 f"{pooler=} does not support {task=}. "
66 f"Supported tasks: {pooler.get_supported_tasks()}"
67 )
68
69 self.poolers_by_task = poolers_by_task
70
71 def get_supported_tasks(self) -> Set[PoolingTask]:
72 return set(self.poolers_by_task)
73
74 def get_pooling_updates(self, task: PoolingTask) -> PoolingParamsUpdate:
75 return self.poolers_by_task[task].get_pooling_updates(task)
76
77 def replace_classifier(
78 self,
79 new_classifier: ClassifierFn,
80 ) -> None:
81 """Replaces the classifier to the LoRA-wrapped version."""
82 for task, pooler in self.poolers_by_task.items():
83 if task not in {"classify"}:
84 # Now LoRA only supports classification tasks,
85 # so we only replace the classifier for "classify" task.
86 continue
87 head = getattr(pooler, "head", None)
88 if head is not None and hasattr(head, "classifier"):
89 head.classifier = new_classifier
90
91 def forward(
92 self,
93 hidden_states: torch.Tensor,
94 pooling_metadata: PoolingMetadata,
95 ) -> PoolerOutput:
96 poolers_by_task = self.poolers_by_task
97 cursor = pooling_metadata.pooling_cursor
98
99 outputs = list[torch.Tensor | None]()
100 offset = 0
101 token_offset = 0
102 for task, group in groupby(pooling_metadata.tasks):
103 if not (pooler := poolers_by_task.get(task)):
104 raise ValueError(
105 f"Unsupported task: {task!r} "
106 f"Supported tasks: {self.get_supported_tasks()}"
107 )
108
109 num_items = len(list(group))
110 group_metadata = pooling_metadata[offset : offset + num_items]
111 if cursor is None:
112 group_hidden_states = hidden_states
113 else:
114 # Slice out this group's tokens so sub-poolers see only their
115 # portion of the batch. Token offset is computed from the CPU
116 # `num_scheduled_tokens_cpu` to avoid a GPU->CPU sync.
117 group_cursor = group_metadata.pooling_cursor
118 assert group_cursor is not None
119 num_group_tokens = int(group_cursor.num_scheduled_tokens_cpu.sum())
120 group_hidden_states = hidden_states[
121 token_offset : token_offset + num_group_tokens
122 ]
123 if token_offset:
124 # Shift first/last indices to be relative to the slice
125 # so seqwise poolers (which index `hidden_states` directly)
126 # remain correct.
127 pooling_cursor = dataclasses.replace(
128 group_cursor,
129 first_token_indices_gpu=(
130 group_cursor.first_token_indices_gpu - token_offset
131 ),
132 last_token_indices_gpu=(
133 group_cursor.last_token_indices_gpu - token_offset
134 ),
135 )
136 group_metadata = dataclasses.replace(
137 group_metadata, pooling_cursor=pooling_cursor
138 )
139 token_offset += num_group_tokens
140
141 group_output: PoolerOutput = pooler(group_hidden_states, group_metadata)
142
143 outputs.extend(group_output)
144 offset += num_items
145
146 return outputs
147
148 def extra_repr(self) -> str:
149 s = f"supported_task={self.get_supported_tasks()}"
150 return s
151
152
153 class IdentityPooler(Pooler):
154 def get_supported_tasks(self) -> Set[PoolingTask]:
155 return {"plugin"}
156
157 def forward(
158 self,
159 hidden_states: torch.Tensor,
160 pooling_metadata: PoolingMetadata,
161 ) -> PoolerOutput:
162 return hidden_states
163
164
165 class BOSEOSFilter(Pooler):
166 """Filters the BOS and EOS token results from outputs."""
167
168 def __init__(
169 self,
170 pooler: Pooler,
171 bos_token_id: int = -1, # -1 disables the filtering
172 eos_token_id: int = -1,
173 ) -> None:
174 super().__init__()
175
176 self.pooler = pooler
177 self.bos_token_id = bos_token_id
178 self.eos_token_id = eos_token_id
179
180 def extra_repr(self) -> str:
181 return f"bos_token_id={self.bos_token_id}, eos_token_id={self.eos_token_id}"
182
183 def get_supported_tasks(self) -> Set[PoolingTask]:
184 return self.pooler.get_supported_tasks()
185
186 def get_pooling_updates(self, task: PoolingTask) -> PoolingParamsUpdate:
187 return PoolingParamsUpdate(requires_token_ids=True)
188
189 def forward(
190 self,
191 hidden_states: torch.Tensor | list[torch.Tensor],
192 pooling_metadata: PoolingMetadata,
193 ) -> PoolerOutput:
194 pooled_outputs = self.pooler(hidden_states, pooling_metadata)
195 assert isinstance(pooled_outputs, list)
196 prompt_token_ids = pooling_metadata.get_prompt_token_ids_cpu()
197
198 for i, (prompt_len, token_ids) in enumerate(
199 zip(pooling_metadata.prompt_lens, prompt_token_ids)
200 ):
201 pooled_data = pooled_outputs[i]
202 assert (
203 isinstance(pooled_data, torch.Tensor)
204 and pooled_data.shape[0] == prompt_len
205 )
206 if int(token_ids[0]) == self.bos_token_id:
207 pooled_data = pooled_data[1:]
208 if int(token_ids[-1]) == self.eos_token_id:
209 pooled_data = pooled_data[:-1]
210 pooled_outputs[i] = pooled_data.squeeze(-1)
211
212 return pooled_outputs
213
214
215 class BgeM3Pooler(Pooler):
216 def __init__(self, token_classify_pooler: Pooler, embed_pooler: Pooler) -> None:
217 super().__init__()
218 self.token_classify_pooler = token_classify_pooler
219 self.embed_pooler = embed_pooler
220
221 def forward(
222 self, hidden_states: torch.Tensor, pooling_metadata: PoolingMetadata
223 ) -> PoolerOutput:
224 embed_outputs = self.embed_pooler(hidden_states, pooling_metadata)
225 token_classify_outputs = self.token_classify_pooler(
226 hidden_states, pooling_metadata
227 )
228 pooler_outputs: list[torch.Tensor] = []
229 for embed_output, token_classify_output in zip(
230 embed_outputs, token_classify_outputs
231 ):
232 pooler_outputs.append(
233 torch.cat(
234 [embed_output.view(-1), token_classify_output.view(-1)], dim=-1
235 )
236 )
237
238 return pooler_outputs
239
240 def get_supported_tasks(self) -> Set[PoolingTask]:
241 return {"embed&token_classify"}
242
243 def get_pooling_updates(self, task: PoolingTask) -> PoolingParamsUpdate:
244 return self.embed_pooler.get_pooling_updates(
245 "embed"
246 ) | self.token_classify_pooler.get_pooling_updates("token_classify")
247
248 def extra_repr(self) -> str:
249 s = f"supported_task={self.get_supported_tasks()}"
250 return s
251
252
253 __all__ = ["BOSEOSFilter", "DispatchPooler", "IdentityPooler", "BgeM3Pooler"]