# UForm for C++

> One byte-level encoder for text, images, video and audio, trained in CUDA without a tokenizer, codec or PyTorch, from C++

`cmake -B build_release -D CMAKE_BUILD_TYPE=Release -D UFORM_BUILD_LIBRARIES=ON && cmake --build build_release && cmake --install build_release` 4.0.0-rc.1 · c58749fe

The C++ SDK is a header-only layer over the stable C ABI in `c/uform/`, so it compiles no tower and links the same library C does.

It needs a C++23 compiler: GCC 15, Clang 22 with libstdc++ 15 or libc++ 22, Xcode 26 or VS 2026; CUDA code needs nvcc 13.5. Building from source needs CMake 4.3, or 4.4 with CUDA, which `pip install cmake` provides where the system package is older. It throws nothing: every call answers `auto [value, status]`, and every handle is an RAII owner. Every verb is a batch, and every output whose length the call decides lands in an arena you reuse.

- `model_t` encodes text, images, video and audio into pooled embeddings, per-token states and token vectors, and scores calibrated choices over text.
- `trainer_t` trains one on GPUs, joined across hosts by a `mesh_t`.
- `executor_t` owns the threads or streams every call runs on, apart from any model.

## Installation

`#include <uform/types.hpp>` 4.0.0-rc.1 · c58749fe

The SDK’s headers call into the compiled library, so build and install it first from a checkout:

```sh
cmake -B build_release -D CMAKE_BUILD_TYPE=Release -D UFORM_BUILD_LIBRARIES=ON && cmake --build build_release && cmake --install build_release
```

The install carries the C and C++ headers, both libraries, and a CMake package whose `uform::cpp` target names the SDK headers, the C headers of `uform::abi` beneath them, and the archive `uform::static`:

```cmake
find_package(uform CONFIG REQUIRED)
target_link_libraries(your_target PRIVATE uform::cpp)
```

Inside a superbuild, `add_subdirectory` of the repository gives the same `uform::cpp`. `-D UFORM_ENCODER_DTYPES=bf16` narrows the block-product dtypes the library compiles from the default `bf16;e4m3`, and a model load in a left-out one answers `status_code_t::unsupported_k`. `uform_encoder_dtypes_compiled()` from `c/uform/types.h` answers the kept ones as a mask, bit `n` standing for the `uform_scalar_t` valued `n`. `uform::cpp` reaches only `c/uform/*.h` and the standard library, so the compiler refuses any SDK include of the engine. `-D UFORM_BUILD_STUB=ON -D UFORM_BUILD_TEST=ON` builds a stand-in that answers every verb over the standard library alone, and the suite against it:

```sh
cmake --preset stub_library -D UFORM_BUILD_TEST=ON && cmake --build --preset stub_library --target uform_test_cpp_stub
ctest --test-dir build_stub_library --tests-regex uform_test_cpp_stub
```

### API

#### Functions

##### `version_name`

The linked library's version, a release-candidate suffix included.

[types.hpp:617 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L617)

```cpp
std::string_view version_name() noexcept;
```

## Quickstart

4.0.0-rc.1 · c58749fe

Encode two captions and a photo into one space, then pick the caption closest to the photo:

```cpp
#include <cmath>    // `std::sqrt`
#include <cstdio>   // `std::printf`
#include <fstream>  // `std::ifstream`
#include <iterator> // `std::istreambuf_iterator`
#include <vector>   // `std::vector`

#include <uform/uform.hpp>

namespace uf = unum::uform;

int main() {
    auto [executor, executor_status] = uf::executor_t::for_ram(); // the threads `on(executor)` names
    auto [texts_arena, texts_arena_status] = uf::arena_t::make(); // host pages for the calling thread
    auto [images_arena, images_arena_status] = uf::arena_t::make({.executor = executor.handle()}); // a call rewinds its arena
    auto [model, model_status] = uf::model_t::load_ram( // BFloat16 blocks, as the checkpoint stores them
        {.path = uf::bytes_view("model.safetensors"), .quantization = uform_scalar_bf16_k});
    if (model_status.failed()) return 1;

    std::string_view const captions[] = {"a cat on a mat", "a sunrise over the bay"};
    std::ifstream file("cat.png", std::ios::binary);
    std::vector<std::uint8_t> const photo {std::istreambuf_iterator<char>(file), {}};
    std::size_t const photo_offsets[] = {0, photo.size()};
    std::size_t offsets[3];
    char elements[64];
    auto [captions_tape, gather_status] = uf::gathered<char>(captions, offsets, elements); // one copy, end to end
    auto [texts, texts_status] = model.text_encode(captions_tape, uf::encode_outputs_t::embeddings_k, // the calling thread
                                                   uform_scalar_f32_k, texts_arena);
    auto [images, images_status] = model.on(executor).image_encode({photo, photo_offsets}, uf::encode_outputs_t::embeddings_k,
                                                                   uform_scalar_f32_k, images_arena); // blocks on the executor
    if (texts_status.failed() || images_status.failed()) return 1;

    std::span<float const> const image = images.embeddings.row<float>(0); // zero-copy from the arena; embeddings come unnormalized
    auto cosine = [&](std::span<float const> text) {
        float dot = 0, text_norm = 0, image_norm = 0;
        for (std::size_t dimension = 0; dimension != text.size(); ++dimension) {
            dot += text[dimension] * image[dimension];
            text_norm += text[dimension] * text[dimension];
            image_norm += image[dimension] * image[dimension];
        }
        return dot / std::sqrt(text_norm * image_norm);
    };
    std::size_t const best = cosine(texts.embeddings.row<float>(1)) > cosine(texts.embeddings.row<float>(0));
    std::printf("'%.*s' describes the photo best\n", int(captions[best].size()), captions[best].data());
    return 0;
}
```

## Receivers and Deferred Calls

`#include <uform/types.hpp>` 4.0.0-rc.1 · c58749fe

The receiver decides where a verb runs and how it completes, while the verb and its arguments stay the same:

- `model.text_encode(..)` runs on the calling thread.
- `model.on(executor).text_encode(..)` blocks on the executor, failing `status_code_t::contended_k` while another call holds it.
- `model.deferred(executor).text_encode(..)` submits the call and answers a `deferred`.

