loadState method

Future<bool> loadState(
  1. String path
)

Restores a state written by saveState for this model, weights and backend, and checkpoints it. Returns false, with the model reset, if path is missing, malformed or written for anything else.

Implementation

Future<bool> loadState(String path) async {
  _checkOpen();
  await reset();
  final file = File(path);
  if (!file.existsSync()) return false;
  final input = file.openSync();
  try {
    final prefix = input.readSync(16);
    if (prefix.length < 16 ||
        String.fromCharCodes(prefix.sublist(0, 8)) != _stateMagic) {
      return false;
    }
    final headerLength = ByteData.sublistView(
      prefix,
    ).getUint64(8, Endian.little);
    final header =
        jsonDecode(utf8.decode(input.readSync(headerLength)))
            as Map<String, Object?>;
    final tokens = (header['tokens'] as List).cast<int>();
    if (header['version'] != _stateVersion ||
        header['key'] != _currentStateKey ||
        tokens.isEmpty ||
        tokens.length > maxSeq) {
      return false;
    }
    final blocks = _stateBlocks(tokens.length);
    final lengths = (header['blocks'] as List).cast<int>();
    if (blocks == null ||
        blocks.length != lengths.length ||
        Iterable.generate(
          blocks.length,
        ).any((i) => blocks[i].length != lengths[i])) {
      return false;
    }
    input.setPositionSync(16 + headerLength + _padTo64(16 + headerLength));
    for (final b in blocks) {
      final bytes = b.buffer.asUint8List(b.offsetInBytes, b.lengthInBytes);
      var done = 0;
      while (done < bytes.length) {
        final n = input.readIntoSync(bytes, done);
        if (n <= 0) {
          await reset();
          return false;
        }
        done += n;
      }
    }
    length = tokens.length;
    _history.addAll(tokens);
    _embeddingKeys.addAll(List.filled(tokens.length, null));
    await checkpoint();
    return true;
  } on FormatException {
    await reset();
    return false;
  } finally {
    input.closeSync();
  }
}