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

295 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"""Prefill + decode generation loop.""" 

16 

17from __future__ import annotations 

18import inspect 

19from typing import Any, Optional 

20 

21import torch 

22import torch.distributed as dist 

23 

24from hyper_parallel.infer.kv_cache import ( 

25 ContextParallelKVCache, 

26 KVCache, 

27 detach_and_validate_past_key_values, 

28) 

29from hyper_parallel.infer.sampler import sample_next_token 

30from hyper_parallel.infer.utils import ( 

31 GenerationConfig, 

32 GenerationResult, 

33 append_attention_mask, 

34 apply_logits_processors, 

35 build_causal_mask, 

36 build_position_ids, 

37 prepare_logits_for_sampling, 

38 should_stop_generation, 

39) 

40 

41 

42def _get_output(outputs, name: str): 

43 """Read an output field from dict-like or object-like model outputs.""" 

44 if isinstance(outputs, dict): 

45 return outputs.get(name) 

46 return getattr(outputs, name, None) 

47 

48 

49def _model_forward( 

50 model, 

51 input_ids: torch.Tensor, 

52 position_ids: torch.Tensor, 

53 attention_mask: Optional[torch.Tensor], 

54 past_key_values, 

55 use_cache: bool, 

56 sequence_shard_info=None, 

57 global_seq_len: Optional[int] = None, 

58): 

59 """Call model.forward with only the keyword arguments it accepts.""" 

60 kwargs = { 

61 "input_ids": input_ids, 

62 "position_ids": position_ids, 

63 "attention_mask": attention_mask, 

64 "past_key_values": past_key_values, 

65 "use_cache": use_cache, 

66 "sequence_shard_info": sequence_shard_info, 

67 "global_seq_len": global_seq_len, 

68 } 

69 forward = getattr(model, "forward", model) 

70 try: 

71 signature = inspect.signature(forward) 

72 except (TypeError, ValueError): 

73 return forward(**kwargs) 

74 parameters = signature.parameters 

75 accepts_kwargs = any( 

76 param.kind == inspect.Parameter.VAR_KEYWORD 

77 for param in parameters.values() 

78 ) 

79 if not accepts_kwargs: 

80 for name in list(kwargs): 

81 if name not in parameters: 

82 kwargs.pop(name) 

83 return forward(**kwargs) 

84 

85 

86def _resolve_context_parallel_rank_world(config: GenerationConfig) -> tuple[int, int]: 

87 if config.context_parallel_rank is not None: 

88 return config.context_parallel_rank, config.context_parallel_world_size 

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

90 raise ValueError( 

91 "context_parallel_cache requires initialized torch.distributed " 

92 "or explicit context_parallel_rank/context_parallel_world_size", 

93 ) 

94 return ( 

95 dist.get_rank(group=config.context_process_group), 

96 dist.get_world_size(group=config.context_process_group), 

97 ) 

98 

99 

100def _init_cache(config: GenerationConfig) -> KVCache: 

101 if not config.context_parallel_cache: 

102 return KVCache() 

103 rank, world_size = _resolve_context_parallel_rank_world(config) 

104 return ContextParallelKVCache(rank=rank, world_size=world_size) 

105 

106 

107def _cache_shard_info(cache: KVCache): 

108 return cache.shard_info if isinstance(cache, ContextParallelKVCache) else None 

109 

110 

111def _cache_seq_len(past_key_values) -> Optional[int]: 

112 """Resolve cached sequence length from tuple or opaque HF-style cache.""" 

113 if past_key_values is None: 

114 return None 

115 if hasattr(past_key_values, "get_seq_length") and not isinstance( 

116 past_key_values, (list, tuple), 

117 ): 

118 return int(past_key_values.get_seq_length()) 

119 values = detach_and_validate_past_key_values(past_key_values) 

120 if not values: 

121 return 0 

122 return int(values[0][0].shape[-2]) 

