Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / infer / utils.py: 60%

188 statements  

« 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"""Generation configuration, structured results, and mask helpers.""" 

16 

17from __future__ import annotations 

18from dataclasses import dataclass 

19from typing import Any, Callable, List, Optional 

20 

21import torch 

22import torch.distributed as dist 

23 

24 

25@dataclass 

26class GenerationConfig: 

27 """Runtime options for autoregressive generation.""" 

28 

29 max_new_tokens: int = 256 

30 temperature: float = 1.0 

31 top_k: int = 50 

32 top_p: float = 1.0 

33 do_sample: bool = False 

34 eos_token_id: Optional[int | list[int]] = 2 

35 pad_token_id: int = 0 

36 repetition_penalty: float = 1.0 

37 use_cache: bool = True 

38 prefix_past_key_values: Optional[Any] = None 

39 prefix_attention_mask: Optional[torch.Tensor] = None 

40 prefix_sequence_shard_info: Optional[Any] = None 

41 prefix_cache_length: Optional[int] = None 

42 context_parallel_cache: bool = False 

43 context_parallel_rank: Optional[int] = None 

44 context_parallel_world_size: Optional[int] = None 

45 # context_logits_rank is local to context_process_group. 

46 context_logits_rank: Optional[Any] = None 

47 context_process_group: Optional[Any] = None 

48 gather_logits: bool = False 

49 logits_process_group: Optional[Any] = None 

50 logits_gather_dim: int = -1 

51 mask_dtype: Optional[torch.dtype] = None 

52 logits_processor: Optional[List[Callable]] = None 

53 stopping_criteria: Optional[List[Callable]] = None 

54 rng: Optional[torch.Generator] = None 

55 

56 def __post_init__(self): 

57 self._validate_sampling() 

58 self._validate_prefix() 

59 self._validate_context_parallel() 

60 if self.logits_gather_dim >= 0: 

61 raise ValueError("logits_gather_dim must be negative") 

62 if self.mask_dtype is not None and not isinstance(self.mask_dtype, torch.dtype): 

63 raise ValueError("mask_dtype must be a torch.dtype") 

64 self._validate_callables(self.logits_processor, "logits_processor") 

65 self._validate_callables(self.stopping_criteria, "stopping_criteria") 

66 

67 def _validate_sampling(self) -> None: 

68 """Validate scalar sampling and stopping options.""" 

69 if self.max_new_tokens < 0: 

70 raise ValueError("max_new_tokens must be >= 0") 

71 if self.temperature <= 0: 

72 raise ValueError("temperature must be > 0") 

73 if self.top_k < 0: 

74 raise ValueError("top_k must be >= 0") 

75 if not 0 < self.top_p <= 1.0: 

76 raise ValueError("top_p must be in (0, 1]") 

77 if self.repetition_penalty <= 0: 

78 raise ValueError("repetition_penalty must be > 0") 

79 

80 def _validate_prefix(self) -> None: 

81 """Validate optional prefix cache metadata.""" 

82 if self.prefix_past_key_values is None: 

83 if self.prefix_attention_mask is not None: 

84 raise ValueError("prefix_attention_mask requires prefix_past_key_values") 

85 if self.prefix_sequence_shard_info is not None: 

86 raise ValueError("prefix_sequence_shard_info requires prefix_past_key_values") 

87 if self.prefix_cache_length is not None: 

88 raise ValueError("prefix_cache_length requires prefix_past_key_values") 

89 else: 

90 if not self.use_cache: 

91 raise ValueError("prefix_past_key_values requires use_cache=True") 

92 if self.prefix_cache_length is not None and self.prefix_cache_length < 0: 

93 raise ValueError("prefix_cache_length must be >= 0") 

94 if self.prefix_sequence_shard_info is not None and not self.context_parallel_cache: 

95 raise ValueError("prefix_sequence_shard_info requires context_parallel_cache=True") 

96 

97 def _validate_context_parallel(self) -> None: 

98 """Validate context-parallel cache and logits metadata.""" 

99 if self.context_parallel_cache and not self.use_cache: 

100 raise ValueError("context_parallel_cache requires use_cache=True") 

101 if (self.context_parallel_rank is None) != (self.context_parallel_world_size is None): 

102 raise ValueError( 

103 "context_parallel_rank and context_parallel_world_size must be set together", 

104 ) 

