# Learned answers on a phone

> curva pack writes a project's learned answers and the text embedder into one 8 MB file; a C library under 1 MB answers from it on a phone with no network, in about 5 µs a text.

Source: https://docs.tarkova.com/curva/guides/on-phone/

## How it works, step by step

1. **Learned on server** (Labels, Training, Shadowing): The server does all the learning first, in the usual learned-answers steps. The device never trains, and it only trusts what the server already trusts. In the example: A laptop test on SMS spam: a local server with a stand-in model that always says "not spam" takes 3,619 labels, trains in the next minute and shadows 30 decisions.
2. **curva pack** (--project, --db, -o, 8-bit embedder): The command reads the project's learned questions from the server's database, stores the text embedder in 8 bits instead of 32, and reopens the result before writing it. A project with nothing learned yet gets an error, not a file. In the example: curva pack --project sms --db curva.db -o sms.curvapack
3. **The file** (Tokenizer, Embedder, Heads, Thresholds, CRC-32): One file holds the tokenizer, the embedder and, per question, its learned model, threshold, calibration and whether the server trusts it. A checksum catches damage, but the file is not signed, so check that it came from your own backend. In the example: The pack is 8.1 MB: embedder 7.7 MB, vocabulary 0.45 MB, about 2 KB a question.
4. **C library** (curva_pack.h, curva_pack_open, Any thread): Your app loads the file through the curva-pack C library, which returns an error code for bad input rather than crashing. The library cannot be obtained publicly yet: its source is not published. Android and iOS builds have not been run. In the example: A Python caller on an Apple M-series laptop opens the pack through the library in 33 ms. The shared library is now 784 KB on arm64 macOS.
5. **Ask offline** (curva_pack_ask, No network, No model): The library splits the text into tokens, embeds it and runs the learned model on the device. It sends nothing anywhere. Measure speed on your own device, because phone cores are slower than the laptop these timings come from. In the example: Each of 1,552 held-out texts takes 4.8 µs at the median and 20 µs at p99. Laptop numbers, not phone numbers.
6. **Answer or abstain** (label, probability, abstain): You get the top label, its probability and abstain. abstain is true when the server would not answer by itself either: below the threshold, less accurate than your model, or still shadowing. Then send the text to Curva or treat it as unknown. In the example: 1,480 of 1,552 are answered, 99.6% of them right. The device and the server agree on answering or abstaining on 1,551. The other sat at 0.9005 and 0.89999 around the 0.9 threshold. English SMS with a stand-in model: your numbers will differ.
7. **Update the file** (Run pack again, Ship new file, Keep old): Training stays on the server, so a device learns nothing until you run curva pack again and ship the new file. Open the new pack, switch to it and free the old one. If the new file does not open, keep using the old one. In the example: This test made one pack and did not update it, so there is no number for this step.

Once Curva has [learned a question](/curva/guides/learned/) from your labels, your app can answer it on the
phone itself: no network, no model call, about 5 µs a text. A spam or scam check on every SMS or
call transcript is the use it was built for.

```sh
curva pack --project sms --db curva.db -o sms.curvapack
```

```text
wrote sms.curvapack (8.1 MB) for project `sms`:
  spam: answers when sure, abstains otherwise
```

The file holds every learned question of the project, the threshold and calibration the server
uses, and the text embedder. Ship it with your app or download it; load it with the `curva-pack`
library (C header `curva_pack.h`).

## What the phone gets back