123 

124 

125def _cache_batch_size(past_key_values) -> Optional[int]: 

126 """Resolve cache batch size when cache tensors are inspectable.""" 

127 if past_key_values is None: 

128 return None 

129 if hasattr(past_key_values, "get_seq_length") and not isinstance( 

130 past_key_values, (list, tuple), 

131 ): 

132 return None 

133 values = detach_and_validate_past_key_values(past_key_values) 

134 if not values: 

135 return None 

136 return int(values[0][0].shape[0]) 

137 

138 

139def _resolve_prefix_length(config: GenerationConfig) -> int: 

140 """Validate and resolve reusable prefix cache length.""" 

141 if config.prefix_past_key_values is None: 

142 return 0 

143 candidates = [] 

144 if config.prefix_cache_length is not None: 

145 candidates.append(int(config.prefix_cache_length)) 

146 if config.prefix_attention_mask is not None: 

147 candidates.append(int(config.prefix_attention_mask.shape[-1])) 

148 if config.prefix_sequence_shard_info is not None: 

149 candidates.append(int(config.prefix_sequence_shard_info.global_seq_len)) 

150 seq_len = _cache_seq_len(config.prefix_past_key_values) 

151 if seq_len is not None and config.prefix_sequence_shard_info is None: 

152 candidates.append(seq_len) 

153 if not candidates: 

154 raise ValueError( 

155 "prefix_past_key_values requires prefix_cache_length for opaque caches", 

156 ) 

157 prefix_len = candidates[0] 

158 if any(length != prefix_len for length in candidates): 

159 raise ValueError("prefix cache length metadata is inconsistent") 

160 return prefix_len 

161 

162 

163def _prepare_prefix_attention_mask( 

164 config: GenerationConfig, 

165 input_ids: torch.Tensor, 

166 device, 

167) -> tuple[Optional[torch.Tensor], int]: 

168 """Prepare a 2-D attention mask for reusable prefix cache.""" 

169 prefix_len = _resolve_prefix_length(config) 

170 if prefix_len == 0: 

171 return None, 0 

172 cache_batch_size = _cache_batch_size(config.prefix_past_key_values) 

173 if cache_batch_size is not None and cache_batch_size != input_ids.size(0): 

174 raise ValueError("prefix cache batch size must match input_ids batch size") 

175 prefix_attention_mask = config.prefix_attention_mask 

176 if prefix_attention_mask is None: 

177 return torch.ones( 

178 input_ids.size(0), 

179 prefix_len, 

180 device=device, 

181 dtype=torch.long, 

182 ), prefix_len 

183 if prefix_attention_mask.ndim != 2: 

184 raise ValueError("prefix_attention_mask must have shape (batch, prefix_seq)") 

185 if prefix_attention_mask.shape != (input_ids.size(0), prefix_len): 

186 raise ValueError("prefix_attention_mask batch/sequence length mismatch") 

187 return prefix_attention_mask.to(device=device), prefix_len 

188 

189 

190def _init_cache_with_prefix(config: GenerationConfig) -> tuple[KVCache, int]: 

191 """Create the generation cache and preload prefix cache when present.""" 

192 cache = _init_cache(config) 

193 prefix_len = _resolve_prefix_length(config) 

194 if prefix_len == 0: 

195 return cache, prefix_len 

196 if isinstance(cache, ContextParallelKVCache): 

197 if config.prefix_sequence_shard_info is None: 

198 cache.update_full(config.prefix_past_key_values) 

199 else: 

200 cache.update_local( 

201 config.prefix_past_key_values, 

202 config.prefix_sequence_shard_info, 

203 ) 

204 return cache, prefix_len 

205 cache.update(config.prefix_past_key_values) 

206 return cache, prefix_len 

207 

208 

209def _update_cache(cache: KVCache, outputs) -> None: 

210 """Update normal or context-parallel KV cache from model outputs.""" 

