validateVlBundle function
Verifies all required bundle files and their SHA-256 before native loading. The manifest itself must come from a trusted package/install source; these checks detect incomplete or modified files, not manifest authenticity.
Implementation
Future<void> validateVlBundle(String directory) async {
final manifest = VlBundleManifest.parse(
File('$directory/$_manifest').readAsStringSync(),
);
final other = manifest.weights == 'q8' ? 'q4' : 'q8';
if (File('$directory/language/lfm3-$other.cache').existsSync()) {
throw const FormatException(
'VL bundle contains an unrecorded alternative cache',
);
}
for (final entry in manifest.files.entries) {
final file = File('$directory/${entry.key}');
if (!file.existsSync() ||
file.lengthSync() != entry.value.bytes ||
await _digest(file) != entry.value.sha256) {
throw FormatException(
'VL bundle file failed integrity check: ${entry.key}',
);
}
}
validateVlBackbone(directory, '$directory/language');
if (manifest.inputEmbedding == 'bf16') {
final c = Lfm3Config.load('$directory/language');
final st = SafetensorsFile.open('$directory/language/model.safetensors');
try {
_checkTensor(
st,
'model.embed_tokens.weight',
[c.vocabSize, c.hiddenSize],
File('$directory/language/model.safetensors').lengthSync(),
requireBf16: true,
);
} finally {
st.close();
}
}
if (manifest.inputEmbedding == 'q8-cache') {
final language = '$directory/language';
final st = SafetensorsFile.open('$language/model.safetensors');
try {
if (st.tensors.containsKey('model.embed_tokens.weight')) {
throw const FormatException(
'cache embedding bundle also contains a BF16 table',
);
}
} finally {
st.close();
}
final c = Lfm3Config.load(language);
final cache = Q8Cache.open(
'$language/lfm3-${manifest.weights}.cache',
Q8Cache.keyFor(language, weights: manifest.weights),
);
if (cache == null) {
throw const FormatException('invalid cache embedding cache');
}
try {
_checkCachedMatrix(
cache,
'model.embed_tokens.weight',
c.vocabSize,
c.hiddenSize,
);
if (cache
.offsets('model.embed_tokens.weight', c.vocabSize, c.hiddenSize)!
.format !=
'q8') {
throw const FormatException('input embedding cache must be Q8');
}
} finally {
cache.close();
}
}
}