For a text and a question key: the top label, its probability, all probabilities if you ask, and
`abstain`. `abstain` is true exactly when the server would not answer by itself either: the
probability is under the question's threshold, the learned model is not as accurate as your model,
or the server is still [shadowing](/curva/guides/learned/#the-rules) it. In that case send the text to Curva
as usual, or treat it as unknown.

## C

```c
#include "curva_pack.h"

CurvaPack *pack = NULL;
int32_t code = curva_pack_open(bytes, len, &pack);
if (code != CURVA_PACK_OK) printf("%s\n", curva_pack_error(code));

CurvaAnswer answer;
code = curva_pack_ask(pack, "spam", (const uint8_t *)text, strlen(text), NULL, 0, &answer);
if (code == CURVA_PACK_OK && !answer.abstain)
    printf("%s %.3f\n", curva_pack_label(pack, "spam", answer.label), answer.probability);
curva_pack_free(pack);
```

`text` is UTF-8 with its length (no terminating zero needed). The library copies what it needs
from `bytes`, so you can free them after `curva_pack_open`. One pack answers from any number of
threads at once. For camera frames,
see [camera answers on a device](/curva/guides/edge-video/).

| Code | Meaning |
|---|---|
| 0 | ok |
| 1 | a pointer argument is null |
| 2 | not a pack file |
| 3 | a pack format this library does not read (a newer `curva`) |
| 4 | damaged or cut short (checksum or bounds) |
| 5 | larger than 256 MB |
| 6 | no question with that key in the pack |
| 7 | the text or key is not UTF-8 |
| 8 | internal error (a bug: please report it) |

No call crashes the app: null pointers, bad UTF-8 and damaged files return a code, and an internal
panic is caught and returned as 8.

## Kotlin (Android)

A small JNI file connects the library to Kotlin:

```c
#include <jni.h>
#include <math.h>
#include <stdint.h>
#include "curva_pack.h"

JNIEXPORT jlong JNICALL Java_com_example_Guard_open(JNIEnv *env, jclass cls, jbyteArray file) {
    jsize len = (*env)->GetArrayLength(env, file);
    jbyte *bytes = (*env)->GetByteArrayElements(env, file, NULL);
    CurvaPack *pack = NULL;
    int32_t code = curva_pack_open((const uint8_t *)bytes, (size_t)len, &pack);
    (*env)->ReleaseByteArrayElements(env, file, bytes, JNI_ABORT);
    return code == CURVA_PACK_OK ? (jlong)(intptr_t)pack : 0;
}

JNIEXPORT jdouble JNICALL Java_com_example_Guard_yes(JNIEnv *env, jclass cls, jlong pack, jstring key, jbyteArray text) {
    const char *k = (*env)->GetStringUTFChars(env, key, NULL);
    jsize len = (*env)->GetArrayLength(env, text);
    jbyte *t = (*env)->GetByteArrayElements(env, text, NULL);
    double probs[2] = {NAN, NAN};
    CurvaAnswer answer;
    int32_t code = curva_pack_ask((const CurvaPack *)(intptr_t)pack, k, (const uint8_t *)t, (size_t)len, probs, 2, &answer);
    (*env)->ReleaseByteArrayElements(env, text, t, JNI_ABORT);
    (*env)->ReleaseStringUTFChars(env, key, k);
    return code == CURVA_PACK_OK && !answer.abstain ? probs[0] : NAN;
}

JNIEXPORT void JNICALL Java_com_example_Guard_free(JNIEnv *env, jclass cls, jlong pack) {
    curva_pack_free((CurvaPack *)(intptr_t)pack);
}
```

```kotlin
object Guard {
    init { System.loadLibrary("guard") }
    external fun open(file: ByteArray): Long
    external fun yes(pack: Long, key: String, text: ByteArray): Double
    external fun free(pack: Long)
}

val pack = Guard.open(context.assets.open("sms.curvapack").readBytes())
val spam = Guard.yes(pack, "spam", message.toByteArray(Charsets.UTF_8))
if (spam.isNaN()) askCurva(message) else if (spam >= 0.5) markAsSpam(message)
```

`yes` returns the probability of the question's first label (for a yes/no question, yes), or NaN
when the pack abstains. Pass the text as UTF-8 bytes, not a `jstring`: JNI's string functions use modified UTF-8, which
encodes emoji differently.

## Swift (iOS)

Add `curva_pack.h` to the bridging header and link `libcurva_pack.a`.

```swift
let data = try Data(contentsOf: Bundle.main.url(forResource: "sms", withExtension: "curvapack")!)
var pack: OpaquePointer?
let opened = data.withUnsafeBytes { curva_pack_open($0.bindMemory(to: UInt8.self).baseAddress, data.count, &pack) }
guard opened == CURVA_PACK_OK else { throw GuardError(String(cString: curva_pack_error(opened))) }

let text = Array(message.utf8)
var answer = CurvaAnswer()
if curva_pack_ask(pack, "spam", text, text.count, nil, 0, &answer) == CURVA_PACK_OK, !answer.abstain {
    let label = String(cString: curva_pack_label(pack, "spam", Int(answer.label)))
}
```

## Building the library

:::note[The library source is not published]
Curva's source code is not published, so these `cargo` commands only work with a copy of the
`curva-pack` source.
:::

```sh
cargo build --release -p curva-pack
```

gives `target/release/libcurva_pack.a` (static) and the shared library for your machine. For
phones, add the Rust target and build for it; the library has no platform code:

```sh
rustup target add aarch64-linux-android armv7-linux-androideabi x86_64-linux-android
cargo ndk -t arm64-v8a -t armeabi-v7a -t x86_64 -o app/src/main/jniLibs build --release -p curva-pack

rustup target add aarch64-apple-ios aarch64-apple-ios-sim
cargo build --release -p curva-pack --target aarch64-apple-ios
cargo build --release -p curva-pack --target aarch64-apple-ios-sim
```

`cargo ndk` needs the Android NDK. Add `RUSTFLAGS="--remap-path-prefix=$HOME=~"` so the library
does not carry your build machine's paths.

## Updates

Training, shadowing and trust stay on your server. Run `curva pack` again after the server retrains
(it retrains every minute when new labels come in) and ship the new file the way you ship other app
data. In the app, open the new pack, switch to it, then free the old one. If the new file does not
open (damaged in transit, or made by a newer `curva` than the library in the app), keep using the
old one. The library sends nothing anywhere.

The file is checked against damage (CRC-32), not signed. If the file comes over the network,
check it came from your backend (HTTPS from your own host, or your own signature) before opening
it.

## What was measured

On 23 October 2026, on an Apple M-series laptop, with the [SMS Spam Collection](https://archive.ics.uci.edu/dataset/228/sms+spam+collection)
(Almeida and Gómez Hidalgo, CC BY 4.0): 5,171
distinct messages, 653 of them spam, shuffled, 3,619 to train and 1,552 held out.

End to end: a local `curva serve --learned` with a stand-in model that answers "not spam" to
everything (so no model cost; it is right 88% of the time) took the 3,619 labels, trained in the
next minute, shadowed 30 decisions, then answered the 1,552 held-out texts. `curva pack` wrote the
file, and a Python caller loaded it through the C library and asked the same 1,552 texts.

| | Result |
|---|---|
| Same label as the server | all 1,481 texts the server answered by itself |
| Same answer or abstain as the server | 1,551 of 1,552; the other had P(not spam) 0.9005 on the server and 0.89999 on the phone, either side of the 0.9 threshold, so the phone abstained |
| Largest probability gap | 0.0033 where the server answered |
| Answered by itself (no abstain) | 1,480 of 1,552 (95%) |
| Accuracy when it answers | 99.6%; spam precision 99.4%; 176 of 207 spam messages caught, the rest abstained or missed |
| Accuracy on every text, ignoring abstain | 98.6%; spam precision 96.5%, recall 92.8%; ECE 0.003 |
| Time per text | 4.8 µs median, 20 µs at p99 (texts of 3 to 588 characters) |
| Opening the pack | 33 ms |
| Pack file | 8.1 MB: embedder 7.7 MB, vocab 0.45 MB, each learned question about 2 KB |
| Library | 425 KB shared library and about 420 KB added to a statically linked program when measured; with the camera functions added since, the shared library is 784 KB (arm64 macOS, stripped, 26 October 2026) |
| Memory | 24 MB peak for the C caller, which also holds the 8 MB file while opening |

The gap to the server comes from storing the embedder in 8 bits instead of 32, which makes the
file 3.7 times smaller. With an embedder whose values 8 bits hold exactly, the tests get the
server's answers bit for bit. These numbers are for English SMS spam with a
stand-in teacher; your own question and labels will give their own numbers, which the server shows
before anything answers by itself. Android and iOS builds were not run here; the timings are from
the laptop.
