Batch Mode & Multi-Variant Model Loading
Overview
dl::BatchMode describes what batch sizes a model accepts per forward pass. Models report constraints via ModelBase::batchMode(); metadata is aggregated in ModelInfo::batch_mode for the widget and constraint helpers.
Runtime JSON models use BatchModeSpec in RuntimeModelSpec. Optional weights_variants let a single spec reference multiple compiled artifacts keyed by batch size; RuntimeModel::loadWeightsForBatchSize() selects among them.
Source files:
| File | Role |
|---|---|
models_v2/TensorSlotDescriptor.hpp |
BatchMode variant and query helpers |
models_v2/ModelBase.hpp |
Virtual batchMode() default |
models_v2/ModelInfo.hpp |
Cached batch_mode for UI |
runtime/RuntimeModelSpec.hpp |
BatchModeSpec, WeightsVariant JSON types |
runtime/RuntimeModel.hpp |
loadWeightsForBatchSize() |
constraints/ConstraintEnforcer.hpp |
computeBatchSizeConstraint() |
BatchMode
dl::BatchMode is a std::variant with three alternatives defined in TensorSlotDescriptor.hpp:
| Mode | Struct | Meaning |
|---|---|---|
| Fixed | FixedBatch{size} |
Compiled for exactly size samples per call |
| Dynamic | DynamicBatch{min_size, max_size} |
Accepts a range (max_size=0 → unlimited) |
| Recurrent-only | RecurrentOnlyBatch{} |
Model architecture requires batch = 1 |
Registered model examples
| Model | batchMode() |
Notes |
|---|---|---|
NeuroSAMModel |
DynamicBatch{1, 0} |
Supports batched inference; batch locks to 1 when recurrent bindings are active (see constraints) |
GeneralEncoderModel |
DynamicBatch{1, 0} |
Arbitrary batch sizes |
ModelBase default |
DynamicBatch{1, maxBatchSize()} |
Subclasses override as needed |
RecurrentOnlyBatch is for models whose architecture cannot run with batch > 1. Models like NeuroSAM that support batching but are often used sequentially rely on DynamicBatch plus session recurrent bindings to lock the spinbox when needed.
Query helpers
auto mode = model->batchMode();
bool locked = dl::isBatchLocked(mode);
// true for RecurrentOnlyBatch or FixedBatch{1}
int min_b = dl::minBatchSizeFromMode(mode);
int max_b = dl::maxBatchSizeFromMode(mode); // 0 = unlimited (DynamicBatch only)
std::string desc = dl::batchModeDescription(mode);
// e.g. "Fixed(4)", "Dynamic(1, unlimited)", "RecurrentOnly"ModelBase override
dl::BatchMode batchMode() const override {
return dl::FixedBatch{4}; // fixed-shape AOT export
// return dl::DynamicBatch{1, 8}; // bounded dynamic range
// return dl::RecurrentOnlyBatch{}; // architecture requires batch=1
}JSON specification (RuntimeModelSpec)
BatchModeSpec maps to BatchMode via toBatchMode() with this precedence: recurrent_only → fixed → dynamic → default DynamicBatch{1, 0}.
{
"model_id": "my_model",
"display_name": "My Model",
"batch_mode": { "fixed": 4 },
"inputs": [...],
"outputs": [...]
}Supported batch_mode shapes:
| JSON | BatchMode |
|---|---|
{ "fixed": N } |
FixedBatch{N} (N >= 1) |
{ "dynamic": { "min": 1, "max": 8 } } |
DynamicBatch{1, 8} (max: 0 = unlimited) |
{ "recurrent_only": true } |
RecurrentOnlyBatch{} |
If batch_mode is omitted, RuntimeModel::batchMode() falls back to legacy fields: DynamicBatch{1, max_batch_size} where max_batch_size defaults to 0 (unlimited) when absent.
RuntimeModelSpec::validate() rejects:
- More than one of
fixed,dynamic, orrecurrent_onlyset fixed < 1dynamic.min < 1dynamic.maxstrictly less thandynamic.min(whenmax > 0)
Relative weights_path and weights_variants[].path values are resolved against the JSON file’s directory in fromJsonFile().
Session batch-size constraints
The Properties widget calls dl::constraints::computeBatchSizeConstraint() with ModelInfo and memory_frames from DeepLearningState. See Session Constraints for the full API.
Priority (most restrictive wins):
- Active recurrent bindings (
hasActiveRecurrentBindings) →min=1,max=1,forced_by_recurrent=true. A recurrent frame is active whenoutput_slot_nameis non-empty and not"(None)". RecurrentOnlyBatchorFixedBatch{1}→ locked to 1,forced_by_recurrent=falseFixedBatch{N>1}→min=max=NDynamicBatch→min/maxfrom batch mode
Widget spinbox behaviour (DeepLearningPropertiesWidget::_updateBatchSizeConstraint):
| Constraint | Spinbox |
|---|---|
| Locked to 1 | Value forced to 1, disabled; tooltip distinguishes recurrent vs model lock |
FixedBatch{N>1} |
Range [N, N], disabled |
DynamicBatch |
Enabled; min from constraint; max from constraint or 9999 when unlimited |
On model selection, the spinbox initial value comes from FixedBatch size, 1 for RecurrentOnlyBatch, or preferred_batch_size (default 1) for dynamic models.
Batch size is stored in DeepLearningState::batchSize() and passed to InferenceController::runBatch() as frames per forward pass. See Batch range inference.
Multi-variant model loading
Some models are compiled multiple times for different batch sizes. The weights_variants array in RuntimeModelSpec lists each artifact:
{
"model_id": "neurosam_multi",
"display_name": "NeuroSAM (Multi-Variant)",
"weights_path": "neurosam_default.pt2",
"batch_mode": { "dynamic": { "min": 1, "max": 8 } },
"weights_variants": [
{ "path": "neurosam_b1.pt2", "batch_size": 1, "label": "recurrent" },
{ "path": "neurosam_b8.pt2", "batch_size": 8, "label": "batched", "backend": "aotinductor" }
],
"inputs": [...],
"outputs": [...]
}Each WeightsVariant entry:
| Field | Required | Description |
|---|---|---|
path |
yes | Weights file (relative paths resolved in fromJsonFile()) |
batch_size |
yes | Batch size the variant was compiled for (>= 1, unique per spec) |
label |
no | Display hint |
backend |
no | Override: "auto", "torchscript", "aotinductor", "executorch" |
RuntimeModel::loadWeightsForBatchSize(int batch_size) searches weights_variants for an exact batch_size match. On match it rebuilds ModelExecution with the variant’s backend (or Auto) and loads that path, returning true if loading succeeded. Returns false when no variants are defined or no entry matches — it does not reload weights_path automatically; callers must fall back explicitly if desired.
RuntimeModel::weightsVariants() returns the variant list (empty when unset).
At construction, RuntimeModel auto-loads weights_path when present. The Properties widget does not yet call loadWeightsForBatchSize() when the batch spinbox changes; multi-variant selection is a RuntimeModel API for programmatic or future UI integration.
Dynamic-shape AOT export
For a single .pt2 that accepts variable batch sizes, export with a dynamic batch dimension:
import torch
from torch.export import export, Dim
model = MyModel()
model.eval()
batch = Dim("batch", min=1, max=32)
example_inputs = (torch.randn(1, 3, 256, 256),)
dynamic_shapes = {"x": {0: batch}}
exported = export(model, example_inputs, dynamic_shapes=dynamic_shapes)
so_path = torch._inductor.aot_compile(exported.module(), example_inputs)Pair with "batch_mode": { "dynamic": { "min": 1, "max": 32 } } in the JSON spec.
When to use dynamic vs multi-variant
| Approach | Pros | Cons |
|---|---|---|
| Dynamic shapes | Single file, flexible | May be slower than fixed-shape kernels |
| Multi-variant | Optimal per-batch performance | Multiple files; caller must select variant |
Use dynamic shapes unless profiling shows a meaningful gap for your model.
See also
- Session Constraints —
computeBatchSizeConstraint() - Batch range inference — how batch size drives frame grouping
- RuntimeModelSpec tests — JSON round-trip and validation (
[BatchMode],[WeightsVariant]tags)