Lfm3AudioEncoderConfig.fromGguf constructor
Lfm3AudioEncoderConfig.fromGguf(
- GgufFile file
Implementation
factory Lfm3AudioEncoderConfig.fromGguf(GgufFile file) {
final m = file.metadata;
if (m['general.architecture'] != 'clip' ||
m['clip.audio.projector_type'] != 'lfm3a' ||
m['clip.has_audio_encoder'] != 1) {
throw const FormatException('expected an LFM3-Audio encoder GGUF');
}
int positive(String name) {
final v = m['clip.audio.$name'];
if (v is! int || v <= 0) {
throw FormatException('invalid clip.audio.$name');
}
return v;
}
final h = positive('embedding_length');
final f = positive('feed_forward_length');
final heads = positive('attention.head_count');
final kvHeads = positive('attention.head_count_kv');
final mel = positive('num_mel_bins');
final count = positive('block_count');
final eps = m['clip.audio.attention.layer_norm_epsilon'];
final ds = file.tensors['a.conv1d.0.weight'];
if (h % heads != 0 ||
heads % kvHeads != 0 ||
(h ~/ heads).isOdd ||
h % 32 != 0 ||
f % 32 != 0 ||
mel != 128 ||
eps is! num ||
!eps.isFinite ||
eps <= 0 ||
ds == null ||
ds.dims.length != 4 ||
ds.dims[3] <= 0 ||
ds.dims[3] % 4 != 0) {
throw const FormatException('unsupported LFM3-Audio encoder dimensions');
}
final conv = <bool>[];
for (var i = 0; i < count; i++) {
final p = 'a.blk.$i.';
final isConv = file.tensors.containsKey('${p}conv_dw.weight');
final isAttn = file.tensors.containsKey('${p}attn_q.weight');
if (isConv == isAttn) {
throw FormatException('ambiguous audio encoder layer $i');
}
conv.add(isConv);
}
final c = Lfm3AudioEncoderConfig._(
h,
f,
heads,
kvHeads,
positive('projection_dim'),
ds.dims[3],
mel,
positive('window_size'),
eps.toDouble(),
List.unmodifiable(conv),
Lfm3SpeechVariant.of(file),
);
// Checking every consumed tensor before allocating matrices makes malformed
// layouts fail atomically. Generation tensors are deliberately not loaded.
for (final e in c.tensorShapes.entries) {
final type = c.isQuantized(e.key) ? GgufType.q4_0 : GgufType.f32;
final tensor = file.tensors[e.key];
if (tensor == null ||
tensor.type != type ||
tensor.dims.join(',') != e.value.reversed.join(',')) {
throw FormatException('unsupported audio encoder tensor ${e.key}');
}
}
final expected = c.tensorShapes.keys.toSet();
for (final name in file.tensors.keys) {
if ((name.startsWith('a.') && !name.startsWith('a.gen.')) ||
name.startsWith('mm.a.')) {
if (!expected.contains(name)) {
throw FormatException('unexpected audio encoder tensor $name');
}
}
}
return c;
}