Define your own low-bit encoding
This guide adds a packed weight format from outside the library. You need three things, and the third is optional:
-
an encoding value that names the format,
-
a
BlockDecoderthat decodes one block out of aStorage, -
a
ViewKernelthat multiplies on the packed bytes.
The example format is invented: one sign bit per weight and one FP32 scale per block of 32
weights, which is 2 bits per weight. The code is compiled and run in CI from
skainet-docs-samples (CustomEncoding.kt).
Name the format
TensorEncoding is a sealed interface, so code outside the library cannot add a member to it. The
member for this case is TensorEncoding.Opaque: a name and the byte count.
/** 32 weights per block: a 4-byte FP32 scale, then 32 sign bits. 8 bytes, so 2 bits per weight. */
const val BLOCK: Int = 32
const val BYTES_PER_BLOCK: Int = 8
/**
* `TensorEncoding` is sealed, so an encoding from outside the library is an `Opaque` one: a
* name and the byte count. The name is what a kernel key and a memory report show.
*/
fun encodingOf(elementCount: Int): TensorEncoding =
TensorEncoding.Opaque("SIGN1", elementCount.toLong() / BLOCK * BYTES_PER_BLOCK)
The name appears in view.format (Float32/SIGN1), in memory reports and in kernel keys.
Write the bytes
How the bytes are produced is up to you. Here each block keeps the signs and the mean absolute value.
/** Each block keeps the signs and one scale: the mean absolute value of its 32 weights. */
fun encode(values: FloatArray): ByteArray {
require(values.size % BLOCK == 0) { "SIGN1 stores whole blocks of $BLOCK" }
val out = ByteArray(values.size / BLOCK * BYTES_PER_BLOCK)
for (block in 0 until values.size / BLOCK) {
var sum = 0f
var signs = 0
for (i in 0 until BLOCK) {
val v = values[block * BLOCK + i]
sum += abs(v)
if (v >= 0f) signs = signs or (1 shl i)
}
putInt(out, block * BYTES_PER_BLOCK, (sum / BLOCK).toRawBits())
putInt(out, block * BYTES_PER_BLOCK + 4, signs)
}
return out
}
Decode a block
A BlockDecoder states the block geometry and decodes one block. It receives the storage on every
call, so one decoder reads a heap array, a direct buffer and a mapped file.
/**
* The one thing a view needs to read the encoding: decode a block out of a `Storage`. It gets
* the storage on every call, so the same decoder reads a heap array, a direct buffer or a
* mapped file.
*/
object Sign1Decoder : BlockDecoder {
override val blockSize: Int = BLOCK
override val bytesPerBlock: Int = BYTES_PER_BLOCK
override fun decodeBlock(storage: Storage, blockIndex: Long, out: FloatArray, outOffset: Int) {
val block = ByteArray(BYTES_PER_BLOCK)
storage.copyInto(block, 0, blockIndex * BYTES_PER_BLOCK, BYTES_PER_BLOCK)
val scale = Float.fromBits(getInt(block, 0))
val signs = getInt(block, 4)
for (i in 0 until BLOCK) out[outOffset + i] = if ((signs ushr i) and 1 == 1) scale else -scale
}
}
Make a view
TensorView.packed puts shape, encoding, decoder and storage together.
/** A view over the packed bytes. From here on it is a tensor view like any other. */
fun viewOf(bytes: ByteArray, rows: Int, cols: Int): TensorView =
TensorView.packed(
storage = Storage.Heap.wrap(bytes, mutable = false),
shape = Shape(rows, cols),
encoding = encodingOf(rows * cols),
decoder = Sign1Decoder,
)
From here the weight is a view like any other: element reads, a full decode, a dense copy and the memory tracker all work without knowing the format.
val weight = viewOf(encode(values), rows, cols)
val format = weight.format.toString() // Float32/SIGN1
val first = weight.get(0, 0) // decodes one element
val decoded = weight.toFloatArray() // decodes all of them
val dense = weight.materialize() // a dense FP32 copy, if one is needed
val tracker = MemoryTracker()
tracker.record("w", weight)
val entry = tracker.report().entries.single().report
val bitsPerWeight = entry.physicalBytes * 8.0 / (rows * cols)
The tracker reports 2 bits per weight and a compression ratio of 16 against FP32.
Add a kernel (optional)
A matmul already works at this point: with no kernel registered for the operand pair, the
dispatcher runs its reference kernel, which decodes through your BlockDecoder. It is correct and
slow, and the dispatcher prints a line the first time it happens.
A kernel of your own reads the packed bytes. Register it under the key of the operand pair it serves.
/**
* Optional: a kernel that multiplies on the packed bytes. Without it the dispatcher uses its
* decoding reference kernel, which is correct for any view that has a decoder, and slow.
*
* A sign-bit weight needs no multiply per element: add or subtract the activation, then scale
* once per block.
*/
class Sign1MatmulKernel(override val key: KernelKey) : ViewKernel {
override val name: String = "sample-SIGN1"
override fun run(inputs: List<TensorView>, out: TensorView) {
val (activation, weight) = inputs
val x = activation.toFloatArray()
val (rows, cols) = weight.shape.dimensions
val block = ByteArray(BYTES_PER_BLOCK)
for (r in 0 until rows) {
var sum = 0f
for (b in 0 until cols / BLOCK) {
weight.storage.copyInto(block, 0, (r.toLong() * (cols / BLOCK) + b) * BYTES_PER_BLOCK, BYTES_PER_BLOCK)
val signs = getInt(block, 4)
var acc = 0f
for (i in 0 until BLOCK) {
val v = x[b * BLOCK + i]
acc += if ((signs ushr i) and 1 == 1) v else -v
}
sum += acc * Float.fromBits(getInt(block, 0))
}
out.set(0, r, value = sum)
}
}
}
/** Register the kernel under the key of the operand pair it serves. */
fun installKernel(activation: TensorView, weight: TensorView) {
// Let the library install its own kernels first: a table that is not empty is taken as
// "someone bootstrapped", and the built-in packs would then never be installed.
KernelDispatch.ensureInstalled()
val key = KernelKey.matmul(activation, weight)
if (KernelDispatch.find(key) == null) KernelDispatch.register(Sign1MatmulKernel(key))
}
The same KernelDispatch.matmul call then selects it:
val x = FloatArray(cols) { i -> ((i % 5) - 2) / 2f }
val activation = TensorView.dense(Storage.Heap.wrap(x), Shape(1, cols), FP32)
// Before the kernel is registered: the decoding reference kernel serves the pair.
val before = RecordingTraceSink()
val outBefore = TensorView.dense(Storage.Heap.floats(rows), Shape(1, rows), FP32)
KernelDispatch.matmul(activation, weight, outBefore, Scope.Ambient, before)
// After: the same call selects the kernel by the key of the two views.
installKernel(activation, weight)
val after = RecordingTraceSink()
val outAfter = TensorView.dense(Storage.Heap.floats(rows), Shape(1, rows), FP32)
KernelDispatch.matmul(activation, weight, outAfter, Scope.Ambient, after)
The trace shows the reference kernel for the first call and sample-SIGN1 for the second, and
both give the same product.
Limits of an encoding outside the library
-
The key is per byte count. Two
Opaquevalues are equal only when name and byte count are equal, so a kernel key for anOpaqueencoding matches weights of one size. Register the kernel for each weight size you use, asinstallKernelabove does for one. -
Call
KernelDispatch.ensureInstalled()before you register. The dispatcher installs the built-in kernels on first use only when its table is empty. -
Loaders do not know the format. A GGUF or SafeTensors reader returns a view only for the encodings it maps. For your format, read the raw bytes (
loadTensorData) and build the view yourself. -
No
requantizeTo. It needs a quantizer, and the library has one forQ8_0,Q4_0andBITNET_PLANESonly. Encode your bytes yourself, as above.
When the format should load from model files, take part in memory planning or get kernels on
every platform, it belongs in the library: a new TensorEncoding member with a BlockSpec, a
decoder in StorageBlockDecoder, and kernels in a kernel pack. See
Packed weight layout and
Kernel SPI and the selection algorithm.