importVlVisionGguf function

void importVlVisionGguf(
  1. String path,
  2. Lfm3VlConfig config,
  3. String output
)

Writes only the paired mmproj's vision/projector tensors to output. BF16/F32 payloads are unchanged; split F16 temporal patches widen exactly.

Implementation

void importVlVisionGguf(String path, Lfm3VlConfig config, String output) {
  final gguf = GgufFile.open(path);
  try {
    _checkVisionGguf(gguf, config);
    final c = config.vision;
    final expected = lfm3VisionTensorShapes(config);
    final entries = <String, (GgufTensor, List<int>)>{};
    for (final tensor in gguf.tensors.values) {
      if (tensor.name.startsWith('v.patch_embd.weight')) continue;
      final name = _visionName(tensor.name);
      final shape = tensor.dims.reversed.toList();
      if (entries.containsKey(name) ||
          expected[name]?.join(',') != shape.join(',') ||
          ![GgufType.f32, GgufType.bf16].contains(tensor.type)) {
        throw FormatException('unsupported vision tensor ${tensor.name}');
      }
      entries[name] = (tensor, shape);
    }
    const patchName = 'model.vision_tower.patchifier.weight';
    if (entries.length != expected.length - 1 ||
        expected.keys.any((n) => n != patchName && !entries.containsKey(n))) {
      throw const FormatException('incomplete vision GGUF');
    }
    final patch = _patchifier(gguf, c);
    final header = <String, Object?>{};
    var offset = 0;
    for (final e in entries.entries) {
      final (tensor, shape) = e.value;
      header[e.key] = {
        'dtype': tensor.type == GgufType.f32 ? 'F32' : 'BF16',
        'shape': shape,
        'data_offsets': [offset, offset + tensor.bytes],
      };
      offset += tensor.bytes;
    }
    header[patchName] = {
      'dtype': 'F32',
      'shape': expected[patchName],
      'data_offsets': [offset, offset + patch.lengthInBytes],
    };
    final json = utf8.encode(jsonEncode(header));
    final padded = (json.length + 7) ~/ 8 * 8;
    final prefix = ByteData(8)..setUint64(0, padded, Endian.little);
    final file = File(output).openSync(mode: FileMode.write);
    try {
      file.writeFromSync(prefix.buffer.asUint8List());
      file.writeFromSync(json);
      file.writeFromSync(
        Uint8List(padded - json.length)..fillRange(0, padded - json.length, 32),
      );
      for (final e in entries.values) {
        file.writeFromSync(gguf.bytes(e.$1));
      }
      file.writeFromSync(patch.buffer.asUint8List());
    } finally {
      file.closeSync();
    }
  } finally {
    gguf.close();
  }
}