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

57 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"""Sampling helpers for autoregressive generation.""" 

16 

17from __future__ import annotations 

18import torch 

19from torch.nn import functional as F 

20 

21from hyper_parallel.infer.utils import GenerationConfig 

22 

23 

24def _filter_top_k(logits: torch.Tensor, top_k: int) -> torch.Tensor: 

25 if top_k <= 0 or top_k >= logits.size(-1): 

26 return logits 

27 values, _ = torch.topk(logits, k=top_k, dim=-1) 

28 threshold = values[:, -1:].contiguous() 

29 return logits.masked_fill(logits < threshold, float("-inf")) 

30 

31 

32def greedy_sample(logits: torch.Tensor) -> torch.Tensor: 

33 """Select the highest-logit token for each batch item.""" 

34 if logits.ndim != 2: 

35 raise ValueError("logits must have shape (batch, vocab)") 

36 return logits.argmax(dim=-1, keepdim=True) 

37 

38 

39def top_k_sample( 

40 logits: torch.Tensor, 

41 top_k: int, 

42 temperature: float = 1.0, 

43) -> torch.Tensor: 

44 """Sample from the top-k logits.""" 

45 if logits.ndim != 2: 

46 raise ValueError("logits must have shape (batch, vocab)") 

47 filtered = _filter_top_k(logits, top_k) 

48 probs = F.softmax(filtered / temperature, dim=-1) 

49 sampled = torch.multinomial(probs, num_samples=1) 

50 return sampled 

51 

52 

53def top_p_sample( 

54 logits: torch.Tensor, 

55 top_p: float, 

56 temperature: float = 1.0, 

57 rng: torch.Generator | None = None, 

58) -> torch.Tensor: 

59 """Sample from the nucleus token set. 

60 

61 Args: 

62 logits: Token scores with shape ``(batch, vocab)``. 

63 top_p: Cumulative probability threshold; values at least one retain all tokens. 

64 temperature: Positive divisor applied to logits before softmax. 

65 rng: Random number generator controlling sampling state; ``None`` uses PyTorch's default generator. 

66 

67 Returns: 

68 Sampled token IDs with shape ``(batch, 1)``. 

69 """ 

70 if logits.ndim != 2: 

71 raise ValueError("logits must have shape (batch, vocab)") 

72 if top_p >= 1.0: 

73 probs = F.softmax(logits / temperature, dim=-1) 

74 return torch.multinomial(probs, num_samples=1, generator=rng) 

75 sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1) 

76 sorted_probs = F.softmax(sorted_logits / temperature, dim=-1) 

77 cumulative = sorted_probs.cumsum(dim=-1) 

78 remove = cumulative - sorted_probs > top_p 

79 filtered = sorted_logits.masked_fill(remove, float("-inf")) 

80 probs = F.softmax(filtered / temperature, dim=-1) 

81 sampled = torch.multinomial(probs, num_samples=1, generator=rng) 

82 return sorted_indices.gather(dim=-1, index=sampled) 

83 

84 

85def apply_repetition_penalty( 

86 logits: torch.Tensor, 

87 input_ids: torch.Tensor, 

88 penalty: float, 

89) -> torch.Tensor: 

90 """Apply per-item repetition penalty to seen token ids.""" 

91 if penalty == 1.0: 

92 return logits 

93 if logits.ndim != 2 or input_ids.ndim != 2: 

94 raise ValueError("logits and input_ids must be 2-D tensors") 

95 adjusted = logits.clone() 

96 vocab_size = logits.size(-1) 

97 valid = (input_ids >= 0) & (input_ids < vocab_size) 

98 seen_mask = torch.zeros_like(adjusted, dtype=torch.bool) 

99 token_ids = input_ids.to(dtype=torch.long).clamp(min=0, max=max(vocab_size - 1, 0)) 

100 seen_mask.scatter_(dim=1, index=token_ids, src=valid) 

101 penalized = torch.where(adjusted < 0, adjusted * penalty, adjusted / penalty) 

102 return torch.where(seen_mask, penalized, adjusted) 

103 

104 

105def sample_next_token( 

106 logits: torch.Tensor, 

107 input_ids: torch.Tensor, 

108 config: GenerationConfig, 

109) -> torch.Tensor: 

110 """Apply repetition penalty and select the next token. 

111 

112 Args: 

113 logits: Token scores with shape ``(batch, vocab)``. 

114 input_ids: Previous token IDs per batch item; out-of-vocabulary IDs are ignored. 

115 config: Repetition penalty, greedy or sampling options, and optional sampling RNG. 

116 

117 Returns: 

118 Selected token IDs with shape ``(batch, 1)``. 

119 """ 

120 logits = apply_repetition_penalty( 

121 logits, 

122 input_ids=input_ids, 

123 penalty=config.repetition_penalty, 

124 ) 

125 if not config.do_sample: 

126 return greedy_sample(logits) 

127 logits = _filter_top_k(logits, config.top_k) 

128 if config.top_p < 1.0: 

129 return top_p_sample(logits, top_p=config.top_p, temperature=config.temperature, rng=config.rng) 

130 probs = F.softmax(logits / config.temperature, dim=-1) 

131 return torch.multinomial(probs, num_samples=1, generator=config.rng)