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

--ctx N

The context length shown in the report (default: the header’s context length, or 2048). Weights do not depend on it

--budget 1.3G

The memory available; without it, the JVM’s own maximum is used

--profile mobile|desktop|native|browser

Plan under a device profile โ€” see below

--list 'blk.3.*'

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 TensorId; a tool built on an architecture library passes that library’s name map to planInput and can match on ids such as model.layers[3].*

--no-budget

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

MOBILE_2GB

700 MB reserved, off-heap above 256 KB, the cost model’s cheaper variant taken once the plan passes 80 % of the budget (cheaperVariantAbove), dispatcher dequantization warns above 5 % of bytes read, weights mapped

DESKTOP

The same reserve, no automatic switch to a cheaper variant, heap staging

NATIVE

The smaller 300 MB Kotlin/Native reserve

EDGE

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 %

BROWSER

A tab (Kotlin/Wasm or Kotlin/JS): 256 MB reserved for the page, the JavaScript heap and the Kotlin runtime; dense checkpoints quantized to Q8_0 at load (quantizeDenseTo) so a Hugging Face FP32 checkpoint is held in a quarter of its bytes and served by the SIMD128 kernels; the cheaper variant taken past 80 %; nothing mapped โ€” there is no file. Off-heap allocations go to the kernel sidecar’s linear memory once WasmSimd.install() has bound it. Plan against PlannerProfile.BROWSER_AVAILABLE_BYTES (2 GB) unless the host tells you more.

PlannerProfile.forDevice(device)

BROWSER on a web host; otherwise MOBILE_2GB at or below 3 GB of RAM, DESKTOP above

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 RuntimeCost is one line of the plan. CostScope.MODEL is memory held as long as the model is loaded; CostScope.STEP is memory of one forward pass.

  • costs(ctx) is called again with half the context, to price the --ctx suggestion, so it must depend on ctx alone.

  • 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.

  • planInput of the GGUF, safetensors and ONNX readers all take runtime.

  • ResolvedGguf.resolve and 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.