Lfm3AudioGenerator.load constructor

Lfm3AudioGenerator.load(
  1. String mmproj, {
  2. bool int8Inputs = false,
})

Loads the generation weights of mmproj. With int8Inputs the depth decoder's and codec's Q4 products quantize their inputs to int8 per block of 32 and use the CPU's integer dot products, as the language model's CPU path does: speech generates about 1.4 times faster, and its arithmetic is no longer the float reference's, so sampled codes and the waveform differ (depth logits by about 1.4% relative L2). The output heads, products of one row, keep float inputs.

Implementation

factory Lfm3AudioGenerator.load(String mmproj, {bool int8Inputs = false}) {
  if (!NativeKernels.isLoaded) NativeKernels.load(null);
  final file = GgufFile.open(mmproj);
  final matrices = <String, _Matrix>{};
  final floats = <String, Float32List>{};
  final heads = <_Matrix>[];
  try {
    if (file.metadata['clip.gen.audio.projector_type'] != 'lfm3a_gen') {
      throw const FormatException('not an LFM3 audio generator');
    }
    final variant = speechVariantOf(file);
    final sampling = Lfm3SpeechSampling.fromGguf(file);
    List<int> dims(String name) =>
        file.tensors[name]?.dims.reversed.toList() ??
        (throw FormatException('missing $name'));
    int meta(String key) {
      final n = file.metadata['clip.gen.audio.$key'];
      if (n is! int || n <= 0) {
        throw FormatException('invalid generation $key');
      }
      return n;
    }

    final emb = dims('a.gen.code.embd.weight');
    if (emb.length != 3) {
      throw const FormatException('invalid codebook embedding');
    }
    final cb = emb[0],
        vocab = emb[1],
        dh = emb[2],
        hidden = meta('projection_dim');
    final depth = _Graph(
      'a.gen.code.',
      dh,
      meta('feed_forward_length'),
      meta('attention.head_count'),
      meta('attention.head_count_kv'),
      dims('a.gen.code.blk.0.attn_q_norm.weight')[0],
      meta('block_count'),
      7,
      false,
      0,
    );
    final ch = dims('a.gen.wav.tfm.output_norm.weight')[0];
    final cd = dims('a.gen.wav.tfm.blk.2.attn_q_norm.weight')[0];
    final ck = dims('a.gen.wav.tfm.blk.2.attn_k.weight')[0];
    final codec = _Graph(
      'a.gen.wav.tfm.',
      ch,
      dims('a.gen.wav.tfm.blk.0.ffn_gate.weight')[0],
      ch ~/ cd,
      ck ~/ cd,
      cd,
      8,
      7,
      true,
      30,
    );
    final qdim = dims('a.gen.wav.quant.first.out_proj.bias')[0];
    final bins = dims('a.gen.wav.tfm.out_proj.bias')[0] ~/ 2;
    final fft = 2 * (bins - 1);
    if (cb != 12 ||
        vocab < 2 ||
        dh != meta('embedding_length') ||
        dh % 32 != 0 ||
        hidden % 32 != 0 ||
        depth.heads * depth.d != dh ||
        depth.heads % depth.kvHeads != 0 ||
        depth.d.isOdd ||
        depth.layers != 3 ||
        ch % 32 != 0 ||
        codec.heads % codec.kvHeads != 0 ||
        cd.isOdd ||
        qdim % 32 != 0 ||
        fft < 20 ||
        fft % 5 != 0 ||
        ((fft ~/ 5) & ((fft ~/ 5) - 1)) != 0) {
      throw const FormatException('unsupported generation dimensions');
    }
    final shapes = <String, List<int>>{
      ...depth.shapes,
      ...codec.shapes,
      'a.gen.code.embd.weight': [cb, vocab, dh],
      'a.gen.code.head_norm.weight': [cb, dh],
      'a.gen.code.mask_embd': [dh],
      'a.gen.code.proj_in.weight': [cb * dh, hidden],
      'a.gen.code.proj_in.bias': [cb * dh],
      'a.gen.code.out_embd.weight': [cb * vocab, hidden],
      'a.gen.wav.quant.first.codebook.weight': [vocab - 1, 4],
      'a.gen.wav.quant.first.out_proj.weight': [qdim, cb * 4],
      'a.gen.wav.quant.first.out_proj.bias': [qdim],
      'a.gen.wav.tfm.in_proj.weight': [ch, qdim],
      'a.gen.wav.tfm.in_proj.bias': [ch],
      'a.gen.wav.tfm.out_proj.weight': [2 * bins, ch],
      'a.gen.wav.tfm.out_proj.bias': [2 * bins],
    };
    bool vector(String name) =>
        name.endsWith('.bias') ||
        name.contains('norm') ||
        name.contains('.ln') ||
        name.endsWith('mask_embd') ||
        name.endsWith('conv_dw.weight') ||
        name.endsWith('first.codebook.weight');
    for (final e in shapes.entries) {
      final t = file.tensors[e.key];
      if (t == null ||
          t.dims.reversed.join(',') != e.value.join(',') ||
          (vector(e.key)
              ? t.type != GgufType.f32
              : ![GgufType.f32, GgufType.q4_0].contains(t.type))) {
        throw FormatException('unsupported generation tensor ${e.key}');
      }
    }
    if (file.tensors.keys.any(
      (n) => n.startsWith('a.gen.') && !shapes.containsKey(n),
    )) {
      throw const FormatException('unexpected generation tensor');
    }
    _Matrix matrix(GgufTensor t, int rows, int cols, [int byteOffset = 0]) {
      if (t.type == GgufType.q4_0) {
        final bytes = rows * cols ~/ 32 * 18;
        return _Matrix(
          rows,
          cols,
          NativeQ4Matrix.fromGgufBlocks(
            Uint8List.sublistView(
              file.bytes(t),
              byteOffset,
              byteOffset + bytes,
            ),
            rows,
            cols,
          ),
          null,
        );
      }
      final data = file.f32(t);
      return _Matrix(
        rows,
        cols,
        null,
        Float32List.fromList(
          data.sublist(byteOffset ~/ 4, byteOffset ~/ 4 + rows * cols),
        ),
      );
    }

    for (final e in shapes.entries) {
      final t = file.tensors[e.key]!;
      if (vector(e.key)) {
        floats[e.key] = file.f32(t);
      } else if (e.key == 'a.gen.code.embd.weight') {
        final per = vocab * dh ~/ t.type.blockValues * t.type.blockBytes;
        for (var i = 0; i < cb; i++) {
          heads.add(matrix(t, vocab, dh, i * per));
        }
      } else {
        matrices[e.key] = matrix(t, e.value[0], e.value[1]);
      }
    }
    return Lfm3AudioGenerator._(
      depth,
      codec,
      cb,
      vocab,
      hidden,
      qdim,
      fft,
      floats,
      matrices,
      heads,
      variant,
      sampling,
      int8Inputs,
    );
  } catch (_) {
    for (final m in [...matrices.values, ...heads]) {
      m.native?.free();
    }
    rethrow;
  } finally {
    file.close();
  }
}