llamppl
Probabilistic programming with Large Language Models.
Bernoulli
Bases: Distribution
A Bernoulli distribution.
Source code in llamppl/distributions/bernoulli.py
__init__(p)
Create a Bernoulli distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
the probability-of-True for the Bernoulli distribution. |
required |
CachedCausalLM
Wrapper around a genlm.backend.llm.AsyncLM.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
AsyncLM
|
The underlying language model (either |
str_vocab |
list[str]
|
List mapping token IDs to their string representations. |
byte_vocab |
list[bytes]
|
List mapping token IDs to their byte representations. |
masks |
Masks
|
Token masks for filtering logits during generation. |
Source code in llamppl/llms.py
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 | |
vocab
property
Legacy accessor for string vocabulary. Prefer using .str_vocab directly for access to the model's string vocabulary.
__init__(model)
Create a CachedCausalLM from an AsyncLM.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
AsyncLM
|
an |
required |
Source code in llamppl/llms.py
cache_kv(prompt_tokens)
Cache the key and value vectors for a prompt.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt_tokens
|
list[int]
|
token ids for the prompt to cache. |
required |
Source code in llamppl/llms.py
clear_cache()
Clear the cache of log probabilities and key/value pairs.
For HuggingFace backend: Clears both logprob cache and KV cache.
For vLLM backend: Only clears logprob cache (KV cache is managed internally by vLLM).
Source code in llamppl/llms.py
clear_kv_cache()
Clear any key and value vectors from the cache.
Source code in llamppl/llms.py
from_pretrained(model_id, backend=None, **kwargs)
classmethod
Create a CachedCausalLM from a HuggingFace model name.
This is a convenience method that instantiates the underlying AsyncLM from a HuggingFace model name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
Name or path of the HuggingFace pretrained model to load. |
required |
backend
|
str
|
|
None
|
**kwargs
|
Additional keyword arguments passed to the |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
CachedCausalLM |
The llamppl-compatible interface to the |
Source code in llamppl/llms.py
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 | |
next_token_logprobs(token_ids)
async
Request log probabilities of next token. This version is asynchronous and support auto batching of concurrent requests; use with await.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_ids
|
list[int]
|
a list of token ids, representing a prompt to the language model. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
logprobs |
array
|
a numpy array of length |
Source code in llamppl/llms.py
next_token_logprobs_unbatched(token_ids)
Request log probabilities of next token. Not asynchronous, and does not support auto-batching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_ids
|
list[int]
|
a list of token ids, representing a prompt to the language model. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
logprobs |
array
|
a numpy array of length |
Source code in llamppl/llms.py
reset_async_queries()
Clear any pending language model queries from the queue.
Source code in llamppl/llms.py
Distribution
Abstract base class for a distribution.
Source code in llamppl/distributions/distribution.py
argmax(n)
async
Return the nth most probable outcome under this distribution (assuming this is a discrete distribution).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
which value to return to, indexed from most probable (n=0) to least probable (n=|support|). |
required |
Returns: x: the nth most probable outcome from this distribution.
Source code in llamppl/distributions/distribution.py
log_prob(x)
async
Compute the log probability of a value under this distribution, or the log probability density if the distribution is continuous.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
the point at which to evaluate the log probability. |
required |
Returns:
logprob (float): the log probability of x.
Source code in llamppl/distributions/distribution.py
sample()
async
Generate a random sample from the distribution.
Returns:
| Name | Type | Description |
|---|---|---|
x |
a value randomly sampled from the distribution. |
Geometric
Bases: Distribution
A Geometric distribution.
Source code in llamppl/distributions/geometric.py
__init__(p)
Create a Geometric distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
p
|
the rate of the Geometric distribution. |
required |
LMContext
Represents a generation-in-progress from a language model.
The state tracks two pieces of information:
- A sequence of tokens — the ever-growing context for the language model.
- A current mask — a set of tokens that have not yet been ruled out as the next token.
Storing a mask enables sub-token generation: models can use LMContext to sample
the next token in stages, first deciding, e.g., whether to use an upper-case or lower-case
first letter, and only later deciding which upper-case or lower-case token to generate.
The state of a LMContext can be advanced in two ways:
- Sampling, observing, or intervening the
next_token()distribution. This causes a token to be added to the growing sequence of tokens. Supports auto-batching. - Sampling, observing, or intervening the
mask_dist(mask)distribution for a given mask (set of token ids). This changes the current mask.
Attributes:
| Name | Type | Description |
|---|---|---|
lm |
CachedCausalLM
|
the language model for which this is a context |
tokens |
list[int]
|
the underlying sequence of tokens, including prompt, in this context |
next_token_logprobs |
array
|
numpy array holding the log probabilities for the next token. Unlike the log probabilities reported by |
temp |
float
|
temeprature for next-token distribution (0 < temp < float('inf')) |
model_mask |
set[int]
|
set of tokens that have not been ruled out as the next token. This mask is managed by the |
show_prompt |
bool
|
controls whether the string representation of this |
Source code in llamppl/distributions/lmcontext.py
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 | |
__init__(lm, prompt, temp=1.0, show_prompt=False, show_eos=True)
Create a new LMContext with a given prompt and temperature.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lm
|
CachedCausalLM
|
the language model for which this is a context. |
required |
prompt
|
str
|
a string with which to initialize the context. Will be tokenized using |
required |
temp
|
float
|
temeprature for next-token distribution (0 < temp < float('inf')) |
1.0
|
Note
For async initialization of LMContext, use LMContext.create().
Source code in llamppl/distributions/lmcontext.py
create(lm, prompt, temp=1.0, show_prompt=False, show_eos=True)
async
classmethod
Asynchronously create a new LMContext with a given prompt and temperature.
Source code in llamppl/distributions/lmcontext.py
mask_dist(mask)
Bernoulli distribution, with probability of True equal to the probability that the next token of this LMContext belongs
to the given mask.
Sampling or observing from this distribution modifies the state of this LMContext instance, so that
the next_token() distribution either will (if True) or will not (if False) generate a token from
the given mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
|
a |
required |
Source code in llamppl/distributions/lmcontext.py
next_token()
Distribution over the next token.
Sampling or observing from this distribution advances the state of this LMContext instance.
LogCategorical
Bases: Distribution
A Geometric distribution.
Source code in llamppl/distributions/logcategorical.py
__init__(logits)
Create a Categorical distribution from unnormalized log probabilities (logits).
Given an array of logits, takes their softmax and samples an integer in range(len(logits))
from the resulting categorical.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
array
|
a numpy array of unnormalized log probabilities. |
required |
Source code in llamppl/distributions/logcategorical.py
Masks
Source code in llamppl/llms.py
precompute_token_lengths(lm)
Precompute the length of each token. Special tokens are considered to have length 0.
Source code in llamppl/llms.py
Model
Base class for all LLaMPPL models.
Your models should subclass this class. Minimally, you should provide an __init__ method
that calls super().__init__(self), and a step method.
Source code in llamppl/modeling.py
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 | |
condition(b)
Constrain a given Boolean expression to be True.
If the condition is False, the particle's weight is set to zero and self.finish()
is called, so that no further step calls are made.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
b
|
the Boolean expression whose value is constrained to be True. |
required |
Source code in llamppl/modeling.py
immutable_properties()
Return a set[str] of properties that LLaMPPL may assume do not change during execution of step.
This set is empty by default but can be overridden by subclasses to speed up inference.
Returns:
| Name | Type | Description |
|---|---|---|
properties |
set[str]
|
a set of immutable property names |
Source code in llamppl/modeling.py
intervene(dist, x)
async
Force the distribution to take on the value x, but do not condition on this result.
This is useful primarily with distributions that have side effects (e.g., modifying some state). For example, a model with the code
token_1 = await self.sample(self.stateful_lm.next_token())
await self.observe(self.stateful_lm.next_token(), token_2)
encodes a posterior inference problem, to find token_1 values that likely preceded token_2. By contrast,
token_1 = await self.sample(stateful_lm.next_token())
await self.intervene(self.stateful_lm.next_token(), token_2)
encodes a much easier task: freely generate token_1 and then force-feed token_2 as the following token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dist
|
Distribution
|
the distribution on which to intervene. |
required |
x
|
the value to intervene with. |
required |
Source code in llamppl/modeling.py
observe(dist, x)
async
Condition the model on the value x being sampled from the distribution dist.
For discrete distributions dist, await self.observe(dist, x) specifies the same constraint as
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dist
|
a |
required | |
x
|
the value observed from |
required |
Source code in llamppl/modeling.py
sample(dist, proposal=None)
async
Extend the model with a sample from a given Distribution, with support for autobatching.
If specified, the Distribution proposal is used during inference to generate informed hypotheses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dist
|
the |
required | |
proposal
|
if provided, inference algorithms will use this |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
value |
the value sampled from the distribution. |
Source code in llamppl/modeling.py
score(score)
Multiply this particle's weight by exp(score).
The score method is a low-level way to change the target distribution.
For many use cases, it is sufficient to use sample, observe, condition,
and twist, all of which are implemented in terms of score.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
score
|
logarithm of the amount by which the particle's weight should be multiplied. |
required |
Source code in llamppl/modeling.py
step()
async
Defines the computation performed in each step of the model.
All subclasses should override this method.
string_for_serialization()
Return a string representation of the particle for serialization purposes.
Returns:
| Name | Type | Description |
|---|---|---|
str |
a string representation of the particle. |
twist(amt)
Multiply this particle's weight by exp(amt), but divide it back out before the next step.
Use this method to provide heuristic guidance about whether a particle is "on the right track" without changing the ultimate target distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
amt
|
the logarithm of the amount by which to (temporarily) multiply this particle's weight. |
required |
Source code in llamppl/modeling.py
Token
Class representing a token.
Attributes:
| Name | Type | Description |
|---|---|---|
lm |
CachedCausalLM
|
the language model for which this is a Token. |
token_id |
int
|
the integer token id (an index into the vocabulary). |
token_str |
str
|
a string, which the token represents—equal to |
Source code in llamppl/llms.py
TokenCategorical
Bases: Distribution
Source code in llamppl/distributions/tokencategorical.py
__init__(lm, logits)
Create a Categorical distribution whose values are Tokens, not integers.
Given a language model lm and an array of unnormalized log probabilities (of length len(lm.vocab)),
uses softmax to normalize them and samples a Token from the resulting categorical.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lm
|
CachedCausalLM
|
the language model whose vocabulary is to be generated from. |
required |
logits
|
array
|
a numpy array of unnormalized log probabilities. |
required |
Source code in llamppl/distributions/tokencategorical.py
TokenSequence
A sequence of tokens.
Supports addition (via + or mutating +=) with:
- other
TokenSequenceinstances (concatenation) - individual tokens, represented as integers or
Tokeninstances - strings, which are tokenized by
lm.tokenizer
Attributes:
| Name | Type | Description |
|---|---|---|
lm |
CachedCausalLM
|
the language model whose vocabulary the tokens come from. |
seq |
list[Token]
|
the sequence of tokens. |
Source code in llamppl/llms.py
__init__(lm, seq=None)
Create a TokenSequence from a language model and a sequence.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lm
|
CachedCausalLM
|
the language model whose vocabulary the tokens come from. |
required |
seq
|
str | list[int]
|
the sequence of token ids, or a string which will be automatically tokenized. Defaults to the singleton sequence containing a bos token. |
None
|
Source code in llamppl/llms.py
Transformer
Bases: Distribution
Source code in llamppl/distributions/transformer.py
__init__(lm, prompt, temp=1.0)
Create a Categorical distribution whose values are Tokens, with probabilities given by a language model. Supports auto-batching.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lm
|
CachedCausalLM
|
the language model. |
required |
prompt
|
str | TokenSequence
|
the sequence of tokens to use as the prompt. If a string, |
required |
temp
|
float
|
temperature at which to generate (0 < |
1.0
|
Source code in llamppl/distributions/transformer.py
log_softmax(nums)
Compute log(softmax(nums)).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nums
|
a vector or numpy array of unnormalized log probabilities. |
required |
Returns:
| Type | Description |
|---|---|
|
np.array: an array of log (normalized) probabilities. |
sample_word(self, context, max_tokens=5, allow_punctuation=True)
async
Sample a word from the LMContext object context.
Source code in llamppl/chunks.py
sample_word_2(self, context, max_chars=None, allow_mid_punctuation=True, allow_end_punctuation=True)
async
Sample a word from the LMContext object context.
Unlike sample_word() above, this method allows for character-level control over the length of the word. It also allows for control over the presence of punctuation in the middle and at the end of the word.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_chars
|
int
|
Maximum number of characters in the word. If None, the model will sample a word of any length. |
None
|
allow_mid_punctuation
|
bool
|
If True, the model may sample punctuation in the middle of the word. |
True
|
allow_end_punctuation
|
bool
|
If True, the model may sample punctuation at the end of the word. |
True
|
Returns:
| Type | Description |
|---|---|
|
Tuple[str, str]: The sampled word and punctuation |
Source code in llamppl/chunks.py
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 | |
submodel(f)
Decorator to create a SubModel implementation from an async function.
For example:
@submodel
async def sample_two_tokens(self, context):
token1 = await self.sample(context.next_token())
token2 = await self.sample(context.next_token())
return token1, token2
This SubModel can then be used from another model or submodel, using the syntax await self.call(sample_two_tokens(context)).