token
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
logw_eos(context)
async
Returns the weight of EOS, used to force termination in sequence.py.
Subclasses may override with cheaper, sampler-specific computations
that avoid materializing the full logw_next vector.
Source code in genlm/control/sampler/token.py
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
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 |
proposal
|
Potential
|
If supplied, tokens are drawn from
|
None
|
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
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 | |
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}) $$
Without a proposal, the returned weight is the log normalizing constant of \(\textsf{target.logw_next}\). With a proposal \(q\), the returned weight is the importance weight \(\textsf{target.logw_next}[x_n] - \log q_{\text{norm}}(x_n)\).
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
logw_eos(context)
async
Boundary EOS log-weight via the complete - prefix identity.
Set samplers exist to avoid materializing the full target.logw_next
vector; for the EOS entry specifically we get the same value as
complete(context) - prefix(context), which for the typical
iter_potential * item_potential target reduces to a constant
number of scalar evaluations on the underlying potentials.
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
|
proposal
|
Potential
|
If supplied, the rejection loop proposes
from |
None
|
Source code in genlm/control/sampler/token.py
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 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 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 | |
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.
With no proposal, the returned weight is the log normalizing constant of \(\textsf{target.logw_next}\). With a proposal \(q\), the inner loop proposes from \(q\) and the returned weight adds an importance correction \(\textsf{potential.logw_next}[x_n] - q.\textsf{logw_next}[x_n]\).
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
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 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 | |
improper_sample(*, logps, toks, accept, rng, max_rejects)
async
Implements a single rejection sampling loop which returns the first value found with no attempt to make a properly weighted sample.
Source code in genlm/control/sampler/token.py
recursive_awrs(*, logps, toks, accept, rng, max_rejects)
async
Implements Recursive AWRS.
This uses the observation that
E(f(X)) = P(X = x) f(x) + (1 - P(X = x)) E(f(X)|X != x)
To construct a recursive estimator of the weight from a single sampling-with-rejection run. The first time accept(x) passes, we use a simple coin flip estimator for the tail.
Source code in genlm/control/sampler/token.py
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 | |
geometric_awrs(*, logps, toks, accept, rng, max_rejects, max_accepts)
async
Implements Geometric AWRS.
This simulates a single run of sampling with replacement from a sampling without replacement run, reconstructing the counts of "phantom" elements discarded from the without-replacement run as a series of draws from geometric distributions. We can then use an appropriate estimator for the with-replacement run at the end.
Source code in genlm/control/sampler/token.py
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 | |