Support logit_bias in v1 Sampler (#13079)

This commit is contained in:
Lu Fang
2025-02-14 04:34:59 -08:00
committed by GitHub
parent 085b7b2d6c
commit 6224a9f620
6 changed files with 200 additions and 101 deletions
+16
View File
@@ -37,6 +37,8 @@ class Sampler(nn.Module):
# Use float32 for the logits.
logits = logits.to(torch.float32)
# Apply logits bias.
logits = self.apply_logits_bias(logits, sampling_metadata)
# Apply penalties (e.g., min_tokens, freq_penalties).
logits = self.apply_penalties(logits, sampling_metadata)
# Apply temperature.
@@ -166,3 +168,17 @@ class Sampler(nn.Module):
sampling_metadata.repetition_penalties,
sampling_metadata.output_token_ids)
return logits
def apply_logits_bias(
self,
logits: torch.Tensor,
sampling_metadata: SamplingMetadata,
) -> torch.Tensor:
# TODO(houseroad): this implementation is extremely inefficient.
# One idea is implement this as a PyTorch C++ op, and we may
# even optimize the logit_bias layout.
for i, logit_bias in enumerate(sampling_metadata.logit_bias):
if logit_bias:
for token_id, bias in logit_bias.items():
logits[i, token_id] += bias
return logits