211 past_key_values = _get_output(outputs, "past_key_values") 

212 if not isinstance(cache, ContextParallelKVCache): 

213 cache.update(past_key_values) 

214 return 

215 if past_key_values is None: 

216 return 

217 sequence_shard_info = _get_output(outputs, "sequence_shard_info") 

218 if sequence_shard_info is not None: 

219 cache.update_local(past_key_values, sequence_shard_info) 

220 return 

221 if cache.is_empty: 

222 cache.update_full(past_key_values) 

223 return 

224 raise ValueError( 

225 "context-parallel cached decode requires model output sequence_shard_info", 

226 ) 

227 

228 

229def _resolve_mask_dtype(model, config: GenerationConfig) -> torch.dtype: 

230 """Choose additive-mask dtype from config or model floating state.""" 

231 if config.mask_dtype is not None: 

232 return config.mask_dtype 

233 for iterator_name in ("parameters", "buffers"): 

234 iterator = getattr(model, iterator_name, None) 

235 if iterator is None: 

236 continue 

237 for tensor in iterator(): 

238 if tensor.is_floating_point(): 

239 return tensor.dtype 

240 return torch.float32 

241 

242 

243def _build_decode_key_mask( 

244 attention_mask: Optional[torch.Tensor], 

245 dtype: torch.dtype, 

246) -> Optional[torch.Tensor]: 

247 """Build additive key padding mask for one-token cached decode.""" 

248 if attention_mask is None: 

249 return None 

250 if attention_mask.ndim != 2: 

251 raise ValueError("attention_mask must have shape (batch, seq)") 

252 batch_size, seq_len = attention_mask.shape 

253 mask = torch.zeros( 

254 batch_size, 

255 1, 

256 1, 

257 seq_len, 

258 device=attention_mask.device, 

259 dtype=dtype, 

260 ) 

261 padding = attention_mask == 0 

262 return mask.masked_fill(padding.view(batch_size, 1, 1, seq_len), float("-inf")) 

263 

264 

265def _combined_attention_mask( 

266 prefix_attention_mask: Optional[torch.Tensor], 

267 attention_mask: Optional[torch.Tensor], 

268) -> Optional[torch.Tensor]: 

269 if prefix_attention_mask is None: 

270 return attention_mask 

271 if attention_mask is None: 

272 return prefix_attention_mask 

273 return torch.cat([prefix_attention_mask, attention_mask], dim=-1) 

274 

275 

276def _build_prefill_mask( 

277 input_ids: torch.Tensor, 

278 attention_mask: Optional[torch.Tensor], 

279 prefix_attention_mask: Optional[torch.Tensor], 

280 dtype: torch.dtype, 

281) -> torch.Tensor: 

282 """Build the prefill causal mask, including optional prefix keys.""" 

283 if prefix_attention_mask is None: 

284 return build_causal_mask(input_ids, attention_mask, dtype=dtype) 

285 batch_size, query_len = input_ids.shape 

286 prefix_len = prefix_attention_mask.shape[-1] 

287 device = input_ids.device 

288 if attention_mask is None: 

289 attention_mask = torch.ones( 

290 batch_size, 

291 query_len, 

292 device=device, 

293 dtype=prefix_attention_mask.dtype, 

294 ) 

295 if attention_mask.shape != input_ids.shape: 

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

297 mask = torch.zeros( 

298 batch_size, 

299 1, 

300 query_len, 

301 prefix_len + query_len, 

302 device=device, 

303 dtype=dtype, 

304 ) 

305 causal = torch.triu( 

306 torch.full((query_len, query_len), float("-inf"), device=device, dtype=dtype), 

307 diagonal=1, 

308 ) 

309 mask[:, :, :, prefix_len:] = causal.view(1, 1, query_len, query_len) 

310 current_padding = attention_mask == 0 

311 current_key_padding = torch.cat([prefix_attention_mask == 0, current_padding], dim=-1) 

