llm.generation — Sampling and Backends
Token sampling and the generation backend abstraction. The backend is what the serving tier and the trainer's evaluation loop both call into.
Sampling Utilities
sampling
Shared token sampling utilities for generation backends.
apply_repetition_penalty
Apply repetition penalty in-place on 1D logits.
源代码位于: src/llm/generation/sampling.py
apply_frequency_penalty
Subtract frequency_penalty * count(token) from each seen token's logit.
Implements the OpenAI-compatible frequency_penalty semantics
(see https://platform.openai.com/docs/api-reference/chat/create):
positive values penalise tokens in proportion to how often they
have already appeared in the generated text. Zero (the default)
is a no-op so callers don't need to special-case the off state.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
logits
|
Tensor
|
1D |
必需 |
token_ids
|
list[int]
|
List of token ids generated so far (may include duplicates; duplicates count toward the penalty). |
必需 |
frequency_penalty
|
float
|
Penalty coefficient. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Tensor
|
A new 1D tensor with the per-frequency penalty subtracted. |
源代码位于: src/llm/generation/sampling.py
apply_presence_penalty
Subtract a flat presence_penalty from each seen token's logit.
Implements the OpenAI-compatible presence_penalty semantics
(see https://platform.openai.com/docs/api-reference/chat/create):
positive values penalise tokens that have appeared at least
once in the generated text, encouraging the model to talk
about new topics. The penalty is flat — a token that
appeared 5 times is penalised the same as one that appeared
once. That is the key distinction from
:func:apply_frequency_penalty, which scales by count.
Negative values boost seen tokens (less common, but valid per OpenAI's spec — useful when you want the model to stay on topic).
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
logits
|
Tensor
|
1D |
必需 |
token_ids
|
list[int]
|
List of token ids generated so far. Order and duplicates are ignored — only the set matters. |
必需 |
presence_penalty
|
float
|
Penalty coefficient. |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Tensor
|
A new 1D tensor with the flat per-presence penalty applied. |
源代码位于: src/llm/generation/sampling.py
apply_logit_bias
Add a per-token additive bias to 1D logits before sampling.
Implements the OpenAI-compatible logit_bias semantics
(see https://platform.openai.com/docs/api-reference/chat/create):
the bias is added to the affected token's logit prior to
sampling. Negative values discourage the token (down to -100
for a hard ban in OpenAI's spec); positive values encourage it
(up to +100 for near-exclusive selection).
The bias is applied after the penalty helpers
(:func:apply_repetition_penalty,
:func:apply_frequency_penalty,
:func:apply_presence_penalty). Rationale: a penalty subtracts
to discourage repetition, and the bias is a user-intent override
— applying it last lets the bias dominate any natural penalty
the model would otherwise impose. This matches OpenAI's
reference ordering (logit-bias is the final logit-stage
modification before sampling).
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
logits
|
Tensor
|
1D |
必需 |
logit_bias
|
Mapping[Any, float] | None
|
Mapping |
必需 |
返回:
| 类型 | 描述 |
|---|---|
Tensor
|
A new 1D tensor with the per-token bias added. |
源代码位于: src/llm/generation/sampling.py
sample_next_token
Sample one token id from 1D logits.
源代码位于: src/llm/generation/sampling.py
Generation Backend ABC
backends
Generation backend abstractions.
GenerationConfig
dataclass
Shared generation hyperparameters across inference backends.
源代码位于: src/llm/generation/backends.py
GenerationBackend
Bases: ABC
Backend protocol for text generation.
源代码位于: src/llm/generation/backends.py
EagerGenerationBackend
Bases: GenerationBackend
Default in-process generation using the library stream_generate path.
源代码位于: src/llm/generation/backends.py
BatchedGenerationBackend
Bases: GenerationBackend
Generation via ContinuousBatchingEngine (iteration-level scheduling).
源代码位于: src/llm/generation/backends.py
SpeculativeDecodingBackend
Bases: GenerationBackend
Speculative decoding: small draft model proposes, large target verifies.
Implements Leviathan et al. 2023 - the draft model speculates
gamma tokens ahead; the target scores them in a single
forward pass and accepts each with probability
min(1, q_target / q_draft). On rejection, sample a
correction token from (q_target - q_draft)+. The output
distribution exactly matches the target distribution under the
same sampling parameters.
The model argument to :meth:stream / :meth:batch_generate
is ignored - the target and draft models are bound at
construction time. tokenizer must be the shared tokenizer
used by both models (same vocab, pad id, eos id).
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
target_model
|
DecoderModel
|
The "expensive" model whose distribution is the canonical output distribution. |
必需 |
draft_model
|
DecoderModel
|
The "cheap" model used for speculation. Must
share vocabulary with |
必需 |
gamma
|
int
|
Number of speculative tokens per round (default 5). Typical values: 4-8. |
5
|
源代码位于: src/llm/generation/backends.py
Backend Registry
registry
Generation backend registry and bootstrap.
build_speculative_backend
Build a speculative decoding backend (Leviathan et al., 2023).
Both target_model and draft_model must share vocabulary
with the tokenizer passed at generation time. The gamma
parameter controls how many candidate tokens the draft proposes
per round.
源代码位于: src/llm/generation/registry.py
get_generation_backend
Resolve a generation backend by registry name.
Backend-specific kwargs are forwarded to the factory — e.g.
target_model=..., draft_model=..., gamma=... for the
speculative backend, or engine=... for batched.
源代码位于: src/llm/generation/registry.py
Eager (Streaming) Backend
eager
stream_generate
stream_generate(model, tokenizer, prompt, max_new_tokens, temperature=1.0, top_k=None, top_p=None, repetition_penalty=1.0, frequency_penalty=0.0, presence_penalty=0.0, logit_bias=None, use_cache=True)
Generator function for incremental text generation.
产生:
| 名称 | 类型 | 描述 |
|---|---|---|
str |
Generator[str]
|
Newly generated text chunk (usually one token decoded). |
源代码位于: src/llm/generation/eager.py
generate
generate(model, tokenizer, prompt, max_new_tokens, temperature=1.0, top_k=None, top_p=None, repetition_penalty=1.0, frequency_penalty=0.0, presence_penalty=0.0, logit_bias=None, use_cache=True)
Generate text from a prompt using a trained model.
源代码位于: src/llm/generation/eager.py
batch_generate
batch_generate(model, tokenizer, prompts, max_new_tokens, temperature=1.0, top_k=None, top_p=None, repetition_penalty=1.0, frequency_penalty=0.0, presence_penalty=0.0, logit_bias=None)
Batch generate text from multiple prompts.
参数:
| 名称 | 类型 | 描述 | 默认 |
|---|---|---|---|
model
|
DecoderModel
|
The decoder model. |
必需 |
tokenizer
|
SimpleCharacterTokenizer
|
The tokenizer. |
必需 |
prompts
|
list[str]
|
List of input prompts. |
必需 |
max_new_tokens
|
int
|
Maximum tokens to generate per prompt. |
必需 |
temperature
|
float
|
Sampling temperature. 0 for greedy. |
1.0
|
top_k
|
int | None
|
Top-k sampling parameter. |
None
|
top_p
|
float | None
|
Nucleus sampling parameter. |
None
|
repetition_penalty
|
float
|
Repetition penalty. |
1.0
|
frequency_penalty
|
float
|
OpenAI-compatible per-frequency penalty
(subtracts |
0.0
|
presence_penalty
|
float
|
OpenAI-compatible per-presence penalty
(subtracts a flat |
0.0
|
logit_bias
|
dict[int, float] | None
|
OpenAI-compatible additive per-token biases
( |
None
|
返回:
| 类型 | 描述 |
|---|---|
list[str]
|
List of generated texts (prompt + generated tokens). |
源代码位于: src/llm/generation/eager.py
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | |