sampler
DirectTokenSampler
Bases: TokenSampler
Samples individual tokens directly from the log-normalized logw_next function
of a potential.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
potential
|
Potential
|
The potential function to sample from |
required |
Warning
Only use this sampler if the potential's logw_next method is efficient. This is the case
for potentials like PromptedLLM, but for custom potentials with a large vocabulary size,
the default implementation of logw_next generally will not be efficient, and thus this
sampler will be slow.
Source code in genlm/control/sampler/token.py
sample(context, draw=None)
async
Sample a token and weight that are properly weighted with respect to the target potential's logw_next method.
Given a context of tokens \(x_1, \ldots, x_{n-1}\) in the target potential's vocabulary, this method samples a token \(x_n \in \textsf{target.vocab_eos}\) and weight \(w\).
The sampled token and weight are properly weighted with respect to $$ \textsf{target.logw_next}(x_n | x_1, \ldots, x_{n-1}) $$
The returned weight corresponds to the log normalizing constant of \(\textsf{target.logw_next}(x_n | x_1, \ldots, x_{n-1})\).
Returns:
| Type | Description |
|---|---|
(token, weight, logp)
|
A tuple containing the sampled token, weight, and log-probability of the sampled token. |
Source code in genlm/control/sampler/token.py
SetTokenSampler
Bases: TokenSampler
Samples individual tokens by sampling a weighted set of tokens and then selecting one proportional to its weight.
This class wraps a SetSampler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
set_sampler
|
SetSampler
|
The set sampler to sample from |
required |
Source code in genlm/control/sampler/token.py
sample(context, draw=None)
async
Sample a token and weight by sampling a weighted set of tokens from the set_sampler
and then selecting one proportional to its weight.
Given a context of tokens \(x_1, \ldots, x_{n-1}\) in the vocabulary of the set sampler's target potential, this method samples a token \(x_n \in \textsf{set_sampler.target.vocab_eos}\) and a weight.
The sampled token and weight are properly weighted with respect to $$ \textsf{set_sampler.target.logw_next}(x_n | x_1, \ldots, x_{n-1}) $$
The returned weight corresponds to the sum of the weights of the sampled set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list[int]
|
A sequence of tokens in the vocabulary of the set sampler's target potential. |
required |
Returns:
| Type | Description |
|---|---|
(token, weight, logp)
|
A tuple containing the sampled token, weight, and log-probability of the random choices made in sampling that token. |
Note
For properly weighted sampling, the set_sampler must assign correct weights to each token. See
SetSampler for more details.
Source code in genlm/control/sampler/token.py
cleanup()
async
Clean up the sampler.
This method should be called when the sampler is no longer needed.
AWRS
Bases: TokenSampler
Samples individual tokens through an adaptive weighted rejection sampling algorithm.
This sampler is based on the algorithm described in Fast Controlled Generation from Language Models with Adaptive Weighted Rejection Sampling
It draws properly weighted samples from the product of a non-boolean potential and a boolean condition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
potential
|
Potential
|
The non-boolean potential. |
required |
condition
|
Potential
|
The boolean condition. This potential must only output boolean values (0 or -inf in log-space). |
required |
seed
|
int or None
|
The seed for the random number generator. |
None
|
prune_logws
|
bool
|
Whether to prune the logws to only include the tokens in the intersection of the potential and condition vocabularies |
True
|
proper_weights
|
bool
|
Whether to return properly weighted samples. If False, the sampler will only run one round of adaptive rejection sampling. |
True
|
max_accepts
|
int
|
The maximum number of tokens to accept - higher values will decrease the variance of the weight estimate. |
2
|
max_rejects
|
int or float(inf)
|
The maximum number of tokens to reject - lower values will run faster, but at the cost of returning a weight of zero for some samples where there are tokens that would be accepted if tested. |
float('inf')
|
n_monte_carlo_samples
|
int
|
The number of Monte Carlo samples to use to estimate the weight. Higher values will decrease the variance of the weight estimate, but will run slower. |
None
|
Source code in genlm/control/sampler/token.py
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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 | |
sample(context, verbosity=0)
async
Sample a token and weight that are properly weighted with respect to the target potential's logw_next method via adaptive weighted rejection sampling.
The returned weight corresponds to the log normalizing constant of \(\textsf{target.logw_next}(x_n | x_1, \ldots, x_{n-1})\).
Returns:
| Type | Description |
|---|---|
(token, weight, nan)
|
A tuple containing the sampled token, weight, and a dummy value for the log-probability of the sampled token. |
Source code in genlm/control/sampler/token.py
TokenSampler
Bases: SubModel
Base class for sampling a token from a potential's vocabulary.
TokenSamplers generate properly weighted samples with respect to a target potential.
Given a context of tokens \(x_1, \ldots, x_{n-1}\) in the target potential's vocabulary,
a TokenSampler samples a token \(x_n \in \textsf{target.vocab_eos}\) and weight \(w\).
The sampled token and weight are properly weighted with respect to $$ \textsf{target.logw_next}(x_n | x_1, \ldots, x_{n-1}) $$
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
Potential
|
The potential that samples are properly weighted with respect to. |
required |
Source code in genlm/control/sampler/token.py
start_weight()
async
sample(context, draw)
async
Sample a token and weight from the targetpotential's vocabulary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list[int]
|
A sequence of tokens in the |
required |
draw
|
callable
|
A callable that draws a sample from a distribution. |
required |
Returns:
| Type | Description |
|---|---|
(token, weight, logp)
|
A tuple containing the sampled token, weight, and log-probability of the sampled token. |
Source code in genlm/control/sampler/token.py
smc(n_particles, ess_threshold, max_tokens, critic=None, **kwargs)
async
Generate sequences using sequential Monte Carlo (SMC) inference with this token sampler and an optional critic.
This method is a convenience wrapper around SMC.
See SMC for more details on the generation process.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_particles
|
int
|
The number of particles to use in the SMC algorithm. |
required |
ess_threshold
|
float
|
The threshold for the effective sample size (ESS). |
required |
max_tokens
|
int
|
The maximum number of tokens to generate. |
required |
critic
|
Potential
|
A potential function that guides the generation process by scoring candidate sequences. Must have the same token type as the token sampler. |
None
|
**kwargs
|
dict
|
Additional keyword arguments to pass to |
{}
|
Source code in genlm/control/sampler/token.py
EagerSetSampler
Bases: TrieSetSampler
A trie-based set sampler that implements an eager sampling strategy for generating a set of tokens.
An EagerSetSampler samples tokens by incrementally sampling items from the item-wise product of the iter_potential and item_potential.
The sampled set is the set of sequences of items that correspond to valid tokens in iter_potential's vocabulary.
Source code in genlm/control/sampler/set.py
sample_set(context, draw=None)
async
Sample a set of tokens given a context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
A sequence of tokens in the |
required |
Returns:
| Type | Description |
|---|---|
(LazyWeights, float)
|
A weighted set of tokens and the log-probability of the sampled set. |
Source code in genlm/control/sampler/set.py
TopKSetSampler
Bases: TrieSetSampler
A trie-based set sampler that lazily enumerates the top K tokens by weight in the target, and samples an additional "wildcard" token to ensure absolute continuity.
Warning
This sampler is not guaranteed to be correct if the item_potential's
prefix weights do not monotonically decrease with the length of the context.
That is, \(\textsf{item_potential.prefix}(x) \leq \textsf{item_potential.prefix}(xy)\) for all sequences of items \(x, y\).
Source code in genlm/control/sampler/set.py
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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 | |
__init__(iter_potential, item_potential, K)
Initialize the TopKSetSampler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
iter_potential
|
Potential
|
The potential defined over a vocabulary of iterables. |
required |
item_potential
|
Potential
|
The potential defined over a vocabulary of items. |
required |
K
|
int | None
|
The number of top tokens to enumerate. If None, all tokens are enumerated. |
required |
Source code in genlm/control/sampler/set.py
sample_set(context, draw=None)
async
Sample a set of tokens given a context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
A sequence of tokens in the |
required |
Returns:
| Type | Description |
|---|---|
(LazyWeights, float)
|
A weighted set of tokens and the log-probability of the sampled set. |
Source code in genlm/control/sampler/set.py
SMC
This class implements sequential Monte Carlo (SMC) inference for controlled text generation. The generation process works as follows:
-
Token Sampling: At each step, the
unit_sampleris used to extend each particle (candidate sequence) by sampling a new token. This grows all sequences by one token at a time. The sampler also outputs an importance weight with each extension to correct for the myopic nature of token-by-token sampling. -
Critic Evaluation: If a
criticis provided, it scores the updated sequences (via it'sscoremethod), reweighting the particles based on how well they satisfy the constraints encoded by the critic. -
Resampling: When the effective sample size (ESS) falls below the threshold, particles are resampled according to their weights. This helps focus computation on more promising sequences.
-
Termination: The process continues until either:
-
All sequences reach an end-of-sequence (EOS) token
-
The maximum token length is reached
-
If a critic is provided, the resulting sequences are properly weighted with respect to the product of the unit sampler's
target potential and the critic potential (unit_sampler.target * critic). If a critic is not provided,
the resulting sequences are weighted with respect to the unit sampler's target potential.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unit_sampler
|
TokenSampler
|
The sampler that generates tokens. |
required |
critic
|
Potential
|
A potential function that guides the generation process by scoring candidate sequences. Must have the same token type as the unit_sampler. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If unit_sampler is not a TokenSampler, if critic is not a Potential, or if the token types of unit_sampler and critic don't match. |
Source code in genlm/control/sampler/sequence.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
__call__(n_particles, ess_threshold, max_tokens, verbosity=0, json_path=None, **kwargs)
async
Generate sequences using sequential Monte Carlo inference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_particles
|
int
|
Number of particles (candidate sequences) to maintain during generation. Higher values provide better exploration but require more computation. |
required |
ess_threshold
|
float
|
Effective sample size threshold for resampling, expressed as a fraction of the number of particles. When ESS falls below this value, particles are resampled according to their weights. Should be between 0 and 1. Higher values lead to more frequent resampling. Note that when ess_threshold = 0, the critic is only applied at the end of the generation (if it is provided). |
required |
max_tokens
|
int
|
Maximum number of tokens to generate per sequence. Generation may terminate earlier if all sequences reach an EOS token. |
required |
verbosity
|
int
|
Verbosity level for the SMC algorithm. 0 is silent, 1 prints the particles at each step. Default is 0. |
0
|
json_path
|
str
|
JSON file path for saving a record of the inference run.
This can be used in conjunction with the |
None
|
**kwargs
|
dict
|
Additional keyword arguments to pass to the SMC algorithm.
See the |
{}
|
Returns:
| Type | Description |
|---|---|
Sequences
|
A container holding the generated sequences, their importance weights, and other metadata from the generation process. |
Source code in genlm/control/sampler/sequence.py
cleanup()
async
Clean up resources used by the inference engine.
This method should be called when the InferenceEngine is no longer needed.
Example
Source code in genlm/control/sampler/sequence.py
MultiTokenUnitSampler
Bases: TokenSampler
Sampler that groups multiple tokens into larger units.
This sampler enables generation at a coarser granularity than individual tokens by repeatedly sampling tokens until a boundary condition is met. Common use cases:
- Word-level sampling: Group tokens until a word boundary (e.g., whitespace)
- Sentence-level sampling: Group tokens until punctuation marks
- Grammar-based units: Group tokens completing a grammar terminal
The sampler delegates to a subunit_sampler (typically a token-level sampler)
and accumulates samples until the boundary_predicate signals completion. The final
weight is the product of weights from each individual token sample. This ensures that
sampling remains properly weighted w.r.t. the target potential.
Weight calculation: If sampling a unit requires \(n\) token samples with weights \(w_1, w_2, \ldots, w_n\), the unit weight is \(w = \prod_{i=1}^{n} w_i\) (or \(\log w = \sum_{i=1}^{n} \log w_i\) in log-space).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subunit_sampler
|
TokenSampler
|
Sampler for subunits \(s \in \mathcal{B}\) |
required |
boundary_predicate
|
BoundaryPredicate
|
Determines when a sequence of tokens forms
a complete unit. Also controls how to finalize the unit via |
required |
max_subunits_per_unit
|
int
|
Safety timeout to prevent non-termination. Default: 100. |
100
|
Example
Sample word-level units (multi-token)
llm = PromptedLLM.from_name("gpt2") subunit_sampler = DirectTokenSampler(llm)
Word boundaries at whitespace
boundary = TokenSetBoundary({b" ", b"\n"}) unit_sampler = MultiTokenUnitSampler( ... subunit_sampler=subunit_sampler, ... boundary_predicate=boundary, ... max_subunits_per_unit=50 ... )
Units will be words WITH trailing space: [b"hello", b" "]
Source code in genlm/control/sampler/unit.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 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 | |
start_weight()
async
forward()
async
Called by LLaMPPL Model.call() to sample one multi-token unit.
Called by SequenceModel.step() when it calls self.call(unit_sampler).
Source code in genlm/control/sampler/unit.py
sample(flat_token_context, unit_context=None, draw=None)
async
Sample a multi-token unit by running sequence sampling for \(\varphi_{\bm{x}}\). SIS for the localized potential:
- Repeatedly sample \((s_i, w_i) \sim q_{\text{sub}}(\cdot \mid \bm{s}_{<i})\) until boundary
- Accumulate weights: \(w = \overrightarrow{\psi}_{\bm{x}}(\epsilon) \prod_i w_i\)
- Return \((\bm{s}, w)\) where \(\bm{s} \in \mathcal{B}^*\) forms unit \(x \in \mathcal{A}\)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
flat_token_context
|
list
|
Flat sequence of all previously sampled tokens. This is pre-flattened by forward() to ensure compatibility with potentials. |
required |
unit_context
|
list
|
Structured sequence of previously sampled units. Used by boundary predicates that need context. Defaults to []. |
None
|
draw
|
callable
|
Sampling function passed to subunit_sampler |
None
|
Returns:
| Type | Description |
|---|---|
(unit, weight, logp)
|
|
Source code in genlm/control/sampler/unit.py
BoundaryPredicate
Bases: ABC
Abstract base class for boundary predicates.
A boundary predicate determines when a sequence of subunits \(\bm{s} \in \mathcal{B}^*\) forms a complete unit \(x \in \mathcal{A}\).
__call__ method receives unit context and subunit buffer, allowing predicates
to be stateless and context-aware.
finalize_unit method transforms the buffer into the final unit after boundary
detection, allowing predicates to control what tokens are included (e.g., removing
delimiter tokens).
Source code in genlm/control/sampler/unit.py
__call__(unit_context, subunit_buffer)
abstractmethod
Check if subunit buffer forms a complete unit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unit_context
|
list
|
Sequence of completed units \(\bm{x} \in \mathcal{A}^*\) |
required |
subunit_buffer
|
list
|
Current sequence of subunits \(\bm{s} \in \mathcal{B}^*\) |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if \(\bm{s}\) forms a complete unit \(x \in \mathcal{A}\) |
Source code in genlm/control/sampler/unit.py
finalize_unit(subunit_buffer)
Transform buffer into final unit after boundary detected.
Called after __call__ returns True. Override to customize which tokens
are included in the final unit (e.g., to remove delimiter tokens).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subunit_buffer
|
list
|
The buffer that triggered the boundary |
required |
Returns:
| Name | Type | Description |
|---|---|---|
list |
list
|
The final unit to return |
Note
Default implementation returns the entire buffer unchanged.
Source code in genlm/control/sampler/unit.py
TokenSetBoundary
Bases: BoundaryPredicate
Stateless boundary predicate based on token membership.
A unit is complete when the last subunit is in a specified set of boundary tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
boundary_tokens
|
Iterable
|
Set or iterable of tokens that mark unit boundaries |
required |
Example
boundary = TokenSetBoundary({b" ", b"\n"}) boundary([], [b"hello", b" "]) # True (ends with whitespace)
Unit will be [b"hello", b" "] - boundary token included
Source code in genlm/control/sampler/unit.py
__call__(unit_context, subunit_buffer)
Check boundary (ignore unit_context for stateless predicate).
FixedLengthBoundary
Bases: BoundaryPredicate
Stateless boundary predicate based on fixed unit length. A unit is complete when it reaches a specified number of subunits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
length
|
int
|
Number of subunits per unit |
required |
Example
boundary = FixedLengthBoundary(10) boundary([], [b"a"] * 9) # False boundary([], [b"a"] * 10) # True
Source code in genlm/control/sampler/unit.py
__call__(unit_context, subunit_buffer)
CFGBoundary
Bases: BoundaryPredicate
Boundary predicate using Lark parser for context-free grammar-based boundaries.
This uses Lark's parser to determine when a sequence of subunits forms a syntactically complete unit according to a context-free grammar.
A unit can be marked as complete when: - The subunit buffer parses successfully - The parse tree's root matches one of the complete_rules
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grammar_text
|
str
|
Lark grammar specification |
required |
start_rule
|
str
|
Starting rule for parsing (default: "start") |
'start'
|
complete_rules
|
set or None
|
Set of rule names that constitute complete units. If None, any successful parse is complete. If provided, only parses with matching root are complete. |
None
|
min_length
|
int
|
Minimum buffer length before attempting to parse (default: 2) |
2
|
parser_type
|
str
|
Lark parser type: 'earley' (default, supports ambiguity) or 'lalr' (faster) |
'earley'
|
ambiguity
|
str
|
How to handle ambiguous grammars: 'explicit' (default) or 'resolve' |
'explicit'
|
encoding
|
str
|
Text encoding for token decoding (default: "utf-8") |
'utf-8'
|
decode_errors
|
str
|
How to handle decode errors (default: "ignore") |
'ignore'
|
Example
Simple arithmetic grammar
grammar = ''' ... start: expr ... expr: term | expr "+" term ... term: NUMBER ... NUMBER: /[0-9]+/ ... ''' boundary = CFGBoundary(grammar, complete_rules={"start"}) boundary([], [b"1", b"+", b"2"]) # True (complete expression) boundary([], [b"1", b"+"]) # False (incomplete)
Source code in genlm/control/sampler/unit.py
290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 | |
__call__(unit_context, subunit_buffer)
Check if buffer forms a complete syntactic unit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unit_context
|
list
|
Previous completed units (ignored) |
required |
subunit_buffer
|
list
|
Current sequence of subunits to check |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if buffer parses successfully and meets criteria |
Source code in genlm/control/sampler/unit.py
get_parse_tree(text)
Get the parse tree for a given text.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
String to parse |
required |
Returns:
| Type | Description |
|---|---|
Optional[Any]
|
Lark Tree object or None if parsing fails |
Source code in genlm/control/sampler/unit.py
flatten_units(context)
Flatten nested unit context to a flat token list. When using MultiTokenUnitSampler, token_ctx becomes nested [[...], [...], ...]. This helper flattens it for use with coercion functions like b"".join.
Usage
potential.coerce(LLM, f=lambda ctx: b"".join(flatten_units(ctx)))
Args: context: Either a flat list [token1, token2, ...] or nested [[token1, token2], [token3], ...] Returns: list: Flattened list of tokens
Source code in genlm/control/sampler/unit.py
direct_token_sampler(potential)
Create a DirectTokenSampler that samples directly from a potential's vocabulary.
See DirectTokenSampler for more details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
potential
|
Potential
|
The potential function to sample from. Should have an efficient logw_next method. |
required |
Returns:
| Type | Description |
|---|---|
DirectTokenSampler
|
A sampler that directly samples tokens from the potential's vocabulary. |
Source code in genlm/control/sampler/__init__.py
eager_token_sampler(iter_potential, item_potential)
Create a SetTokenSampler that uses the EagerSetSampler to sample a set of tokens.
See EagerSetSampler for more details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
iter_potential
|
Potential
|
A potential function defined over a vocabulary of iterables. |
required |
item_potential
|
Potential
|
A potential function defined over a vocabulary of items which are elements of the iterables. |
required |
Returns:
| Type | Description |
|---|---|
SetTokenSampler
|
A sampler that wraps an |
Note
This is the fastest sampler in most cases.
Source code in genlm/control/sampler/__init__.py
topk_token_sampler(iter_potential, item_potential, K)
Create a SetTokenSampler that uses the TopKSetSampler to sample a set of tokens.
See TopKSetSampler for more details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
iter_potential
|
Potential
|
A potential function defined over a vocabulary of iterables. |
required |
item_potential
|
Potential
|
A potential function defined over a vocabulary of items which are elements of the iterables. |
required |
K
|
int | None
|
The |
required |
Returns:
| Type | Description |
|---|---|
SetTokenSampler
|
A sampler that wraps an |