Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / infer / predict / predictor.py: 98%
58 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"""In-memory text prediction using the shared infer generation loop."""
17from __future__ import annotations
19from dataclasses import replace
20from typing import Any, Iterator
22import torch
23from transformers import GenerationConfig
25from hyper_parallel.infer import GenerationConfig as EngineGenerationConfig, generate
26from hyper_parallel.infer.predict.batching import EncodedRequest, encode_requests, pad_batch, plan_batches
27from hyper_parallel.infer.predict.generation import _build_engine_config, _copy_generation_config
28from hyper_parallel.infer.predict.types import normalize_requests
31def _validate_settings(batch_size: int, max_batch_tokens: int | None, bucket_by_length: bool) -> None:
32 """Validate static batch limits before binding the model."""
33 if (not isinstance(batch_size, int) or isinstance(batch_size, bool)) or batch_size < 1:
34 raise ValueError("batch_size must be a positive integer")
35 if max_batch_tokens is not None and (
36 not isinstance(max_batch_tokens, int)
37 or isinstance(max_batch_tokens, bool) or max_batch_tokens < 1):
38 raise ValueError("max_batch_tokens must be a positive integer or None")
39 if not isinstance(bucket_by_length, bool):
40 raise ValueError("bucket_by_length must be a bool")
43class Predictor:
44 """Generate text for caller-supplied requests and return results in memory.
46 Each instance processes only the requests passed to ``predict``. The caller
47 owns any distribution of requests across processes and collection of results.
49 Args:
50 model: Materialized model with weights already restored by the caller.
51 tokenizer: Tokenizer used for prompt encoding and completion decoding.
52 generation_config: Optional HF generation defaults; otherwise copy the model's in-memory config.
53 device: Input tensor device; defaults to the model's parameter device and does not move the model.
54 rng: Optional random generator whose state advances across sampling calls.
55 batch_size: Maximum number of requests per forward batch.
56 max_batch_tokens: Optional maximum number of padded prompt tokens per batch.
57 bucket_by_length: Whether to group requests by prompt length before generation.
58 chat_template: Optional Jinja template overriding the tokenizer's template for messages.
59 chat_template_kwargs: Template parameters, such as enable_thinking.
60 """
62 def __init__(
63 self, model: Any, tokenizer: Any, generation_config: GenerationConfig | None = None, *,
64 device: torch.device | str | None = None, rng: torch.Generator | None = None, batch_size: int = 1,
65 max_batch_tokens: int | None = None, bucket_by_length: bool = False,
66 chat_template: str | None = None,
67 chat_template_kwargs: dict[str, Any] | None = None,
68 ) -> None:
69 """Bind the model, tokenizer, and generation parameters without generating."""
70 _validate_settings(batch_size, max_batch_tokens, bucket_by_length)
71 if tokenizer is None:
72 raise ValueError("prediction requires a tokenizer")
73 self.model = model
74 self.tokenizer = tokenizer
75 self.generation_config = _copy_generation_config(model, generation_config)
76 self.rng = rng
77 self.device = torch.device(device) if device is not None else next(model.parameters()).device
78 self.batch_size = batch_size
79 self.max_batch_tokens = max_batch_tokens
80 self.bucket_by_length = bucket_by_length
81 self.chat_template = chat_template
82 self.chat_template_kwargs = dict(chat_template_kwargs or {})
84 def _records(
85 self, batches: list[list[EncodedRequest]], configs: list[EngineGenerationConfig],
86 ) -> Iterator[dict[str, Any]]:
87 """Call the shared generator and decode only each row's completion span."""
88 for batch, config in zip(batches, configs):
89 inputs = pad_batch(batch, config.pad_token_id, self.device)
90 result = generate(self.model, **inputs, generation_config=config, return_dict=True)
91 sequences = result.sequences.cpu()
92 prompts, generated = result.prompt_lengths.tolist(), result.generated_lengths.tolist()
93 for row, encoded in enumerate(batch):
94 start, count = prompts[row], generated[row]
95 completion = sequences[row, start:start + count].tolist()
96 yield {
97 "id": encoded.request.input_id, "ordinal": encoded.request.ordinal,
98 "generated_text": self.tokenizer.decode(completion, skip_special_tokens=True),
99 "prompt_tokens": start, "generated_tokens": count, "finish_reason": result.finish_reasons[row],
100 }
102 def predict(self, inputs: str | dict | list[str | dict], **generation_kwargs: Any) -> list[dict[str, Any]]:
103 """Generate one completion per request without file I/O or communication.
105 Args:
106 inputs: One prompt string, a request dictionary with ``prompt`` or
107 ``messages`` and an optional ``id``, or a list of these inputs.
108 **generation_kwargs: HF parameters overriding this call's defaults. ``max_new_tokens`` takes
109 precedence over ``max_length``; otherwise the latter includes the padded prompt width.
110 If both are None, generate up to 256 new tokens. ``eos_token_id=None`` disables EOS stopping.
112 Returns:
113 Results in input order, each containing ``id``, ``ordinal``,
114 ``generated_text``, ``prompt_tokens``, ``generated_tokens``, and
115 ``finish_reason``. An empty input list returns an empty result list.
116 """
117 requests = normalize_requests(inputs)
118 if not requests:
119 return []
120 config, max_length = _build_engine_config(
121 self.generation_config, self.tokenizer, self.rng, generation_kwargs,
122 )
123 encoded = encode_requests(requests, self.tokenizer, self.chat_template, self.chat_template_kwargs)
124 batches = list(plan_batches(encoded, batch_size=self.batch_size, max_batch_tokens=self.max_batch_tokens,
125 bucket_by_length=self.bucket_by_length))
126 configs = []
127 for batch in batches:
128 if max_length is None:
129 configs.append(config)
130 continue
131 prompt_width = max(len(item.token_ids) for item in batch)
132 if prompt_width >= max_length:
133 raise ValueError("max_length must exceed every batch's padded prompt length")
134 configs.append(replace(config, max_new_tokens=max_length - prompt_width))
135 return sorted(self._records(batches, configs), key=lambda record: record["ordinal"])