load static method
Loads the model.
With workers = 0 a single layer shard runs in this isolate. With
workers > 0 the layers are split into that many shards, one per
worker isolate (tensor parallel; see shard.dart). weights quantizes
every matrix, the tied LM head included, at load time, except those
whose tensor name contains an entry of keepF32. For Q8 and Q4
(WeightFormat.isNative), q8CachePath
names a cache file: mapped if it matches this checkpoint, written
after quantizing otherwise.
With the native kernels loaded, the bf16 embedding table is mapped from model.safetensors instead of read, so it costs no heap.
gpu runs every token on the GPU from the cache (built first if
missing), so it needs Q8 or Q4 weights, a cache path and the native
kernels, which map the cache. gpuLib does too, with the GPU layer of
the library at that path instead of the package's kernels asset.
Implementation
static Future<Lfm3Model> load(
String modelDir, {
int maxSeq = 4096,
int maxChunk = 64,
int workers = 0,
WeightFormat weights = WeightFormat.f32,
List<String> keepF32 = const [],
String? q8CachePath,
bool gpu = false,
String? gpuLib,
}) async {
final onGpu = gpu || gpuLib != null;
if (onGpu && (!weights.isNative || q8CachePath == null || workers > 0)) {
throw ArgumentError(
'the GPU needs --weights=q8 or q4, a cache and --workers=0',
);
}
if (weights.isNative && workers > 0) {
// Native kernels already split each product across native threads;
// isolates on top would oversubscribe the cores.
throw ArgumentError(
'--weights=${weights.name} runs in one isolate; use --workers=0',
);
}
final c = Lfm3Config.load(modelDir);
final h = c.hiddenSize;
final st = SafetensorsFile.open('$modelDir/model.safetensors');
final List<_LayerNorms> norms;
final Float32List finalNorm;
// Token lookup reads the bf16 patterns, which widen to exactly the
// checkpoint's floats at half the memory of a float32 table.
Uint16List? embedBf16;
MappedFile? embedFile;
try {
norms = [
for (var i = 0; i < c.numLayers; i++)
_LayerNorms(
st.readF32('model.layers.$i.operator_norm.weight', [h]),
c.sandwichNorm
? st.readF32('model.layers.$i.post_operator_norm.weight', [h])
: null,
st.readF32('model.layers.$i.ffn_norm.weight', [h]),
c.sandwichNorm
? st.readF32('model.layers.$i.post_ffn_norm.weight', [h])
: null,
),
];
finalNorm = st.readF32('model.embedding_norm.weight', [h]);
// A bundle imported from GGUF (`lfm3 import-gguf`) has no bf16
// embedding: tokens are then looked up in the Q8 LM head below.
if (st.tensors.containsKey(_embedName)) {
final mapped = _mapEmbedding(modelDir, st, c);
embedFile = mapped?.$1;
embedBf16 = mapped?.$2 ?? st.readBf16Bits(_embedName, [c.vocabSize, h]);
}
} finally {
st.close();
}
String? cacheKey;
Q8Cache? cache;
Map<String, NativeMatrix>? built;
// Whatever fails from here gives back the mappings made so far.
try {
if (weights.isNative && q8CachePath != null) {
cacheKey = Q8Cache.keyFor(modelDir, weights: weights.name);
cache = Q8Cache.open(q8CachePath, cacheKey);
if (cache == null) built = {};
}
// What a saved state depends on: the checkpoint, the weights, and the
// backend, whose arithmetic differs in the last bits.
final native = NativeKernels.isLoaded ? NativeKernels.instance : null;
final backend = onGpu
? 'gpu ${Platform.operatingSystem}'
: 'cpu inputs=${weights.isNative && native!.int8Inputs ? 'int8' : 'f32'}'
' attention=${native?.attention == true ? 'c' : 'dart'}';
final stateKey =
'${Q8Cache.keyFor(modelDir, weights: weights.name)} '
'${weights.name} keep=${keepF32.join(',')} $backend';
NativeQ8Matrix? embedQ8;
if (embedBf16 == null) {
embedQ8 = switch (cache?.matrix(_embedName, c.vocabSize, h)) {
final NativeQ8Matrix m => m,
_ => throw StateError(
'model.safetensors lacks the embedding and no Q8 cache holds it',
),
};
}
if (onGpu) {
if (cache == null) {
// Quantize through the CPU loader once to build the cache.
LayerShard.load(
modelDir,
index: 0,
shards: 1,
maxSeq: 1,
maxChunk: 1,
format: weights,
keepF32: keepF32,
q8Built: built,
);
Q8Cache.write(q8CachePath!, cacheKey!, built!);
cache = Q8Cache.open(q8CachePath, cacheKey)!;
}
final gpu = GpuForward.create(
libPath: gpuLib,
modelDir: modelDir,
config: c,
cache: cache,
maxSeq: maxSeq,
maxChunk: maxChunk,
);
return Lfm3Model._(
c,
embedBf16,
embedQ8,
norms,
finalNorm,
null,
gpu,
stateKey,
maxSeq,
maxChunk,
cache,
embedFile,
);
}
final LayerExecutor executor = workers == 0
? LocalExecutor(
LayerShard.load(
modelDir,
index: 0,
shards: 1,
maxSeq: maxSeq,
maxChunk: maxChunk,
format: weights,
keepF32: keepF32,
q8Cache: cache,
q8Built: built,
),
)
: await PooledExecutor.spawn(
modelDir,
workers: workers,
maxSeq: maxSeq,
maxChunk: maxChunk,
format: weights,
keepF32: keepF32,
);
if (built != null) Q8Cache.write(q8CachePath!, cacheKey!, built);
return Lfm3Model._(
c,
embedBf16,
embedQ8,
norms,
finalNorm,
executor,
null,
stateKey,
maxSeq,
maxChunk,
cache,
embedFile,
);
} catch (_) {
cache?.close();
embedFile?.release();
rethrow;
}
}