Plan a model’s memory before loading it
Loading a model to find out whether it fits is an expensive way to ask the question. SKaiNET answers it from the file’s header: the tensor table and the metadata, no tensor bytes.
The engine prices the weights. It knows no model architecture, so what a model allocates besides
them (caches, activations) comes from the library that builds the network, as a RuntimeCostModel
(see Plan what the model needs besides its weights). Without one, a plan is weights and heap headroom.
Print a plan from the command line
./gradlew :skainet-apps:skainet-plan:installDist
./skainet-apps/skainet-plan/build/install/skainet-plan/bin/skainet-plan \
model.gguf --ctx 4096 --budget 1.3G
llama-1b ยท llama ยท ctx 4096 weights heap-staged, packed 640 MB resident heap headroom 64 MB total 704 MB of 1.3 GB โ fits weights only: what the model allocates besides its weights is not planned here
skainet-plan is the engine’s own tool, so it plans weights only. For a plan that includes a
model’s caches and activations, use the tool of the architecture library: the skainet CLI of
SKaiNET-transformers prints one before it loads a model.
Useful flags:
| Flag | Effect |
|---|---|
|
The context length shown in the report (default: the header’s context length, or 2048). Weights do not depend on it |
|
The memory available; without it, the JVM’s own maximum is used |
|
Plan under a device profile โ see below |
|
List matching tensors with their format and size. The pattern matches the checkpoint’s own tensor names. This tool knows no model family, so it shows no |
|
Print the plan without a fit check |
The exit code is non-zero when the plan does not fit, so it works in a script.
Plan under a device profile
A profile is the set of rules for a class of device, so the numbers are not retyped at every call site:
val profiled = PlannerProfile.MOBILE_2GB.plan(input, availableBytes = deviceRam)
println(profiled.render())
profiled.requireFits() // throws, naming the pool that ran out
| Profile | Rules |
|---|---|
|
700 MB reserved, off-heap above 256 KB, the cost model’s cheaper variant taken once the plan passes 80 % of the budget ( |
|
The same reserve, no automatic switch to a cheaper variant, heap staging |
|
The smaller 300 MB Kotlin/Native reserve |
|
An embedded device with limited memory and compute: zero reserve โ the number you pass is the usable RAM, already net of what the OS holds โ weights mapped, the cheaper variant taken past 80 % |
|
A tab (Kotlin/Wasm or Kotlin/JS): 256 MB reserved for the page, the JavaScript heap and the Kotlin runtime; dense checkpoints quantized to |
|
|
A ProfiledPlan records what the profile decided โ a switch to the cheaper variant appears as a
note, not a silent rewrite โ so a plan read months later says which rules produced it. What the
cheaper variant is, a compressed cache for example, is the cost model’s knowledge: the profile
only decides when to take it, and a plan without a cost model is never switched.
Will it fit on an embedded device? Any format, in seconds
The planner answers the pre-conversion question โ is it worth spending a day converting this model for a device with ~2.1 GB of usable RAM? โ for GGUF, safetensors and ONNX files, from the header/metadata only. A multi-gigabyte file is answered in seconds, and tensor payloads are never read:
val input = when (ModelFormat.fromFilePath(path)) {
ModelFormat.GGUF -> StreamingGGUFReader.open(src).planInput(ctx = 4096)
ModelFormat.SAFETENSORS -> StreamingSafeTensorsReader.open(src).planInput(modelName)
ModelFormat.ONNX -> StreamingOnnxReader.open(src).planInput(modelName)
null -> error("not a model file")
}
val verdict = PlannerProfile.EDGE.plan(input, availableBytes = parse("2.1G"))
println(verdict.render()) // โ fits / โ does not fit, with suggestions
EDGE treats the number you pass as the usable RAM โ nothing is subtracted. ONNX weights kept
in a sibling external_data file are priced by their declared lengths, so multi-gigabyte models
report their real size. Two honest limits: every plan is weights-only unless the caller passes a
RuntimeCostModel (see below); and file weights are a lower bound โ leave headroom for the runtime’s own buffers on
top of the verdict. A standalone multi-format CLI over this API is incubating in the
SKaiNET-research repository; the in-repo skainet-plan CLI covers GGUF.
Plan what the model needs besides its weights
The planner prices weights from the file. What else a model allocates depends on its architecture
and on choices of the caller, such as the kind of cache, so the library that knows the
architecture says it. It passes a RuntimeCostModel:
class MyDecoderCost(private val cacheBytesPerToken: Long, private val scratchBytes: Long) : RuntimeCostModel {
override fun costs(ctx: Int) = listOf(
RuntimeCost("cache", "dense @ ctx $ctx", cacheBytesPerToken * ctx, CostScope.MODEL),
RuntimeCost("scratch", "one pass", scratchBytes, CostScope.STEP),
)
}
val input = reader.planInput(ctx = 4096, runtime = MyDecoderCost(cacheBytesPerToken, scratchBytes))
-
Each
RuntimeCostis one line of the plan.CostScope.MODELis memory held as long as the model is loaded;CostScope.STEPis memory of one forward pass. -
costs(ctx)is called again with half the context, to price the--ctxsuggestion, so it must depend onctxalone. -
A model that has a variant needing less memory, for example a compressed cache, returns it from
cheaper(). A profile takes it once the plan passes the profile’s threshold, and a plan that does not fit suggests it. -
planInputof the GGUF, safetensors and ONNX readers all takeruntime. -
ResolvedGguf.resolveand the Android helpers (AndroidGguf.plan,fits,profiledPlan) open the file themselves, so they take a factory,runtime = { reader → … }, which builds the cost model from the open header.
Without a cost model every plan is weights and heap headroom, whatever the format. Until 0.67.0
the engine had an estimate of its own for a decoder transformer (ModelGeometry, KvCacheMode,
read from a GGUF header). It did not know which cache an architecture library really allocates
and is removed. With SKaiNET-transformers, pass its cost model:
val input = reader.planInput(ctx = 4096, runtime = reader.decoderMemoryCost())
Check a real device, before allocating
A phone has two memory pools, and one total cannot express the difference: the managed heap is hard-capped per app, while mapped weights live in file-backed pages that never count against that cap.
val device = AndroidGguf.deviceMemory(context) // ActivityManager + the ART cap
val fit = AndroidGguf.fits(context, path, ctx = 2048, runtime = { reader -> costModelFor(reader) }) // header-only
if (!fit.fits) {
log(fit.render()) // names the pool that ran out and what would help
return
}
llama-1b ยท ctx 2048 ยท weights mapped managed heap 434 MB of 472 MB โ device RAM 1.0 GB of 720 MB โ short by 320 MB suggestions: --cache compressed (โ216 MB) ยท --ctx 1024 (โ42 MB)
Charging the heap for weights only when they are not mapped is the whole point: the same model can be impossible on the heap and unremarkable when mapped.
Load with mapped weights on Android
val loader = AndroidGguf.loader(path) // weightForm = WeightForm(residency = MAPPED)
loader.load<FP32, Float>(ctx, FP32::class) { name, tensor -> model.put(name, tensor) }
The loader takes one WeightForm โ encoding ร byte order ร shape ร residency โ resolved
for you by WeightFormResolver (or passed explicitly; your form always wins). MAPPED
residency serves dense FP32 tensors as zero-heap views over file-backed pages, and falls
back to the heap when the platform cannot map or the source has no path.
Packed (quantized) tensors still arrive as heap arrays under MAPPED, because the packed
matmul kernels take `ByteArray`s. Mapping lifts the heap ceiling for dense checkpoints today, not
yet for a Q4_K_M one.
|
Check the plan against what actually happened
The plan is an estimate until something compares it with reality:
val actual = ActualMemory.from(sink.events())
val comparison = PlanVsActual.compare(plan, actual)
check(comparison.withinTolerance) { comparison.render() }
The same trace also yields TTFT, tokens per second, the per-module breakdown and the effective memory bandwidth โ see the memory model.