prefill method
Feeds the prompt ids for a new reply, reusing what the model has
already computed: the longest common prefix of ids and history
if history does not go past it, else the state at the latest
checkpoint inside it, else nothing. At least the last token is always
fed, so logits are the prompt's. Saves checkpoints at checkpoints
(positions in ids, such as the end of the system prompt) and at the
end of the prompt. Returns how many tokens were reused.
embeddingOverrides replaces token lookup at positions of ids, as
in forward. Such a position is reused only if it was fed an override
under an equal key in embeddingKeys (positions in ids); without a
key it is always fed again. A key promises that equal keys stand for
equal embeddings, such as one image's rows in one conversation.
Each token's arithmetic does not depend on how tokens are chunked, so
the logits are the same as feeding ids from scratch.
Implementation
Future<int> prefill(
List<int> ids, {
Iterable<int> checkpoints = const [],
Map<int, Float32List> embeddingOverrides = const {},
Map<int, Object> embeddingKeys = const {},
}) async {
final common = await restorePromptPrefix(
ids,
embeddingOverrides: embeddingOverrides,
embeddingKeys: embeddingKeys,
);
final stops = {
for (final p in checkpoints)
if (p > common && p < ids.length) p,
ids.length,
}.toList()..sort();
var at = common;
for (final stop in stops) {
await forward(
ids.sublist(at, stop),
computeLogits: stop == ids.length,
embeddingOverrides: {
for (final e in embeddingOverrides.entries)
if (e.key >= at && e.key < stop) e.key - at: e.value,
},
embeddingKeys: {
for (final e in embeddingKeys.entries)
if (e.key >= at && e.key < stop) e.key - at: e.value,
},
);
await checkpoint();
at = stop;
}
return common;
}