GgufFile.open constructor

GgufFile.open(
  1. String path
)

Maps and parses path. Needs the native kernels (for the mapping).

Implementation

factory GgufFile.open(String path) {
  final file =
      MappedFile.open(path) ??
      (throw FileSystemException('cannot map', path));
  try {
    final data = ByteData.sublistView(file.bytes(0, file.length));
    var at = 0;
    // Each reader returns the value at the cursor and moves past it.
    T read<T>(int size, T Function(int offset) get) {
      if (size < 0 || at + size > data.lengthInBytes) {
        throw const FormatException('truncated GGUF metadata');
      }
      at += size;
      return get(at - size);
    }

    int u32() => read(4, (o) => data.getUint32(o, Endian.little));
    int u64() => read(8, (o) => data.getUint64(o, Endian.little));
    String str() {
      final n = u64();
      if (n > file.length - at) {
        throw const FormatException('truncated GGUF string');
      }
      at += n;
      return utf8.decode(file.bytes(at - n, n), allowMalformed: true);
    }

    if (utf8.decode(file.bytes(0, 4)) != 'GGUF') {
      throw FormatException('$path is not GGUF');
    }
    at = 4;
    final version = u32();
    if (version < 2) throw FormatException('GGUF version $version');
    final tensorCount = u64();
    final kvCount = u64();

    // Scalars as their values; arrays are skipped and kept as their length.
    Object? value(int type) {
      switch (type) {
        case 0 || 1 || 7:
          return read(1, data.getUint8);
        case 2 || 3:
          return read(2, (o) => data.getUint16(o, Endian.little));
        case 4:
          return u32();
        case 5:
          return read(4, (o) => data.getInt32(o, Endian.little));
        case 6:
          return read(4, (o) => data.getFloat32(o, Endian.little));
        case 8:
          return str();
        case 9:
          final elementType = u32();
          final n = u64();
          for (var i = 0; i < n; i++) {
            value(elementType);
          }
          return n;
        case 10:
          return u64();
        case 11:
          return read(8, (o) => data.getInt64(o, Endian.little));
        case 12:
          return read(8, (o) => data.getFloat64(o, Endian.little));
      }
      throw FormatException('GGUF metadata type $type');
    }

    final metadata = <String, Object?>{};
    for (var i = 0; i < kvCount; i++) {
      final key = str();
      metadata[key] = value(u32());
    }
    final infos = <(String, List<int>, int, int)>[];
    for (var i = 0; i < tensorCount; i++) {
      final name = str();
      final dims = [for (var d = u32(); d > 0; d--) u64()];
      infos.add((name, dims, u32(), u64()));
    }
    final alignment = (metadata['general.alignment'] ?? 32) as int;
    if (alignment <= 0 || (alignment & (alignment - 1)) != 0) {
      throw const FormatException('invalid GGUF alignment');
    }
    final dataStart = (at + alignment - 1) ~/ alignment * alignment;
    final tensors = <String, GgufTensor>{};
    for (final (name, dims, typeId, offset) in infos) {
      final type = GgufType.values.where((t) => t.id == typeId).firstOrNull;
      if (type == null) continue; // a type this importer never needs
      final tensor = GgufTensor(name, dims, type, dataStart + offset);
      if (tensors.containsKey(name) ||
          dims.isEmpty ||
          dims.any((n) => n <= 0) ||
          tensor.values % type.blockValues != 0 ||
          offset % alignment != 0 ||
          tensor.offset < dataStart ||
          tensor.offset + tensor.bytes > file.length) {
        throw FormatException('invalid GGUF tensor bounds: $name');
      }
      tensors[name] = tensor;
    }
    return GgufFile._(file, metadata, tensors);
  } catch (_) {
    file.release();
    rethrow;
  }
}