312 mask = mask.masked_fill( 

313 current_key_padding.view(batch_size, 1, 1, prefix_len + query_len), 

314 float("-inf"), 

315 ) 

316 mask = mask.masked_fill(current_padding.view(batch_size, 1, query_len, 1), 0.0) 

317 return mask 

318 

319 

320def _build_prefill_position_ids( 

321 input_ids: torch.Tensor, 

322 attention_mask: Optional[torch.Tensor], 

323 prefix_attention_mask: Optional[torch.Tensor], 

324) -> torch.Tensor: 

325 """Build position ids for prefill with optional prefix offset.""" 

326 position_ids = build_position_ids(input_ids, attention_mask) 

327 if prefix_attention_mask is None: 

328 return position_ids 

329 prefix_lengths = prefix_attention_mask.long().sum(dim=-1).view(-1, 1) 

330 return position_ids + prefix_lengths 

331 

332 

333def _prompt_lengths(input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor]): 

334 """Count valid prompt tokens per batch row.""" 

335 if attention_mask is None: 

336 return torch.full( 

337 (input_ids.size(0),), 

338 input_ids.size(1), 

339 device=input_ids.device, 

340 dtype=torch.long, 

341 ) 

342 return attention_mask.long().sum(dim=-1) 

343 

344 

345def _finalize_sequences( 

346 sequences: torch.Tensor, 

347 initial_attention_mask: Optional[torch.Tensor], 

348 prompt_lengths: torch.Tensor, 

349 generated_counts: torch.Tensor, 

350 pad_token_id: int, 

351) -> torch.Tensor: 

352 """Strip left padding and right-pad finalized generated sequences.""" 

353 rows = [] 

354 max_len = 0 

355 for batch_idx in range(sequences.size(0)): 

356 if initial_attention_mask is None: 

357 start = 0 

358 else: 

359 starts = torch.nonzero( 

360 initial_attention_mask[batch_idx].bool(), as_tuple=False, 

361 ) 

362 if starts.numel() == 0: 

363 raise ValueError("attention_mask row must contain at least one valid token") 

364 start = int(starts[0].item()) 

365 total_len = int(prompt_lengths[batch_idx].item() + generated_counts[batch_idx].item()) 

366 row = sequences[batch_idx, start:start + total_len] 

367 rows.append(row) 

368 max_len = max(max_len, row.numel()) 

369 output = sequences.new_full((len(rows), max_len), pad_token_id) 

370 for idx, row in enumerate(rows): 

371 output[idx, :row.numel()] = row 

372 return output 

373 

374 

375def _validate_generate_inputs( 

376 input_ids: torch.Tensor, 

377 attention_mask: Optional[torch.Tensor], 

378) -> None: 

379 """Validate nonempty token batches and contiguous left-padding masks.""" 

380 if input_ids.ndim != 2 or input_ids.numel() == 0: 

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

382 if attention_mask is not None and attention_mask.shape != input_ids.shape: 

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

384 if attention_mask is not None and ( 

385 torch.any((attention_mask != 0) & (attention_mask != 1)) 

386 or torch.any(attention_mask[:, 1:] < attention_mask[:, :-1])): 

387 raise ValueError("attention_mask must describe contiguous left padding") 

388 if attention_mask is not None and torch.any(attention_mask.long().sum(dim=-1) == 0): 

389 raise ValueError("attention_mask rows must contain at least one valid token") 

390 

391 

392def _finalize_zero_new_tokens( 

393 input_ids: torch.Tensor, 

394 attention_mask: Optional[torch.Tensor], 

395 config: GenerationConfig, 

396) -> torch.Tensor: 

397 """Finalize left-padded prompts when no new tokens are requested.""" 

398 prompt_lengths = _prompt_lengths(input_ids, attention_mask) 

399 generated_counts = torch.zeros( 

400 input_ids.size(0), 

401 device=input_ids.device, 

402 dtype=torch.long, 

403 ) 

