A cache of keys and values that is trained, as a matrix of rows (one per virtual token) of every layer's key and value.
A row holds 2 * num_layers * token_dim numbers laid out as prefix tuning's are, the key and the
value of each layer one after another, so the cache goes in front of the model's own like a
prefix's. The first num_frozen_tokens rows are stored as a parameter that is never trained
(the Cartridges paper recommends freezing the first token as an attention sink), the rest as the
trained one. Both start as a standard normal draw, which the reference's embedding table also
starts as; load_prompt_embeddings replaces them, from the first keys and values of a document
the model has read (initialize_kv_prefix_from_text), say.
Parameters
configCartridgeConfignum_virtual_tokens, num_layers, token_dim (all set; the tuner fills them in from the
model), num_frozen_tokens and inference_mode.Attributes
Raises
ValueErrornum_frozen_tokens is outside [0, num_virtual_tokens].Examples
>>> import lucid
>>> from lucid.peft import CartridgeConfig, CartridgeEncoder
>>> config = CartridgeConfig(num_virtual_tokens=5, num_frozen_tokens=2, num_layers=3, token_dim=4)
>>> encoder = CartridgeEncoder(config)
>>> tuple(encoder.frozen_embedding.shape), tuple(encoder.trainable_embedding.shape)
((2, 24), (3, 24))
>>> encoder(lucid.zeros(2, 5).long()).shape
(2, 5, 24)
>>> encoder.frozen_embedding.requires_grad, encoder.trainable_embedding.requires_grad
(False, True)Used by 2
Constructors
1Properties
3How many virtual tokens the cache holds: the frozen rows and the trained ones.
True: the parameters are the cache itself, nothing maps them.
The whole cache (num_virtual_tokens, hidden): the frozen rows, then the trained ones.
Attributes
2Whether the prompt depends on the task each batch row belongs to (task_ids).
The encoder's own tensors by the file's key: the trained rows are the file's prompt_embeddings (the frozen rows join them on the way out).
Class methods
1Instance methods
6The cache for each row of a batch: (batch, ...) ids to (batch, num_virtual_tokens, hidden).
The ids are ignored; they are there so a cache is called as every prompt is.
The virtual-token ids (1, num_embeddings) the encoder is called with.
Copy a whole cache (num_virtual_tokens, hidden) in, the first rows into the frozen ones.
Parameters
prompt_ embeddingsTensorRaises
ValueError(num_virtual_tokens, hidden).The prompt as an adapter file stores it: (rows, width), one row per virtual token.
A per-task encoder's is the shared prompt its tasks scale, which is what the file holds.
The prompt of each of batch rows: (batch, num_embeddings, width).
tasks is the task of each row, which a per_task encoder needs and the others
do not read.
Draw every row again from a standard normal.