readF32 method

Float32List readF32(
  1. String name,
  2. List<int> shape, {
  3. int rowStart = 0,
  4. int? rowEnd,
})

Reads a tensor as float32, checking its shape. BF16 widens exactly: a bfloat16 is the top half of the float32 with the same value.

rowStart and rowEnd select rows of the first dimension. Rows of a row-major tensor are contiguous, so a slice is a single read.

Implementation

Float32List readF32(
  String name,
  List<int> shape, {
  int rowStart = 0,
  int? rowEnd,
}) {
  final info = tensors[name];
  if (info == null) throw ArgumentError('tensor $name not found');
  if (info.shape.length != shape.length ||
      !Iterable.generate(
        shape.length,
      ).every((i) => info.shape[i] == shape[i])) {
    throw ArgumentError(
      'tensor $name has shape ${info.shape}, expected $shape',
    );
  }
  final elementBytes = switch (info.dtype) {
    'F32' => 4,
    'BF16' => 2,
    _ => throw UnsupportedError('tensor $name has dtype ${info.dtype}'),
  };
  final rows = shape.isEmpty ? 1 : shape.first;
  final end = rowEnd ?? rows;
  if (rowStart < 0 || end > rows || rowStart > end) {
    throw RangeError('rows $rowStart..$end of $name with $rows rows');
  }
  final rowElements = rows == 0 ? 0 : info.numel ~/ rows;
  final count = (end - rowStart) * rowElements;
  final bytes = count * elementBytes;
  if (_scratch.length < bytes) _scratch = Uint8List(bytes);
  _readFully(
    _file,
    _scratch,
    _dataStart + info.begin + rowStart * rowElements * elementBytes,
    bytes,
  );

  final out = Float32List(count);
  if (elementBytes == 4) {
    out.setRange(0, count, Float32List.view(_scratch.buffer, 0, count));
  } else {
    _widenBf16(Uint16List.view(_scratch.buffer, 0, count), out);
  }
  return out;
}