writeEach static method

void writeEach(
  1. String path,
  2. String key,
  3. List<(String, String, int, int)> shapes,
  4. CachedMatrix matrix(
    1. String name
    ), {
  5. void done(
    1. CachedMatrix written
    )?,
})

Writes a cache of the matrices shapes lists (name, format, rows, cols), in that order, asking matrix for each when its turn comes and handing it to done once written. A producer that makes each matrix on demand keeps only one in memory at a time, however large the cache.

Implementation

static void writeEach(
  String path,
  String key,
  List<(String, String, int, int)> shapes,
  CachedMatrix Function(String name) matrix, {
  void Function(CachedMatrix written)? done,
}) {
  int align(int v, int a) => (v + a - 1) ~/ a * a;
  // Data offsets depend on the header size, which depends on the offsets:
  // reserve a generous fixed header region instead.
  const headerRegion = 1 << 20;
  var offset = headerRegion;
  final tensors = <String, Object?>{};
  for (final (name, format, rows, cols) in shapes) {
    final (qsLength, scalesLength) = _byteLengths(format, rows, cols);
    final qs = offset = align(offset, 64);
    offset += qsLength;
    final scales = offset = align(offset, 64);
    offset += scalesLength;
    tensors[name] = {
      'format': format,
      'rows': rows,
      'cols': cols,
      'qs': qs,
      'scales': scales,
    };
  }
  final header = utf8.encode(
    jsonEncode({'version': _version, 'key': key, 'tensors': tensors}),
  );
  if (16 + header.length > headerRegion) {
    throw StateError('Q8 cache header does not fit');
  }
  final temp = File('$path.partial');
  final out = temp.openSync(mode: FileMode.write);
  try {
    final prefix = ByteData(16);
    final magic = utf8.encode(_magic);
    for (var i = 0; i < 8; i++) {
      prefix.setUint8(i, magic[i]);
    }
    prefix.setUint64(8, header.length, Endian.little);
    out
      ..writeFromSync(prefix.buffer.asUint8List())
      ..writeFromSync(header);
    for (final (name, format, rows, cols) in shapes) {
      final m = matrix(name);
      try {
        final (qsLength, scalesLength) = _byteLengths(format, rows, cols);
        if (m.format != format ||
            m.qsBytes.length != qsLength ||
            m.scaleBytes.length != scalesLength) {
          throw StateError('$name is not a $format [$rows, $cols] matrix');
        }
        final e = tensors[name] as Map<String, Object?>;
        out
          ..setPositionSync(e['qs'] as int)
          ..writeFromSync(m.qsBytes)
          ..setPositionSync(e['scales'] as int)
          ..writeFromSync(m.scaleBytes);
      } finally {
        done?.call(m);
      }
    }
  } finally {
    out.closeSync();
  }
  temp.renameSync(path);
}