`model<receiver>` writes every verb once for all three: `model_t` owns the model and loads it, while `on` and `deferred` answer a `model_on<completion>` that refers to it and the executor, and `trainer<receiver>` does the same for a trainer. A blocking verb answers a `status_t` when it outputs nothing else and an `expected<T>` otherwise, so nothing about asynchrony reaches a caller who never asks for it. Each class spells that choice once, as its `deferrable<T>`, which names a `deferred<T>` under a deferred receiver.

```cpp
uf::deferred<uf::encoded_t> call =
    model.deferred(executor).text_encode(texts, uf::encode_outputs_t::embeddings_k, uform_scalar_f32_k, arena); // running now
other_work();
auto [encoded, status] = call.wait(); // blocks until final; destruction waits too
```

Any coroutine type awaits a deferred call, with any loop offering `post(void (*)(void*) noexcept, void*)`, so one model encodes on two executors at once:

```cpp
app::task encode_both(uf::model_t const& model, uf::executor_t const& east_executor, uf::executor_t const& west_executor,
                      uf::tape_view<char> texts, app::loop& loop) {
    auto [east_arena, east_arena_status] = uf::arena_t::make({.executor = east_executor.handle()});
    auto [west_arena, west_arena_status] = uf::arena_t::make({.executor = west_executor.handle()});
    uf::deferred<uf::encoded_t> east_call = model.deferred(east_executor)
                                                .text_encode(texts, uf::encode_outputs_t::embeddings_k,
                                                             uform_scalar_f32_k, east_arena);
    uf::deferred<uf::encoded_t> west_call = model.deferred(west_executor)
                                                .text_encode(texts, uf::encode_outputs_t::embeddings_k,
                                                             uform_scalar_f32_k, west_arena);
    auto [east_encoded, east_status] = co_await east_call.wait(loop); // both calls were already running
    auto [west_encoded, west_status] = co_await west_call.wait(loop);
    if (east_status.failed() || west_status.failed()) co_return;
    merge(east_encoded, west_encoded);
}
```

A `deferred` never moves, since the library writes into it, so it lives on the caller’s stack or in the awaiting coroutine’s frame. `status` answers `status_code_t::deferred_k` until the call is final, then its final status, and `wait()` blocks until then and answers what a blocking call would have. `co_await call.wait(loop)` suspends the coroutine and re-polls the status through `loop`, any type with `post(void (*)(void*) noexcept, void*)`, so the awaiter posts two words and allocates nothing, as Rust’s waker re-wakes itself. The library has no wake-up, so a scheduler runs other posted work between polls, and its own coroutine type owns the frame. Destroying an unfinished `deferred` waits for the call.

The library reads a deferred call’s inputs after the verb returns, so the tapes, spans, handlers and reports a deferred verb names must outlive the call, which C++ leaves to the caller. A deferred call allocates nothing: its outcome and outputs live inside the `deferred` itself. A refusal the SDK catches before the call crosses answers a `deferred` that is final from the start. An executor without threads of its own may run a deferred call at submission, final when the verb returns.

### API

#### Types

##### `awaiter`

