Load quantized weights from a GGUF file
You have a block-quantized GGUF checkpoint and want to run it without inflating it to dense floats. ClikaRT loads the file as-is: io::load_gguf returns the tensors plus the file's metadata, quantized entries keep their packed bytes, and nn::QLinearWoQ runs the matmul off the packed form. The checkpoint's on-disk footprint is its in-memory footprint.
The programs below use SmolLM2-135M-Instruct (Apache-2.0, 145 MB in Q8_0), small enough to download in a minute. Any .gguf file works; nothing here depends on the architecture.
curl -LO "https://huggingface.co/bartowski/SmolLM2-135M-Instruct-GGUF/resolve/main/SmolLM2-135M-Instruct-Q8_0.gguf"
Each program is a complete main.cpp; build them like any bundle consumer (tutorial part 1 has the four-line CMake project). The C samples abbreviate the api-table bootstrap that part 1 shows in full.
Load the file and read its metadata
io::load_gguf returns a GgufModel: the weights as a NamedTensors map and the file's metadata as one Json object. The loader takes the target device (CPU by default), and the tensor payloads are mmap-backed, so loading is cheap.
- C++
- C
- Python
- Kotlin
- Go
- Rust
#include <cstdio>
#include "ClikaRT/clika_rt.h"
namespace io = ClikaRT::io;
int main() {
const io::GgufModel model = io::load_gguf("SmolLM2-135M-Instruct-Q8_0.gguf");
std::printf("tensors %zu\n", model.tensors.size());
std::printf("metadata %zu keys\n", model.metadata.size());
for (const char* key : {"general.architecture", "general.size_label",
"llama.block_count", "llama.embedding_length"}) {
std::printf(" %-24s = %s\n", key, model.metadata.at(key).dump(0).c_str());
}
return 0;
}
#include <stdio.h>
#include <string.h>
#include "clika_rt/clika_rt_core.h"
/* api, check(): the bootstrap from tutorial part 1 (dlopen + clika_rt_get_api). */
extern const clika_rt_api* api;
extern void check(clika_rt_error* e, const char* where);
int main(void) {
const char* path = "SmolLM2-135M-Instruct-Q8_0.gguf";
const clika_rt_stream_or_device dflt = {CLIKA_RT_STREAM_OR_DEVICE_DEFAULT};
clika_rt_gguf_checkpoint* ckpt = NULL;
check(api->load_gguf_to_gguf_checkpoint(path, strlen(path), dflt, 0, &ckpt), "load_gguf");
clika_rt_tensors_container* tensors = NULL;
check(api->gguf_checkpoint_take_tensors(ckpt, &tensors), "take_tensors");
printf("tensors %zu\n", api->tensors_container_size(tensors));
/* The metadata arrives as ONE JSON document (sized-string protocol). */
static char meta[65536];
size_t mlen = sizeof meta;
check(api->gguf_checkpoint_metadata(ckpt, meta, &mlen), "metadata");
printf("metadata document: %zu bytes; keys such as general.architecture,\n"
"general.size_label, llama.block_count ride inside it\n", mlen);
api->tensors_container_free(tensors);
api->gguf_checkpoint_free(ckpt);
return 0;
}
import json
import clika_runtime as crt
def main() -> None:
tensors, metadata_json = crt.io.load_gguf("SmolLM2-135M-Instruct-Q8_0.gguf")
metadata = json.loads(metadata_json)
print(f"tensors {len(tensors)}")
print(f"metadata {len(metadata)} keys")
for key in ("general.architecture", "general.size_label",
"llama.block_count", "llama.embedding_length"):
print(f" {key:<24} = {json.dumps(metadata[key])}")
if __name__ == "__main__":
main()
import io.clika.runtime.ClikaRtGen
fun main() {
ClikaRtGen.load()
val ckpt = ClikaRtGen.loadGgufToGgufCheckpoint(
"SmolLM2-135M-Instruct-Q8_0.gguf",
ClikaRtGen.STREAM_OR_DEVICE_DEFAULT, 0, 0, 0L, false)
val tensors = ClikaRtGen.ggufCheckpointTakeTensors(ckpt)
println("tensors ${ClikaRtGen.tensorsContainerSize(tensors)}")
// The metadata arrives as ONE JSON document; keys such as
// general.architecture and llama.block_count ride inside it.
val metadata = ClikaRtGen.ggufCheckpointMetadata(ckpt)
println("metadata document: ${metadata.length} bytes")
ClikaRtGen.tensorsContainerFree(tensors)
ClikaRtGen.ggufCheckpointFree(ckpt)
}
package main
import (
"encoding/json"
"fmt"
"log"
"github.com/Clika/clika_runtime/bindings/go/clikart"
)
func must[T any](v T, err error) T {
if err != nil {
log.Fatal(err)
}
return v
}
func main() {
api := must(clikart.Load("libClikaRT.so"))
ckpt := must(api.LoadGgufToGgufCheckpoint("SmolLM2-135M-Instruct-Q8_0.gguf",
clikart.StreamOrDevice{}, false))
tensors := must(api.GgufCheckpointTakeTensors(ckpt))
fmt.Printf("tensors %d\n", api.TensorsContainerSize(tensors))
// The metadata arrives as ONE JSON document.
var metadata map[string]any
if err := json.Unmarshal([]byte(must(api.GgufCheckpointMetadata(ckpt))), &metadata); err != nil {
log.Fatal(err)
}
fmt.Printf("metadata %d keys\n", len(metadata))
for _, key := range []string{"general.architecture", "general.size_label",
"llama.block_count", "llama.embedding_length"} {
out := must(json.Marshal(metadata[key]))
fmt.Printf(" %-24s = %s\n", key, out)
}
}
use clika_rt::{sys, Api};
fn default_placement() -> sys::clika_rt_stream_or_device {
sys::clika_rt_stream_or_device {
kind: sys::clika_rt_stream_or_device_kind_CLIKA_RT_STREAM_OR_DEVICE_DEFAULT as i32,
device: sys::clika_rt_device { api: 0, index: 0 },
stream: std::ptr::null_mut(),
}
}
fn main() -> clika_rt::Result<()> {
let api = Api::load("libClikaRT.so")?;
let ckpt = api.f_load_gguf_to_gguf_checkpoint(
"SmolLM2-135M-Instruct-Q8_0.gguf", default_placement(), false)?;
let tensors = api.f_gguf_checkpoint_take_tensors(&ckpt)?;
println!("tensors {}", api.tensors_container_size(&tensors));
// The metadata arrives as ONE JSON document; keys such as
// general.architecture and llama.block_count ride inside it.
let metadata = api.f_gguf_checkpoint_metadata(&ckpt)?;
println!("metadata document: {} bytes", metadata.len());
Ok(())
}
tensors 272
metadata 37 keys
general.architecture = "llama"
general.size_label = "135M"
llama.block_count = 30
llama.embedding_length = 576
The metadata carries everything the file knows about itself: architecture, hyperparameters, tokenizer configuration (tokenizer.chat_template included; the chat-template guide picks that up). at(key) raises ClikaRT::Error on a missing key; probe with contains when a key is optional.
What a quantized weight is in memory
A quantized entry rides a plain Tensor whose element data is the packed block stream, exactly as it sits in the file. is_quantized() separates those from the dense entries (norms and embeddings stay floating point in most files). quantized_view names what the payload is: the packed bytes, the scheme, and the logical element shape they encode.
- C++
- C
- Python
- Kotlin
- Go
- Rust
#include <cstdio>
#include <string_view>
#include "ClikaRT/clika_rt.h"
using ClikaRT::QTensor;
using ClikaRT::Tensor;
namespace io = ClikaRT::io;
int main() {
const io::GgufModel model = io::load_gguf("SmolLM2-135M-Instruct-Q8_0.gguf");
int quantized = 0, dense = 0;
model.tensors.for_each([&](std::string_view, const Tensor& t) {
t.is_quantized() ? ++quantized : ++dense;
});
std::printf("%d quantized, %d dense\n", quantized, dense);
const QTensor q = ClikaRT::quantized_view(model.tensors.get("blk.0.ffn_up.weight"));
std::printf("scheme %s\n", q.scheme.c_str());
std::printf("logical [%lld, %lld]\n",
(long long)q.logical_shape[0], (long long)q.logical_shape[1]);
std::printf("payload %s\n", q.payload.to_string().c_str());
const Tensor norm = model.tensors.get("blk.0.attn_norm.weight");
std::printf("dense %s\n", norm.to_string().c_str());
return 0;
}
#include <stdio.h>
#include <string.h>
#include "clika_rt/clika_rt_core.h"
extern const clika_rt_api* api;
extern void check(clika_rt_error* e, const char* where);
int main(void) {
const char* path = "SmolLM2-135M-Instruct-Q8_0.gguf";
const clika_rt_stream_or_device dflt = {CLIKA_RT_STREAM_OR_DEVICE_DEFAULT};
clika_rt_gguf_checkpoint* ckpt = NULL;
check(api->load_gguf_to_gguf_checkpoint(path, strlen(path), dflt, 0, &ckpt), "load_gguf");
clika_rt_tensors_container* tensors = NULL;
check(api->gguf_checkpoint_take_tensors(ckpt, &tensors), "take_tensors");
clika_rt_string_list* names = api->tensors_container_names(tensors);
int quantized = 0, dense = 0;
for (size_t i = 0; i < api->string_list_count(names); ++i) {
char name[512];
size_t nlen = sizeof name;
api->string_list_get_at(names, i, name, &nlen);
clika_rt_tensor* t = NULL;
check(api->tensors_container_get(tensors, name, strlen(name), &t), "get");
api->tensor_is_quantized(t) ? ++quantized : ++dense;
api->tensor_release(t);
}
api->string_list_free(names);
printf("%d quantized, %d dense\n", quantized, dense);
clika_rt_tensor* w = NULL;
check(api->tensors_container_get(tensors, "blk.0.ffn_up.weight", 19, &w), "get");
char buf[512];
size_t blen = sizeof buf;
api->tensor_to_string(w, buf, &blen);
printf("packed %s\n", buf); /* the payload bytes, as they sit in the file */
/* The scheme and logical-shape readers are C++ QTensor fields; this
* surface reads a packed entry by viewing and dequantizing it (both
* calls consume their operand). */
clika_rt_qtensor* q = NULL;
check(api->quantized_view(w, &q), "quantized_view");
clika_rt_tensor* logical = NULL;
check(api->op_dequantize(q, CLIKA_RT_DATA_TYPE_UNDEFINED, &logical), "dequantize");
blen = sizeof buf;
api->tensor_to_string(logical, buf, &blen);
printf("logical %s\n", buf);
clika_rt_tensor* norm = NULL;
check(api->tensors_container_get(tensors, "blk.0.attn_norm.weight", 22, &norm), "get");
blen = sizeof buf;
api->tensor_to_string(norm, buf, &blen);
printf("dense %s\n", buf);
api->tensor_release(norm);
api->tensor_release(logical);
api->tensors_container_free(tensors);
api->gguf_checkpoint_free(ckpt);
return 0;
}
import clika_runtime as crt
def main() -> None:
tensors, _ = crt.io.load_gguf("SmolLM2-135M-Instruct-Q8_0.gguf")
quantized = sum(1 for t in tensors.values() if t.is_quantized)
print(f"{quantized} quantized, {len(tensors) - quantized} dense")
q = crt.quantized_view(tensors["blk.0.ffn_up.weight"])
print(f"scheme {q.scheme}")
print(f"logical [{q.logical_shape[0]}, {q.logical_shape[1]}]")
print(f"payload {q.payload}")
print(f"dense {tensors['blk.0.attn_norm.weight']}")
if __name__ == "__main__":
main()
import io.clika.runtime.ClikaRtGen
fun main() {
ClikaRtGen.load()
val ckpt = ClikaRtGen.loadGgufToGgufCheckpoint(
"SmolLM2-135M-Instruct-Q8_0.gguf",
ClikaRtGen.STREAM_OR_DEVICE_DEFAULT, 0, 0, 0L, false)
val tensors = ClikaRtGen.ggufCheckpointTakeTensors(ckpt)
val names = ClikaRtGen.tensorsContainerNames(tensors)
var quantized = 0
var dense = 0
for (i in 0 until ClikaRtGen.stringListCount(names)) {
val t = ClikaRtGen.tensorsContainerGet(tensors,
ClikaRtGen.stringListGetAt(names, i))
if (ClikaRtGen.tensorIsQuantized(t)) quantized++ else dense++
ClikaRtGen.tensorRelease(t)
}
ClikaRtGen.stringListFree(names)
println("$quantized quantized, $dense dense")
val w = ClikaRtGen.tensorsContainerGet(tensors, "blk.0.ffn_up.weight")
println("packed ${ClikaRtGen.tensorToString(w)}")
// The scheme and logical-shape readers are C++ QTensor fields; this
// surface reads a packed entry by viewing and dequantizing it (both
// calls consume their operand).
val logical = ClikaRtGen.opDequantize(ClikaRtGen.quantizedView(w),
ClikaRtGen.DATA_TYPE_UNDEFINED)
println("logical ${ClikaRtGen.tensorToString(logical)}")
val norm = ClikaRtGen.tensorsContainerGet(tensors, "blk.0.attn_norm.weight")
println("dense ${ClikaRtGen.tensorToString(norm)}")
ClikaRtGen.tensorRelease(norm)
ClikaRtGen.tensorRelease(logical)
ClikaRtGen.tensorsContainerFree(tensors)
ClikaRtGen.ggufCheckpointFree(ckpt)
}
package main
import (
"fmt"
"log"
"github.com/Clika/clika_runtime/bindings/go/clikart"
)
func must[T any](v T, err error) T {
if err != nil {
log.Fatal(err)
}
return v
}
func main() {
api := must(clikart.Load("libClikaRT.so"))
ckpt := must(api.LoadGgufToGgufCheckpoint("SmolLM2-135M-Instruct-Q8_0.gguf",
clikart.StreamOrDevice{}, false))
tensors := must(api.GgufCheckpointTakeTensors(ckpt))
quantized, dense := 0, 0
names := api.TensorsContainerNames(tensors)
for i := uint(0); i < api.StringListCount(names); i++ {
t := must(api.TensorsContainerGet(tensors, must(api.StringListGetAt(names, i))))
if api.TensorIsQuantized(t) {
quantized++
} else {
dense++
}
t.Release()
}
fmt.Printf("%d quantized, %d dense\n", quantized, dense)
w := must(api.TensorsContainerGet(tensors, "blk.0.ffn_up.weight"))
fmt.Printf("packed %s\n", w) // the payload bytes, as they sit in the file
// The scheme and logical-shape readers are C++ QTensor fields; this
// surface reads a packed entry by viewing and dequantizing it.
logical := must(api.OpDequantize(must(api.QuantizedView(w)), clikart.DataTypeUndefined))
fmt.Printf("logical %s\n", logical)
norm := must(api.TensorsContainerGet(tensors, "blk.0.attn_norm.weight"))
fmt.Printf("dense %s\n", norm)
}
use clika_rt::{sys, Api};
fn default_placement() -> sys::clika_rt_stream_or_device {
sys::clika_rt_stream_or_device {
kind: sys::clika_rt_stream_or_device_kind_CLIKA_RT_STREAM_OR_DEVICE_DEFAULT as i32,
device: sys::clika_rt_device { api: 0, index: 0 },
stream: std::ptr::null_mut(),
}
}
fn main() -> clika_rt::Result<()> {
let api = Api::load("libClikaRT.so")?;
let ckpt = api.f_load_gguf_to_gguf_checkpoint(
"SmolLM2-135M-Instruct-Q8_0.gguf", default_placement(), false)?;
let tensors = api.f_gguf_checkpoint_take_tensors(&ckpt)?;
let names = api.tensors_container_names(&tensors).expect("names");
let mut quantized = 0;
let mut dense = 0;
for i in 0..api.string_list_count(&names) {
let t = api.f_tensors_container_get(&tensors, &api.f_string_list_get_at(&names, i)?)?;
if api.tensor_is_quantized(&t) { quantized += 1 } else { dense += 1 }
}
println!("{quantized} quantized, {dense} dense");
let w = api.f_tensors_container_get(&tensors, "blk.0.ffn_up.weight")?;
println!("packed {}", api.tensor_to_string(&w)?);
// The scheme and logical-shape readers are C++ QTensor fields; this
// surface reads a packed entry by viewing and dequantizing it (both
// calls consume their operand).
let logical = api.f_op_dequantize(
api.f_quantized_view(w)?,
sys::clika_rt_data_type_CLIKA_RT_DATA_TYPE_UNDEFINED)?;
println!("logical {}", api.tensor_to_string(&logical)?);
let norm = api.f_tensors_container_get(&tensors, "blk.0.attn_norm.weight")?;
println!("dense {}", api.tensor_to_string(&norm)?);
Ok(())
}
211 quantized, 61 dense
scheme GGUF_Q8_0
logical [576, 1536]
payload Tensor(shape=[1536, 612], dtype=UInt8, device=CPU, numel=940032, quantized=true, mmap=checkpoint:SmolLM2-135M-Instruct-Q8_0.gguf+33749344, data=[232, 27, 234, 24, 66, 230, ...])
dense Tensor(shape=[576], dtype=Float32, device=CPU, numel=576, mmap=checkpoint:SmolLM2-135M-Instruct-Q8_0.gguf+31866976, data=[0.01398, 0.0238, -0.01978, -0.03027, -0.01965, -0.03516, ...])
Two facts to keep. The logical shape is [in_features, out_features], the row-contiguous dimension first; that is the orientation every quantized consumer below expects. The payload is UInt8 [rows, row_bytes]: for Q8_0, each row of 576 elements packs into blocks of 32 (one fp16 scale plus 32 int8 codes each), 34 bytes per block.
Serve it packed with QLinearWoQ
nn::QLinearWoQ is a Linear over a quantized weight. The weight stays packed for the module's lifetime; the first forward reshapes the payload once into the backend's kernel layout, and every later call runs the quantized-weight matmul off that. Nothing is ever materialized dense.
The lifecycle is the same as every weight-bearing nn module: make(in, out) declares the slots, set_weights binds the loaded tensor, forward runs.
- C++
- C
- Python
- Kotlin
- Go
- Rust
#include <cstdio>
#include <memory>
#include "ClikaRT/clika_rt.h"
using ClikaRT::DataType;
using ClikaRT::nn::QLinearWoQ;
using ClikaRT::QTensor;
using ClikaRT::Tensor;
namespace io = ClikaRT::io;
int main() {
const io::GgufModel model = io::load_gguf("SmolLM2-135M-Instruct-Q8_0.gguf");
const QTensor w = ClikaRT::quantized_view(model.tensors.get("blk.0.ffn_up.weight"));
const std::int64_t in = w.logical_shape[0], out = w.logical_shape[1];
const std::shared_ptr<QLinearWoQ> ffn_up = QLinearWoQ::make(in, out);
ffn_up->set_weights(w);
const Tensor x = Tensor::full({1, in}, 0.01, DataType::Float32);
const Tensor y = ffn_up->forward(x); // first call packs, later calls reuse
std::printf("y = %s\n", y.to_string().c_str());
return 0;
}
#include <stdio.h>
#include <string.h>
#include "clika_rt/clika_rt_core.h"
extern const clika_rt_api* api;
extern void check(clika_rt_error* e, const char* where);
int main(void) {
const char* path = "SmolLM2-135M-Instruct-Q8_0.gguf";
const clika_rt_stream_or_device dflt = {CLIKA_RT_STREAM_OR_DEVICE_DEFAULT};
clika_rt_gguf_checkpoint* ckpt = NULL;
check(api->load_gguf_to_gguf_checkpoint(path, strlen(path), dflt, 0, &ckpt), "load_gguf");
clika_rt_tensors_container* tensors = NULL;
check(api->gguf_checkpoint_take_tensors(ckpt, &tensors), "take_tensors");
clika_rt_tensor* w = NULL;
check(api->tensors_container_get(tensors, "blk.0.ffn_up.weight", 19, &w), "get");
/* No logical-shape reader at this surface: probe the dims once by
* dequantizing a retained handle ([out, in] comes back). */
api->tensor_retain(w);
clika_rt_qtensor* qprobe = NULL;
check(api->quantized_view(w, &qprobe), "view");
clika_rt_tensor* probe = NULL;
check(api->op_dequantize(qprobe, CLIKA_RT_DATA_TYPE_UNDEFINED, &probe), "dequantize");
int64_t oi[2];
size_t ocount = 2;
check(api->tensor_shape(probe, oi, &ocount), "shape");
const int64_t in = oi[1];
api->tensor_release(probe);
/* The C surface serves the packed weight through the op directly; the
* packed-once caching the module description promises rides inside. */
clika_rt_qtensor* q = NULL;
check(api->quantized_view(w, &q), "quantized_view");
clika_rt_tensor* x = NULL;
check(api->tensor_full((const int64_t[]){1, in}, 2, 0.01,
CLIKA_RT_DATA_TYPE_FLOAT32, dflt, dflt, &x), "full");
/* The GGUF weight is [in, out]; qmatmul_woq contracts x [1, in]
* against it directly. (qlinear_woq expects the Linear [out, in]
* layout instead - the orientation trap below.) Consumes x and the
* packed view. */
clika_rt_tensor* y = NULL;
check(api->op_qmatmul_woq(x, q, NULL, 0, CLIKA_RT_ACTIVATION_IDENTITY,
0, 0, CLIKA_RT_QCOMPUTE_MODE_EXACT_FP, &y), "qmatmul_woq");
char buf[512];
size_t blen = sizeof buf;
api->tensor_to_string(y, buf, &blen);
printf("y = %s\n", buf);
api->tensor_release(y);
api->tensors_container_free(tensors);
api->gguf_checkpoint_free(ckpt);
return 0;
}
import clika_runtime as crt
import clika_runtime.nn.functional as F
def main() -> None:
tensors, _ = crt.io.load_gguf("SmolLM2-135M-Instruct-Q8_0.gguf")
q = crt.quantized_view(tensors["blk.0.ffn_up.weight"])
in_f, out_f = q.logical_shape
# Dequantize to the scheme's float target and run dense math on it.
# Serving the matmul off the PACKED form (no dense copy at rest) is
# done through the quantized modules of the C++ API; the C++ tab
# shows it.
w = crt.dequantize(q)
x = crt.full((1, in_f), 0.01)
y = F.linear(x, w)
print(f"y = {y}")
if __name__ == "__main__":
main()
import io.clika.runtime.ClikaRtGen
fun main() {
ClikaRtGen.load()
val ckpt = ClikaRtGen.loadGgufToGgufCheckpoint(
"SmolLM2-135M-Instruct-Q8_0.gguf",
ClikaRtGen.STREAM_OR_DEVICE_DEFAULT, 0, 0, 0L, false)
val tensors = ClikaRtGen.ggufCheckpointTakeTensors(ckpt)
val w = ClikaRtGen.tensorsContainerGet(tensors, "blk.0.ffn_up.weight")
// No logical-shape reader at this surface: probe the dims once by
// dequantizing a retained handle ([out, in] comes back).
ClikaRtGen.tensorRetain(w)
val probe = ClikaRtGen.opDequantize(ClikaRtGen.quantizedView(w),
ClikaRtGen.DATA_TYPE_UNDEFINED)
val inF = ClikaRtGen.tensorShape(probe)[1]
ClikaRtGen.tensorRelease(probe)
// The generated surface serves the packed weight through the op directly.
val x = ClikaRtGen.tensorFull(longArrayOf(1, inF), 0.01,
ClikaRtGen.DATA_TYPE_FLOAT32,
ClikaRtGen.STREAM_OR_DEVICE_DEFAULT, 0, 0, 0L,
ClikaRtGen.STREAM_OR_DEVICE_DEFAULT, 0, 0, 0L)
// The GGUF weight is [in, out]; qmatmul_woq contracts x [1, in] against
// it directly (qlinear_woq expects the Linear [out, in] layout instead).
val y = ClikaRtGen.opQmatmulWoq(x, ClikaRtGen.quantizedView(w), 0L, false,
ClikaRtGen.ACTIVATION_IDENTITY, false, false,
ClikaRtGen.QCOMPUTE_MODE_EXACT_FP)
println("y = ${ClikaRtGen.tensorToString(y)}")
ClikaRtGen.tensorRelease(y)
ClikaRtGen.tensorsContainerFree(tensors)
ClikaRtGen.ggufCheckpointFree(ckpt)
}
package main
import (
"fmt"
"log"
"github.com/Clika/clika_runtime/bindings/go/clikart"
)
func must[T any](v T, err error) T {
if err != nil {
log.Fatal(err)
}
return v
}
func main() {
api := must(clikart.Load("libClikaRT.so"))
ckpt := must(api.LoadGgufToGgufCheckpoint("SmolLM2-135M-Instruct-Q8_0.gguf",
clikart.StreamOrDevice{}, false))
tensors := must(api.GgufCheckpointTakeTensors(ckpt))
w := must(api.TensorsContainerGet(tensors, "blk.0.ffn_up.weight"))
q := must(api.QuantizedView(w))
// No logical-shape reader at this surface: probe the dims once by
// dequantizing ([out, in] comes back; the wrappers are non-consuming).
probe := must(api.OpDequantize(q, clikart.DataTypeUndefined))
shape := must(api.TensorShape(probe))
out, in := shape[0], shape[1]
// The Go surface serves the packed weight through the op directly.
x := must(api.TensorFull([]int64{1, in}, 0.01, clikart.Float32))
// The GGUF weight is [in, out]; qmatmul_woq contracts x [1, in] against
// it directly (qlinear_woq expects the Linear [out, in] layout instead).
// The generated wrappers carry no absent-optional spelling yet, so the
// no-bias case passes an explicit zero bias.
bias := must(api.TensorFull([]int64{out}, 0.0, clikart.Float32))
y := must(api.OpQmatmulWoq(x, q, bias, false, clikart.ActivationIdentity,
false, false, clikart.QcomputeModeExactFp))
fmt.Printf("y = %s\n", y)
}
use clika_rt::{sys, Api};
const F32: sys::clika_rt_data_type = sys::clika_rt_data_type_CLIKA_RT_DATA_TYPE_FLOAT32;
const UNDEF: sys::clika_rt_data_type = sys::clika_rt_data_type_CLIKA_RT_DATA_TYPE_UNDEFINED;
const IDENTITY: sys::clika_rt_activation = sys::clika_rt_activation_CLIKA_RT_ACTIVATION_IDENTITY;
const EXACT_FP: sys::clika_rt_qcompute_mode =
sys::clika_rt_qcompute_mode_CLIKA_RT_QCOMPUTE_MODE_EXACT_FP;
fn default_placement() -> sys::clika_rt_stream_or_device {
sys::clika_rt_stream_or_device {
kind: sys::clika_rt_stream_or_device_kind_CLIKA_RT_STREAM_OR_DEVICE_DEFAULT as i32,
device: sys::clika_rt_device { api: 0, index: 0 },
stream: std::ptr::null_mut(),
}
}
fn main() -> clika_rt::Result<()> {
let api = Api::load("libClikaRT.so")?;
let ckpt = api.f_load_gguf_to_gguf_checkpoint(
"SmolLM2-135M-Instruct-Q8_0.gguf", default_placement(), false)?;
let tensors = api.f_gguf_checkpoint_take_tensors(&ckpt)?;
let w = api.f_tensors_container_get(&tensors, "blk.0.ffn_up.weight")?;
// No logical-shape reader at this surface: probe the dims once by
// dequantizing a shallow clone ([out, in] comes back).
let probe = api.f_op_dequantize(api.f_quantized_view(w.shallow_clone())?, UNDEF)?;
let in_f = api.tensor_shape(&probe)[1];
// The Rust surface serves the packed weight through the op directly.
let x = api.tensor_full(&[1, in_f], 0.01, F32)?;
// The GGUF weight is [in, out]; qmatmul_woq contracts x [1, in] against
// it directly (qlinear_woq expects the Linear [out, in] layout instead).
let y = api.f_op_qmatmul_woq(x, api.f_quantized_view(w)?, api.absent(),
false, IDENTITY, false, false, EXACT_FP)?;
println!("y = {}", api.tensor_to_string(&y)?);
Ok(())
}
y = Tensor(shape=[1, 1536], dtype=Float32, device=CPU, numel=1536, data=[0.03397, -0.02917, 0.0793, 0.03382, -0.02785, 0.005078, ...])
One orientation trap: QLinearWoQ consumes the [in, out] logical shape that load_gguf produces, while dense Linear takes the HuggingFace [out, in] layout. Bind the GGUF entry as-is; do not transpose. Moving the module (ffn_up->to(...)) re-packs the weight on the target device, and a dtype move is refused: the weight stays quantized at rest.
Inspect a weight by dequantizing
ops::dequantize decodes a packed weight into a dense tensor, [out, in] row-major. It is the inspection and tooling path, not the serving path; use it to eyeball values or to check a conversion. The program decodes the same weight, checks the packed forward against the dense one, and prints what staying packed saves.
- C++
- C
- Python
- Kotlin
- Go
- Rust
#include <cmath>
#include <cstdio>
#include <memory>
#include <vector>
#include "ClikaRT/clika_rt.h"
using ClikaRT::DataType;
using ClikaRT::nn::QLinearWoQ;
using ClikaRT::QTensor;
using ClikaRT::Tensor;
namespace io = ClikaRT::io;
namespace ops = ClikaRT::ops;
int main() {
const io::GgufModel model = io::load_gguf("SmolLM2-135M-Instruct-Q8_0.gguf");
const QTensor w = ClikaRT::quantized_view(model.tensors.get("blk.0.ffn_up.weight"));
const std::int64_t in = w.logical_shape[0], out = w.logical_shape[1];
const Tensor dense = ops::dequantize(w); // [out, in], the scheme's float target
std::printf("dense = %s\n", dense.to_string().c_str());
// The packed path and the dense path compute the same values.
const std::shared_ptr<QLinearWoQ> packed = QLinearWoQ::make(in, out);
packed->set_weights(w);
const Tensor x = Tensor::full({1, in}, 0.01, DataType::Float32);
const std::vector<float> y = packed->forward(x).reshape({-1}).item_as_vec<float>();
const std::vector<float> yr = ops::linear(x, dense).reshape({-1}).item_as_vec<float>();
float max_diff = 0.0F;
for (std::size_t i = 0; i < y.size(); ++i)
max_diff = std::max(max_diff, std::fabs(y[i] - yr[i]));
std::printf("max |packed - dense| over %zu outputs: %g\n", y.size(), max_diff);
std::printf("bytes: dense %lld, packed %lld (%.2fx)\n",
(long long)(dense.numel() * 4), (long long)w.payload.numel(),
(double)(dense.numel() * 4) / (double)w.payload.numel());
return 0;
}
#include <math.h>
#include <stdio.h>
#include <string.h>
#include "clika_rt/clika_rt_core.h"
extern const clika_rt_api* api;
extern void check(clika_rt_error* e, const char* where);
int main(void) {
const char* path = "SmolLM2-135M-Instruct-Q8_0.gguf";
const clika_rt_stream_or_device dflt = {CLIKA_RT_STREAM_OR_DEVICE_DEFAULT};
clika_rt_gguf_checkpoint* ckpt = NULL;
check(api->load_gguf_to_gguf_checkpoint(path, strlen(path), dflt, 0, &ckpt), "load_gguf");
clika_rt_tensors_container* tensors = NULL;
check(api->gguf_checkpoint_take_tensors(ckpt, &tensors), "take_tensors");
clika_rt_tensor* w = NULL;
check(api->tensors_container_get(tensors, "blk.0.ffn_up.weight", 19, &w), "get");
/* Two consumers of the packed entry (the dequantize and the packed
* matmul), plus the byte count reads it: retain twice. */
api->tensor_retain(w);
api->tensor_retain(w);
clika_rt_qtensor* qd = NULL;
check(api->quantized_view(w, &qd), "view");
clika_rt_tensor* dense = NULL; /* [out, in], the scheme's float target */
check(api->op_dequantize(qd, CLIKA_RT_DATA_TYPE_UNDEFINED, &dense), "dequantize");
char buf[512];
size_t blen = sizeof buf;
api->tensor_to_string(dense, buf, &blen);
printf("dense = %s\n", buf);
int64_t oi[2];
size_t ocount = 2;
check(api->tensor_shape(dense, oi, &ocount), "shape");
const int64_t out = oi[0], in = oi[1];
/* The packed path and the dense path compute the same values. */
clika_rt_tensor* x = NULL;
check(api->tensor_full((const int64_t[]){1, in}, 2, 0.01,
CLIKA_RT_DATA_TYPE_FLOAT32, dflt, dflt, &x), "full");
api->tensor_retain(x);
clika_rt_qtensor* qw = NULL;
check(api->quantized_view(w, &qw), "view");
clika_rt_tensor* y = NULL; /* GGUF layout: qmatmul_woq, not qlinear_woq */
check(api->op_qmatmul_woq(x, qw, NULL, 0, CLIKA_RT_ACTIVATION_IDENTITY,
0, 0, CLIKA_RT_QCOMPUTE_MODE_EXACT_FP, &y), "qmatmul_woq");
api->tensor_retain(dense);
clika_rt_tensor* yr = NULL;
check(api->op_linear(x, dense, NULL, 0, CLIKA_RT_ACTIVATION_IDENTITY,
0.0, 0.0, &yr), "linear");
const void* py = NULL;
const void* pyr = NULL;
check(api->tensor_const_data_ptr(y, &py), "data_ptr");
check(api->tensor_const_data_ptr(yr, &pyr), "data_ptr");
float max_diff = 0.0F;
for (int64_t i = 0; i < out; ++i) {
const float d = fabsf(((const float*)py)[i] - ((const float*)pyr)[i]);
if (d > max_diff) max_diff = d;
}
printf("max |packed - dense| over %lld outputs: %g\n", (long long)out, max_diff);
/* The packed entry IS the payload byte stream: numel(w) counts bytes. */
int64_t dense_numel = 0, packed_bytes = 0;
check(api->tensor_numel(dense, &dense_numel), "numel");
check(api->tensor_numel(w, &packed_bytes), "numel");
printf("bytes: dense %lld, packed %lld (%.2fx)\n",
(long long)(dense_numel * 4), (long long)packed_bytes,
(double)(dense_numel * 4) / (double)packed_bytes);
api->tensor_release(yr);
api->tensor_release(y);
api->tensor_release(dense);
api->tensor_release(w);
api->tensors_container_free(tensors);
api->gguf_checkpoint_free(ckpt);
return 0;
}
import clika_runtime as crt
def main() -> None:
tensors, _ = crt.io.load_gguf("SmolLM2-135M-Instruct-Q8_0.gguf")
q = crt.quantized_view(tensors["blk.0.ffn_up.weight"])
dense = crt.dequantize(q) # [out, in], the scheme's float target
print(f"dense = {dense}")
# The packed payload is the checkpoint's own byte stream; inflating it
# to dense floats shows what staying packed saves. (The packed-vs-dense
# VALUE check runs where the packed matmul lives: the C++ tab.)
dense_bytes = dense.numpy().size * 4
packed_bytes = q.payload.numpy().size
print(f"bytes: dense {dense_bytes}, packed {packed_bytes} "
f"({dense_bytes / packed_bytes:.2f}x)")
if __name__ == "__main__":
main()
import io.clika.runtime.ClikaRtGen
fun main() {
ClikaRtGen.load()
val ckpt = ClikaRtGen.loadGgufToGgufCheckpoint(
"SmolLM2-135M-Instruct-Q8_0.gguf",
ClikaRtGen.STREAM_OR_DEVICE_DEFAULT, 0, 0, 0L, false)
val tensors = ClikaRtGen.ggufCheckpointTakeTensors(ckpt)
val w = ClikaRtGen.tensorsContainerGet(tensors, "blk.0.ffn_up.weight")
// Two consumers of the packed entry (the dequantize and the packed
// matmul), plus the byte count reads it: retain twice.
ClikaRtGen.tensorRetain(w)
ClikaRtGen.tensorRetain(w)
val dense = ClikaRtGen.opDequantize(ClikaRtGen.quantizedView(w),
ClikaRtGen.DATA_TYPE_UNDEFINED) // [out, in]
println("dense = ${ClikaRtGen.tensorToString(dense)}")
val inF = ClikaRtGen.tensorShape(dense)[1]
// The packed path and the dense path compute the same values; the two
// summaries print the same leading data. (The numeric max-diff runs
// where a data pointer is readable: the C, C++ and Go tabs.)
val x = ClikaRtGen.tensorFull(longArrayOf(1, inF), 0.01,
ClikaRtGen.DATA_TYPE_FLOAT32,
ClikaRtGen.STREAM_OR_DEVICE_DEFAULT, 0, 0, 0L,
ClikaRtGen.STREAM_OR_DEVICE_DEFAULT, 0, 0, 0L)
ClikaRtGen.tensorRetain(x)
val y = ClikaRtGen.opQmatmulWoq(x, ClikaRtGen.quantizedView(w), 0L, false,
ClikaRtGen.ACTIVATION_IDENTITY, false, false,
ClikaRtGen.QCOMPUTE_MODE_EXACT_FP)
ClikaRtGen.tensorRetain(dense)
val yr = ClikaRtGen.opLinear(x, dense, 0L, false,
ClikaRtGen.ACTIVATION_IDENTITY, 0.0, 0.0)
println("packed y = ${ClikaRtGen.tensorToString(y)}")
println("dense y = ${ClikaRtGen.tensorToString(yr)}")
// The packed entry IS the payload byte stream: numel(w) counts bytes.
val denseBytes = ClikaRtGen.tensorNumel(dense) * 4
val packedBytes = ClikaRtGen.tensorNumel(w)
println("bytes: dense $denseBytes, packed $packedBytes " +
"(%.2fx)".format(denseBytes.toDouble() / packedBytes))
ClikaRtGen.tensorRelease(yr)
ClikaRtGen.tensorRelease(y)
ClikaRtGen.tensorRelease(dense)
ClikaRtGen.tensorRelease(w)
ClikaRtGen.tensorsContainerFree(tensors)
ClikaRtGen.ggufCheckpointFree(ckpt)
}
package main
import (
"fmt"
"log"
"math"
"unsafe"
"github.com/Clika/clika_runtime/bindings/go/clikart"
)
func must[T any](v T, err error) T {
if err != nil {
log.Fatal(err)
}
return v
}
func floats(api *clikart.Api, t *clikart.Tensor, n int) []float32 {
return unsafe.Slice((*float32)(must(api.TensorConstDataPtr(t))), n)
}
func main() {
api := must(clikart.Load("libClikaRT.so"))
ckpt := must(api.LoadGgufToGgufCheckpoint("SmolLM2-135M-Instruct-Q8_0.gguf",
clikart.StreamOrDevice{}, false))
tensors := must(api.GgufCheckpointTakeTensors(ckpt))
w := must(api.TensorsContainerGet(tensors, "blk.0.ffn_up.weight"))
q := must(api.QuantizedView(w)) // non-consuming wrappers: w stays live
dense := must(api.OpDequantize(q, clikart.Float32)) // [out, in]
fmt.Printf("dense = %s\n", dense)
shape := must(api.TensorShape(dense))
out, in := shape[0], shape[1]
// The packed path and the dense path compute the same values.
x := must(api.TensorFull([]int64{1, in}, 0.01, clikart.Float32))
// The generated wrappers carry no absent-optional spelling yet: an
// explicit zero bias stands in for the no-bias case.
bias := must(api.TensorFull([]int64{out}, 0.0, clikart.Float32))
y := floats(api, must(api.OpQmatmulWoq(x, q, bias, false,
clikart.ActivationIdentity, false, false, clikart.QcomputeModeExactFp)), int(out))
yr := floats(api, must(clikart.Linear(x, dense, nil, nil)), int(out))
maxDiff := 0.0
for i := range y {
maxDiff = math.Max(maxDiff, math.Abs(float64(y[i]-yr[i])))
}
fmt.Printf("max |packed - dense| over %d outputs: %g\n", len(y), maxDiff)
// The packed entry IS the payload byte stream: numel counts its bytes.
denseBytes := must(api.TensorNumel(dense)) * 4
packedBytes := must(api.TensorNumel(w))
fmt.Printf("bytes: dense %d, packed %d (%.2fx)\n",
denseBytes, packedBytes, float64(denseBytes)/float64(packedBytes))
}
use clika_rt::{sys, Api};
const F32: sys::clika_rt_data_type = sys::clika_rt_data_type_CLIKA_RT_DATA_TYPE_FLOAT32;
const UNDEF: sys::clika_rt_data_type = sys::clika_rt_data_type_CLIKA_RT_DATA_TYPE_UNDEFINED;
const IDENTITY: sys::clika_rt_activation = sys::clika_rt_activation_CLIKA_RT_ACTIVATION_IDENTITY;
const EXACT_FP: sys::clika_rt_qcompute_mode =
sys::clika_rt_qcompute_mode_CLIKA_RT_QCOMPUTE_MODE_EXACT_FP;
fn default_placement() -> sys::clika_rt_stream_or_device {
sys::clika_rt_stream_or_device {
kind: sys::clika_rt_stream_or_device_kind_CLIKA_RT_STREAM_OR_DEVICE_DEFAULT as i32,
device: sys::clika_rt_device { api: 0, index: 0 },
stream: std::ptr::null_mut(),
}
}
fn main() -> clika_rt::Result<()> {
let api = Api::load("libClikaRT.so")?;
let ckpt = api.f_load_gguf_to_gguf_checkpoint(
"SmolLM2-135M-Instruct-Q8_0.gguf", default_placement(), false)?;
let tensors = api.f_gguf_checkpoint_take_tensors(&ckpt)?;
let w = api.f_tensors_container_get(&tensors, "blk.0.ffn_up.weight")?;
let dense = api.f_op_dequantize(
api.f_quantized_view(w.shallow_clone())?, UNDEF)?; // [out, in]
println!("dense = {}", api.tensor_to_string(&dense)?);
let in_f = api.tensor_shape(&dense)[1];
// The packed path and the dense path compute the same values; the two
// summaries print the same leading data. (The numeric max-diff runs
// where a data pointer is readable: the C, C++ and Go tabs.)
let x = api.tensor_full(&[1, in_f], 0.01, F32)?;
let y = api.f_op_qmatmul_woq(x.shallow_clone(), api.f_quantized_view(w.shallow_clone())?,
api.absent(), false, IDENTITY, false, false, EXACT_FP)?;
let yr = api.f_op_linear(x, dense.shallow_clone(), api.absent(),
false, IDENTITY, 0.0, 0.0)?;
println!("packed y = {}", api.tensor_to_string(&y)?);
println!("dense y = {}", api.tensor_to_string(&yr)?);
// The packed entry IS the payload byte stream: numel counts its bytes.
let dense_bytes = api.tensor_numel(&dense) * 4;
let packed_bytes = api.tensor_numel(&w);
println!("bytes: dense {dense_bytes}, packed {packed_bytes} ({:.2}x)",
dense_bytes as f64 / packed_bytes as f64);
Ok(())
}
dense = Tensor(shape=[1536, 576], dtype=Float32, device=CPU, numel=884736, data=[-0.08493, 0.09265, 0.2548, -0.1004, 0.1699, -0.193, ...])
max |packed - dense| over 1536 outputs: 7.15256e-07
bytes: dense 3538944, packed 940032 (3.76x)
The packed forward matches the dequantize-then-ops::linear reference to float rounding, at 3.76x fewer bytes for Q8_0 (Q4 and Q5 schemes save more).
When the bytes did not come from GGUF
A packed payload from any other source gets the same treatment through make_quantized(payload, scheme, logical_shape): a UInt8 CPU tensor of packed block rows, the scheme's name ("GGUF_Q8_0", "MXFP4_E8M0"), and the element shape it encodes, row-contiguous dimension first. Checkpoints that ship MXFP4 as a split pair, 16 nibble-packed code bytes plus one E8M0 scale byte per 32-element group, go through make_quantized_mxfp4(blocks, scales, logical_shape), which weaves the pair into the packed row layout the runtime consumes. Either way the result is the same QTensor the programs above served.
You can now open any GGUF checkpoint, say what every entry is, and serve its weights at their packed size. The bundle's io example (chapter 02_gguf) inspects arbitrary files from the command line, and the runtime example wraps modules like QLinearWoQ into sessions and batching for serving.