damccorm commented on code in PR #40905:
URL: https://github.com/apache/beam/pull/40905#discussion_r4483929280


##########
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:
   Should the delimiter(s) be configurable here? I've seen some prompts like:
   
   ```
   Foo, bar, baz. Choose from one of these options when responding:
   - x
   - y
   - z
   - ```
   
   where I could imagine a `:` being a useful delimeter.



##########
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:
   Nit: Should we limit the search to `element[:_prefix_char_len].find('\n\n')` 
to shrink the search space for large prompts.



-- 
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]

Reply via email to