404 return _finalize_sequences( 

405 input_ids.clone(), 

406 initial_attention_mask=attention_mask, 

407 prompt_lengths=prompt_lengths, 

408 generated_counts=generated_counts, 

409 pad_token_id=config.pad_token_id, 

410 ) 

411 

412 

413def _prepare_generation_context( 

414 model, 

415 input_ids: torch.Tensor, 

416 attention_mask: Optional[torch.Tensor], 

417 config: GenerationConfig, 

418): 

419 """Create the mutable generation context used by the decode loop.""" 

420 mask_dtype = _resolve_mask_dtype(model, config) 

421 sequences = input_ids.clone() 

422 prefix_attention_mask, prefix_len = _prepare_prefix_attention_mask( 

423 config, 

424 input_ids, 

425 input_ids.device, 

426 ) 

427 current_attention_mask = attention_mask.clone() if attention_mask is not None else None 

428 if prefix_attention_mask is not None and current_attention_mask is None: 

429 current_attention_mask = torch.ones_like(sequences, dtype=torch.long) 

430 prompt_lengths = _prompt_lengths(input_ids, current_attention_mask) 

431 prefix_valid_lengths = ( 

432 prefix_attention_mask.long().sum(dim=-1) 

433 if prefix_attention_mask is not None 

434 else torch.zeros(input_ids.size(0), device=input_ids.device, dtype=torch.long) 

435 ) 

436 cache, prefix_len = _init_cache_with_prefix(config) 

437 return { 

438 "mask_dtype": mask_dtype, 

439 "sequences": sequences, 

440 "prefix_attention_mask": prefix_attention_mask, 

441 "current_attention_mask": current_attention_mask, 

442 "initial_attention_mask": ( 

443 current_attention_mask.clone() 

444 if current_attention_mask is not None 

445 else None 

446 ), 

447 "prompt_lengths": prompt_lengths, 

448 "generated_counts": torch.zeros( 

449 input_ids.size(0), device=input_ids.device, dtype=torch.long, 

450 ), 

451 "finish_codes": torch.zeros(input_ids.size(0), device=input_ids.device, dtype=torch.long), 

452 "unfinished": torch.ones( 

453 input_ids.size(0), device=input_ids.device, dtype=torch.bool, 

454 ), 

455 "prefix_valid_lengths": prefix_valid_lengths, 

456 "cache": cache, 

457 "prefix_len": prefix_len, 

458 } 

459 

460 

461def _prefill( 

462 model, 

463 config: GenerationConfig, 

464 context: dict, 

465): 

466 """Run the initial full-prompt forward pass.""" 

467 position_ids = _build_prefill_position_ids( 

468 context["sequences"], 

469 context["current_attention_mask"], 

470 context["prefix_attention_mask"], 

471 ) 

472 attention_mask = _build_prefill_mask( 

473 context["sequences"], 

474 context["current_attention_mask"], 

475 context["prefix_attention_mask"], 

476 dtype=context["mask_dtype"], 

477 ) 

478 cache = context["cache"] 

479 return _model_forward( 

480 model, 

481 input_ids=context["sequences"], 

482 position_ids=position_ids, 

483 attention_mask=attention_mask, 

484 past_key_values=None if cache.is_empty else cache.past_key_values, 

485 use_cache=config.use_cache, 

486 sequence_shard_info=_cache_shard_info(cache), 

487 global_seq_len=context["prefix_len"] + context["sequences"].shape[-1], 

488 ) 

489 

490 

491def _required_logits(outputs) -> torch.Tensor: 

492 logits = _get_output(outputs, "logits") 

493 if logits is None: 

494 raise ValueError("model output must contain logits") 

495 return logits 

496 

497 

498def _finalize_prefill_outputs( 

499 config: GenerationConfig, 

500 context: dict, 

501 outputs, 

502) -> tuple[torch.Tensor, bool]: 

