saveState method

Future<void> saveState(
  1. String path
)

Writes the state at the current position to path: the tokens, the KV rows before it and the conv histories, about 45 KB per token for LFM3-1.7B (34 MB for a 761-token system prompt with tools). A later process on the same model, weights and backend can loadState it instead of computing those tokens. Written through a temporary file and a rename, so a reader never sees half a state.

Layout: magic LFM3ST01, a little-endian u64 header length, a JSON header (version, key, tokens, block lengths), zero padding to a multiple of 64, then the float blocks of _stateBlocks in order.

Implementation

Future<void> saveState(String path) async {
  _checkOpen();
  final blocks =
      _stateBlocks(length) ??
      (throw UnsupportedError('worker isolates do not save states'));
  final header = utf8.encode(
    jsonEncode({
      'version': _stateVersion,
      'key': _currentStateKey,
      'tokens': _history,
      'blocks': [for (final b in blocks) b.length],
    }),
  );
  final temp = File('$path.partial');
  final out = temp.openSync(mode: FileMode.write);
  try {
    final prefix = ByteData(16);
    for (var i = 0; i < 8; i++) {
      prefix.setUint8(i, _stateMagic.codeUnitAt(i));
    }
    prefix.setUint64(8, header.length, Endian.little);
    out
      ..writeFromSync(prefix.buffer.asUint8List())
      ..writeFromSync(header)
      ..writeFromSync(Uint8List(_padTo64(16 + header.length)));
    for (final b in blocks) {
      out.writeFromSync(
        b.buffer.asUint8List(b.offsetInBytes, b.lengthInBytes),
      );
    }
  } finally {
    out.closeSync();
  }
  temp.renameSync(path);
}