AMOOOMA commented on code in PR #40905:
URL: https://github.com/apache/beam/pull/40905#discussion_r4485092552
##########
sdks/python/apache_beam/ml/inference/base.py:
##########
@@ -213,6 +213,10 @@ def __init__(
element_size_fn: Optional[Callable[[Any], int]] = None,
batch_length_fn: Optional[Callable[[Any], int]] = None,
batch_bucket_boundaries: Optional[list[int]] = None,
+ batch_key_fn: Optional[Callable[[Any], Any]] = None,
+ batch_key_num_shards: Optional[Union[int,
+ Mapping[Any, int],
+ Callable[[Any], int]]] = None,
large_model: bool = False,
Review Comment:
Done in 7acd8e9. `_validate_batching_args` now also covers `batch_key_fn` /
`batch_key_num_shards`, using the same `_validate_num_shards` as
`BatchElements`, so bad combinations (e.g. `batch_key_num_shards` without
`batch_key_fn`, or `batch_key_fn` + `batch_length_fn`) fail when the handler is
constructed.
##########
sdks/python/apache_beam/ml/inference/base.py:
##########
@@ -273,6 +292,10 @@ def __init__(
self._batching_kwargs['length_fn'] = batch_length_fn
if batch_bucket_boundaries is not None:
self._batching_kwargs['bucket_boundaries'] = batch_bucket_boundaries
+ if batch_key_fn is not None:
+ self._batching_kwargs['key_fn'] = batch_key_fn
Review Comment:
Good catch, fixed in 7acd8e9. `key_fn` is now wrapped in `_ApplyToExample`
like `element_size_fn` / `length_fn`. I added a unit test for keyed and
maybe-keyed handlers and an end-to-end `RunInference(KeyedModelHandler(...))`
test.
##########
sdks/python/apache_beam/transforms/util.py:
##########
@@ -1339,9 +1461,29 @@ def __init__(
self._bucket_boundaries = self._DEFAULT_BUCKET_BOUNDARIES
else:
self._bucket_boundaries = bucket_boundaries
+ self._key_fn = key_fn
+ self._num_shards = num_shards
def expand(self, pcoll):
- if getattr(pcoll.pipeline.runner, 'is_streaming', False):
+ if self._key_fn is not None:
+ element_type = pcoll.element_type
+ # GroupIntoBatches treats a buffering duration of 0 as "no limit", which
+ # in a streaming global window would hold an incomplete batch forever.
+ buffering_secs = (
+ self._max_batch_dur if self._max_batch_dur is not None else
+ _DEFAULT_KEYED_MAX_BUFFERING_SECS)
+ return (
+ pcoll
+ | 'WithBatchKey' >> ParDo(
+ WithBatchKey(self._key_fn, self._num_shards)).with_output_types(
+ tuple[str, element_type])
+ | 'GroupIntoBatchesByKey' >> GroupIntoBatches(
+ self._batch_size_estimator._max_batch_size,
+ max_buffering_duration_secs=buffering_secs,
+ clock=self._clock)
+ | 'DropBatchKey' >> Map(lambda kv: list(kv[1])).with_output_types(
+ list[element_type]))
Review Comment:
Agreed, switched in 7acd8e9. `key_fn` now just swaps the keying DoFn
(`WithBatchKey` instead of `WithSharedKey` / `WithLengthBucketKey`) in front of
the existing stateful batching DoFn. The estimator, `element_size_fn` and
`max_batch_weight` all apply per key, and batches start at `min_batch_size` and
grow from there instead of using the 10k `max_batch_size`. Setting
`min_batch_size == max_batch_size` keeps fixed batch sizes. `key_fn` +
`length_fn` is still rejected because both pick the state key.
##########
sdks/python/apache_beam/ml/inference/prefix_batching.py:
##########
@@ -0,0 +1,229 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Prefix-aware batching for LLM model handlers.
+
+Generic across LLM servers that keep a prefix (KV) cache, such as vLLM, SGLang
+or TensorRT-LLM; nothing here depends on a particular server.
+
+``ModelHandler(batch_key_fn=...)`` makes ``BatchElements`` route elements that
+share a key to the same worker via ``GroupIntoBatches``, so each batch the
+server sees is homogeneous and its prefix cache gets hit instead of thrashed.
+This module packages the knobs for that into one :class:`PrefixBatchingConfig`
+plus the default key extractors a handler installs when the user does not
+supply their own:
+
+* :class:`PromptPrefixKeyFn` -- for plain-text prompts (completions API).
+* :class:`ChatPrefixKeyFn` -- for chat message lists (chat API).
+
+Both see the element *after* any ``with_preprocess_fn`` has run, i.e. the
+prompt / message list the handler will actually send. A handler exposes a
+``PrefixBatchingConfig`` argument, picks which extractor is its default, and
+passes :func:`resolve_batching_kwargs` to ``ModelHandler.__init__``.
+"""
+
+# pytype: skip-file
+
+import dataclasses
+from collections.abc import Callable
+from collections.abc import Mapping
+from collections.abc import Sequence
+from dataclasses import dataclass
+from typing import Any
+from typing import Optional
+from typing import Union
+
+__all__ = [
+ 'ChatPrefixKeyFn',
+ 'PrefixBatchingConfig',
+ 'PromptPrefixKeyFn',
+]
+
+# Characters of prompt (or leading message content) the default extractors key
+# on. Long enough to cover a typical system prompt, short enough that keys are
+# cheap to hash and shuffle.
+DEFAULT_PREFIX_CHAR_LEN = 128
+# GroupIntoBatches buffering applied when the handler's own
+# ``max_batch_duration_secs`` is unset, so low-traffic keys still flush in
+# streaming instead of waiting for a full batch.
+DEFAULT_KEYED_BATCH_DURATION_SECS = 1.0
+# Shards per prefix key. A single shard serves a hot prefix (e.g. a common
+# system prompt) on one worker at a time; a few shards keep that prefix's
+# throughput scaling with the pool while every shard still batches a single
+# prefix.
+DEFAULT_NUM_SHARDS = 8
+
+# Accepted forms of ``num_shards``: one count for every key, a per-key table,
+# or a callable computed per key (see ``WithBatchKey`` in transforms/util.py).
+NumShardsSpec = Union[int, Mapping[Any, int], Callable[[Any], int]]
+
+
+class PromptPrefixKeyFn:
+ """Default prefix key extractor for plain-text prompts.
+
+ Keys a prompt string by its leading ``prefix_char_len`` characters, or by
+ everything before the first ``\\n\\n`` when that comes sooner, so prompts
Review Comment:
Yes, done in 7acd8e9. `PromptPrefixKeyFn` / `ChatPrefixKeyFn` take
`delimiters`, and `PrefixBatchingConfig(prefix_delimiters=(':',))` sets them
for the handler's default extractor. The defaults are unchanged: a blank line
for prompts, none for chat. The earliest delimiter within `prefix_char_len`
wins.
##########
sdks/python/apache_beam/ml/inference/prefix_batching.py:
##########
@@ -0,0 +1,229 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Prefix-aware batching for LLM model handlers.
+
+Generic across LLM servers that keep a prefix (KV) cache, such as vLLM, SGLang
+or TensorRT-LLM; nothing here depends on a particular server.
+
+``ModelHandler(batch_key_fn=...)`` makes ``BatchElements`` route elements that
+share a key to the same worker via ``GroupIntoBatches``, so each batch the
+server sees is homogeneous and its prefix cache gets hit instead of thrashed.
+This module packages the knobs for that into one :class:`PrefixBatchingConfig`
+plus the default key extractors a handler installs when the user does not
+supply their own:
+
+* :class:`PromptPrefixKeyFn` -- for plain-text prompts (completions API).
+* :class:`ChatPrefixKeyFn` -- for chat message lists (chat API).
+
+Both see the element *after* any ``with_preprocess_fn`` has run, i.e. the
+prompt / message list the handler will actually send. A handler exposes a
+``PrefixBatchingConfig`` argument, picks which extractor is its default, and
+passes :func:`resolve_batching_kwargs` to ``ModelHandler.__init__``.
+"""
+
+# pytype: skip-file
+
+import dataclasses
+from collections.abc import Callable
+from collections.abc import Mapping
+from collections.abc import Sequence
+from dataclasses import dataclass
+from typing import Any
+from typing import Optional
+from typing import Union
+
+__all__ = [
+ 'ChatPrefixKeyFn',
+ 'PrefixBatchingConfig',
+ 'PromptPrefixKeyFn',
+]
+
+# Characters of prompt (or leading message content) the default extractors key
+# on. Long enough to cover a typical system prompt, short enough that keys are
+# cheap to hash and shuffle.
+DEFAULT_PREFIX_CHAR_LEN = 128
+# GroupIntoBatches buffering applied when the handler's own
+# ``max_batch_duration_secs`` is unset, so low-traffic keys still flush in
+# streaming instead of waiting for a full batch.
+DEFAULT_KEYED_BATCH_DURATION_SECS = 1.0
+# Shards per prefix key. A single shard serves a hot prefix (e.g. a common
+# system prompt) on one worker at a time; a few shards keep that prefix's
+# throughput scaling with the pool while every shard still batches a single
+# prefix.
+DEFAULT_NUM_SHARDS = 8
+
+# Accepted forms of ``num_shards``: one count for every key, a per-key table,
+# or a callable computed per key (see ``WithBatchKey`` in transforms/util.py).
+NumShardsSpec = Union[int, Mapping[Any, int], Callable[[Any], int]]
+
+
+class PromptPrefixKeyFn:
+ """Default prefix key extractor for plain-text prompts.
+
+ Keys a prompt string by its leading ``prefix_char_len`` characters, or by
+ everything before the first ``\\n\\n`` when that comes sooner, so prompts
+ sharing the same system prompt or instruction header are routed to the same
+ worker and batched together.
+ """
+ def __init__(self, prefix_char_len: int = DEFAULT_PREFIX_CHAR_LEN):
+ if prefix_char_len <= 0:
+ raise ValueError('prefix_char_len must be positive.')
+ self._prefix_char_len = prefix_char_len
+
+ def __call__(self, element: str) -> str:
+ if not isinstance(element, str):
+ raise TypeError(
+ f'Expected str prompt for prefix key extraction, got '
+ f'{type(element).__name__}.')
+ sep_idx = element.find('\n\n')
Review Comment:
Done in 7acd8e9. The search is bounded to the first `prefix_char_len`
characters (plus the delimiter length), so long prompts cost the same as short
ones.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]