503 """Validate prefill output and decide whether cached decode can be used.""" 

504 logits = _required_logits(outputs) 

505 if ( 

506 config.prefix_past_key_values is not None 

507 and _get_output(outputs, "past_key_values") is None 

508 ): 

509 raise ValueError("prefix_past_key_values requires model to return past_key_values") 

510 _update_cache(context["cache"], outputs) 

511 return logits, config.use_cache and not context["cache"].is_empty 

512 

513 

514def _append_next_token(context: dict, next_tokens: torch.Tensor, config: GenerationConfig): 

515 """Append sampled tokens and advance per-row generation metadata.""" 

516 if config.eos_token_id is not None: 

517 next_tokens = torch.where( 

518 context["unfinished"].view(-1, 1), 

519 next_tokens, 

520 torch.full_like(next_tokens, config.pad_token_id), 

521 ) 

522 context["sequences"] = torch.cat([context["sequences"], next_tokens], dim=-1) 

523 context["generated_counts"] = ( 

524 context["generated_counts"] + context["unfinished"].long() 

525 ) 

526 context["current_attention_mask"] = append_attention_mask( 

527 context["current_attention_mask"], 

528 next_tokens, 

529 ) 

530 if config.eos_token_id is not None: 

531 eos_ids = torch.as_tensor(config.eos_token_id, device=next_tokens.device).reshape(-1) 

532 finished = (next_tokens == eos_ids).any(dim=-1) & context["unfinished"] 

533 context["finish_codes"].masked_fill_(finished, 1) 

534 context["unfinished"] = context["unfinished"] & ~finished 

535 return next_tokens 

536 

537 

538def _should_finish_generation( 

539 context: dict, 

540 logits: torch.Tensor, 

541 config: GenerationConfig, 

542 step: int, 

543) -> bool: 

544 """Check EOS, custom stopping criteria, and max token limit.""" 

545 if config.eos_token_id is not None and not context["unfinished"].any(): 

546 return True 

547 if should_stop_generation(context["sequences"], logits, config): 

548 context["finish_codes"].masked_fill_(context["unfinished"], 2) 

549 return True 

550 return step == config.max_new_tokens - 1 

551 

552 

553def _decode( 

554 model, 

555 context: dict, 

556 next_tokens: torch.Tensor, 

557 use_cached_decode: bool, 

558): 

559 """Run one cached or no-cache decode step.""" 

560 model_attention_mask = _combined_attention_mask( 

561 context["prefix_attention_mask"], 

562 context["current_attention_mask"], 

563 ) 

564 if use_cached_decode: 

565 decode_pos = ( 

566 context["prefix_valid_lengths"] 

567 + context["prompt_lengths"] 

568 + context["generated_counts"] 

569 - 1 

570 ) 

571 return _model_forward( 

572 model, 

573 input_ids=next_tokens, 

574 position_ids=decode_pos.view(-1, 1), 

575 attention_mask=_build_decode_key_mask( 

576 model_attention_mask, 

577 context["mask_dtype"], 

578 ), 

579 past_key_values=context["cache"].past_key_values, 

580 use_cache=True, 

581 sequence_shard_info=_cache_shard_info(context["cache"]), 

582 global_seq_len=context["prefix_len"] + context["sequences"].shape[-1], 

583 ) 

584 decode_pos = _build_prefill_position_ids( 

585 context["sequences"], 

586 context["current_attention_mask"], 

587 context["prefix_attention_mask"], 

588 ) 

589 decode_mask = _build_prefill_mask( 

590 context["sequences"], 

591 context["current_attention_mask"], 

592 context["prefix_attention_mask"], 

593 dtype=context["mask_dtype"], 

594 ) 

