importGguf function

List<String> importGguf(
  1. String ggufPath,
  2. String hfDir,
  3. String outDir
)

Writes an engine bundle for the GGUF checkpoint ggufPath into outDir: config.json and tokenizer.json from the Hugging Face directory hfDir (the same model's), a model.safetensors with the float tensors under their Hugging Face names, and lfm3-q4.cache holding every matrix as Q4 and the tied embedding, Q6_K in the file, re-quantized to Q8 for the LM head and token lookup. Load it with --weights=q4.

Returns lines comparing each imported tensor family with hfDir's weights (relative L2 difference over layers 0-3), which shows the layout is read right: a transposed or reordered tensor differs by about 1.4.

Implementation

List<String> importGguf(String ggufPath, String hfDir, String outDir) {
  final gguf = GgufFile.open(ggufPath);
  try {
    final c = Lfm3Config.load(hfDir);
    final h = c.hiddenSize, f = c.intermediateSize, hd = c.headDim;
    if (gguf.metadata['general.architecture'] != 'lfm3' ||
        gguf.metadata['lfm3.block_count'] != c.numLayers) {
      throw StateError('$ggufPath is not this LFM3 model');
    }

    final small = <String, (List<int>, Float32List)>{};
    // The cache's matrices, made one at a time while it is written: on a
    // phone the whole set (1.1 GB) does not fit in memory at once.
    final shapes = <(String, String, int, int)>[];
    final produce = <String, CachedMatrix Function()>{};
    // Imported tensors keyed by their Hugging Face name, for the comparison.
    final imported = <String, Float32List Function()>{};

    void vector(String gguf_, String hf, List<int> shape) {
      final values = gguf.f32(
        gguf.tensor(gguf_, GgufType.f32, shape.reversed.toList()),
      );
      small[hf] = (shape, values);
      imported[hf] = () => values;
    }

    void matrix(
      String gguf_,
      String cacheName,
      String hfName,
      int rows,
      int cols,
    ) {
      final t = gguf.tensor(gguf_, GgufType.q4_0, [cols, rows]);
      CachedMatrix split() => splitQ4_0(gguf.bytes(t), rows, cols);
      shapes.add((cacheName, 'q4', rows, cols));
      produce[cacheName] = split;
      imported[hfName] = () => _dequantizeQ4(split());
    }

    for (var i = 0; i < c.numLayers; i++) {
      final g = 'blk.$i.';
      final p = 'model.layers.$i.';
      vector('${g}attn_norm.weight', '${p}operator_norm.weight', [h]);
      vector(
        '${g}post_attention_norm.weight',
        '${p}post_operator_norm.weight',
        [h],
      );
      vector('${g}ffn_norm.weight', '${p}ffn_norm.weight', [h]);
      vector('${g}post_ffw_norm.weight', '${p}post_ffn_norm.weight', [h]);
      final ff = '${p}feed_forward.';
      matrix('${g}ffn_gate.weight', '${ff}w1', '${ff}w1.weight', f, h);
      matrix('${g}ffn_up.weight', '${ff}w3', '${ff}w3.weight', f, h);
      matrix('${g}ffn_down.weight', '${ff}w2', '${ff}w2.weight', h, f);
      if (c.layerTypes[i] == LayerType.conv) {
        final t = gguf.tensor('${g}shortconv.conv.weight', GgufType.f32, [
          c.convKernel,
          h,
        ]);
        final values = gguf.f32(t);
        small['${p}conv.conv.weight'] = ([h, 1, c.convKernel], values);
        imported['${p}conv.conv.weight'] = () => values;
        for (final (gName, hfName, rows) in [
          ('shortconv.in_proj', 'conv.in_proj.weight', 3 * h),
          ('shortconv.out_proj', 'conv.out_proj.weight', h),
        ]) {
          matrix('$g$gName.weight', '$p$hfName', '$p$hfName', rows, h);
        }
      } else {
        final a = '${p}self_attn.';
        vector('${g}attn_q_norm.weight', '${a}q_norm.weight', [hd]);
        vector('${g}attn_k_norm.weight', '${a}k_norm.weight', [hd]);
        for (final (gName, hfName, rows, cols) in [
          ('attn_q', 'q_proj', c.numHeads * hd, h),
          ('attn_k', 'k_proj', c.kvDim, h),
          ('attn_v', 'v_proj', c.kvDim, h),
          ('attn_gate', 'gate_proj', c.numHeads, h),
          ('attn_output', 'o_proj', h, c.numHeads * hd),
        ]) {
          matrix(
            '$g$gName.weight',
            '$a$hfName',
            '$a$hfName.weight',
            rows,
            cols,
          );
        }
      }
    }
    vector('output_norm.weight', 'model.embedding_norm.weight', [h]);
    const embed = 'model.embed_tokens.weight';
    final embedding = gguf.tensor('token_embd.weight', GgufType.q6K, [
      h,
      c.vocabSize,
    ]);
    final embedBytes = gguf.bytes(embedding);
    final perRow = h ~/ 256;
    shapes.add((embed, 'q8', c.vocabSize, h));
    produce[embed] = () => NativeQ8Matrix.quantizeRows(
      c.vocabSize,
      h,
      (first, count, out) =>
          dequantizeQ6K(embedBytes, first * perRow, count * perRow, out, 0),
    );
    imported[embed] = () {
      const rows = 4096;
      final out = Float32List(rows * h);
      dequantizeQ6K(embedBytes, 0, rows * perRow, out, 0);
      return out;
    };

    Directory(outDir).createSync(recursive: true);
    for (final name in ['config.json', 'tokenizer.json']) {
      File('$hfDir/$name').copySync('$outDir/$name');
    }
    writeSafetensorsF32('$outDir/model.safetensors', small);
    Q8Cache.writeEach(
      '$outDir/lfm3-q4.cache',
      Q8Cache.keyFor(outDir, weights: 'q4'),
      shapes,
      (name) => produce[name]!(),
      done: (m) {
        if (m is NativeQ8Matrix) m.free();
      },
    );
    return _compare(hfDir, c, imported);
  } finally {
    gguf.close();
  }
}