writeSafetensorsF32 function

void writeSafetensorsF32(
  1. String path,
  2. Map<String, (List<int>, Float32List)> tensors
)

Writes float32 tensors (name: shape and values) to a new safetensors file at path.

Implementation

void writeSafetensorsF32(
  String path,
  Map<String, (List<int>, Float32List)> tensors,
) {
  final header = <String, Object?>{
    '__metadata__': {'format': 'pt'},
  };
  var offset = 0;
  for (final MapEntry(key: name, value: (shape, values)) in tensors.entries) {
    header[name] = {
      'dtype': 'F32',
      'shape': shape,
      'data_offsets': [offset, offset + values.lengthInBytes],
    };
    offset += values.lengthInBytes;
  }
  final out = File(path).openSync(mode: FileMode.write);
  try {
    SafetensorsFile._writeHeader(out, header);
    for (final (_, values) in tensors.values) {
      out.writeFromSync(
        values.buffer.asUint8List(values.offsetInBytes, values.lengthInBytes),
      );
    }
  } finally {
    out.closeSync();
  }
}