packVlBundle function
Future<void>
packVlBundle(
- String modelDir,
- String backboneDir,
- String outDir, {
- WeightFormat weights = WeightFormat.q8,
- bool useCacheEmbedding = false,
Packages a VL checkpoint and an existing Q8/Q4 language cache into outDir.
No matrix is requantized. Vision tensors, small language tensors and BF16
token embeddings retain their original bytes. useCacheEmbedding explicitly
selects Q8 lookup for GGUF imports that have no BF16 embedding table. Only the cache header/key is
rebuilt for the packed layout. The full original checkpoint and imported
language matrices are unnecessary at runtime.
Writes to a sibling staging directory and publishes only when every file and its SHA-256 manifest are complete. Never overwrites existing output.
Implementation
Future<void> packVlBundle(
String modelDir,
String backboneDir,
String outDir, {
WeightFormat weights = WeightFormat.q8,
bool useCacheEmbedding = false,
}) async {
if (!weights.isNative) throw ArgumentError('VL packing needs Q8 or Q4');
validateVlBackbone(modelDir, backboneDir);
final config = Lfm3VlConfig.load(modelDir);
final text = Lfm3Config.load(backboneDir);
final processor = Lfm3ImageProcessor.load(modelDir);
if (processor.patchSize != config.vision.patchSize ||
processor.mergeSize != config.vision.spatialMergeSize ||
processor.temporalPatchSize != config.vision.temporalPatchSize ||
config.vision.inChannels != 3) {
throw const FormatException('processor and vision configuration differ');
}
for (final name in [
'config.json',
'processor_config.json',
'tokenizer.json',
'LICENSE',
]) {
if (!File('$modelDir/$name').existsSync()) {
throw FileSystemException('VL checkpoint lacks $name', modelDir);
}
}
final destination = Directory(outDir).absolute;
if (FileSystemEntity.typeSync(destination.path, followLinks: false) !=
FileSystemEntityType.notFound) {
throw FileSystemException('output already exists', outDir);
}
final cache = Q8Cache.open(
'$backboneDir/lfm3-${weights.name}.cache',
Q8Cache.keyFor(backboneDir, weights: weights.name),
);
if (cache == null) {
throw StateError('build a matching ${weights.name} cache before packing');
}
Directory? staging;
try {
final vision = SafetensorsFile.open('$modelDir/model.safetensors');
try {
final visionShapes = lfm3VisionTensorShapes(config);
final sourceLength = File('$modelDir/model.safetensors').lengthSync();
for (final entry in visionShapes.entries) {
_checkTensor(vision, entry.key, entry.value, sourceLength);
}
final language = SafetensorsFile.open('$backboneDir/model.safetensors');
try {
final matrices = <String, NativeMatrix>{};
final smallNames = <String>{};
final languageLength = File(
'$backboneDir/model.safetensors',
).lengthSync();
for (final entry in lfm3LanguageTensorShapes(text).entries) {
final name = entry.key, shape = entry.value;
if (shape.length == 2) {
final cachedName =
name.contains('.self_attn.') || name.contains('.feed_forward.')
? name.substring(0, name.length - '.weight'.length)
: name;
_checkCachedMatrix(cache, cachedName, shape[0], shape[1]);
matrices[cachedName] = cache.matrix(
cachedName,
shape[0],
shape[1],
)!;
}
if (name == 'model.embed_tokens.weight' && useCacheEmbedding) {
if (language.tensors.containsKey(name) ||
matrices[name]!.format != 'q8') {
throw const FormatException(
'cache embedding requires an absent BF16 table and Q8 head',
);
}
continue;
}
if (shape.length != 2 || name == 'model.embed_tokens.weight') {
_checkTensor(
language,
name,
shape,
languageLength,
requireBf16: name == 'model.embed_tokens.weight',
);
smallNames.add(name);
}
}
destination.parent.createSync(recursive: true);
staging = destination.parent.createTempSync('.dianoia-vl-bundle-');
final root = staging.path;
Directory('$root/language').createSync();
for (final name in [
'config.json',
'processor_config.json',
'tokenizer.json',
'LICENSE',
]) {
File('$modelDir/$name').copySync('$root/$name');
}
File('$backboneDir/config.json').copySync('$root/language/config.json');
File(
'$modelDir/tokenizer.json',
).copySync('$root/language/tokenizer.json');
vision.writeSubset(
'$root/model.safetensors',
(name, _) => visionShapes.containsKey(name),
);
language.writeSubset(
'$root/language/model.safetensors',
(name, _) => smallNames.contains(name),
);
Q8Cache.write(
'$root/language/lfm3-${weights.name}.cache',
Q8Cache.keyFor('$root/language', weights: weights.name),
matrices,
);
writeVlBackboneIdentity(root, '$root/language');
final files = <String, Object?>{};
for (final name in _files(weights.name)) {
final file = File('$root/$name');
files[name] = {
'bytes': file.lengthSync(),
'sha256': await _digest(file),
};
}
File('$root/$_manifest').writeAsStringSync(
const JsonEncoder.withIndent(' ').convert({
'version': 1,
'kind': 'lfm3-vl',
'weights': weights.name,
if (useCacheEmbedding) 'input_embedding': 'q8-cache',
'origin_source_key': Q8Cache.keyFor(modelDir),
'files': files,
}),
);
} finally {
language.close();
}
} finally {
vision.close();
}
staging.renameSync(destination.path);
staging = null;
} finally {
cache.close();
if (staging != null) staging.deleteSync(recursive: true);
}
}