105 if self.context_parallel_world_size is not None: 

106 if self.context_parallel_world_size <= 0: 

107 raise ValueError("context_parallel_world_size must be > 0") 

108 if ( 

109 self.context_parallel_rank < 0 

110 or self.context_parallel_rank >= self.context_parallel_world_size 

111 ): 

112 raise ValueError("context_parallel_rank must be in [0, context_parallel_world_size)") 

113 

114 @staticmethod 

115 def _validate_callables(values: Optional[List[Callable]], field_name: str) -> None: 

116 """Validate optional generation extension hooks.""" 

117 if values is None: 

118 return 

119 if not isinstance(values, list): 

120 raise ValueError(f"{field_name} must be a list of callables") 

121 if not all(callable(item) for item in values): 

122 raise ValueError(f"{field_name} must contain only callables") 

123 

124 

125@dataclass 

126class GenerationResult: 

127 """Final sequences with left padding removed and per-request stopping metadata. 

128 

129 Generated lengths include a terminating EOS token, and exclude right padding. 

130 Completion tokens occupy ``[prompt_length:prompt_length + generated_length]``. 

131 """ 

132 

133 sequences: torch.Tensor 

134 prompt_lengths: torch.Tensor 

135 generated_lengths: torch.Tensor 

136 finish_reasons: list[str] 

137 

138 

139def build_position_ids( 

140 input_ids: torch.Tensor, 

141 attention_mask: Optional[torch.Tensor] = None, 

142) -> torch.Tensor: 

143 """Build left-padding aware position ids.""" 

144 if input_ids.ndim != 2: 

145 raise ValueError("input_ids must have shape (batch, seq)") 

146 if attention_mask is None: 

147 seq_len = input_ids.size(1) 

148 return torch.arange( 

149 seq_len, device=input_ids.device, dtype=torch.long, 

150 ).view(1, -1).expand(input_ids.size(0), -1) 

151 if attention_mask.shape != input_ids.shape: 

152 raise ValueError("attention_mask must match input_ids shape") 

153 position_ids = attention_mask.long().cumsum(dim=-1) - 1 

154 return position_ids.clamp_min_(0) 

155 

156 

157def gather_context_parallel_logits(logits: torch.Tensor, config: GenerationConfig) -> torch.Tensor: 

158 """Select final-token logits from the owning CP rank before sampling.""" 

159 if config.context_logits_rank is None: 

160 return logits 

161 if not dist.is_available() or not dist.is_initialized(): 

162 return logits 

163 world_size = dist.get_world_size(group=config.context_process_group) 

164 if world_size == 1: 

165 return logits 

166 gathered = [torch.empty_like(logits) for _ in range(world_size)] 

167 dist.all_gather(gathered, logits, group=config.context_process_group) 

168 stacked = torch.stack(gathered, dim=0) 

169 owner = torch.as_tensor( 

170 config.context_logits_rank, 

171 device=logits.device, 

172 dtype=torch.long, 

173 ) 

174 if owner.ndim == 0: 

175 owner_rank = int(owner.item()) 

176 if owner_rank < 0 or owner_rank >= world_size: 

177 raise ValueError("context_logits_rank contains an invalid rank") 

178 return stacked[owner_rank] 

179 if owner.shape != (logits.shape[0],): 

180 raise ValueError("context_logits_rank must be a scalar or a batch-sized tensor") 

181 if torch.any((owner < 0) | (owner >= world_size)): 

182 raise ValueError("context_logits_rank contains an invalid rank") 

183 batch_indices = torch.arange(logits.shape[0], device=logits.device) 

184 return stacked[owner, batch_indices] 

185 

186 

187def gather_tensor_parallel_logits(logits: torch.Tensor, config: GenerationConfig) -> torch.Tensor: 

188 """Gather vocab-sharded logits before sampling when TP inference is active.""" 

189 if not config.gather_logits: 

190 return logits 

191 if not dist.is_available() or not dist.is_initialized(): 

192 return logits 

193 world_size = dist.get_world_size(group=config.logits_process_group) 

194 if world_size == 1: 

195 return logits 

196 gather_dim = logits.ndim + config.logits_gather_dim 

197 if gather_dim < 0 or gather_dim >= logits.ndim: 

