hfppl
Probabilistic programming with HuggingFace Transformer models.
Bernoulli
Bases: Distribution
A Bernoulli distribution.
Source code in hfppl/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 HuggingFace causal language model, with support for caching.
Attributes:
Name | Type | Description |
---|---|---|
model |
the underlying HuggingFace model. |
|
tokenizer |
the underlying HuggingFace tokenizer. |
|
device |
str
|
the PyTorch device identifier (e.g. "cpu" or "cuda:0") on which the model is loaded. |
cache |
TokenTrie
|
the cache of previously evaluated log probabilities and key/value vectors. |
vocab |
list[str]
|
a list mapping token ids to strings. |
batch_size |
int
|
when auto-batching, maximum number of queries to process in one batch. |
timeout |
float
|
number of seconds to wait since last query before processing the current batch of queries, even if not full. |
Source code in hfppl/llms.py
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 |
|
__init__(hf_model, hf_tokenizer, batch_size=20)
Create a CachedCausalLM
from a loaded HuggingFace model and tokenizer.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
hf_model
|
a HuggingFace |
required | |
hf_tokenizer
|
a HuggingFace |
required | |
batch_size
|
int
|
when auto-batching, maximum number of queries to process in one batch. |
20
|
Source code in hfppl/llms.py
cache_kv(prompt_tokens)
Cache the key and value vectors for a prompt. Future queries that have this prompt as a prefix will only run the LLM on new tokens.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prompt_tokens
|
list[int]
|
token ids for the prompt to cache. |
required |
Source code in hfppl/llms.py
clear_cache()
clear_kv_cache()
from_pretrained(model_id, auth_token=False, load_in_8bit=True)
classmethod
Create a CachedCausalLM
from a pretrained HuggingFace model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_id
|
str
|
the string identifier of the model in HuggingFace's model library. |
required |
auth_token
|
str
|
a HuggingFace API key. Only necessary if using private models, e.g. Meta's Llama models, which require authorization. |
False
|
load_in_8bit
|
bool
|
whether to use the |
True
|
Returns:
Name | Type | Description |
---|---|---|
model |
CachedCausalLM
|
the LLaMPPL-compatible interface to the HuggingFace model. |
Source code in hfppl/llms.py
next_token_logprobs(token_ids)
async
Request log probabilities of next token. This version is asynchronous because it automatically batches concurrent requests; use with await
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
token_ids
|
list[int]
|
a list of token ids starting with |
required |
Returns:
Name | Type | Description |
---|---|---|
logprobs |
array
|
a numpy array of |
Source code in hfppl/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 starting with |
required |
Returns:
Name | Type | Description |
---|---|---|
logprobs |
array
|
a numpy array of |
Source code in hfppl/llms.py
reset_async_queries()
Clear any pending language model queries from the queue. Use this method when an exception prevented an inference algorithm from executing to completion.
Distribution
Abstract base class for a distribution.
Source code in hfppl/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 hfppl/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 hfppl/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 hfppl/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 hfppl/distributions/lmcontext.py
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 |
|
__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
|
Source code in hfppl/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 hfppl/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 hfppl/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 hfppl/distributions/logcategorical.py
Masks
Source code in hfppl/llms.py
precompute_token_length_masks(lm)
Precompute masks for tokens of different lengths.
Each mask is a set of token ids that are of the given length or shorter.
Source code in hfppl/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 hfppl/modeling.py
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 |
|
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 hfppl/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 hfppl/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 hfppl/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 hfppl/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 hfppl/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 hfppl/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 hfppl/modeling.py
Query
A query to a language model, waiting to be batched.
Source code in hfppl/llms.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 hfppl/llms.py
TokenCategorical
Bases: Distribution
Source code in hfppl/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 hfppl/distributions/tokencategorical.py
TokenSequence
A sequence of tokens.
Supports addition (via +
or mutating +=
) with:
- other
TokenSequence
instances (concatenation) - individual tokens, represented as integers or
Token
instances - 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 hfppl/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 hfppl/llms.py
TokenTrie
Class used internally to cache language model results.
Source code in hfppl/llms.py
Transformer
Bases: Distribution
Source code in hfppl/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 hfppl/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 hfppl/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 hfppl/chunks.py
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 |
|
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))
.