Skip to content
fn

initialize_kv_prefix_from_text

→Tensor
initialize_kv_prefix_from_text(model: PeftModel, tokenizer: _TextEncoder, text: str, adapter_name: str | None = None, num_virtual_tokens: int | None = None, use_chat_template: bool = True, max_length: int | None = None)

Start a Cartridge from a text: read it with the model, and keep the first keys and values.

The base model runs over the text with the adapters off (use_cache=True), and the first num_virtual_tokens entries of the cache it returns are loaded into the adapter (initialize_kv_prefix_from_past_key_values). No tokenizer package is needed: tokenizer is any object with encode(text) -> list[int], as the ones of lucid.utils.tokenizer are, and one that also has apply_chat_template reads the text as a system message.

Parameters

A model with a CARTRIDGE or PREFIX_TUNING adapter, whose base model returns its cache as past_key_values when called with use_cache=True.
tokenizerobject with encode(text) -> list[int]
Turns the text into token ids.
textstr
The document, or the first part of it.
adapter_namestr= None
The adapter to initialise; the active one when left out.
num_virtual_tokensint= None
How many leading tokens to keep; the adapter's own count when left out.
use_chat_templatebool= True
Read the text through the tokenizer's chat template as a system message when it has one.
max_lengthint= None
Cut the token ids to this many before the model reads them.

Returns

Tensor

The rows that were loaded.

Raises

TypeError
tokenizer offers neither encode nor a chat template, or returns something that is not token ids.
ValueError
The adapter cannot be initialised from a cache (see initialize_kv_prefix_from_past_key_values), the text has no tokens, or the model returned no cache.

Used by 1