198 raise ValueError("logits_gather_dim is out of range for logits") 

199 local_shard = torch.tensor( 

200 [logits.shape[gather_dim]], 

201 device=logits.device, 

202 dtype=torch.long, 

203 ) 

204 shard_sizes = [torch.empty_like(local_shard) for _ in range(world_size)] 

205 dist.all_gather(shard_sizes, local_shard, group=config.logits_process_group) 

206 shard_sizes = torch.cat(shard_sizes) 

207 if torch.any(shard_sizes != shard_sizes[0]): 

208 raise ValueError( 

209 "tensor-parallel logits gather requires equal local vocab shard sizes; " 

210 "pad vocab shards before generation", 

211 ) 

212 gathered = [torch.empty_like(logits) for _ in range(world_size)] 

213 dist.all_gather(gathered, logits, group=config.logits_process_group) 

214 return torch.cat(gathered, dim=config.logits_gather_dim) 

215 

216 

217def prepare_logits_for_sampling(logits: torch.Tensor, config: GenerationConfig) -> torch.Tensor: 

218 """Apply distributed logits handoffs before sampling.""" 

219 logits = gather_context_parallel_logits(logits, config) 

220 return gather_tensor_parallel_logits(logits, config) 

221 

222 

223def apply_logits_processors( 

224 input_ids: torch.Tensor, 

225 logits: torch.Tensor, 

226 config: GenerationConfig, 

227) -> torch.Tensor: 

228 """Apply user-supplied logits processors in order.""" 

229 if config.logits_processor is None: 

230 return logits 

231 processed = logits 

232 for processor in config.logits_processor: 

233 processed = processor(input_ids, processed) 

234 if not isinstance(processed, torch.Tensor): 

235 raise ValueError("logits_processor must return a tensor") 

236 return processed 

237 

238 

239def should_stop_generation( 

240 input_ids: torch.Tensor, 

241 logits: torch.Tensor, 

242 config: GenerationConfig, 

243) -> bool: 

244 """Return whether any configured stopping criterion requests termination.""" 

245 if config.stopping_criteria is None: 

246 return False 

247 for criterion in config.stopping_criteria: 

248 result = criterion(input_ids, logits) 

249 if isinstance(result, torch.Tensor): 

250 if result.numel() != 1: 

251 raise ValueError("stopping_criteria tensor output must be scalar") 

252 result = bool(result.item()) 

253 if bool(result): 

254 return True 

255 return False 

256 

257 

258def build_causal_mask( 

259 input_ids: torch.Tensor, 

260 attention_mask: Optional[torch.Tensor] = None, 

261 dtype: torch.dtype = torch.float32, 

262) -> torch.Tensor: 

263 """Build additive causal + padding mask for prefill.""" 

264 if input_ids.ndim != 2: 

265 raise ValueError("input_ids must have shape (batch, seq)") 

266 batch_size, seq_len = input_ids.shape 

267 device = input_ids.device 

268 mask = torch.zeros( 

269 batch_size, 1, seq_len, seq_len, device=device, dtype=dtype, 

270 ) 

271 causal = torch.triu( 

272 torch.full((seq_len, seq_len), float("-inf"), device=device, dtype=dtype), 

273 diagonal=1, 

274 ) 

275 mask = mask + causal.view(1, 1, seq_len, seq_len) 

276 if attention_mask is not None: 

277 if attention_mask.shape != input_ids.shape: 

278 raise ValueError("attention_mask must match input_ids shape") 

279 padding = attention_mask.to(device=device) == 0 

280 mask = mask.masked_fill(padding.view(batch_size, 1, 1, seq_len), float("-inf")) 

281 mask = mask.masked_fill(padding.view(batch_size, 1, seq_len, 1), 0.0) 

282 return mask 

283 

284 

285def append_attention_mask( 

286 attention_mask: Optional[torch.Tensor], 

287 next_tokens: torch.Tensor, 

288) -> Optional[torch.Tensor]: 

289 """Append valid-token mask entries for generated tokens.""" 

290 if attention_mask is None: 

291 return None 

292 ones = torch.ones( 

293 next_tokens.shape, 

294 device=attention_mask.device, 

295 dtype=attention_mask.dtype, 

296 ) 

297 return torch.cat([attention_mask, ones], dim=-1)