Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / infer / predict / batching.py: 98%
50 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Static request encoding and padded-token-budget batching."""
17from __future__ import annotations
19from dataclasses import dataclass
20from typing import Any, Iterator
22import torch
24from hyper_parallel.infer.predict.types import PredictionRequest
27@dataclass
28class EncodedRequest:
29 """Request identity paired with the complete encoded prompt."""
31 request: PredictionRequest
32 token_ids: list[int]
35def encode_requests(
36 requests: list[PredictionRequest], tokenizer: Any,
37 chat_template: str | None = None, chat_template_kwargs: dict[str, Any] | None = None,
38) -> list[EncodedRequest]:
39 """Encode plain prompts or templated histories without truncation.
41 Args:
42 requests: Requests containing plain prompts or message histories.
43 tokenizer: Tokenizer providing ``encode`` and ``apply_chat_template``.
44 chat_template: Optional Jinja template overriding the tokenizer's template.
45 chat_template_kwargs: Extra template arguments excluding reserved rendering options.
47 Returns:
48 Requests paired with prompt token IDs in their original order.
49 """
50 kwargs = dict(chat_template_kwargs or {})
51 reserved = {"chat_template", "tokenize", "add_generation_prompt", "return_dict", "conversation"}
52 if reserved.intersection(kwargs):
53 raise ValueError("chat_template_kwargs cannot override prediction rendering arguments")
54 encoded = []
55 for request in requests:
56 if request.messages is None:
57 tokens = tokenizer.encode(request.prompt, add_special_tokens=True)
58 else:
59 if chat_template is None and not getattr(tokenizer, "chat_template", None):
60 raise ValueError("messages require a tokenizer chat_template or an explicit chat_template")
61 tokens = tokenizer.apply_chat_template(
62 request.messages, chat_template=chat_template, tokenize=True,
63 add_generation_prompt=True, return_dict=False, **kwargs,
64 )
65 if not tokens:
66 raise ValueError(f"request {request.input_id!r} encodes to an empty prompt")
67 encoded.append(EncodedRequest(request, list(tokens)))
68 return encoded
71def plan_batches(
72 requests: list[EncodedRequest], *, batch_size: int,
73 max_batch_tokens: int | None = None, bucket_by_length: bool = False,
74) -> Iterator[list[EncodedRequest]]:
75 """Yield batches bounded by both request count and padded prompt token count.
77 Args:
78 requests: Encoded requests supplied by the caller.
79 batch_size: Maximum number of requests in one batch.
80 max_batch_tokens: Optional maximum number of padded prompt tokens per batch.
81 bucket_by_length: Whether to sort requests by ascending prompt length.
83 Yields:
84 A batch satisfying both limits, optionally ordered by ascending prompt length.
85 """
86 ordered = sorted(requests, key=lambda value: len(value.token_ids)) if bucket_by_length else requests
87 batch = []
88 width = 0
89 for request in ordered:
90 length = len(request.token_ids)
91 if max_batch_tokens is not None and length > max_batch_tokens:
92 raise ValueError(f"request {request.request.input_id!r} exceeds max_batch_tokens")
93 new_width = max(width, length)
94 over_budget = max_batch_tokens is not None and new_width * (len(batch) + 1) > max_batch_tokens
95 if batch and (len(batch) == batch_size or over_budget):
96 yield batch
97 batch, width = [], 0
98 batch.append(request)
99 width = max(width, length)
100 if batch:
101 yield batch
104def pad_batch(batch: list[EncodedRequest], pad_token_id: int, device: torch.device) -> dict[str, torch.Tensor]:
105 """Create left-padded model inputs without changing the tokenizer's settings.
107 Args:
108 batch: Non-empty batch of encoded requests.
109 pad_token_id: Token ID used to fill positions before shorter prompts.
110 device: Device on which to allocate the model input tensors.
112 Returns:
113 Long ``input_ids`` and ``attention_mask`` tensors with a shared padded width.
114 """
115 width = max(len(request.token_ids) for request in batch)
116 ids, masks = [], []
117 for request in batch:
118 padding = width - len(request.token_ids)
119 ids.append([pad_token_id] * padding + request.token_ids)
120 masks.append([0] * padding + [1] * len(request.token_ids))
121 return {
122 "input_ids": torch.tensor(ids, device=device, dtype=torch.long),
123 "attention_mask": torch.tensor(masks, device=device, dtype=torch.long),
124 }