potential
Potential
Bases: ABC, PotentialOps, PotentialTests
Abstract base class for potentials.
A Potential is a function that maps sequences of tokens in a vocabulary to non-negative real numbers (weights).
Potentials assign weights to sequences of tokens based on whether they are complete sequences or prefixes of complete sequences.
complete: Assess the log weight of a sequence of tokens in the vocabulary as a complete sequence.prefix: Assess the log weight of a sequence of tokens in the vocabulary as a prefix.
Potentials additionally implement a logw_next method:
logw_next: Compute the next-token log weights of each token in the vocabulary and a special EOS (end-of-sequence) token given a context.
Subclasses must minimally implement complete and prefix. logw_next and batched versions of the above methods
come with default implementations, but may be overridden by subclasses for improved performance.
All Potentials must satisfy a set of properties which can be tested using PotentialTests.
Attributes:
| Name | Type | Description |
|---|---|---|
token_type |
TokenType
|
The type of tokens in the vocabulary. |
vocab |
list
|
List of tokens making up the vocabulary. |
eos |
EndOfSequence
|
Special token to use as end-of-sequence. |
vocab_eos |
list
|
List of tokens in |
lookup |
dict
|
Mapping from tokens and |
Source code in genlm/control/potential/base.py
12 13 14 15 16 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 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 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 | |
__init__(vocabulary, token_type=None, eos=None)
Initialize the potential.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vocabulary
|
list
|
List of tokens that make up the vocabulary. |
required |
token_type
|
TokenType
|
Optional TokenType of all elements of the vocabulary. If None, will be inferred from vocabulary. |
None
|
eos
|
EndOfSequence
|
Special token to use as end-of-sequence. Defaults to |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If vocabulary is empty. |
TypeError
|
If vocabulary contains tokens which are not of |
Source code in genlm/control/potential/base.py
complete(context)
abstractmethod
async
Assess the weight of context as a complete sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
Sequence of tokens. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Log weight of the context under the language. |
Source code in genlm/control/potential/base.py
prefix(context)
abstractmethod
async
Assess the weight of context as a prefix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
Sequence of tokens. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Log weight of the context as a prefix. |
Source code in genlm/control/potential/base.py
score(context)
async
Assess the weight of context based on EOS-termination.
This is a convenience method which dispatches to complete if context ends with self.eos, otherwise to prefix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
Sequence of tokens. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Log weight of the context, either as a prefix or complete sequence. |
Source code in genlm/control/potential/base.py
logw_next(context)
async
Compute the next-token weights of each token in self.vocab_eos given context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
Sequence of tokens. |
required |
Returns:
| Type | Description |
|---|---|
LazyWeights
|
Weights of each token in the vocabulary and EOS. |
Source code in genlm/control/potential/base.py
batch_complete(contexts)
async
Batched equivalent to complete.
Assess the weight of each context as a complete sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contexts
|
list
|
List of sequences of tokens. |
required |
Returns:
| Type | Description |
|---|---|
array
|
Array of log weights for each context. |
Source code in genlm/control/potential/base.py
batch_prefix(contexts)
async
Batched equivalent to prefix.
Assess the weight of each context as a prefix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contexts
|
list
|
List of sequences of tokens. |
required |
Returns:
| Type | Description |
|---|---|
array
|
Array of log weights for each context. |
Source code in genlm/control/potential/base.py
batch_score(contexts)
async
Batched equivalent to score.
Assess the weight of each context based on EOS-termination.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contexts
|
list
|
List of sequences of tokens. |
required |
Returns:
| Type | Description |
|---|---|
array
|
Array of log weights for each context. |
Source code in genlm/control/potential/base.py
batch_logw_next(contexts)
async
Batched equivalent to logw_next.
Computes the next-token weights of each token in self.vocab_eos given each context in the batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contexts
|
list
|
List of sequences of tokens. |
required |
Returns:
| Type | Description |
|---|---|
list
|
List of LazyWeights objects, one for each context. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any context has zero weight (log weight of -inf) under |
Source code in genlm/control/potential/base.py
make_lazy_weights(weights, log=True)
Helper method to create a LazyWeights object over the potential's vocabulary and EOS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
array
|
Array of weights. |
required |
log
|
bool
|
Whether the weights are in log space. Defaults to True. |
True
|
Returns:
| Type | Description |
|---|---|
LazyWeights
|
LazyWeights object defined over |
Source code in genlm/control/potential/base.py
alloc_logws(default=float('-inf'))
Allocate a new array of log weights for the potential's vocabulary and EOS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
default
|
float
|
Default log weight. Defaults to -inf. |
float('-inf')
|
Returns:
| Type | Description |
|---|---|
array
|
Array of length |
Source code in genlm/control/potential/base.py
spawn()
Spawn a fresh instance of the potential.
This method is not required by default, but may be implemented by subclasses
to support CPU-parallelism using (MultiProcPotential)[genlm.control.potential.multi_proc.MultiProcPotential].
Source code in genlm/control/potential/base.py
cleanup()
async
AutoBatchedPotential
Bases: Potential
AutoBatchedPotential is a wrapper around a Potential that enables automatic batching of concurrent requests.
This class manages a background loop that collects concurrent requests to instance methods
(complete, prefix, score, logw_next) and batches them together before
delegating to the corresponding batch methods of the underlying potential
(batch_complete, batch_prefix, batch_score, batch_logw_next).
This class inherits all methods from Potential.
Attributes:
| Name | Type | Description |
|---|---|---|
potential |
Potential
|
The underlying potential instance that is being wrapped. |
background_loop |
AsyncBatchLoop
|
An asynchronous loop that manages batch requests. |
Source code in genlm/control/potential/autobatch.py
MultiProcPotential
Bases: Potential
A Potential that adds parallel processing capabilities to any base Potential implementation.
Creates a process pool of worker processes, each containing an instance of the potential.
This class inherits all methods from Potential.
Each method delegates to a corresponding method of the potential instances running in the
worker processes, distributing work across multiple processes for improved performance.
Source code in genlm/control/potential/multi_proc.py
7 8 9 10 11 12 13 14 15 16 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 | |
__init__(potential_factory, factory_args, num_workers=2)
Initialize the MultiProcPotential.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
potential_factory
|
callable
|
A factory function that creates a potential instance. |
required |
factory_args
|
tuple
|
Arguments to pass to the potential factory. |
required |
num_workers
|
int
|
The number of worker processes to spawn. Each will contain an instance of the potential. |
2
|
Source code in genlm/control/potential/multi_proc.py
PotentialOps
Mixin providing operations for potential functions:
-
Product (
*): Take the product of two potentials. -
Coercion (
coerce): Coerce the potential to operate on another potential's vocabulary. -
Auto-batching (
to_autobatched): Create a version that automatically batches concurrent requests to the instance methods. -
Parallelization (
to_multiprocess): Create a version that parallelizes operations over multiple processes.
Source code in genlm/control/potential/operators.py
__mul__(other)
Take the product of two potentials.
See Product for more details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Potential
|
Another potential instance to take the product with. |
required |
Returns:
| Type | Description |
|---|---|
Product
|
A Product instance representing the unnormalized product of the two potentials. |
Note
Potentials must operate on the same token type and the intersection of their vocabularies must be non-empty.
Source code in genlm/control/potential/operators.py
coerce(other, f, prune=True)
Coerce the current potential to operate on the vocabulary of another potential.
See Coerced for more details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Potential
|
The potential instance whose vocabulary will be used. |
required |
f
|
callable
|
A function mapping sequences of tokens from self's vocab to sequences of tokens from other's vocab. |
required |
prune
|
bool
|
Whether to prune the coerced potential's vocabulary to only include tokens that can be mapped to the original potential's vocabulary.
If |
True
|
Returns:
| Type | Description |
|---|---|
Coerced
|
A Potential that operates on the vocabulary of |
Source code in genlm/control/potential/operators.py
to_autobatched()
Create a new potential instance that automatically batches concurrent requests to the instance methods.
See AutoBatchedPotential for more details.
Returns:
| Type | Description |
|---|---|
AutoBatchedPotential
|
A new potential instance that wraps the current potential and automatically batches concurrent requests to the instance methods. |
Source code in genlm/control/potential/operators.py
to_multiprocess(num_workers=2, spawn_args=None)
Create a new potential instance that parallelizes operations using multiprocessing.
See MultiProcPotential for more details.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_workers
|
int
|
The number of workers to use in the multiprocessing pool. |
2
|
spawn_args
|
tuple
|
The positional arguments to pass to the potential's |
None
|
Returns:
| Type | Description |
|---|---|
MultiProcPotential
|
A new potential instance that wraps the current potential and uses multiprocessing to parallelize operations. |
Note
For this method to be used, the potential must implement a picklable spawn method.
Source code in genlm/control/potential/operators.py
Product
Bases: Potential
Combine two potential instances via element-wise multiplication (sum in log space).
This class creates a new potential that is the element-wise product of two potentials:
prefix(xs) = p1.prefix(xs) + p2.prefix(xs)
complete(xs) = p1.complete(xs) + p2.complete(xs)
logw_next(x | xs) = p1.logw_next(x | xs) + p2.logw_next(x | xs)
The new potential's vocabulary is the intersection of the two potentials' vocabularies.
This class inherits all methods from Potential,
see there for method documentation.
Attributes:
| Name | Type | Description |
|---|---|---|
p1 |
Potential
|
The first potential instance. |
p2 |
Potential
|
The second potential instance. |
token_type |
str
|
The type of tokens that this product potential operates on. |
vocab |
list
|
The common vocabulary shared between the two potentials. |
Warning
Be careful when taking products of potentials with minimal vocabulary overlap. The resulting potential will only operate on tokens present in both vocabularies.
Source code in genlm/control/potential/product.py
6 7 8 9 10 11 12 13 14 15 16 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 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
__init__(p1, p2)
Initialize a Product potential.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p1
|
Potential
|
First potential |
required |
p2
|
Potential
|
Second potential |
required |
Source code in genlm/control/potential/product.py
Coerced
Bases: Potential
Coerce a potential to operate on another vocabulary.
This class allows a potential to be adapted to work with a different set of tokens, defined by a target vocabulary and coersion function.
This class inherits all methods from Potential.
Each method delegates to the corresponding method of the underlying potential, but first
maps any input token sequences from the target vocabulary to the original potential's vocabulary
using the coercion function.
Formally, if \(f\) is the coercion function, then for any sequence \(x_1, \ldots, x_n\) of tokens from the target vocabulary, $$ \textsf{Coerced.prefix}(x_1, \ldots, x_n) = \textsf{Coerced.potential.prefix}(f(x_1, \ldots, x_n)) $$
Attributes:
| Name | Type | Description |
|---|---|---|
potential |
Potential
|
The original potential instance that is being coerced. |
f |
callable
|
A function that maps sequences of tokens from the target vocabulary to sequences of tokens from the original potential's vocabulary. |
Note
The coerced potential's vocabulary will by default be pruned to only include tokens that can be mapped to the original potential's vocabulary
via the coercion function (i.e. set(f([x])) <= set(potential.vocab)). If no such tokens are found, a ValueError is raised.
This behavior can be overridden by setting prune=False, in which case the coerced potential's vocabulary will include all tokens from the target vocabulary.
Source code in genlm/control/potential/coerce.py
7 8 9 10 11 12 13 14 15 16 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 | |
__init__(potential, target_vocab, f, prune=True)
Initialize a Coerced potential.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
potential
|
Potential
|
The original potential instance that is being coerced. |
required |
target_vocab
|
list
|
The target vocabulary that the potential will operate on.
Each element of |
required |
f
|
callable
|
A function that maps iterables of tokens from the target vocabulary to the original potential's vocabulary. |
required |
prune
|
bool
|
Whether to prune the coerced potential's vocabulary to only include tokens that can be mapped to the original potential's vocabulary.
If |
True
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If no valid tokens are found in the target vocabulary that can be mapped to the original potential's vocabulary. |
Source code in genlm/control/potential/coerce.py
HarmonyPotential
Bases: Potential
A potential that applies a base constraint to specific channels of the Harmony chat format.
The Harmony chat format structures LLM output into named channels (analysis, final, commentary). This potential extracts the content of specified channels and evaluates them under a base potential, leaving unconstrained channels free.
Attributes:
| Name | Type | Description |
|---|---|---|
base_potential |
Potential
|
The potential applied to constrained channel contents. |
harmony_chat |
HarmonyChat
|
Parser for the Harmony chat format. |
constrained_channels |
list[str]
|
Channels to which the base potential is applied. |
Source code in genlm/control/potential/harmony.py
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 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 | |
__init__(base_potential, llm_tokenizer, constrained_channels)
Initialize the HarmonyPotential.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_potential
|
Potential
|
A base potential applied to the constrained channels. |
required |
llm_tokenizer
|
Any
|
A tokenizer that supports the harmony chat format. |
required |
constrained_channels
|
list[str]
|
A non-empty list of channels to constrain.
Each element must be one of |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
AssertionError
|
If the base potential's vocabulary is not a subset of the harmony potential's vocabulary. |
Source code in genlm/control/potential/harmony.py
complete(context)
async
Compute the log weight of the constrained channels as complete sequences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list[bytes]
|
A list of byte tokens. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The sum (in log space) of the base potential's complete weight for each constrained channel. Returns 0 if no constrained channel is present. |
Source code in genlm/control/potential/harmony.py
prefix(context)
async
Compute the log weight of the constrained channels as a prefix.
Each constrained channel is evaluated with the base potential: completed
channels use complete, while the currently open channel uses prefix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list[bytes]
|
A list of byte tokens. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The sum (in log space) of the base potential's weight for each constrained channel. Returns 0 if no constrained channel is present. |
Source code in genlm/control/potential/harmony.py
logw_next(context)
async
Compute next-token log weights for each possible next token, including EOS.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list[bytes]
|
A list of byte tokens. |
required |
Returns:
| Type | Description |
|---|---|
LazyWeights
|
Weights of each token in the vocabulary and EOS. |
Note
In the harmony chat format, the analysis and commentary channels are
closed by the <|end|> token, while the final channel is closed by
<|return|> (which also closes the chat and halts generation).
The base potential uses the built-in EOS symbol to represent "the constrained string ends here." We need to remap this to the token the LLM actually emits to close the channel:
- analysis/commentary: Move the base potential's EOS weight to the
<|end|>token and set EOS to -inf, since generation must not halt mid-turn. - final: No remapping needed, because
PromptedLLMalready moves<|return|>probability to EOS, so the base potential and the LLM are already aligned.
Source code in genlm/control/potential/harmony.py
HarmonyChat
Encodes the structure of the "assistant" field of the Harmony chat format.
Provides methods to extract the "harmony channels" (analysis, final, commentary) from it. Since it operates on the byte representation of tokens, it also provides methods to convert between token IDs and byte representations.
Attributes:
| Name | Type | Description |
|---|---|---|
tokenizer |
The tokenizer used to encode and decode tokens. |
|
token_maps |
TokenMappings
|
Mappings between token IDs and byte representations. |
potential_vocab |
list[bytes]
|
The byte vocabulary used by potentials. |
end_token |
bytes
|
Byte representation of the |
message_token |
bytes
|
Byte representation of the |
channel_token |
bytes
|
Byte representation of the |
analysis_tokens |
list[bytes]
|
Byte representation of the |
final_tokens |
list[bytes]
|
Byte representation of the |
commentary_tokens |
list[bytes]
|
Byte representation of the |
Source code in genlm/control/potential/harmony.py
16 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 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 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 | |
__init__(tokenizer)
Initialize HarmonyChat with a tokenizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokenizer
|
Any
|
A tokenizer that supports the harmony chat format. The tokenizer must be able to encode the harmony chat tokens as single tokens. |
required |
Source code in genlm/control/potential/harmony.py
extract_channel_content(token_bytes, i)
Extract content between the <|message|> token at position i and the next <|end|> token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_bytes
|
list[bytes]
|
The full token sequence. |
required |
i
|
int
|
Index of the |
required |
Returns:
| Type | Description |
|---|---|
dict | None
|
A dict with keys |
Source code in genlm/control/potential/harmony.py
extract_harmony_channels_from_tokens(token_bytes)
Extract analysis, final, and commentary content from token bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_bytes
|
list[bytes]
|
List of byte tokens. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary mapping channel names to their extracted content,
or |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the token bytes do not form a valid harmony chat. |
Source code in genlm/control/potential/harmony.py
extract_harmony_channels_from_string(string, add_special_tokens=False)
Extract analysis, final, and commentary content from a string.
Uses the tokenizer to map from string to token IDs and from token IDs to token bytes,
then calls :meth:extract_harmony_channels_from_tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
string
|
str
|
The harmony chat format string to extract channels from. |
required |
add_special_tokens
|
bool
|
Whether to add special tokens during encoding. |
False
|
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary mapping channel names to their extracted content
(same format as :meth: |
Source code in genlm/control/potential/harmony.py
encode_tokens(tokens)
Encode a list of Token objects (or bytes) to token IDs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
list[Token] | list[bytes]
|
List of tokens to encode. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
A list of token IDs corresponding to the input tokens. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any token is not in the vocabulary. |
Source code in genlm/control/potential/harmony.py
decode_tokens(ids)
Decode a list of token IDs to byte tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ids
|
list[int]
|
A list of token IDs in the language model's vocabulary. |
required |
Returns:
| Type | Description |
|---|---|
list[bytes]
|
A list of byte tokens corresponding to the input token IDs. |
Source code in genlm/control/potential/harmony.py
validate_harmony_format(context)
Validate that the context is a valid harmony chat.
Validates the "assistant" field of the chat format, which is generated by the language model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
str | list[bytes]
|
A string or a list of byte tokens. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
Source code in genlm/control/potential/harmony.py
PromptedLLM
Bases: Potential
A potential representing a language model conditioned on a fixed prompt prefix.
PromptedLLMs operate on byte sequences.
Notes on EOS Token Handling:
-
Tokens to treat as end-of-sequence tokens are specified via the
eos_byte_stringsargument. -
These tokens are excluded from the potential's vocabulary and as such do not appear in the
vocabattribute.This means they cannot appear in any input contexts to the potential nor in the output of
logw_next. They can be used in the prompt however. -
The log probability assigned to the
genlm.control's reservedEOStoken is the sum of the log probabilities of all the specified EOS tokens.
This class wraps an AsyncLM instance.
Source code in genlm/control/potential/built_in/llm.py
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 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 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 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 557 558 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 | |
__init__(llm, prompt_ids=None, eos_byte_strings=None, temperature=1.0, token_maps=None, **kwargs)
` Initializes the PromptedLLM potential.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm
|
AsyncLM
|
The language model to use. |
required |
prompt_ids
|
list[int]
|
Optional prompt to use as a prompt prefix for all input contexts.
Must be a list of token IDs. Defaults to None. The prompt ids can be set post-init via |
None
|
eos_byte_strings
|
list[bytes]
|
List of tokens to treat as end-of-sequence tokens. Defaults to the EOS token of the language model's tokenizer. |
None
|
temperature
|
float
|
The temperature to apply to the language model's logits. Defaults to 1. |
1.0
|
token_maps
|
TokenMappings
|
A precomputed mapping of tokens to token IDs with the potential's vocabulary.
If provided, |
None
|
Source code in genlm/control/potential/built_in/llm.py
from_name(name, backend=None, eos_byte_strings=None, prompt_ids=None, temperature=1.0, **kwargs)
classmethod
Create a PromptedLLM from a Hugging Face model name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the model to load |
required |
backend
|
str
|
Defaults to 'vllm' if CUDA is available, otherwise 'hf'. |
None
|
eos_byte_strings
|
list[bytes]
|
List of tokens to treat as end-of-sequence tokens. Defaults to the EOS token of the language model's tokenizer. |
None
|
prompt_ids
|
list[int]
|
Optional prompt to use as a prompt prefix for all input contexts.
Must be a list of token IDs. Defaults to None. The prompt ids can be set post-init via |
None
|
temperature
|
float
|
The temperature to apply to the language model's logits. Defaults to 1. |
1.0
|
**kwargs
|
dict
|
Additional arguments passed to AsyncLM constructor |
{}
|
Returns:
| Type | Description |
|---|---|
PromptedLLM
|
An instance of PromptedLLM |
Source code in genlm/control/potential/built_in/llm.py
prompt
property
Get the current prompt as Token objects.
Returns:
| Type | Description |
|---|---|
list[Token] | None
|
The current prompt as Token objects, or None if no prompt_ids are set. |
set_prompt_from_str(prompt_str)
Set the fixed prompt from a string.
Modifies prompt_ids to be the token IDs of the input prompt according to the language model's tokenizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt_str
|
str
|
The prompt to set. |
required |
Source code in genlm/control/potential/built_in/llm.py
encode_tokens(tokens)
Encode a list of Token objects to token IDs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
list[Token]
|
List of Token objects |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
A list of token IDs corresponding to the input tokens. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any token is not in the vocabulary. |
Note
Passing bytes is deprecated. Use Token objects from llm.tokenize().
Source code in genlm/control/potential/built_in/llm.py
decode_tokens(ids)
Decode a list of token IDs to Token objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ids
|
list[int]
|
A list of token IDs in the language model's vocabulary. |
required |
Returns:
| Type | Description |
|---|---|
list[Token]
|
Token objects corresponding to the input token IDs. |
Source code in genlm/control/potential/built_in/llm.py
tokenize(context_str)
Tokenize a string to a list of Token objects.
Uses the language model's tokenizer to map context_str to token IDs,
then returns the corresponding Token objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context_str
|
str
|
A string to encode |
required |
Returns:
| Type | Description |
|---|---|
list[Token]
|
Token objects corresponding to the input string. |
Source code in genlm/control/potential/built_in/llm.py
log_probability(context)
async
Compute the log probability of context given the prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list[bytes] | list[Token]
|
A sequence of byte tokens or Token objects. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The log probability of |
Source code in genlm/control/potential/built_in/llm.py
prefix(context)
async
Compute the log probability of context given the prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list[bytes] | list[Token]
|
A sequence of byte tokens or Token objects. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The log probability of |
Source code in genlm/control/potential/built_in/llm.py
complete(context)
async
Compute the log probability of context and the eos tokens given the prompt.
If the model has multiple eos tokens, their probabilities will be summed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list[bytes] | list[Token]
|
A sequence of byte tokens or Token objects. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The log probability of the context. |
Source code in genlm/control/potential/built_in/llm.py
logw_next(context)
async
Get log probabilities for next tokens given the prompt and context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list[bytes] | list[Token]
|
A sequence of byte tokens or Token objects. |
required |
Returns:
| Type | Description |
|---|---|
LazyWeights
|
Log probabilities for next tokens and EOS. Keys are Token objects. |
Source code in genlm/control/potential/built_in/llm.py
batch_logw_next(contexts)
async
Get log probabilities for next tokens given the prompt and context, for a batch of contexts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contexts
|
list[list[bytes]] | list[list[Token]]
|
A list of sequences of byte tokens or Token objects. |
required |
Returns:
| Type | Description |
|---|---|
list[LazyWeights]
|
Log probabilities for next tokens and EOS for each context. Keys are Token objects. |
Source code in genlm/control/potential/built_in/llm.py
spawn(prompt_ids=None, eos_byte_strings=None, temperature=None, **kwargs)
Spawn a new PromptedLLM.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt_ids
|
(optional, list[int])
|
The prompt to use as a prompt prefix for all input contexts.
Defaults to the same prompt_ids as |
None
|
eos_byte_strings
|
(optional, list[bytes])
|
A list of tokens to treat as end-of-sequence tokens.
Defaults to the same eos_byte_strings as |
None
|
temperature
|
(optional, float)
|
The temperature with which to rescale logprobs.
Defaults to the same temperature as |
None
|
Returns:
| Type | Description |
|---|---|
PromptedLLM
|
A new PromptedLLM with the same prompt and eos tokens. |
Note
This is a shallow copy. The new PromptedLLM will share the underlying AsyncLM instance.
Source code in genlm/control/potential/built_in/llm.py
spawn_new_eos(eos_byte_strings=None, **kwargs)
Create a new PromptedLLM with a different set of end-of-sequence tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eos_byte_strings
|
list[bytes]
|
A list of tokens to treat as end-of-sequence tokens. |
None
|
Returns:
| Type | Description |
|---|---|
PromptedLLM
|
A new PromptedLLM with the specified end-of-sequence tokens.
The new model will have the same prompt_ids as |
Source code in genlm/control/potential/built_in/llm.py
ByteLLM
Bases: Potential
A potential representing a language model operating at the byte level using beam search.
ByteLLM wraps a language model and uses beam search to compute log probabilities
over byte sequences. This enables constrained generation at the byte level while
maintaining coherent token-level probabilities through adaptive token healing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm
|
Any
|
The language model to use (from |
required |
beam_params
|
BeamParams
|
Configuration for beam search, including beam width |
required |
cache_size
|
int
|
Maximum number of beam states to cache. Defaults to 1024. |
1024
|
Example
from genlm.bytes import BeamParams
from genlm.control import ByteLLM
beam_params = BeamParams(K=5, eos_byte_strings=[b"<|endoftext|>"], heal=True)
async with ByteLLM.from_name("gpt2", beam_params) as byte_llm:
byte_llm.set_prompt_from_str("Hello")
logp = await byte_llm.prefix([b" ", b"w", b"o", b"r", b"l", b"d"])
Source code in genlm/control/potential/built_in/bytellm.py
11 12 13 14 15 16 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 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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | |
logw_next(context)
async
Efficient next-token weights using the cached beam state.
Uses the beam's next-token distribution directly instead of the default (slower) fallback that recomputes scores for each token.
Source code in genlm/control/potential/built_in/bytellm.py
cleanup()
async
Cleans up resources used by the beam states.
This method is called automatically when using ByteLLM as an async context manager. If not using a context manager, you should call this method manually when done.
Source code in genlm/control/potential/built_in/bytellm.py
__aenter__()
async
__aexit__(exc_type, exc_val, exc_tb)
async
WCFG
Bases: Potential
A weighted context-free grammar potential.
This class wraps a genlm_grammar.CFG and provides methods for computing the log-weight of a sequence,
the prefix log-weight of a sequence, and the log-weights of the next token given a sequence.
Source code in genlm/control/potential/built_in/wcfg.py
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 | |
__init__(cfg)
Initialize the WCFG potential.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
CFG
|
The context-free grammar configuration to use. The CFG must in the Float semiring. |
required |
Source code in genlm/control/potential/built_in/wcfg.py
from_string(grammar, to_bytes=True, **kwargs)
classmethod
Create a WCFG from a string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grammar
|
str
|
The string grammar specification to create the WCFG from. |
required |
to_bytes
|
bool
|
Whether to convert the WCFG terminals to indivudual bytes. Defaults to True. |
True
|
**kwargs
|
dict
|
Additional arguments passed to the WCFG constructor. |
{}
|
Returns:
| Type | Description |
|---|---|
WCFG
|
The created WCFG. |
Source code in genlm/control/potential/built_in/wcfg.py
complete(context)
async
Compute the log weight of context under the WCFG.
For example, if the WCFG accepts "cat" and "car" with weights \(w_{cat}\) and \(w_{car}\):
-
complete("c")returns \(-\infty\) since this sequence is not accepted by the WCFG -
complete("cat")returns \(\log(w_{cat})\) -
complete("d")returns \(-\infty\) since this sequence is not accepted by the WCFG
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
A sequence of tokens in the WCFG's alphabet. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The log weight of |
Source code in genlm/control/potential/built_in/wcfg.py
prefix(context)
async
Compute the log prefix weight of context under the WCFG.
This corresponds to the log of the sum of the weights of all sequences with prefix context.
For example, if the WCFG accepts "cat" and "car" with weights \(w_{cat}\) and \(w_{car}\):
-
prefix("c")returns \(\log(w_{cat} + w_{car})\) -
prefix("cat")returns \(\log(w_{cat})\) -
prefix("d")returns \(-\infty\) since the WCFG does not accept any sequences with prefix "d"
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
A sequence of tokens in the WCFG's alphabet. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The log prefix weight of |
Source code in genlm/control/potential/built_in/wcfg.py
logw_next(context)
async
Compute the next token log weights given context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
A sequence of tokens in the WCFG's alphabet. |
required |
Returns:
| Type | Description |
|---|---|
LazyWeights
|
The log weights for the next tokens and EOS given |
Source code in genlm/control/potential/built_in/wcfg.py
clear_cache()
BoolCFG
Bases: Potential
BoolCFG represents a boolean context-free grammar.
Source code in genlm/control/potential/built_in/wcfg.py
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 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 | |
from_lark(lark_string, charset='core')
classmethod
Create a BoolCFG instance from a Lark grammar string.
The output grammar will be defined at the byte-level.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lark_string
|
str
|
The Lark grammar string to parse. See Lark documentation for correct syntax. |
required |
charset
|
str
|
The character set to use. Defaults to "core".
See |
'core'
|
Returns:
| Type | Description |
|---|---|
BoolCFG
|
An instance of BoolCFG created from the provided Lark grammar. |
Source code in genlm/control/potential/built_in/wcfg.py
complete(context)
async
Checks whether the context is accepted by the CFG.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
A sequence of tokens in the CFG's alphabet. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Log weight for whether |
Source code in genlm/control/potential/built_in/wcfg.py
prefix(context)
async
Checks whether context is accepted as a prefix by the CFG, i.e.,
whether there exists a completion to context that is accepted by the CFG.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
A sequence of tokens in the CFG's alphabet. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Log weight for whether |
Source code in genlm/control/potential/built_in/wcfg.py
logw_next(context)
async
Compute the next token log weights given context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
A sequence of tokens in the CFG's alphabet. |
required |
Returns:
| Type | Description |
|---|---|
LazyWeights
|
The log weights for the next tokens and EOS given |
Source code in genlm/control/potential/built_in/wcfg.py
batch_logw_next(contexts)
async
Batch version of logw_next.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contexts
|
list
|
A list of sequences of tokens in the CFG's alphabet. |
required |
Returns:
| Type | Description |
|---|---|
list
|
A list of log-weights for next token, one per context. |
Source code in genlm/control/potential/built_in/wcfg.py
spawn()
WFSA
Bases: Potential
A weighted finite state automaton (WFSA) potential.
This class wraps a genlm_grammar.WFSA and provides methods for computing the log-weight of a context,
the prefix log-weight of a context, and the log-weights of the next token given a context.
Attributes:
| Name | Type | Description |
|---|---|---|
wfsa |
WFSA
|
The weighted finite state automaton used for potential calculations. |
Source code in genlm/control/potential/built_in/wfsa.py
11 12 13 14 15 16 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 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 192 193 194 195 196 197 198 199 200 201 202 | |
__init__(wfsa)
Initializes the WFSA potential.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
wfsa
|
WFSA
|
The weighted finite state automaton. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the semiring of the provided WFSA is not Float or Log. |
Note
The WFSA will be converted to the Log semiring to avoid underflow if the semiring is Float.
Source code in genlm/control/potential/built_in/wfsa.py
from_regex(pattern, charset=None, to_bytes=True)
classmethod
Create a WFSA from a regex pattern.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pattern
|
str
|
The regex pattern to convert into a WFSA. |
required |
charset
|
set
|
The character set to use for negative character classes. Defaults to characters in string.printable. |
None
|
to_bytes
|
bool
|
Whether to convert the WFSA transitions to bytes. Defaults to True. When set to False, the WFSA transitions will be strings. |
True
|
Returns:
| Type | Description |
|---|---|
WFSA
|
An instance of the WFSA class. |
Note
The transition weights are automatically normalized to form a probability distribution.
For each state, the weights of all outgoing transitions (including final state transitions)
sum to 1.0. This means if a state has n possible transitions, each transition will have
weight 1/n. To create a WFSA from a regex with non-probabilistic transitions, use BoolFSA.
Source code in genlm/control/potential/built_in/wfsa.py
complete(context)
async
Computes the log weight of the context under the weighted language represented by the WFSA.
For example, if the WFSA accepts "cat" and "car" with weights \(w_{cat}\) and \(w_{car}\):
-
complete("c")returns \(-\infty\) since this sequence is not accepted by the WFSA -
complete("cat")returns \(\log(w_{cat})\) -
complete("d")returns \(-\infty\) since this sequence is not accepted by the WFSA
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
A sequence of tokens in the WFSA's alphabet. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Log weight of context under the WFSA. |
Source code in genlm/control/potential/built_in/wfsa.py
prefix(context)
async
Computes the prefix log weight of context under the WFSA.
This corresponds to the log of the sum of the weights of all sequences with prefix context.
For example, if the WFSA accepts "cat" and "car" with weights \(w_{cat}\) and \(w_{car}\):
-
prefix("c")returns \(\log(w_{cat} + w_{car})\) -
prefix("ca")returns \(\log(w_{cat})\) -
prefix("d")returns \(-\infty\) since the WFSA does not accept any sequences with prefix "d"
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
A sequence of tokens in the WFSA's alphabet. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Log weight of |
Source code in genlm/control/potential/built_in/wfsa.py
logw_next(context)
async
Returns next token log weights given context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
A sequence of tokens in the WFSA's alphabet. |
required |
Returns:
| Type | Description |
|---|---|
LazyWeights
|
Log-weights for next token and EOS. |
Source code in genlm/control/potential/built_in/wfsa.py
BoolFSA
Bases: WFSA
Boolean FSA potential.
Source code in genlm/control/potential/built_in/wfsa.py
prefix(context)
async
Computes whether the context is accepted as a prefix by the FSA.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
A sequence of tokens in the WFSA's alphabet. |
required |
Returns:
| Type | Description |
|---|---|
float
|
|
Source code in genlm/control/potential/built_in/wfsa.py
complete(context)
async
Computes whether the context is accepted by the FSA.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
A sequence of tokens in the WFSA's alphabet. |
required |
Returns:
| Type | Description |
|---|---|
float
|
|
Source code in genlm/control/potential/built_in/wfsa.py
logw_next(context)
async
Returns next token log weights given context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
A sequence of tokens in the WFSA's alphabet. |
required |
Returns:
| Type | Description |
|---|---|
LazyWeights
|
Boolean log-weights for next token. |
Source code in genlm/control/potential/built_in/wfsa.py
batch_logw_next(contexts)
async
Returns next token log weights for a batch of contexts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
contexts
|
list
|
The list of contexts. |
required |
Returns:
| Type | Description |
|---|---|
list
|
List of log-weights for next token, one per context. |
Source code in genlm/control/potential/built_in/wfsa.py
CanonicalTokenization
Bases: Potential
A custom potential that enforces canonical BPE tokenization.
This potential ensures that tokens follow the canonical tokenization rules by using the FastCanonicalityFilterBPE under the hood.
Source code in genlm/control/potential/built_in/canonical.py
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 | |
__init__(canonicality_filter)
Initialize the Canonical Potential
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
canonicality_filter
|
FastCanonicalityFilterBPE
|
An initialized FastCanonicalityFilterBPE instance. |
required |
Source code in genlm/control/potential/built_in/canonical.py
from_llm(llm)
classmethod
Factory method to create CanonicalTokenization from a PromptedLLM instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
llm
|
PromptedLLM
|
An instance of PromptedLLM containing the model and tokenizer. |
required |
Returns:
| Type | Description |
|---|---|
CanonicalTokenization
|
An initialized CanonicalTokenization instance. |
Source code in genlm/control/potential/built_in/canonical.py
complete(context)
async
Assess if a complete sequence follows canonical tokenization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
Sequence of tokens |
required |
Returns:
| Type | Description |
|---|---|
float
|
0.0 if canonical, float('-inf') otherwise |
Source code in genlm/control/potential/built_in/canonical.py
prefix(context)
async
Assess if a prefix sequence could potentially extend to a canonical sequence. For canonicality, this is the same as complete.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
Sequence of tokens |
required |
Returns:
| Type | Description |
|---|---|
float
|
0.0 if potentially canonical, float('-inf') otherwise |
Source code in genlm/control/potential/built_in/canonical.py
logw_next(context)
async
Compute weights for each possible next token given the context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
list
|
Sequence of tokens |
required |
Returns:
| Type | Description |
|---|---|
LazyWeights
|
Weights for each token in the vocabulary and EOS |