lab library
Everything inside dianoia, for the command-line tool, benchmarks and research: the forward pass and its executors, the kernels and their tuning, quantization, file formats and the measurement helpers.
Apps should import package:dianoia/dianoia.dart instead. What is here
changes without notice.
Classes
- AssistantReply
- AudioConversationReply
- AudioConversationSession
- A bounded, transactional conversation on caller-owned language/generation models. Input is projected encoder rows. Completed turns retain exact audio input/output embeddings; no waveform or microphone recording is retained. Begin reuses matching language state and replays slots when necessary, so other operations may use the backbone between turns. Use the backbone exclusively throughout begin/add/finish.
- AudioFeatures
-
One clip's normalized log-mel features in
mel bin, frameorder. - AudioGgufSpec
- Official paired Audio Q4_0 sources, prepared on device for the audio preview.
- AudioInterleavingState
- The pinned upstream generation schedule: six text slots, twelve audio slots. EOS speech frames return to text mode and still supply feedback embeddings.
- AudioLiveBlock
- AudioLiveSession
- Rolling language contexts on a caller-owned backbone. The prompt/text-end is deferred until a chunk completes audio rows. A sampled closing marker is not fed; a nonfinal block queues text-end for the next chunk, even at the token cap.
- AudioLiveTokenPolicy
- Token suppression differs on final/nonfinal chunks; placeholders are always forbidden. This policy follows the pinned transcribe_live implementation.
- AudioSynthesisResult
- Synthesized speech: mono float PCM in -1..1.
- AudioSynthesizer
- Speaks text with an LFM3-Audio or LFM3-Omni model.
- AudioTranscriptionPrefill
- Incrementally feeds one recording's projected rows into the ASR backbone.
- AudioTranscriptionPrompt
-
Research prompt for transcription, with one audio-token run.
No tool calls, speech output or history is added; LFM3-Omni's prompt
wraps the run in span markers and opens the reply with
<think></think>. - CachedMatrix
- What a Q8 cache file stores for one matrix (q8_cache.dart).
- ChatImage
- Owned, immutable RGB uint8 pixels supplied directly or decoded from PNG/JPEG.
- ChatSession
- ChatTurn
- One reply and what it cost.
- ControlVector
- ControlVectorEval
- Runs the evaluation of one vector on one loaded model.
- EvalRow
- One evaluation row: a prompt and, for reference sets, its answer.
- ExecutorStats
- Where the time of the executor's calls went, for profiling.
- GgufFile
- GgufTensor
- GpuForward
- GpuLinear
- Products of quantized matrices on the GPU for work outside the language forward pass, such as the vision encoder's linear layers: each apply copies the inputs in, runs one matrix product over all n rows in its own command buffer and copies the outputs back. The GPU computes the same products as the CPU kernels with float inputs, its sums in another order, so the outputs differ from theirs in the last bits.
- InstallableModel
- A pinned checkpoint or bundle installed by ModelStore.
- InstallProgress
- Where a ModelStore.install stands.
- LayerExecutor
- LayerSeparation
- How well one layer's mean-difference direction separates two sets of residuals (each a row of hidden size, such as the residual leaving that layer at each prompt's last token).
- LayerShard
- Lfm3AudioEncoder
- Synchronous lab implementation for complete clips or streaming input.
- Lfm3AudioEncoderConfig
- Input encoder configuration read from an LFM3-Audio or LFM3-Omni Q4_0 mmproj GGUF; Omni's vision tensors are left to the vision loader. Does not treat the LFM2 encoder as a language or LFM3 graph.
- Lfm3AudioEncoderStream
- A single feature stream with bounded LFM2 convolution/KV state.
- Lfm3AudioFeatureStream
- Incremental frontend retaining only overlapping, unconsumed PCM samples.
- Lfm3AudioFrontend
- Fixed preprocessing contract of LFM3-Audio-2B format version 1.
- Lfm3AudioGenerator
- Published generation weights only; does not load the ASR encoder. All matrix blocks are retained exactly. Their products take float activation inputs unless int8Inputs.
- Lfm3AudioQ4Source
- Shared source pins for research preparation and AudioGgufSpec installation.
- Lfm3Config
- Lfm3ImageProcessor
- Processes packed RGB uint8 pixels. Decoding JPEG/PNG and applying EXIF orientation are the caller's responsibility. This lab API supports the official processor's RGB, antialiased bicubic and normalization settings.
- Lfm3LiveTranscriber
- Mono 16 kHz PCM to incremental English text. The encoder follows one stream; language decoding happens after every 96 mel frames (about 0.96 seconds). Owns only per-recording states; the caller owns the model and encoder.
- Lfm3Model
- Lfm3OmniQ4Source
- The official Q4_0 language GGUF and its combined vision/audio mmproj. The language tensors share LFM3-Audio's layout; the mmproj adds the LFM3-VL vision tower and projector to the audio encoder and generator.
- Lfm3SpeechSampling
- The official speech sampling defaults, stored in each mmproj GGUF: LFM3-Audio samples at temperature 1 from the top 128 codes; LFM3-Omni at 0.4 from all codes, penalizing codes of the last 64 frames.
- Lfm3Tokenizer
- Lfm3VideoProcessor
- The LFM3-VL video processor as LFM3-Omni configures it: frames sampled at fps (between minFrames and maxFrames), every frame resized to one size from the whole clip's pixel budget, and grouped in temporal pairs. Decoding the video and its soundtrack is the caller's responsibility.
- Lfm3VisionConfig
- Lfm3VisionEncoder
- Correctness-first, synchronous inference. Weights are widened to f32 on the Dart heap, except matrices given as native Q4/Q8 blocks, whose products run in the native kernels with float inputs, or on the GPU after useGpu; the rest stays on the CPU. This is a lab API, not the optimized on-device path. Images are encoded independently; no cross-image attention or video state. close frees native matrices.
- Lfm3VlConfig
- Validated configuration for the LFM3 vision encoder and projector. Parsing this metadata does not load weights or enable image inference.
- Linear
- LiquidCodecStream
- Stateful code-to-waveform decoder. Causal LFM3 caches and the 960-sample overlap-add tail are retained; emitted audio is owned by the caller.
- LocalExecutor
- One shard owning everything, in this isolate.
- LocalModel
- A language model on this device: its weights mapped, the native kernels and, where possible, the GPU ready. Conversations come from chat.
- LocalVisionModel
- An experimental visual model using the CPU reference vision encoder and a quantized CPU/Metal/Vulkan language backbone. Load and run it in an inference isolate: each vision layer performs synchronous CPU work. Prepare the checkpoint and quantized backbone with the import/vision-run tools before loading, or install a prebuilt VL bundle with ModelStore.
- MappedFile
- A file mapped read-only into memory by the native library. Its pages are read on first touch and stay clean, so the OS can drop them under memory pressure. Opening a path that is already mapped returns its mapping: an iOS app's address space has room for the 1.95 GB Q8 cache, but not for two copies of it. The opens are counted, each needs a release, and the last release unmaps the file.
- ModelSpec
- A model ModelStore can install: a GGUF checkpoint and the matching Hugging Face model's config, tokenizer and license.
- ModelStore
- The models on this device, one directory each under directory (an app's support directory, say).
- NativeKernels
- Process-wide settings of the native kernels.
- NativeMatrix
- A quantized matrix in native memory that the C kernels multiply.
- NativeQ4Matrix
-
A row-major
rows, colsmatrix in Q4 (Q4_0) in native memory. - NativeQ8Matrix
-
A row-major
rows, colsmatrix quantized to Q8 in native memory. - OmniGgufSpec
-
Official paired LFM3-Omni Q4_0 sources, prepared on device. The bundle
holds
language/, the original mmproj,omni_config.jsonandprocessor_config.json; the experimental Omni lab APIs consume it. - OmniMediaSpan
- A contiguous run of media rows in an expanded prompt.
- OmniPrompt
- A tokenized Omni prompt with every media run placed in message order.
- OmniVideoLayout
- How one video expands: its frame groups, their times, and optionally the encoder rows of its soundtrack, split between the groups.
- PooledExecutor
- One shard per worker isolate.
- Q8Cache
- QuantizedMatrix
- RemoteFile
- A file to download: where it is published, and the size and SHA-256 it must have.
- Rope
-
Rotation table for one RoPE flavour at one position. Values are rounded
to float32 at the same points as the reference, which computes
inv_freq * positionand its cosine in float32. - RopeSpec
- SafetensorsFile
- SpeechReply
- TensorInfo
- ToolCall
- VisionChatSession
- VisionCheckpointSpec
- An upstream BF16 VL checkpoint converted into a standalone Q8/Q4 bundle. Installation imports its language backbone, quantizes it, then packs it.
- VisionGgufSpec
- Paired official language QAD Q4_0 and BF16 vision GGUFs, imported on device.
- VisionImageInput
- One image in the processor's flattened, spatially grouped patch layout.
- VisionModelSpec
-
A prebuilt
pack-vlbundle hosted by an app or its model distributor. - VisionProgress
- Encoder stage counts cover only new images; prior visual features are reused.
- VisionPrompt
- A tokenized visual prompt with image rows placed in message order.
- VisionTokenSpan
- A contiguous run of image tokens in an expanded prompt.
- VisionVideoInput
- Frames sampled from one video, prepared as frame groups. Each group pairs VisionImageInput.temporalPatchSize consecutive frames and is encoded alone, as upstream attends within each frame group only.
- VlBundleManifest
- Validated version-one layout, shared by installers and runtime loaders.
Enums
- AudioReplyMode
- ControlMode
- How a ControlVector changes the residual stream.
- GgufType
- InferenceBackend
- Where the forward pass runs.
- InstallStage
- LayerType
- Lfm3SpeechVariant
- Prompt conventions of the two speech-capable LFM3 checkpoints. Their language, audio encoder and generation tensors share one layout.
- OmniMediaKind
- VisionLayerType
- VisionPhase
- Work before the first visible reply text.
- VisionQuantization
- Language matrix quantization; the tied output head stays Q8.
- WeightFormat
Extensions
- LocalModelControlVector on LocalModel
-
Experimental, lab-only: steering a LocalModel with a control vector
(docs/control_vectors.md).
package:dianoia/lab.dartexports this extension;package:dianoia/dianoia.darthides it, so apps see no new member on LocalModel. - LocalVisionModelControlVector on LocalVisionModel
- Experimental, lab-only: steering a LocalVisionModel's language backbone with a control vector, as LocalModelControlVector does for a LocalModel. Every visual turn prefills from scratch, so a new vector applies from the next turn on.
Constants
- audioConversationAssistant → const String
- audioConversationHead → const String
- audioConversationSystem → const String
- audioConversationUser → const String
- audioLivePrompt → const String
- benchSystemPrompt → const String
- defaultMaxDecodedImagePixels → const int
- defaultMaxEncodedImageBytes → const int
Properties
- refusalOpeningPattern → RegExp
-
Replies that open with a refusal:
I can't,I cannot,I'm sorry,I am sorryorI won't, with a straight or a curly apostrophe, after leading white space.final
Functions
-
audioBundleIsInstalled(
String directory, List< RemoteFile> sources, String audio) → bool - A quick presence/source check. Loading must also call validateAudioBundle.
-
audioBundleSource(
List< RemoteFile> files) → Map<String, Object> -
audioConversationAssistantOpen(
Lfm3SpeechVariant variant) → String - Closes the user's audio and opens the interleaved assistant reply.
-
audioConversationUserOpen(
Lfm3SpeechVariant variant) → String -
The user-turn opening for
variant, ending where audio rows begin. -
benchmarkControlVector(
{required String bundle, required WeightFormat weights, required ControlVector vector, required List< String> prompts, List<String> refusalPrompts = const [], List<bool> backends = const [false, true], int maxNewTokens = 24, int refusalTokens = 8, int rateTokens = 128, int rateRounds = 3, int contextLength = 1024, void log(String) = _ignore, void onRecord(Map<String, Object?> ) = _ignoreRecord}) → Future<Map< String, Object?> > -
Runs the checks on each of
backends(falsethe CPU kernels,truethe GPU) for the bundle inbundlewithweights, and returns the record;onRecordreceives it after every step. -
benchmarkVisionBundle(
{required String bundle, required String imagePath, required String prompt, InferenceBackend backend = InferenceBackend.gpu, int contextLength = 512, int threads = 4, int maxNewTokens = 32, int runs = 3, int maxImageTokens = LocalVisionModel.defaultMaxImageTokens, String? expectedText, void onRecord(Map< String, Object?> record)?, void log(String message)?}) → Future<Map< String, Object?> > - Measures verified bundle loading, image decoding, fresh image turns and a text-only follow-up retaining visual features. Run in an inference isolate. Each fresh turn uses a new conversation, so it re-encodes the image.
-
bootstrapMean(
List< double> values, {int resamples = 10000, int seed = 0}) → (double, double, double) -
The mean of
valuesand its 95 % percentile bootstrap interval overresamplesresamples from a generator seeded withseed. -
buildAudioGgufBundle(
String downloads, String language, String audio, List< RemoteFile> sources, String output) → Future<void> -
Source downloads have already passed size and SHA-256 verification.
outputis unpublished staging storage; the caller publishes atomically. -
buildOmniGgufBundle(
String downloads, String language, String mmproj, List< RemoteFile> sources, String output) → Future<void> -
Builds an Omni bundle from verified
downloadsinto unpublished staging storageoutput; the caller publishes it atomically. Every consumer of the mmproj (audio encoder, speech generator, vision tower) is validated before the language GGUF is converted. -
buildVlBackboneCache(
String backboneDir, {required WeightFormat weights}) → void - Quantizes one matrix at a time without constructing an inference model. Each native allocation is released immediately after it is written.
-
catalogTools(
Map< String, Object?> spec) → List<Map< String, Object?> > - The tool definitions of a tool-case file, in template form.
-
chatBench(
Lfm3Model model, Lfm3Tokenizer tokenizer, Map< String, Object?> spec, void log(String), {required String statePath}) → Future<Map< String, Object?> > -
Runs the benchmark on
modelwith the cases ofspec, reporting lines tolog, and returns a record of the timings. -
decodeImageRgb(
Uint8List encoded, {int maxEncodedBytes = defaultMaxEncodedImageBytes, int maxPixels = defaultMaxDecodedImagePixels}) → DecodedRgbImage - Decodes one still PNG or JPEG to RGB8 without resizing. JPEG EXIF orientation is applied by the decoder. Alpha is composited over white in channel space. PNG samples use stored orientation; ICC color conversion is not performed. Pixel limits are supplied to both decoders before raster allocation.
-
decodeSpeechReply(
{required Lfm3Model model, required Lfm3Tokenizer tokenizer, required AudioReplyMode mode, required int maxSlots, required Future< void> feed(int id, Float32List? embedding, {required bool logits, void meanwhile()?}), Lfm3AudioGenerator? generator, Lfm3SpeechVariant? variant, int maxFrames = 375, int seed = 0, void check()?, void onText(String text)?, void onAudio(Float32List pcm)?, void onSlot(int token, List<int> ? codes)?}) → Future<SpeechReply> -
Decodes one reply. The caller has already fed the prompt, ending with the
mode's opening marker (
<|mixed_start|>or<|audio_start|>; none for text), somodel.logitsandmodel.lastHiddenStatedescribe the first slot.feedforwards one generated slot — a token, or<|audio_out|>with its feedback embedding — and computes logits when asked; callers use it to record history. When it getsmeanwhile, decoding the frame just sampled to audio, it should pass it to Lfm3Model.forward so the codec runs on the CPU while the GPU computes; if it does not call it, the reply runs it afterfeed.checkmay throw to cancel between slots. -
dequantizeQ4_0(
Uint8List blocks, int values) → Float32List -
Widens
valuesweights of raw GGUF Q4_0 blocks (half scale, then 16 nibble bytes, low nibbles first) to float32, as ggml's dequantize_row_q4_0. -
dequantizeQ6K(
Uint8List data, int first, int count, Float32List out, int offset) → void -
Dequantizes
countQ6_K super-blocks (256 values each) starting at blockfirstintooutatoffset, as ggml's dequantize_row_q6_K. -
downloadFile(
HttpClient client, RemoteFile file, String path, {void onBytes(int bytes)?, bool cancelled()?}) → Future< void> -
Downloads
filetopath, reusing an existing file only after checking its pinned size and SHA-256. Bytes arrive in[path].part, which a later call resumes with a Range request; only a file of the right size and SHA-256 is renamed topath.onBytessees how many bytes of the file are on disk;cancelledis polled between chunks and stops the download, keeping the part. -
encodeSpeechWav(
Float32List samples, {int sampleRate = 24000}) → Uint8List -
samplesas a mono 16-bit PCM WAV file atsampleRate, clipped to full scale. Throws ArgumentError for a non-finite sample. -
formatOmniSeconds(
double x) → String -
Python's
f'{x:.1f}': the exact binary value, ties to even. -
gemm(
Float32List w, Float32List xs, Float32List ys, int rows, int cols, int n) → void -
ys
t= wrows, cols* xstfor t < n, with xs packed asn, colsand ys asn, rows. Falls back to gemv per vector for the last n % 4 vectors and when rows is odd. -
gemv(
Float32List w, Float32List x, Float32List y, int rows, int cols) → void -
y
0:rows= wrows, cols* x0:cols. -
halfToDouble(
int bits) → double - An IEEE half-precision bit pattern as a double.
-
importGguf(
String ggufPath, String hfDir, String outDir) → List< String> -
Writes an engine bundle for the GGUF checkpoint
ggufPathintooutDir: config.json and tokenizer.json from the Hugging Face directoryhfDir(the same model's), a model.safetensors with the float tensors under their Hugging Face names, andlfm3-q4.cacheholding every matrix as Q4 and the tied embedding, Q6_K in the file, re-quantized to Q8 for the LM head and token lookup. Load it with--weights=q4. -
importVlBackbone(
String modelDir, String outDir) → void -
Writes a standalone language checkpoint into a new
outDir. -
importVlQadBundle(
String language, String projector, String metadata, String output) → Future< void> - Imports into a portable bundle, retaining Q4 blocks and using the validated Q6_K-to-Q8 embedding/head adapter. Intermediate files are always removed.
-
importVlVisionGguf(
String path, Lfm3VlConfig config, String output) → void -
Writes only the paired mmproj's vision/projector tensors to
output. BF16/F32 payloads are unchanged; split F16 temporal patches widen exactly. -
klDivergence(
Float32List p, Float32List q) → double - KL(p ‖ q) of the softmax distributions of two logit vectors, in nats.
-
lfm3LanguageTensorShapes(
Lfm3Config c) → Map< String, List< int> > - Canonical language tensor names and shapes, shared by import and packing.
-
lfm3VisionTensorShapes(
Lfm3VlConfig config) → Map< String, List< int> > - Required vision/projector checkpoint tensor names and shapes for I/O.
-
loadOmniVisionConfig(
String configPath, Lfm3Tokenizer tokenizer) → Lfm3VlConfig -
The vision part of an Omni config.json. Omni names no span marker IDs in
its config; they are the tokenizer's
<|vision_start|>/<|vision_end|>. -
loadVisionEncoderGguf(
String path, Lfm3VlConfig config, {bool nativeQ4 = true}) → Lfm3VisionEncoder -
Loads the CPU vision encoder straight from an mmproj GGUF, without
writing an intermediate safetensors file. Q4_0 linear weights stay native
Q4 blocks, multiplied with float inputs, unless
nativeQ4is false; then every weight is widened to float32 on the Dart heap. -
logProbability(
Float32List logits, int token) → double -
log softmax of
logitsattoken, in double. -
nativeAttention(
Float32List q, Float32List keys, Float32List values, Float32List? gate, Float32List out, {required int n, required int position, required int heads, required int kvHeads, required int headDim, required int window}) → void -
Grouped-query attention of
ntokens at positionsposition, ... in C (src/c/lab_native.c,lab_attention), with an optional per-head output gate. Shapes as in LayerShard: q and outn, heads * headDim, keys and valuesmaxSeq, kvHeads * headDimalready holding this chunk, gaten, headsbefore the sigmoid.window0 is full attention. -
nativeAudioDepthwise(
Float32List x, Float32List w, Float32List bias, Float32List y, {required int channels, required int freq, required int time, required bool first}) → void - Stride-2 audio convolution in channel, frequency, time order.
-
nativeAudioPointwise(
Float32List x, Float32List w, Float32List bias, Float32List y, {required int channels, required int positions}) → bool - Channel-major 1x1 convolution. Returns false without Accelerate.
-
nativeFullAttention(
Float32List q, Float32List keys, Float32List values, Float32List out, {required int n, required int heads, required int kvHeads, required int headDim, required double scale}) → void -
Grouped-query attention in which each of
ntokens attends to alln(no mask, no gate), in C (src/c/lab_native.c,lab_attention_full): the vision encoder's. q and out aren, heads * headDim, keys and valuesn, kvHeads * headDim; scores are scaled byscale. -
omniBundleIsInstalled(
String directory, List< RemoteFile> sources, String mmproj) → bool - A quick presence and source check. Loading must also call validateOmniBundle.
-
opensWithRefusal(
String reply) → bool -
Whether
replyopens with a refusal (refusalOpeningPattern). -
packVlBundle(
String modelDir, String backboneDir, String outDir, {WeightFormat weights = WeightFormat.q8, bool useCacheEmbedding = false}) → Future< void> -
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.useCacheEmbeddingexplicitly 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. -
parseAssistantReply(
String text) → AssistantReply -
Parses generated text. The prompt usually ends in
<think>or<think></think>, so the reply may start with the reasoning body itself and contain only the closing tag. -
physFootprint(
) → int - The process's physical footprint in bytes (what iOS holds against an app's memory limit); on Windows, its working set; on Linux and Android, its resident set size from /proc; -1 where none is available.
-
prepareAudioTranscriptionPrompt(
{required Lfm3Tokenizer tokenizer, required int audioTokens, String? language, Lfm3SpeechVariant variant = Lfm3SpeechVariant.audio}) → AudioTranscriptionPrompt -
prepareOmniPrompt(
List< Map< messages, {required Lfm3Tokenizer tokenizer, required Lfm3VlConfig config, List<String, Object?> >int> imageTokenCounts = const [], List<int> audioTokenCounts = const [], List<OmniVideoLayout> videos = const [], AudioReplyMode mode = AudioReplyMode.text, List<Map< ? tools}) → OmniPromptString, Object?> > -
Tokenizes an Omni conversation and expands each media placeholder as the
upstream processor does. Images and audio clips repeat their placeholder
per encoder row (
imageTokenCounts: VisionImageInput.imageTokens,audioTokenCounts: AudioFeatures.encoderTokens). A video becomes, per frame group, its<t seconds>time, the group's span-wrapped rows and its share of the soundtrack's rows, all inside one outer span (videos, one layout per video part). Counts are in message and content order. Rejects placeholders that are unbound, malformed or in plain text. -
prepareVisionPrompt(
List< Map< messages, {required Lfm3Tokenizer tokenizer, required Lfm3VlConfig config, required List<String, Object?> >int> imageTokenCounts, List<Map< ? tools, bool enableThinking = true, bool preserveThinking = false}) → VisionPromptString, Object?> > -
Tokenizes a VL conversation and repeats each image placeholder to match
imageTokenCounts, in message/content order, as the upstream processor does. These counts are VisionImageInput.imageTokens (or encoder row counts). Checks tokenizer/config special-token agreement and rejects unbound image or video tokens, including placeholders embedded in plain text. -
pyJsonDumps(
Object? value) → String -
json.dumps(value, ensure_ascii=False): ", " and ": " separators, keys in insertion order, non-ASCII kept. Dart's jsonEncode omits the spaces, which would change the prompt and therefore the tokens. -
readEvalRows(
String path) → List< EvalRow> -
Reads
path:.jsonlas one JSON object per non-empty line with a stringpromptand an optional stringreference(prompts may then hold newlines); anything else as one prompt per non-empty line, trimmed. -
readImageRgb(
String path, {int maxEncodedBytes = defaultMaxEncodedImageBytes, int maxPixels = defaultMaxDecodedImagePixels}) → Future< DecodedRgbImage> - Reads a local file with a bounded stream, then performs synchronous decoding. No URL fetching or filename-extension detection. A file that grows between the length check and the read cannot bypass the encoded-byte limit.
-
readSlice(
SafetensorsFile st, String name, int rows, int cols, {List< (int, int)> ? rowRanges, int colStart = 0, int? colEnd}) → Float32List -
Reads part of a 2-D
rows, colstensor as float32: the concatenation ofrowRanges(all rows by default), restricted to the columns [colStart, colEnd). -
readVisionGgufWeights(
GgufFile gguf, Lfm3VlConfig config) → Map< String, Float32List> - Vision and projector weights of an LFM3-VL or LFM3-Omni mmproj, widened to float32 under checkpoint names for Lfm3VisionEncoder.fromWeights. F32, F16, BF16 and Q4_0 payloads convert exactly; audio tensors in an Omni mmproj are ignored, and every vision tensor must be present.
-
renderAudioTtsPrompt(
String text, {String language = 'en', String voice = 'female', Lfm3SpeechVariant variant = Lfm3SpeechVariant.audio}) → String -
The official single-text TTS prompt for
text. -
renderChat(
List< Map< messages, {List<String, Object?> >Map< ? tools, bool addGenerationPrompt = true, bool enableThinking = true, bool preserveThinking = false}) → StringString, Object?> > -
Renders a conversation exactly as
tokenizer.apply_chat_templatedoes. -
renderOmniChat(
List< Map< messages, {AudioReplyMode mode = AudioReplyMode.text, List<String, Object?> >Map< ? tools}) → StringString, Object?> > -
Renders the official LFM3-Omni template for messages whose content parts
may be
{'type': 'image'},{'type': 'audio'}(alsoinput_audioandaudio_url) and{'type': 'video'}, each as one span-wrapped placeholder. A video's soundtrack is not a separate part here: it is declared in the video's OmniVideoLayout. The reply opens with<think></think>, then themode's marker: none for text,<|audio_start|>for speech and<|mixed_start|>for interleaved. -
renderVisionChat(
List< Map< messages, {List<String, Object?> >Map< ? tools, bool addGenerationPrompt = true, bool enableThinking = true, bool preserveThinking = false}) → StringString, Object?> > - Renders the still-image subset of the VL template. Images are represented by a single placeholder here; prepareVisionPrompt expands it to the number of projected image rows. Image parts use {'type': 'image'} and can be interleaved with text parts. Video is explicitly unsupported.
-
rmsNorm(
Float32List x, Float32List weight, Float32List out, int xOffset, int outOffset, int n, double eps) → void - RMSNorm of x[xOffset, xOffset + n) into out[outOffset, ...). The reference rounds x * rsqrt(...) to float32 before multiplying by the weight, so this does too.
-
The contiguous share [start, end) of
countitems that shardindexofshardsowns, with inner boundaries rounded down to a multiple ofalign. -
speechMmprojIn(
String directory) → String - The speech mmproj of a prepared research directory: LFM3-Omni's when present, otherwise LFM3-Audio's.
-
speechVariantOf(
GgufFile mmproj) → Lfm3SpeechVariant -
The model a speech
mmprojbelongs to. Omni mmprojs also carry the LFM3-VL vision tower and projector. -
splitQ4_0(
Uint8List blocks, int rows, int cols) → CachedMatrix - Q4_0 blocks (half scale, then 16 nibble bytes) split into the engine's nibble and scale arrays (lab_native.c); the nibble order is GGUF's.
-
toolCallMatches(
List< ToolCall> calls, Map<String, Object?> ? expect) → bool -
One call with the expected name whose every expected argument contains
one of its fragments, ignoring case; a null
expectwants no call. -
validateAudioBundle(
String directory, List< RemoteFile> sources, String audio, {void check()?}) → Future<void> - Full installed payload verification, cancellable between file chunks.
-
validateOmniBundle(
String directory, List< RemoteFile> sources, String mmproj, {void check()?}) → Future<void> - Full installed payload verification, cancellable between file chunks.
-
validateVlBackbone(
String modelDir, String backboneDir) → void - Checks import fingerprints before pairing a VL encoder with its backbone. Uses the same metadata-based identity policy as weight caches, not a full tensor-payload checksum. The importer writes this provenance file.
-
validateVlBundle(
String directory) → Future< void> - 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.
-
wilsonInterval(
int successes, int trials, {double z = 1.96}) → (double, double) -
The 95 % (by
z) Wilson score interval ofsuccessesintrials. -
writeSafetensorsF32(
String path, Map< String, (List< tensors) → voidint> , Float32List)> -
Writes float32
tensors(name: shape and values) to a new safetensors file atpath. -
writeVlBackboneIdentity(
String modelDir, String backboneDir) → void - Records the pairing used by importers and portable bundle packing.
Typedefs
- DecodedRgbImage = ({int height, Uint8List pixels, int width})
Exceptions / Errors
- AudioSynthesisCancelled
- Thrown by AudioSynthesizer.synthesize after AudioSynthesizer.cancel.
- ContextLengthExceeded
- A conversation that no longer fits the model's context: start a new one (ChatSession.clear) or load the model with a longer context.
- ModelDownloadException
- A download that failed for good: the server answered with an error, or the file arrived different from what was published.
- VisionRequestCancelled
- An explicitly cancelled visual turn. Its draft message and streamed reply are not committed to history. Return false from onText to retain a partial reply instead.