Weights at 1.7 bits: one view for every format
You will write one weight into a GGUF file six times, as FP32, FP16, Q8_0, Q4_0 and the two ternary formats, and read every one of them back with the same call. Then you will map one of them from the file without a heap copy, read what each form costs, convert between forms, and multiply by a packed weight.
All six are one type, TensorView. A view is a shape, a format, a layout and a storage. The
format says what the bytes mean (Float32/TQ1_0: logically FP32, stored as ternary blocks). The
storage says where they are (a heap array, a mapped file). Code that reads a view does not ask
which of the six it has.
Every snippet below is compiled and run in CI from skainet-docs-samples (LowBitWeights.kt),
and the numbers on this page are asserted by its test.
This page is about how a low-bit weight is stored and read. Ternary networks: getting started trains a ternary classifier and runs it through the native ternary kernel.
Prerequisites
-
JDK 21+ with the Vector API module (
--enable-preview --add-modules jdk.incubator.vector). -
sk.ainet.core:skainet-lang-core,sk.ainet.core:skainet-backend-api,sk.ainet.core:skainet-io-coreandsk.ainet.core:skainet-io-ggufon the classpath.
import sk.ainet.backend.api.kernel.KernelDispatch
import sk.ainet.io.JvmRandomAccessSource
import sk.ainet.io.gguf.GGMLQuantizationType
import sk.ainet.io.gguf.StreamingGGUFReader
import sk.ainet.io.gguf.export.GGUFWriter
import sk.ainet.io.gguf.export.GgufTensorEntry
import sk.ainet.io.gguf.export.GgufWriteRequest
import sk.ainet.lang.memory.Scope
import sk.ainet.lang.memory.Storage
import sk.ainet.lang.memory.TensorView
import sk.ainet.lang.memory.TernaryCodec
import sk.ainet.lang.memory.trace.RecordingTraceSink
import sk.ainet.lang.memory.trace.TraceEvent
import sk.ainet.lang.tensor.Shape
import sk.ainet.lang.tensor.storage.MemoryTracker
import sk.ainet.lang.tensor.storage.TensorEncoding
import sk.ainet.lang.types.FP32
import sk.ainet.lang.types.Fp16Codec
Step 1 โ Write one weight six ways
The weight is an [8, 256] matrix of smooth values, standing in for a trained FP32 weight.
/** Stands in for a trained FP32 weight: smooth values in [-1, 1]. */
fun trainedWeight(): FloatArray = FloatArray(ROWS * COLS) { i -> sin(0.37f * i) * 0.8f }
The file gets it six times. requantizeTo produces the Q8_0 and Q4_0 bytes; TernaryCodec
produces the ternary ones, where every weight becomes -1, 0 or +1 times a scale per block of 256.
/** The same weight six ways in one GGUF file. */
fun writeModel(file: File, weight: FloatArray) {
val shape = listOf(ROWS, COLS)
// A view over the trained floats. `requantizeTo` is the lossy direction: it returns a view
// over new packed bytes.
val dense = TensorView.dense(Storage.Heap.wrap(weight), Shape(ROWS, COLS), FP32)
fun entry(name: String, type: GGMLQuantizationType, bytes: ByteArray) =
GgufTensorEntry(ggufName = name, quantization = type, shape = shape, rawBytes = bytes)
val tensors = listOf(
entry("w.f32", GGMLQuantizationType.F32, floatBytes(weight)),
entry("w.f16", GGMLQuantizationType.F16, halfBytes(weight)),
entry("w.q8_0", GGMLQuantizationType.Q8_0, bytesOf(dense.requantizeTo(TensorEncoding.Q8_0))),
entry("w.q4_0", GGMLQuantizationType.Q4_0, bytesOf(dense.requantizeTo(TensorEncoding.Q4_0))),
entry("w.tq2_0", GGMLQuantizationType.TQ2_0, TernaryCodec.encodeTq2_0(weight)),
entry("w.tq1_0", GGMLQuantizationType.TQ1_0, TernaryCodec.encodeTq1_0(weight)),
)
val request = GgufWriteRequest(
metadata = mapOf("general.architecture" to "tutorial"),
tensors = tensors,
tensorMap = tensors.associate { it.ggufName to it.ggufName },
)
val (_, bytes) = GGUFWriter.writeToByteArray(request)
file.writeBytes(bytes)
}
/** The bytes a view's storage holds. */
fun bytesOf(view: TensorView): ByteArray =
ByteArray(view.storage.sizeBytes.toInt()).also { view.storage.copyInto(it) }
Step 2 โ Read all six through one type
loadTensorView reads a tensor’s bytes and returns a view over them. It decodes nothing.
view.format says what the bytes are, and get and toFloatArray decode on read, whatever the
format.
for (info in reader.tensors) {
// One call and one type for every format. Nothing is decoded here: the view holds
// the file's bytes, and `view.format` says what they are.
val view: TensorView = reader.loadTensorView(info)
val decoded = view.toFloatArray() // decodes on read, whatever the format
val first = view.get(0, 1) // one element, the same call for all six
check(first == decoded[1])
tracker.record(info.name, view) // logical against physical bytes
}
val report = tracker.report()
// report.totalLogicalBytes: what the tensors are worth as their dtype
// report.totalPhysicalBytes: what they occupy
The loop body has no branch on the format. This is what it measures:
| Tensor | view.format |
Bytes | Bits per weight | Largest error |
|---|---|---|---|---|
|
|
8192 |
32 |
0 |
|
|
4096 |
16 |
0.0002 |
|
|
2176 |
8.5 |
0.0033 |
|
|
1152 |
4.5 |
0.0996 |
|
|
528 |
2.0625 |
0.3993 |
|
|
432 |
1.6875 |
0.3993 |
Three things to read off the table:
-
The packed forms are
Float32/…. A Q4_0 or ternary weight is logically FP32; the encoding says how it is stored. Only the FP16 tensor has another dtype. -
TQ1_0stores five ternary weights in one byte, which is 1.6 bits; with the block’s scale it comes to 1.6875 bits per weight. That is 19 times smaller than FP32. -
The error column is the price. A ternary weight keeps a sign and a scale, so a weight has to be trained for it; ternarizing a trained FP32 weight afterwards, as here, loses most of it.
MemoryTracker gives the same numbers for a whole model: report().totalPhysicalBytes is what
the tensors occupy, totalLogicalBytes what they would occupy as their dtype.
Step 3 โ The same view over the mapped file
loadTensorViewMapped maps the tensor’s byte range of the file. Nothing is read into the heap, so
it also works for a tensor above 2 GB. The view is used the same way. Its storage owns the
mapping, and the caller closes it.
// The same view over the mapped file: no heap copy, and the same code reads it.
val info = reader.tensors.single { it.name == "w.tq2_0" }
val heap = reader.loadTensorView(info)
val mapped = reader.loadTensorViewMapped(info, file.path)
val mappedDomain = mapped.storage.domain.name // MMAP_FILE
val mappedEqualsHeap = mapped.toFloatArray().contentEquals(heap.toFloatArray())
mapped.storage.close() // the caller unmaps
The storage’s domain is MMAP_FILE, and the values equal the heap read.
Step 4 โ Convert: lossless one way, lossy the other
There are two conversions, and their names say which one loses information.
// Lossless: packed to dense FP32. The values are the ones the packed bytes decode to.
val materialized = heap.materialize()
val lossless = materialized.toFloatArray().contentEquals(heap.toFloatArray())
// Lossy, and it says so in its name: dense FP32 to a packed encoding.
val f32 = reader.loadTensorView("w.f32")
val q4 = f32.requantizeTo(TensorEncoding.Q4_0)
val requantizeError = maxError(q4.toFloatArray(), f32.toFloatArray())
materialize() decodes into a new dense FP32 view: the values are exactly the ones the packed
bytes decode to. requantizeTo(encoding) goes the other way and loses precision: here the largest
error against the FP32 weight is 0.0996. It supports Q8_0, Q4_0 and BITNET_PLANES.
Step 5 โ Multiply by the packed weight
A matmul does not need the dense weight. KernelDispatch.matmul builds a key from the formats and
layouts of its two operands and runs the kernel registered under it. The kernel reads the packed
blocks.
// x ยท Wแต on the packed Q4_0 weight. The kernel is looked up by the formats of the two
// views and reads the packed blocks: no dense copy of the weight is made. The trace
// names the kernel that ran.
val weightQ4 = reader.loadTensorView("w.q4_0")
val x = FloatArray(COLS) { i -> ((i % 7) - 3) / 3f }
val activation = TensorView.dense(Storage.Heap.wrap(x), Shape(1, COLS), FP32)
val out = TensorView.dense(Storage.Heap.floats(ROWS), Shape(1, ROWS), FP32)
val sink = RecordingTraceSink()
// `prepackWeights`: put the file-order blocks into the order the kernel feeds on, for
// this one call. A model does that once at load with `view.prepack(...)`.
KernelDispatch.matmul(activation, weightQ4, out, Scope.Ambient, sink, prepackWeights = true)
val kernel = sink.eventsOf<TraceEvent.KernelRun>().single().kernel
val product = FloatArray(ROWS) { out.get(0, it) }
The trace names the kernel that ran: scalar-Q4_0 in this sample’s setup. Another kernel
provider registers its kernel under the same key, and the call does not change. The product equals
the one computed from the decoded weight.
Not every format has a kernel on every platform. When none is registered for a pair, the
dispatcher runs its reference kernel, which decodes and is slow, and prints that once.
In this sample’s setup (a plain JVM without the native kernel library) that is the case for
TQ1_0 and TQ2_0; the BitNet encoding has native kernels
(see Ternary networks: getting started and
Kernel ร platform support).
What to read next
-
Define your own low-bit encoding: a decoder and a kernel for a format the library does not know.
-
The memory model: storage, view, format and scope, and what the model replaced.