A [`deferred`](https://www.unum.cloud/docs/uform/cpp/training.md#deferred) being awaited, living in the awaiting coroutine's frame: each poll reads the status word, and one not yet final posts itself again.

[types.hpp:176 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L176)

```cpp
template <typename value_type_,
          a_scheduler scheduler_type_>
class awaiter
```

##### `answer_value`

What a final `answer_type_` carries beside its status, `void` for a bare `status_t`.

[types.hpp:205 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L205)

```cpp
template <typename answer_type_>
struct answer_value
```

##### `progress_t`

A progress handler the caller keeps for one call, passed as its own state; empty hears nothing.

[types.hpp:510 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L510)

```cpp
class progress_t
```

##### Class `deferred`

A submitted call: its outcome and its outputs, owned until the call is final, while the receiver, inputs, arena and handlers it was handed stay allocated and unchanged until then.7

[types.hpp:118 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L118)

```cpp
template <typename value_type_ = void>
class deferred
```

It never moves, as the library writes into it, and its one owner polls [`status`](#status), blocks in [`wait`](#wait) or awaits [`wait`](#wait) on its own loop; destruction waits, so nothing the call writes into goes away under it.

###### `answer_type`

What [`wait`](#wait) answers: what the blocking call would have.

[types.hpp:124 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L124)

```cpp
using answer_type = std::conditional_t<std::is_void_v<value_type_>, status_t, expected<value_type_>>;
```

###### `deferred`

An empty slot, final from the start, which [`resubmit`](#resubmit) fills.

[types.hpp:127 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L127)

```cpp
deferred() noexcept=default;
```

```cpp
template <typename submit_type_>
requires std::invocable<submit_type_ const&, uform_outcome_t*, outputs<value_type_>*>
deferred(submit_type_ const & submit) noexcept;
```

Runs `submit` with this call's outcome and outputs, where the library reports.

```cpp
deferred(status_t status) noexcept;
```

A call refused before it crossed, final from the start.

```cpp
deferred(deferred const &)=delete;
```

###### `resubmit`

Waits only while the slot's previous call still runs, then runs `submit` in its place.

[types.hpp:139 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L139)

```cpp
template <typename submit_type_>
requires std::invocable<submit_type_ const&, uform_outcome_t*, outputs<value_type_>*>
void resubmit(submit_type_ const & submit) noexcept;
```

###### `operator=`

[types.hpp:150 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L150)

```cpp
deferred & operator=(deferred const &)=delete;
```

###### `~deferred`

[types.hpp:151 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L151)

```cpp
~deferred() noexcept;
```

###### `status`

[`status_code_t::deferred_k`](https://www.unum.cloud/docs/uform/cpp/errors.md#deferred_k) until the call is final, then its final status, polled without blocking.

[types.hpp:155 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L155)

```cpp
status_code_t status() noexcept;
```

###### `wait`

Blocks until the call is final and answers what a blocking call would have.

[types.hpp:158 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L158)

```cpp
answer_type wait() noexcept;
```

```cpp
template <a_scheduler scheduler_type_>
awaiter<value_type_, scheduler_type_> wait(
    scheduler_type_ & loop) noexcept;
```

Awaits the call on `loop`, which polls its status until it is final.

#### Constants

##### `is_deferred`

Whether `answer_type_` is a call the caller holds rather than a final answer.

[types.hpp:199 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L199)

```cpp
bool is_deferred;
```

## Executors

`#include <uform/types.hpp>``#include <uform/train.hpp>` 4.0.0-rc.1 · c58749fe

An executor owns host threads or device streams, the activation scratch, and the pinned buffers staging passes through, grown to a high-water mark. One executor serves any number of models of its residency.

```cpp
auto [threads, threads_status] = uf::executor_t::for_ram({.threads = 8});         // eight threads, where zero takes 7/8 of the cores less one
std::int32_t const domains[] = {1};
auto [numa, numa_status] = uf::executor_t::for_ram({.ram = {.memory_domains = domains, .memory_domains_count = 1}});
auto [serial, serial_status] = uf::executor_t::for_ram({.ram = {.cpu_class_ceiling = uform_cpu_class_serial_k}});
std::int32_t const devices[] = {0, 1};
auto [streams, streams_status] = uf::executor_t::for_vram({.vram = {.devices = devices, .devices_count = 2}});
uf::executor_t local;                                                   // owns nothing, runs on the calling thread

uf::status_t const drained = threads.drain(uform_mood_spinning_k);     // waits until no call holds it, then keeps spinning
```

Every factory takes the C argument struct by designator, so a field left out is zero, which the library derives. Naming one memory domain spawns the threads near it, while none or several interleave them across the machine. `for_vram` opens one stream per device, or adopts the caller’s `streams`, one per named device, and the executor destroys them; naming no devices drives every listed device of the first vendor with a known class. `uf::gpu_devices(devices)` fills a span of `uform_gpu_device_t` and answers how many GPUs the process can drive, and a device’s position there is the ordinal `for_vram` and `load_vram` name it by, while `uf::version_name()` spells the linked library’s version. An executor runs one call at a time, so two threads that genuinely overlap take one apiece. Destroying an executor waits until no call holds it, and asserts in Debug builds that no arena made with it lives.

### API

#### Types

##### `mesh_t`

Owns one process's place among the processes of a run; each trainer made over it holds it, so either may be freed first.

[train.hpp:33 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/train.hpp#L33)

```cpp
class mesh_t
```

##### Class `executor_t`

Owns one executor: the host threads or device streams every call runs on, apart from any model; an empty one runs every call on the caller's own thread.3

[types.hpp:538 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L538)

```cpp
class executor_t
```

It outlives every arena it made.

###### `drain`

Waits until no call holds the executor, then sets its threads' idle `mood`.

[types.hpp:560 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L560)

```cpp
status_t drain(uform_mood_t mood = uform_mood_parked_k) noexcept;
```

###### `for_ram`

Creates an executor of host threads for RAM-resident models, near the one memory domain `arguments` names, or interleaved across the machine for none or several.

[types.hpp:547 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L547)

```cpp
expected<executor_t> for_ram(
    uform_executor_for_ram_t arguments = {}) noexcept;
```

###### `for_vram`

Opens one submission stream on every device `arguments` names, or adopts the caller's `streams` : a CUDA or HIP stream becomes the executor's, which synchronizes and destroys it; a Metal queue is retained, the executor releasing its own reference while the caller keeps and releases theirs.

[types.hpp:555 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L555)

```cpp
expected<executor_t> for_vram(
    uform_executor_for_vram_t arguments = {}) noexcept;
```

#### Functions

##### `free_executor`

Frees `executor` as its owner dies, which every arena made with it refuses while it lives; declaring the executor before its arenas destroys them first.

[types.hpp:531 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L531)

```cpp
void free_executor(uform_executor_t executor) noexcept;
```

##### `gpu_devices`

Fills `devices` with the GPUs this process can drive, in ordinal order, answering how many there are, which may exceed what `devices` holds.

[types.hpp:606 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L606)

```cpp
expected<std::size_t> gpu_devices(
    std::span<uform_gpu_device_t> devices) noexcept;
```

## Arenas

`#include <uform/types.hpp>` 4.0.0-rc.1 · c58749fe

Every output whose length only the call knows, the embeddings, the states and their offsets, lands in an `arena_t` you pass, and the verb answers views over it without copying. `arena_t::make({.executor = executor.handle()})` places it where that executor computes, decided once, and `arena_t::make()` makes host pages for the calling thread. Each call rewinds its arena, so the previous call’s views die and a steady loop allocates once. To keep a result past the next call, pass that call another arena; an arena serves one call at a time, so each deferred call needs its own. An arena from a VRAM executor holds device memory, which `describe()` reports as `uform_residency_vram_k` and host code must not read, while `view.data` still hands the rows to another library, such as a USearch VRAM index. Views are plain spans that nothing invalidates, so check `describe().host_access` before host code reads one, and copy what you keep instead of holding a span across calls.

```cpp
auto [arena, arena_status] = uf::arena_t::make({.executor = executor.handle()});
for (uf::tape_view<char> const batch : batches) {
    auto [encoded, status] = model.on(executor).text_encode(batch, uf::encode_outputs_t::embeddings_k, uform_scalar_f32_k, arena);
    consume(encoded.embeddings); // rewinds next iteration
}
```

Destroying an arena waits for the calls writing into it, and a call naming an arena that serves another call finishes with `status_code_t::contended_k`. An arena never outlives the executor that made it, so declare the executor before the arena and scope exit destroys the arena first, and an arena from `arena_t::make()` lives until it is destroyed.

### API

#### Types

##### `owner`

Owns one handle of `handle_type_`, which `free_` releases, moving it and never copying it.

[types.hpp:242 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L242)

```cpp
template <typename handle_type_,
          void(*)(handle_type_) free_>
class owner
```

##### `owning`

A handle owned, moved and never copied, whose verbs block on the calling thread.

[types.hpp:285 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L285)

```cpp
template <typename handle_type_,
          void(*)(handle_type_) free_>
struct owning
```

##### Fields

| `completion` | `uform_completion_t` | |
| - | - | - |

##### `caller_owned`

A handle the caller owns and the executor its verbs run on, completing as `completion_` says.

[types.hpp:296 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L296)

```cpp
template <typename handle_type_,
          uform_completion_t completion_>
struct caller_owned
```

##### Fields

| `completion` | `uform_completion_t` | |
| - | - | - |

##### Class `arena_t`

Owns one arena; every call writing outputs into it rewinds it first, ending the previous call's views.3

[types.hpp:578 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L578)

```cpp
class arena_t
```

It must not outlive the executor that made it, so declare that executor first; one made with no executor lives until it is destroyed. It must outlive every export opened on its outputs: a free those refuse leaves the arena allocated with no owner left to free it.

###### `handle`

The C handle, for [`uform_arena_export_open`](https://www.unum.cloud/docs/uform/c/arenas.md#uform_arena_export_open) among others; close every export opened through it before this owner dies.

[types.hpp:584 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L584)

```cpp
uform_arena_t handle() const noexcept;
```

###### `describe`

Reports where the arena's outputs live, which decides whether host code may read them.

[types.hpp:593 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L593)

```cpp
expected<uform_arena_description_t> describe() const noexcept;
```

###### `make`

Creates an empty arena where the executor `arguments` names computes.

[types.hpp:588 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L588)

```cpp
expected<arena_t> make(uform_arena_init_t arguments = {}) noexcept;
```

#### Functions

##### `free_arena`

Frees `arena` as its owner dies, which an open export of its outputs refuses, leaving it to the export's holder, who closes every export before the owner dies.

[types.hpp:570 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L570)

```cpp
void free_arena(uform_arena_t arena) noexcept;
```

## Encoding

`#include <uform/types.hpp>``#include <uform/encode.hpp>` 4.0.0-rc.1 · c58749fe

One verb per input form, each spelled as in C, and each taking its inputs, the `encode_outputs_t` to keep, a config, and last the arena:

- `text_encode(texts, ..)` takes UTF-8 texts as a `tape_view<char>`, a byte per token, since models are tokenizer-free.
- `image_encode(files, ..)` takes JPEG, PNG or WebP files as a `tape_view<std::uint8_t>`.
- `image_encode_pixels(pixels, heights, widths, ..)` takes interleaved 8-bit RGB, `heights[i]` rows of `widths[i]` pixels per item.
- `video_encode(files, ..)` takes MP4 or WebM clips.
- `audio_encode(files, ..)` takes WAV, FLAC, MP3 or Opus recordings.
- `audio_encode_samples(samples, sample_rate, ..)` takes mono `float` samples as a `tape_view<float>`.

A `tape_view` is the elements and `count + 1` offsets, which the library reads without a copy once the SDK checks the offsets stay inside the elements. Separate items gather into memory the caller owns with one copy, through `gathered<char>(items, offsets, elements)`, which answers the view every verb takes, or `status_code_t::invalid_argument_k` when either span is too short:

```cpp
std::string_view const joined = "first documentthe second";
std::size_t const offsets[] = {0, 14, 24};
auto [encoded, status] = model.text_encode({joined, offsets}, uf::encode_outputs_t::states_k, uform_scalar_bf16_k, arena);
std::span<std::size_t const> const items = encoded.states.offsets(); // item `i` spans rows `items[i]` up to `items[i + 1]`
uf::written_rows_t const second = encoded.states.item(1);              // the rows of one item
```

`encode_outputs_t::embeddings_k`, `states_k` and `token_vectors_k` join with `|`, and a surface left out answers an empty view and costs nothing past the final norm. Token vectors are the token head’s unit rows, one per state, which late-interaction rerankers score; a model without the head answers `status_code_t::unsupported_k`. A bare `uform_scalar_t` converts into the verb’s config, the scalar every output lands as; the config’s other fields reach the knobs:

```cpp
uform_text_encode_stats_t stats {};
auto handler = [](std::size_t completed, std::size_t total) noexcept {
    return completed * 2 < total ? uform_continue_k : uform_cancel_k;
};
uf::text_encode_config_t const config {uform_scalar_f32_k, {handler}, &stats};
auto [encoded, status] = model.text_encode(texts, uf::encode_outputs_t::embeddings_k, config, arena);
```

`written_rows_t` holds the C `view`, its `stride`, `columns` and `scalar`, beside the rows `written`, and `row<float>(i)` reads one row, empty when the rows hold another scalar type. `written_rows_tape_t` adds the `offsets()` and an `item(i)` per input. A handler answering `uform_cancel_k` stops the call, which fails with `status_code_t::cancelled_k` and publishes nothing.

### API

#### Types

##### `outputs`

Where a call writes what `value_type_` is made of.

[types.hpp:87 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L87)

```cpp
template <typename value_type_>
struct outputs
```

##### Fields

| `value` | `value_type_` | The answer, which the call writes in place. |
| - | - | - |

##### `outputs< void >`

A call that outputs nothing but its status.

[types.hpp:97 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L97)

```cpp
template <>
struct outputs< void >
```

##### Fields

| `value` | `void` | The answer, which the call writes in place. |
| - | - | - |

##### `bf16_t`

Bit containers for the formats C++ has no arithmetic type for, so a call can still name them.

[types.hpp:311 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L311)

```cpp
struct bf16_t
```

##### Fields

| `encoding` | `std::uint16_t` | |
| - | - | - |

##### `written_rows_t`

Rows a call wrote packed into its arena, one per item, readable until the arena's next call; host code may read them only from a RAM arena.

[types.hpp:455 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L455)

```cpp
struct written_rows_t
```

##### Fields

| `view` | `uform_rows_view_t` | The rows as the call wrote them. |
| - | - | - |
| `written` | `std::size_t` | Rows written, one per item along the call's batch axis; zero for a surface the call did not keep. |

##### `written_rows_tape_t`

A ragged run of rows a call wrote into its arena, item `i` spanning rows `offsets()`\[i] up to `offsets()`\[i+1]; readable until the arena's next call.

[types.hpp:475 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L475)

```cpp
struct written_rows_tape_t
```

##### Fields

| `view` | `uform_rows_tape_view_t` | The rows and offsets as the call wrote them. |
| - | - | - |
| `written` | `std::size_t` | Items written along the call's batch axis; zero for a surface the call did not keep. |

##### `encode_outputs_t`

The surfaces an encode verb keeps from its one forward, named after the C fields they fill; `operator|` joins them.

[encode.hpp:25 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/encode.hpp#L25)

```cpp
enum encode_outputs_t
```

##### Values

| `embeddings_k` | `1` | One pooled embedding per item, past the attention pool and the projection head. |
| - | - | - |
| `states_k` | `2` | One final-norm state per token left after truncation. |
| `token_vectors_k` | `4` | One unit vector of the token head per token left after truncation; a model without the head fails the call with [`status_code_t::unsupported_k`](https://www.unum.cloud/docs/uform/cpp/errors.md#unsupported_k). |

##### `encoded_t`

What an encode verb wrote into the arena it was given: the surfaces its `encode_outputs_t` named, each empty when left out, and none normalized.

[encode.hpp:50 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/encode.hpp#L50)

```cpp
struct encoded_t
```

##### Fields

| `embeddings` | `written_rows_t` | One pooled embedding of the model's dimensions per item. |
| - | - | - |
| `states` | `written_rows_tape_t` | One final-norm state per token left after truncation, item by item. |
| `token_vectors` | `written_rows_tape_t` | One unit vector of the model's token width per token left after truncation, item by item. |

##### `encode_config`

The knobs of an encode verb reporting `stats_type_:` the scalar every output lands as, which a bare `uform_scalar_t` converts into, a handler, and a report.

[encode.hpp:83 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/encode.hpp#L83)

```cpp
template <typename stats_type_>
struct encode_config
```

##### Fields

| `outputs_scalar` | `uform_scalar_t` | The scalar type every output lands as. |
| - | - | - |
| `progress` | `progress_t` | Hears the items encoded, and may cancel the call. |
| `stats` | `stats_type_ *` | The report the call overwrites; `nullptr` skips it. |

##### `outputs< tape_view< float > >`

Where [`text_choose`](https://www.unum.cloud/docs/uform/cpp/models.md#text_choose) writes one probability per choice: the C tape and its count, from which the answer assembles a `tape_view` over the arena.

[encode.hpp:127 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/encode.hpp#L127)

```cpp
template <>
struct outputs< tape_view< float > >
```

##### Fields

| `written` | `uform_tape_view_t` | |
| - | - | - |
| `count` | `std::size_t` | |
| `value` | `tape_view<float>` | The answer, which the call writes in place. |

##### Struct `tape_view`

A ragged batch of `element_type_` laid out as Apache Arrow lays one out: elements end to end, and one more offset than entries, entry `i` spanning two consecutive offsets.3

[types.hpp:405 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L405)

```cpp
template <an_element element_type_>
struct tape_view
```

The caller owns both spans: as an input, it keeps them alive until the call is final; as an output, it reads the call's arena until the arena's next call.

###### `count`

Entries along the batch axis, one fewer than the offsets.

[types.hpp:410 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L410)

```cpp
std::size_t count() const noexcept;
```

###### `entry`

The elements of the entry at `position`, below [`count`](#count).

[types.hpp:413 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L413)

```cpp
std::span<element_type_ const> entry(
    std::size_t position) const noexcept;
```

###### `check`

Refuses what only the binding sees: no offsets, or a last one past the elements.

[types.hpp:418 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L418)

```cpp
status_t check() const noexcept;
```

#### Functions

##### `bytes_view`

Views `text` as the unterminated run of bytes every path, buffer and name arrives in.

[types.hpp:388 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L388)

```cpp
uform_bytes_view_t bytes_view(std::string_view text) noexcept;
```

```cpp
uform_bytes_view_t bytes_view(
    std::span<std::uint8_t const> bytes) noexcept;
```

Views `bytes` as the caller's run every checkpoint buffer arrives in.

##### `gathered`

Gathers separate items of `element_type_` into one tape laid out in the caller's `offsets` and `elements`, for callers whose items are not laid end to end already.

[types.hpp:436 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L436)

```cpp
template <an_element element_type_, std::ranges::sized_range items_type_>
expected<tape_view<element_type_>> gathered(
    items_type_ const & items,
    std::span<std::size_t> offsets,
    std::span<element_type_> elements) noexcept;
```

Gathering copies every element once, which a caller already holding a tape skips by passing its `tape_view` directly. The answer views both spans, so they outlive every call it is passed to.

##### `contains`

Whether every surface `surface` names is kept by [`outputs`](#outputs).

[encode.hpp:43 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/encode.hpp#L43)

```cpp
bool contains(
    encode_outputs_t outputs,
    encode_outputs_t surface) noexcept;
```

#### Constants

##### `scalar_of`

The scalar kind a C++ element type names, or [`uform_scalar_unknown_k`](https://www.unum.cloud/docs/uform/c/encoding.md#uform_scalar_unknown_k) for none.

[types.hpp:341 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L341)

```cpp
uform_scalar_t scalar_of;
```

##### `values_per_element`

Values one element packs: eight for bit sets, two for nibbles, one otherwise.

[types.hpp:379 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L379)

```cpp
std::size_t values_per_element;
```

## Choices

`#include <uform/encode.hpp>` 4.0.0-rc.1 · c58749fe

`text_choose(texts, choices, ..)` scores each item’s legal choices, one byte each, through one forward, and answers a `tape_view<float>` of one probability per choice that sums to one per item:

```cpp
std::uint32_t const groups[] = {0, 1};
auto [probabilities, status] = model.text_choose(states, choices, {.temperature_groups = groups}, arena);
std::span<float const> const expand = probabilities.entry(1); // the probabilities of 'A' through 'D'
```

Each group is a question type below the model’s `choice_temperature_groups`, and a model without the byte decoder answers `status_code_t::unsupported_k`.

### API

#### Types

##### `text_choose_config_t`

The knobs of [`text_choose`](https://www.unum.cloud/docs/uform/cpp/models.md#text_choose).

[encode.hpp:111 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/encode.hpp#L111)

```cpp
struct text_choose_config_t
```

##### Fields

| `temperature_groups` | `std::span<std::uint32_t const>` | The question type of each item, below the model's `choice_temperature_groups`; empty puts every item in group zero. |
| - | - | - |
| `progress` | `progress_t` | Hears the items scored, and may cancel the call. |
| `stats` | `uform_text_encode_stats_t *` | The report the call overwrites; `nullptr` skips it. |

## Models

`#include <uform/model.hpp>` 4.0.0-rc.1 · c58749fe

`model_t::load_ram` and `model_t::load_vram` copy a safetensors checkpoint into host memory or onto GPUs, and `load_ram_buffer` and `load_vram_buffer` take the checkpoint’s bytes instead. Each takes the C argument struct, which reaches the executor, the placement and its class ceiling, the quantization and a progress handler, and always loads blocking:

```cpp
std::int32_t const device = 0;
auto [model, model_status] = uf::model_t::load_vram({
    .executor = executor.handle(),
    .path = uf::bytes_view("model.safetensors"),
    .vram = {.devices = &device, .devices_count = 1},
    .quantization = uform_scalar_e4m3_k,
});
auto [description, describe_status] = model.on(executor).describe(); // geometry, placement, classes and heads
```

A description reports the `cpu_class` or `gpu_class` the model dispatched as, and the heads the checkpoint carries: a nonzero `token_width` for token vectors, and a nonzero `choice_temperature_groups` for choices. Blocks run in `uform_scalar_bf16_k`, as the checkpoint stores them, or `uform_scalar_e4m3_k` quantized at load, and a zero quantization is refused.

### API

#### Class `model`

A model and its verbs, completed as `receiver_type_` says: the owning handle blocks on the calling thread, [`on`](https://www.unum.cloud/docs/uform/cpp/training.md#on) blocks on an executor, and both answer a `status_t` or an [`expected`](https://www.unum.cloud/docs/uform/cpp/errors.md#expected), while [`deferred`](https://www.unum.cloud/docs/uform/cpp/training.md#deferred) submits to an executor and answers a [`deferred`](https://www.unum.cloud/docs/uform/cpp/training.md#deferred) call.16

[model.hpp:46 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L46)

```cpp
template <typename receiver_type_>
class model
```

Each verb is written once, filling its C struct with the result as its output. Every input, handler, report and arena a deferred call names stays the caller's until it is final.

##### `model`

[model.hpp:57 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L57)

```cpp
requires an_owning_receiver<receiver_type_>
model() noexcept=default;
```

##### `handle_field`

The output field a lifecycle verb writes the new handle into.

[model.hpp:64 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L64)

```cpp
requires an_owning_receiver<receiver_type_>
uform_model_t * handle_field() noexcept;
```

##### `on`

The same handle, whose verbs block on `executor`.

[model.hpp:71 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L71)

```cpp
model<caller_owned<uform_model_t, uform_completion_blocking_k>> on(
    executor_t const & executor) const noexcept;
```

##### `deferred`

The same handle, whose verbs submit to `executor`, each answering a [`deferred`](https://www.unum.cloud/docs/uform/cpp/training.md#deferred) call.

[model.hpp:76 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L76)

```cpp
model<caller_owned<uform_model_t, uform_completion_deferred_k>> deferred(
    executor_t const & executor) const noexcept;
```

##### `describe`

Reports the model's geometry, placement, classes and heads in one call.

[model.hpp:82 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L82)

```cpp
deferrable<uform_model_description_t> describe() const noexcept;
```

##### `text_encode`

Encodes UTF-8 `texts` through one forward, a token per byte, keeping the surfaces `kept` names in `arena`.

[model.hpp:93 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L93)

```cpp
deferrable<encoded_t> text_encode(
    tape_view<char> texts,
    encode_outputs_t kept,
    text_encode_config_t const & config,
    arena_t & arena) const noexcept;
```

##### `text_choose`

Scores each item's legal `choices`, one byte each, after its UTF-8 state in `texts`, answering one probability per choice in `arena`, a softmax over the item's choices.

[model.hpp:116 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L116)

```cpp
deferrable<tape_view<float>> text_choose(
    tape_view<char> texts,
    tape_view<char> choices,
    text_choose_config_t const & config,
    arena_t & arena) const noexcept;
```

##### `image_encode`

Decodes and encodes JPEG, PNG or WebP `images`; an undecodable file fails the call with [`status_code_t::malformed_k`](https://www.unum.cloud/docs/uform/cpp/errors.md#malformed_k).

[model.hpp:150 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L150)

```cpp
deferrable<encoded_t> image_encode(
    tape_view<std::uint8_t> images,
    encode_outputs_t kept,
    image_encode_config_t const & config,
    arena_t & arena) const noexcept;
```

##### `image_encode_pixels`

Encodes decoded images of interleaved 8-bit RGB, item `i` holding `heights` \[i] rows of `widths` \[i] pixels.

[model.hpp:173 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L173)

```cpp
deferrable<encoded_t> image_encode_pixels(
    tape_view<std::uint8_t> pixels,
    std::span<std::uint32_t const> heights,
    std::span<std::uint32_t const> widths,
    encode_outputs_t kept,
    image_encode_config_t const & config,
    arena_t & arena) const noexcept;
```

##### `video_encode`

Decodes and encodes MP4 or WebM `videos`.

[model.hpp:202 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L202)

```cpp
deferrable<encoded_t> video_encode(
    tape_view<std::uint8_t> videos,
    encode_outputs_t kept,
    video_encode_config_t const & config,
    arena_t & arena) const noexcept;
```

##### `audio_encode`

Decodes and encodes WAV, FLAC, MP3 or Opus `recordings`, resampled to mono.

[model.hpp:224 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L224)

```cpp
deferrable<encoded_t> audio_encode(
    tape_view<std::uint8_t> recordings,
    encode_outputs_t kept,
    audio_encode_config_t const & config,
    arena_t & arena) const noexcept;
```

##### `audio_encode_samples`

Encodes decoded mono `samples` sharing one `sample_rate`, resampled to the model's rate where it differs.

[model.hpp:248 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L248)

```cpp
deferrable<encoded_t> audio_encode_samples(
    tape_view<float> samples,
    std::uint32_t sample_rate,
    encode_outputs_t kept,
    audio_encode_config_t const & config,
    arena_t & arena) const noexcept;
```

##### `load_ram`

Copies a safetensors checkpoint file into host memory and packs it for the CPU, blocking.

[model.hpp:273 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L273)

```cpp
requires an_owning_receiver<receiver_type_>
expected<model> load_ram(uform_model_load_ram_t arguments) noexcept;
```

##### `load_ram_buffer`

Copies a checkpoint held in memory into host memory and packs it for the CPU, blocking.

[model.hpp:281 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L281)

```cpp
requires an_owning_receiver<receiver_type_>
expected<model> load_ram_buffer(
    uform_model_load_ram_buffer_t arguments) noexcept;
```

##### `load_vram`

Copies a checkpoint file onto the GPUs `arguments` names and packs it there, blocking.

[model.hpp:289 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L289)

```cpp
requires an_owning_receiver<receiver_type_>
expected<model> load_vram(uform_model_load_vram_t arguments) noexcept;
```

##### `load_vram_buffer`

Copies a checkpoint held in memory onto the GPUs `arguments` names, blocking.

[model.hpp:297 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/model.hpp#L297)

```cpp
requires an_owning_receiver<receiver_type_>
expected<model> load_vram_buffer(
    uform_model_load_vram_buffer_t arguments) noexcept;
```

## Training

`#include <uform/train.hpp>` 4.0.0-rc.1 · c58749fe

Training is GPU-only. The configuration arrives as the C structs themselves, so a field left out is zero, which the library derives:

```cpp
auto [executor, executor_status] = uf::executor_t::for_vram({.vram = {.devices = devices, .devices_count = 2}});
auto [mesh, mesh_status] = uf::mesh_t::bootstrap({
    .executor = executor.handle(),
    .options = {.host_domain_index = rank, .host_domain_count = nodes,
                .directory = uf::bytes_view("/shared/exchange"), .job = uf::bytes_view("run-17")},
});
auto [trainer, trainer_status] = uf::trainer_t::init_vram({
    .executor = executor.handle(),
    .depth = 12,
    .hidden = 512,
    .batch = {.max_rows_per_device = 64, .max_segments_per_device = 256, .max_columns_per_row = 1024,
              .max_bags_per_device = 128, .image = {.patch_side = 16}},
    .objective = uform_objective_joint_k,
    .schedule = {.steps = 100000},
    .mesh = mesh.handle(),
    .seed = 42,
});

std::size_t const attract_offsets[] = {0, 1, 2, 3, 4};
std::uint32_t const attract_ids[] = {1, 0, 3, 2}, bags[] = {0, 0, 1, 1};
uform_trainer_step_stats_t stats {};
uf::trainer_step_config_t const config {
    .bags = bags, .relations = {.attract = {attract_offsets, attract_ids, nullptr}}, .stats = &stats};
auto [embeddings, step_status] = trainer.on(executor).step(modalities, contents, config);
uf::status_t const saved = trainer.on(executor).save(uf::bytes_view("checkpoint.safetensors"));
```

`trainer_step_config_t` gathers a step’s per-item inputs: `bags`, `temperature_groups`, `sides`, the `choices` and `choice_targets` tapes `text_choose` takes and answers, the `relations` edge sets, and an optional `arena` for the pooled embeddings the loss scored. The SDK checks every per-item span and tape against the step’s items before the call, and leaves the edge sets to the library. `step` answers the pooled embeddings when its config names an arena, and an empty `written_rows_t` otherwise. A trainer refers to its mesh, so the mesh outlives every trainer made over it, and `mesh.describe()` answers a `uform_mesh_description_t`.

### API

#### Types

##### `trainer_step_config_t`

The inputs and knobs of a step beside its modalities and contents; every empty span and tape is left out of the call.

[train.hpp:60 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/train.hpp#L60)

```cpp
struct trainer_step_config_t
```

##### Fields

| `bags` | `std::span<std::uint32_t const>` | The bag of each item, whose items land on one device; empty keeps every item its own bag. |
| - | - | - |
| `temperature_groups` | `std::span<std::uint32_t const>` | The temperature group of each item; empty puts every item in group zero. |
| `sides` | `std::span<uform_late_interaction_side_t const>` | The late-interaction side of each item; empty takes no item into late interaction. |
| `choices` | `tape_view<char>` | The legal choices of each item, one byte each, as [`text_choose`](https://www.unum.cloud/docs/uform/cpp/models.md#text_choose) takes them. |
| `choice_targets` | `tape_view<float>` | The target probability of each choice, in `choices` order, as [`text_choose`](https://www.unum.cloud/docs/uform/cpp/models.md#text_choose) answers. |
| `relations` | `uform_relations_view_t` | The attract, repel and ignore edges over the step's items. |
| `arena` | `arena_t *` | Where the pooled embeddings the loss scored land; `nullptr` skips the copy. |
| `outputs_scalar` | `uform_scalar_t` | The scalar type the embeddings land as. |
| `stats` | `uform_trainer_step_stats_t *` | The report the step overwrites; `nullptr` skips it and the readback of the losses. |

##### Class `trainer`

A trainer and its verbs, completed as `receiver_type_` says: the owning handle and [`on`](#on) block, while [`deferred`](#deferred) answers deferred calls, whose every input stays the caller's until final.7

[train.hpp:93 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/train.hpp#L93)

```cpp
template <typename receiver_type_>
class trainer
```

###### `trainer`

[train.hpp:104 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/train.hpp#L104)

```cpp
requires an_owning_receiver<receiver_type_>
trainer() noexcept=default;
```

###### `handle_field`

The output field a lifecycle verb writes the new handle into.

[train.hpp:111 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/train.hpp#L111)

```cpp
requires an_owning_receiver<receiver_type_>
uform_trainer_t * handle_field() noexcept;
```

###### `on`

The same handle, whose verbs block on `executor`.

[train.hpp:118 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/train.hpp#L118)

```cpp
trainer<caller_owned<uform_trainer_t, uform_completion_blocking_k>> on(
    executor_t const & executor) const noexcept;
```

###### `deferred`

The same handle, whose verbs submit to `executor`, each answering a [`deferred`](#deferred) call.

[train.hpp:124 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/train.hpp#L124)

```cpp
trainer<caller_owned<uform_trainer_t, uform_completion_deferred_k>> deferred(
    executor_t const & executor) const noexcept;
```

###### `step`

Applies one optimizer step over this process's items, tagged by `modalities`, and every peer's, answering the pooled embeddings the loss scored when `config` names an arena.

[train.hpp:132 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/train.hpp#L132)

```cpp
deferrable<written_rows_t> step(
    std::span<uform_modality_t const> modalities,
    tape_view<std::uint8_t> contents,
    trainer_step_config_t const & config = {}) const noexcept;
```

###### `save`

Writes the weights and the step to a safetensors checkpoint at `path`, which only the process of index zero writes.

[train.hpp:185 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/train.hpp#L185)

```cpp
deferrable save(
    uform_bytes_view_t path,
    progress_t progress = {}) const noexcept;
```

###### `init_vram`

Builds one replica per device of the executor `arguments` names and starts or resumes the run, blocking until every process of the run has.

[train.hpp:195 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/train.hpp#L195)

```cpp
requires an_owning_receiver<receiver_type_>
expected<trainer> init_vram(
    uform_trainer_init_vram_t arguments) noexcept;
```

## Errors

`#include <uform/types.hpp>` 4.0.0-rc.1 · c58749fe

Every fallible call answers a `status_t` alone, or an `expected<T>`, a plain pair unpacked as `auto [value, status]`, whose value is default-constructed on failure. A `status_t` carries a `status_code_t` and an optional static `note`, so nothing allocates on the failure path. Recovery branches on the code, while the note names the broken invariant, step or resource for logs, falling back to the status name. A failure the SDK catches before the call crosses the boundary reports the status the library would have used.

```cpp
auto [encoded, status] = model.on(executor).text_encode(texts, uf::encode_outputs_t::embeddings_k, uform_scalar_f32_k, arena);
if (status == uf::status_code_t::contended_k) retry();
else if (status.failed()) fmt::println(stderr, "{}", status.note);
else fmt::println("{} items", encoded.embeddings.written);
```

`status_code_t` carries the C enumerators’ values, and `status_code_t::deferred_k` reaches only `deferred::status`. The C name tables, such as `uform_status_name` and `uform_scalar_from_name`, are called directly, since every SDK header includes its C header. A handler is a `noexcept` callable, so no fault unwinds through the library.

### API

#### Types

##### `status_code_t`

What went wrong, with one enumerator per status the library reports.

[types.hpp:38 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L38)

```cpp
enum status_code_t
```

##### Values

| `success_k` | `uform_status_success_k` | |
| - | - | - |
| `deferred_k` | `uform_status_deferred_k` | |
| `out_of_memory_k` | `uform_status_out_of_memory_k` | |
| `shape_mismatch_k` | `uform_status_shape_mismatch_k` | |
| `unsupported_layout_k` | `uform_status_unsupported_layout_k` | |
| `unknown_kind_k` | `uform_status_unknown_kind_k` | |
| `io_k` | `uform_status_io_k` | |
| `device_k` | `uform_status_device_k` | |
| `malformed_k` | `uform_status_malformed_k` | |
| `internal_k` | `uform_status_internal_k` | |
| `overflow_k` | `uform_status_overflow_k` | |
| `uninitialized_k` | `uform_status_uninitialized_k` | |
| `config_mismatch_k` | `uform_status_config_mismatch_k` | |
| `contended_k` | `uform_status_contended_k` | |
| `cancelled_k` | `uform_status_cancelled_k` | |
| `unsupported_k` | `uform_status_unsupported_k` | |
| `invalid_argument_k` | `uform_status_invalid_argument_k` | |

##### `status_t`

Why a call failed: a code recovery branches on, and an optional static note naming the broken invariant, step or resource, for logs and regression analysis.

[types.hpp:62 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L62)

```cpp
struct status_t
```

##### Fields

| `code` | `status_code_t` | |
| - | - | - |
| `note` | `char const *` | |

##### `expected`

A call's value beside its status, bound natively as `auto [value, status]`.

[types.hpp:80 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/cpp/uform/types.hpp#L80)

```cpp
template <typename value_type_>
struct expected
```

##### Fields

| `value` | `value_type_` | |
| - | - | - |
| `status` | `status_t` | |

## Design

4.0.0-rc.1 · c58749fe

- **A thin layer over the C ABI.** One header per C header, `types.hpp`, `model.hpp`, `encode.hpp` and `train.hpp`, behind `uform.hpp`; every name is its C name without `uform_`, and every factory takes its C argument struct by designator.
- **The receiver chooses, the verb stays.** The model runs a verb on the calling thread, `on(executor)` blocks on an executor, and `deferred(executor)` submits it, all with the same arguments.
- **Deferred calls use the language’s own idioms.** `status` polls through `uform_outcome_status`, `wait()` blocks through `uform_outcome_wait`, and `co_await wait(loop)` re-polls through the caller’s scheduler, since the library has no wake-up.
- **No life of its own.** The SDK starts no threads and keeps no queues, counts or caches; destroying a `deferred` waits for the call first.
- **Arenas belong to the caller and are reused, never shared.** Every output verb takes an arena and answers views into it, valid until the arena’s next call.
- **Nothing costs anything until it is used.** A blocking call keeps its outcome and outputs on the stack, a deferred one inside the `deferred` it answers, and awaiting posts two words to the caller’s loop, so the SDK allocates nothing on any path.
- **Suites run against the stub library**, and against the real one with the tiny checkpoint.

| Path | C++ | Rust |
| - | - | - |
| Blocking call | 0 | 0 |
| Refusal before the call | 0 | 1 error |
| Deferred submit and wait | 0: the `deferred` lives with the caller | 0: the `Deferred` is pinned where it is polled |
| Each callback | 0 | 0 |