595 return _model_forward( 

596 model, 

597 input_ids=context["sequences"], 

598 position_ids=decode_pos, 

599 attention_mask=decode_mask, 

600 past_key_values=None, 

601 use_cache=False, 

602 sequence_shard_info=_cache_shard_info(context["cache"]), 

603 global_seq_len=context["prefix_len"] + context["sequences"].shape[-1], 

604 ) 

605 

606 

607@torch.no_grad() 

608def generate( 

609 model: Any, 

610 input_ids: torch.Tensor, 

611 generation_config: Optional[GenerationConfig] = None, 

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

613 *, 

614 return_dict: bool = False, 

615 **kwargs: Any, 

616) -> torch.Tensor | GenerationResult: 

617 """Generate tokens using the shared prefill/decode loop. 

618 

619 Args: 

620 model: Causal language model returning logits and optional cache. 

621 input_ids: Left-padded prompt token ids. 

622 generation_config: Engine configuration; defaults to EOS=2 and PAD=0. 

623 Set ``eos_token_id=None`` to disable EOS-based stopping. Model generation 

624 metadata is not applied automatically. 

625 attention_mask: Binary prompt mask, required for padded input. 

626 return_dict: Return lengths and finish reasons in addition to sequences. 

627 **kwargs: Unknown arguments are rejected. 

628 

629 Returns: 

630 A Tensor by default, or GenerationResult when return_dict is true. 

631 """ 

632 if kwargs: 

633 raise TypeError(f"Unexpected generate kwargs: {sorted(kwargs)}") 

634 config = generation_config or GenerationConfig() 

635 _validate_generate_inputs(input_ids, attention_mask) 

636 if config.max_new_tokens == 0: 

637 sequences = _finalize_zero_new_tokens(input_ids, attention_mask, config) 

638 if not return_dict: 

639 return sequences 

640 return GenerationResult( 

641 sequences, _prompt_lengths(input_ids, attention_mask), 

642 torch.zeros(input_ids.size(0), device=input_ids.device, dtype=torch.long), 

643 ["length"] * input_ids.size(0), 

644 ) 

645 

646 was_training = getattr(model, "training", False) 

647 model.eval() 

648 try: 

649 context = _prepare_generation_context(model, input_ids, attention_mask, config) 

650 outputs = _prefill(model, config, context) 

651 logits, use_cached_decode = _finalize_prefill_outputs( 

652 config, 

653 context, 

654 outputs, 

655 ) 

656 

657 for step in range(config.max_new_tokens): 

658 next_logits = prepare_logits_for_sampling(logits[:, -1, :], config) 

659 next_logits = apply_logits_processors( 

660 context["sequences"], 

661 next_logits, 

662 config, 

663 ) 

664 # Padding is not part of a request's history, even when pad equals EOS. 

665 history = context["sequences"] 

666 if context["current_attention_mask"] is not None: 

667 history = history.masked_fill(context["current_attention_mask"] == 0, -1) 

668 next_tokens = sample_next_token(next_logits, history, config) 

669 next_tokens = _append_next_token(context, next_tokens, config) 

670 if _should_finish_generation(context, next_logits, config, step): 

671 break 

672 

673 outputs = _decode(model, context, next_tokens, use_cached_decode) 

674 if use_cached_decode: 

675 _update_cache(context["cache"], outputs) 

676 logits = _required_logits(outputs) 

677 

678 sequences = _finalize_sequences( 

679 context["sequences"], 

680 initial_attention_mask=context["initial_attention_mask"], 

681 prompt_lengths=context["prompt_lengths"], 

682 generated_counts=context["generated_counts"], 

683 pad_token_id=config.pad_token_id, 

684 ) 

685 if not return_dict: 

686 return sequences 

687 reasons = ("length", "eos", "stop") 

688 return GenerationResult( 

689 sequences, context["prompt_lengths"], context["generated_counts"], 

690 [reasons[code] for code in context["finish_codes"].tolist()], 

691 ) 

692 finally: 

693 if was_training: 

694 model.train()