util
logsumexp(x, axis=-1, keepdims=False)
Log-sum-exp along axis, in the array's own backend. An all--inf slice
reduces to -inf, not nan.
Source code in genlm/control/util.py
to_numpy(w)
stack_weights(arrays)
Stack per-context weight arrays into one [N, V] batch in their own backend.
LRUCache
Bases: OrderedDict
Bounded dict that evicts the least recently used entry; get counts as a use.
Source code in genlm/control/util.py
LazyWeights
A class to represent weights in a lazy manner, allowing for efficient operations on potentially large weight arrays without immediate materialization.
Attributes:
| Name | Type | Description |
|---|---|---|
weights |
ndarray | Tensor
|
The weights associated with the tokens. |
encode |
dict
|
A mapping from tokens to their corresponding indices in the weights array. |
decode |
list
|
A list of tokens corresponding to the weights. |
is_log |
bool
|
A flag indicating whether the weights are in log space. |
Source code in genlm/control/util.py
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 | |
__init__(weights, encode, decode, log=True)
Initialize the LazyWeights instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weights
|
ndarray | Tensor
|
The weights associated with the tokens. |
required |
encode
|
dict
|
A mapping from tokens to their corresponding indices in the weights array. |
required |
decode
|
list
|
A list of tokens corresponding to the weights. |
required |
log
|
bool
|
Indicates if the weights are in log space. Defaults to True. |
True
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the lengths of weights and decode do not match, or if encode has fewer entries than decode. |
Source code in genlm/control/util.py
__getitem__(token)
Retrieve the weight for a given token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
Any
|
The token for which to retrieve the weight. Can be a Token object (direct lookup) or bytes (searches by byte_string). |
required |
Returns:
| Type | Description |
|---|---|
float
|
The weight of the token, or -inf/0 if the token is not found. |
Source code in genlm/control/util.py
keys()
values()
items()
normalize()
Normalize the weights.
Normalization is performed using log-space arithmetic when weights are logarithmic, or standard arithmetic otherwise.
Returns:
| Type | Description |
|---|---|
LazyWeights
|
A new LazyWeights instance with normalized weights. |
Source code in genlm/control/util.py
exp()
Exponentiate the weights. This operation can only be performed when weights are in log space.
Returns:
| Type | Description |
|---|---|
LazyWeights
|
A new LazyWeights instance with exponentiated weights. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the weights are not in log space. |
Source code in genlm/control/util.py
log()
Take the logarithm of the weights. This operation can only be performed when weights are in regular space.
Returns:
| Type | Description |
|---|---|
LazyWeights
|
A new LazyWeights instance with logarithmic weights. |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the weights are already in log space. |
Source code in genlm/control/util.py
sum()
Sum the weights.
Summation is performed using log-space arithmetic when weights are logarithmic, or standard arithmetic otherwise.
Returns:
| Type | Description |
|---|---|
float
|
The sum of the weights, either in log space or regular space. |
Source code in genlm/control/util.py
spawn(new_weights, log=None)
Create a new LazyWeights instance over the same vocabulary with new weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
new_weights
|
ndarray | Tensor
|
The new weights for the LazyWeights instance. |
required |
log
|
bool
|
Indicates if the new weights are in log space. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
LazyWeights
|
A new LazyWeights instance. |
Source code in genlm/control/util.py
materialize(top=None, sort=True)
Materialize the weights into a chart.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
top
|
int
|
The number of top weights to materialize. Defaults to None. |
None
|
sort
|
bool
|
Order the chart by descending weight; ignored when |
True
|
Returns:
| Type | Description |
|---|---|
Chart
|
A chart representation of the weights. |
Source code in genlm/control/util.py
assert_equal(other, **kwargs)
Assert that two LazyWeights instances are equal.
This method asserts that the two LazyWeights instances have the same vocabulary (in identical order) and that their weights are numerically close.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
LazyWeights
|
The other LazyWeights instance to compare. |
required |
**kwargs
|
dict
|
Additional arguments for np.testing.assert_allclose (e.g., rtol, atol). |
{}
|
Source code in genlm/control/util.py
assert_equal_unordered(other, **kwargs)
Assert that two LazyWeights instances are equal, ignoring vocabularyorder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
LazyWeights
|
The other LazyWeights instance to compare. |
required |
**kwargs
|
dict
|
Additional arguments for np.isclose (e.g., rtol, atol). |
{}
|
Source code in genlm/control/util.py
load_trie(V, backend=None, **kwargs)
Load a TokenCharacterTrie.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
V
|
list[Token] | list[bytes] | list[str]
|
The vocabulary. |
required |
backend
|
str
|
The backend to use for trie construction. Defaults to None. |
None
|
**kwargs
|
dict
|
Additional arguments for the trie construction. |
{}
|
Returns:
| Type | Description |
|---|---|
TokenCharacterTrie
|
A trie instance. |
Source code in genlm/control/util.py
load_async_trie(V, backend=None, **kwargs)
Load an AsyncTokenCharacterTrie. This is a TokenCharacterTrie that automatically batches weight_sum and weight_max requests.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
V
|
list
|
The vocabulary. |
required |
backend
|
str
|
The backend to use for trie construction. Defaults to None. |
None
|
**kwargs
|
dict
|
Additional arguments for the trie construction. |
{}
|
Returns:
| Type | Description |
|---|---|
AsyncTokenCharacterTrie
|
An async trie instance. |
Source code in genlm/control/util.py
gumbel_max(logps)
multinomial(logps)
Categorical draw over the last dim (scalar for [V], [N] for [N, V]).
inverse_cdf(logps)
Inverse-CDF draw over the last dim, one uniform per row (scalar for [V], [N]
for [N, V]).
Source code in genlm/control/util.py
flatten_units(context)
Recursively flatten a (possibly unit-nested) context to a flat token list.
Usage
potential.coerce(LLM, f=lambda ctx: b"".join(flatten_units(ctx)))
Source code in genlm/control/util.py
set_draw_method(method)
Set the draw method used by draw_from and draw_indices, process-wide.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str | callable
|
A name in |
required |
Source code in genlm/control/util.py
draw_from(lazyweights, draw=None, target=None)
async
Draw a token from a next-token distribution and weigh it.
Concurrent callers on one event loop are drawn together, one batched reduction per backend, device and vocab size, each row with independent noise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lazyweights
|
LazyWeights
|
The log-weight row to draw from. |
required |
draw
|
callable
|
Custom draw, taking the normalized probability chart and returning a token. Bypasses batching. |
None
|
target
|
LazyWeights
|
A second row over the same vocabulary. Makes
the draw an importance draw: |
None
|
Returns:
| Type | Description |
|---|---|
tuple
|
|
Source code in genlm/control/util.py
BatchAbandoned
join_batch(store, entry)
async
Join the batch of concurrent callers on this event loop.
The first caller holds the batch open until an event-loop pass adds no entry,
then receives it to flush. If that leader dies first, every other queued future
is failed with BatchAbandoned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
store
|
WeakKeyDictionary
|
Event loop to |
required |
entry
|
tuple
|
The request to add, ending in its future. |
required |
Returns:
| Type | Description |
|---|---|
list | None
|
The drained batch for the holding caller, |
Source code in genlm/control/util.py
batch_abandoned(exc)
The failure handed to callers whose batch leader died.
Never the cause itself: a CancelledError given to a caller who never asked for
one leaves their task cancelled and skips their except Exception.
Source code in genlm/control/util.py
fail_futures(entries, exc)
Resolve each entry's future -- its last element -- with exc.
draw_indices(weights)
Draw indices over the last dim of a log-weight array with the configured draw method
(scalar for [V], [N] for [N, V]).