forward method

Future<void> forward(
  1. List<int> tokens, {
  2. void capture(
    1. int slot,
    2. int first,
    3. Float32List rows,
    4. int count,
    )?,
  3. bool computeLogits = true,
  4. Map<int, Float32List> embeddingOverrides = const {},
  5. Map<int, Object> embeddingKeys = const {},
  6. void meanwhile()?,
})

Feeds tokens at positions length, length + 1, ... and advances.

capture receives, per chunk, the residual stream entering layer 0 (slot 0) and leaving each layer (slot i + 1), as count rows of hidden size starting at position first. With computeLogits the last token's logits are left in logits. embeddingOverrides replaces token lookup at zero-based positions in this call with projected multimodal features of Lfm3Config.hiddenSize. Positions are relative to tokens, not the current sequence length. Such positions are recorded as -1 in history so text-only prefill cannot reuse state conditioned on a different image. embeddingKeys names the embedding at override positions for a later prefill, which reuses them only under an equal key.

meanwhile runs once, on the CPU, while the last chunk computes on the GPU (after the whole call on the CPU path), for work that does not depend on this pass, such as decoding audio already generated. It must not use the GPU or this model. If it throws, the pass still completes and the error is rethrown.

Implementation

Future<void> forward(
  List<int> tokens, {
  void Function(int slot, int first, Float32List rows, int count)? capture,
  bool computeLogits = true,
  Map<int, Float32List> embeddingOverrides = const {},
  Map<int, Object> embeddingKeys = const {},
  void Function()? meanwhile,
}) async {
  _checkOpen();
  if (embeddingKeys.keys.any((p) => !embeddingOverrides.containsKey(p))) {
    throw ArgumentError('every embedding key needs an override');
  }
  final overrides = <int, Float32List>{};
  for (final entry in embeddingOverrides.entries) {
    if (entry.key < 0 || entry.key >= tokens.length) {
      throw RangeError.range(entry.key, 0, tokens.length - 1, 'position');
    }
    if (entry.value.length != config.hiddenSize ||
        entry.value.any((v) => !v.isFinite)) {
      throw ArgumentError(
        'embedding at ${entry.key} must contain ${config.hiddenSize} finite values',
      );
    }
    // CPU executors can yield between chunks: own the inputs throughout.
    overrides[entry.key] = Float32List.fromList(entry.value);
  }
  if (length + tokens.length > maxSeq) {
    throw StateError('sequence exceeds maxSeq=$maxSeq');
  }
  if (tokens.isNotEmpty) _hasHiddenState = false;
  _forwarding++;
  Object? meanwhileError;
  StackTrace? meanwhileTrace;
  var ran = false;
  void guarded() {
    ran = true;
    try {
      meanwhile!();
    } catch (e, s) {
      meanwhileError = e;
      meanwhileTrace = s;
    }
  }

  try {
    await _forward(
      tokens,
      capture,
      computeLogits,
      overrides,
      meanwhile == null ? null : guarded,
    );
    _embeddingKeys.addAll([
      for (var t = 0; t < tokens.length; t++)
        overrides.containsKey(t) ? embeddingKeys[t] : null,
    ]);
    // The CPU path, or no tokens: the work runs after the pass.
    if (meanwhile != null && !ran) guarded();
    if (meanwhileError case final e?) {
      Error.throwWithStackTrace(e, meanwhileTrace!);
    }
  } on Object catch (e) {
    if (identical(e, meanwhileError)) rethrow;
    // A chunk that failed partway (a GPU command buffer the system
    // rejected, a worker isolate that died) may have advanced the conv
    // histories and KV rows without [length] and [history]: forget the
    // sequence, so no later prefill reuses state that no longer matches.
    if (!_closed) {
      try {
        await reset();
      } on Object {
        // The original error says more than a failed reset.
      }
    }
    rethrow;
  } finally {
    _forwarding--;
  }
}