Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / infer / predict / generation.py: 98%
85 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"""Private translation from Hugging Face parameters to the existing infer engine."""
17from __future__ import annotations
19from copy import deepcopy
20import math
21from typing import Any
23import torch
24from transformers import GenerationConfig, PretrainedConfig
26from hyper_parallel.infer import GenerationConfig as EngineGenerationConfig
29_SUPPORTED_FIELDS = (
30 "max_new_tokens", "temperature", "top_k", "top_p", "do_sample", "eos_token_id", "pad_token_id",
31 "repetition_penalty", "use_cache",
32)
33_METADATA_FIELDS = {"bos_token_id", "decoder_start_token_id", "transformers_version"}
34_NEUTRAL_VALUES = {
35 "num_beams": 1, "num_return_sequences": 1, "num_beam_groups": 1,
36 "min_length": 0, "min_new_tokens": 0, "early_stopping": False,
37 "length_penalty": 1.0, "encoder_repetition_penalty": 1.0,
38 "no_repeat_ngram_size": 0, "encoder_no_repeat_ngram_size": 0,
39 "diversity_penalty": 0.0, "typical_p": 1.0, "min_p": 0.0,
40 "epsilon_cutoff": 0.0, "eta_cutoff": 0.0, "guidance_scale": 1.0,
41 "renormalize_logits": False, "remove_invalid_values": False, "token_healing": False,
42 "output_attentions": False, "output_hidden_states": False, "output_scores": False, "output_logits": False,
43 "return_dict_in_generate": False, "low_memory": False, "is_assistant": False, "use_mtp": False,
44}
47def _copy_generation_config(model: Any, config: GenerationConfig | None) -> GenerationConfig:
48 """Snapshot an explicit HF config or the model's in-memory defaults."""
49 if config is not None:
50 if not isinstance(config, GenerationConfig):
51 raise ValueError("generation_config must be a transformers.GenerationConfig")
52 return deepcopy(config)
53 config = getattr(model, "generation_config", None)
54 if isinstance(config, GenerationConfig):
55 return deepcopy(config)
56 model_config = getattr(model, "config", None)
57 if isinstance(model_config, PretrainedConfig):
58 return GenerationConfig.from_model_config(model_config)
59 return GenerationConfig()
62def _validate_features(config: GenerationConfig, defaults: dict[str, Any]) -> None:
63 """Reject enabled engine features that the text prediction API cannot honor."""
64 for name, value in config.to_dict().items():
65 if name.startswith("_") or name in _METADATA_FIELDS or name in _SUPPORTED_FIELDS or name == "max_length":
66 continue
67 if name not in defaults:
68 raise ValueError(f"Unknown generation parameter: {name}")
69 if value is None or value == _NEUTRAL_VALUES.get(name, defaults[name]):
70 continue
71 raise ValueError(f"Predictor does not support generation parameter {name}={value!r}")
74def _validate_numeric_values(values: dict[str, Any], max_length: int | None) -> None:
75 """Validate generation lengths and numeric sampling controls."""
76 for name in ("max_new_tokens", "top_k"):
77 value = values[name]
78 if not isinstance(value, int) or isinstance(value, bool) or value < 0:
79 raise ValueError(f"{name} must be a non-negative integer")
80 if max_length is not None and (
81 not isinstance(max_length, int) or isinstance(max_length, bool) or max_length <= 0):
82 raise ValueError("max_length must be a positive integer")
83 for name in ("temperature", "top_p", "repetition_penalty"):
84 value = values[name]
85 if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:
86 raise ValueError(f"{name} must be finite and positive")
87 if values["top_p"] > 1:
88 raise ValueError("top_p must be in (0, 1]")
91def _validate_special_tokens(values: dict[str, Any]) -> None:
92 """Validate optional EOS and padding token identifiers."""
93 for name in ("eos_token_id", "pad_token_id"):
94 value = values[name]
95 if value is None:
96 continue
97 tokens = value if name == "eos_token_id" and isinstance(value, list) else [value]
98 if not tokens or any(not isinstance(token, int) or isinstance(token, bool) or token < 0 for token in tokens):
99 raise ValueError(f"{name} must contain non-negative token ids")
102def _validate_values(values: dict[str, Any], max_length: int | None) -> None:
103 """Apply strict scalar and special-token checks at the prediction boundary."""
104 _validate_numeric_values(values, max_length)
105 for name in ("do_sample", "use_cache"):
106 if not isinstance(values[name], bool):
107 raise ValueError(f"{name} must be a bool")
108 _validate_special_tokens(values)
111def _build_engine_config(
112 config: GenerationConfig, tokenizer: Any, rng: torch.Generator | None, overrides: dict[str, Any],
113) -> tuple[EngineGenerationConfig, int | None]:
114 """Copy and validate per-call overrides; return an engine config and optional total-length limit."""
115 defaults = GenerationConfig().to_dict()
116 unknown = set(overrides) - (set(defaults) - _METADATA_FIELDS)
117 if unknown or any(name.startswith("_") for name in overrides):
118 raise ValueError(f"Unknown generation parameters: {sorted(unknown or overrides)}")
119 config = deepcopy(config)
120 for name, value in overrides.items():
121 setattr(config, name, deepcopy(value))
122 _validate_features(config, defaults)
123 engine_defaults = EngineGenerationConfig()
124 values = {}
125 for name in _SUPPORTED_FIELDS:
126 value = getattr(config, name, None)
127 values[name] = getattr(engine_defaults, name) if value is None else value
128 for name in ("eos_token_id", "pad_token_id"):
129 value = getattr(config, name, None)
130 if value is None and not (name == "eos_token_id" and name in overrides):
131 value = getattr(tokenizer, name, None)
132 values[name] = value
133 if values["pad_token_id"] is None:
134 eos = values["eos_token_id"]
135 values["pad_token_id"] = eos[0] if isinstance(eos, list) and eos else eos
136 if values["pad_token_id"] is None:
137 raise ValueError("pad_token_id is unresolved; configure it or provide tokenizer/model metadata")
138 max_length = config.max_length if config.max_new_tokens is None else None
139 _validate_values(values, max_length)
140 return EngineGenerationConfig(**values, rng=rng), max_length