# UForm for Go

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

`go get github.com/unum-cloud/uform/golang@main` 4.0.0-rc.1 · c58749fe

The Go package binds the stable C ABI in `c/uform/` through cgo and links the precompiled static library, so no tower is compiled in your build.

It needs Go 1.24 or newer with cgo enabled and a C toolchain, and answers every call as `(T, error)`. Building `libuform_static` from a checkout 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. Every verb is a batch, and every output whose length the call decides lands in an arena you reuse.

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

## Installation

`import "github.com/unum-cloud/uform"` 4.0.0-rc.1 · c58749fe

The Go package is a cgo layer over the C library, fetched as a module:

```sh
go get github.com/unum-cloud/uform/golang@main
```

The package includes the headers of its own module’s `c/` folder and links `libuform_static`, which you build from a checkout and name to cgo:

```sh
cmake --preset library && cmake --build --preset library --target uform_static
export CGO_LDFLAGS="-L$PWD/build_library/src -lturbojpeg -lpng -lwebp -lavformat -lavcodec -lavutil -lswresample -lswscale"
```

The archive carries UForm and its bundled libraries, while the system image, video and audio codecs its host decoders call stay shared libraries, which cgo links by name as Rust’s `build.rs` does; the stand-in needs none of them. `-D UFORM_ENCODER_DTYPES=bf16` narrows the block-product dtypes the archive compiles from the default `bf16;e4m3`, and a model load in a left-out one fails with `StatusUnsupported`. `EncoderDTypesCompiled()` answers the kept ones as a mask, bit `n` standing for the `Scalar` valued `n`.

The module carries no version suffix, so pin a branch or a commit, `@main` or `@<commit>`, which `go.sum` locks as a pseudo-version. The suites run against the stand-in library, which answers every verb over the C++ standard library alone:

```sh
cmake --preset stub_library -D UFORM_WITH_CODECS=OFF && cmake --build --preset stub_library --target uform_static_stub
CGO_LDFLAGS="-L$PWD/build_stub_library/stub" go test -race ./golang/...
```

### API

#### Functions

##### `EncoderDTypesCompiled`

EncoderDTypesCompiled is the mask of block-product dtypes the linked encoder compiles, bit n standing for the Scalar valued n.

[uform.go:1269 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/uform.go#L1269)

```go
func EncoderDTypesCompiled() uint64
```

##### `Version`

Version reports the version of the linked library.

[uform.go:1261 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/uform.go#L1261)

```go
func Version() string
```

## Quickstart

`import "github.com/unum-cloud/uform"` 4.0.0-rc.1 · c58749fe

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

```go
package main

import (
	"fmt"
	"log"
	"math"
	"os"

	uform "github.com/unum-cloud/uform/golang"
)

func main() {
	executor, err := uform.ExecutorForRam(nil, uform.CPUClassUnknown, 0) // the threads every receiver names
	if err != nil {
		log.Fatal(err)
	}
	defer executor.Close()
	textsArena, err := uform.NewArena(executor) // a call rewinds its arena, so two outputs need two
	if err != nil {
		log.Fatal(err)
	}
	defer textsArena.Close()
	imagesArena, err := uform.NewArena(executor)
	if err != nil {
		log.Fatal(err)
	}
	defer imagesArena.Close()
	model, err := uform.ModelLoadRam("model.safetensors", nil) // BFloat16 blocks, as the checkpoint stores them
	if err != nil {
		log.Fatal(err)
	}
	defer model.Close()

	captions := []string{"a cat on a mat", "a sunrise over the bay"}
	photo, err := os.ReadFile("cat.png")
	if err != nil {
		log.Fatal(err)
	}
	texts, err := model.On(executor).TextEncode(uform.TapeOf(captions), uform.EncodeOutputsEmbeddings, uform.ScalarF32, textsArena, nil)
	if err != nil {
		log.Fatal(err)
	}
	images, err := model.On(executor).ImageEncode(uform.TapeOf([][]byte{photo}), uform.EncodeOutputsEmbeddings, uform.ScalarF32, imagesArena, nil)
	if err != nil {
		log.Fatal(err)
	}

	image, err := uform.RowValues[float32](images.Embeddings, 0) // zero-copy from the arena; embeddings come unnormalized
	if err != nil {
		log.Fatal(err)
	}
	cosine := func(text []float32) float64 {
		var dot, textNorm, imageNorm float64
		for dimension := range text {
			dot += float64(text[dimension]) * float64(image[dimension])
			textNorm += float64(text[dimension]) * float64(text[dimension])
			imageNorm += float64(image[dimension]) * float64(image[dimension])
		}
		return dot / math.Sqrt(textNorm*imageNorm)
	}
	best, bestCosine := 0, math.Inf(-1)
	for row := range captions {
		text, err := uform.RowValues[float32](texts.Embeddings, uint(row))
		if err != nil {
			log.Fatal(err)
		}
		if similarity := cosine(text); similarity > bestCosine {
			best, bestCosine = row, similarity
		}
	}
	fmt.Printf("'%s' describes the photo best\n", captions[best])
}
```

`golang/example_test.go` holds the same program, so `go test` compiles it.

### API

#### Types

##### `BFloat16`

BFloat16 holds the sixteen bits of a brain floating-point value.

[types.go:240 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L240)

```go
type BFloat16 uint16
```

## Receivers and Deferred Calls

`import "github.com/unum-cloud/uform"` 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.TextEncode(..)` runs on the calling goroutine, through the `ModelOn` a `Model` embeds.
- `model.On(executor).TextEncode(..)` blocks on the executor, failing `StatusContended` while another call holds it.
- `model.Deferred(executor).TextEncode(..)` submits the call and answers a `*Deferred[Encoded]`.

`ModelOn` and `ModelDeferredOn` offer every model verb with the same arguments, as `TrainerOn` and `TrainerDeferredOn` do for a trainer. A blocking verb answers `(T, error)` directly, so nothing about asynchrony reaches a caller who never asks for it.

```go
call, err := model.Deferred(executor).TextEncode(texts, uform.EncodeOutputsEmbeddings, uform.ScalarF32, arena, nil)
if err != nil {
	return err // refused before anything was submitted
}
if call.Status() == uform.StatusDeferred {
	// other work
}
encoded, err := call.Wait()
```

A deferred verb answers `(*Deferred[T], error)`, so a refusal the binding catches arrives at once, as a blocking one would, and nothing is submitted. `Status` answers `StatusDeferred` until the call is final, then its final status, and `Wait` blocks the goroutine in cgo until then, answering the same result every time. A goroutine calling `Wait` overlaps the wait, and a `select` reaches it through a channel that goroutine closes; the package starts no goroutine of its own. `Close` waits the same way and drops the result, and a `Deferred` dropped without either is released by the collector once final, never blocking it.

The library reads a deferred call’s inputs after the verb returns, so the tapes, slices, handlers and reports a deferred verb names must not change until the call is final; the binding pins every one of them. An executor without threads of its own may run a deferred call at submission, final when the verb returns.

### API

#### Types

##### `ProgressCallback`

ProgressCallback is called with the units a long call finished so far and the units it finishes unless stopped; false stops it, and the call fails with [StatusCancelled](https://www.unum.cloud/docs/uform/go/errors.md#StatusCancelled).

[types.go:520 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L520)

```go
type ProgressCallback func(completed, total uint) bool
```

It never runs on two threads at once, and it must not panic.

##### Struct `Deferred`

Deferred is a submitted call, which holds its outcome and inputs until it is final, owned by the one goroutine that polls or waits on it.3

[types.go:1081 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L1081)

```go
type Deferred[Result any] struct {
    // contains filtered or unexported fields
}
```

Status polls without blocking, Wait blocks until the call is final and hands back its result, and Close waits the same way and drops it. A Deferred dropped without Wait or Close is released by the collector once the call is final, never blocking on it: until then every later collection checks it again.

###### `Close`

Close blocks until the call is final, releases its pins, and reports the call's failure.

[types.go:1118 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L1118)

```go
func (deferred *Deferred[Result]) Close() error
```

It is idempotent and safe after Wait.

###### `Status`

Status reports StatusDeferred until the call is final, then its final status, without blocking.

[types.go:1107 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L1107)

```go
func (deferred *Deferred[Result]) Status() Status
```

###### `Wait`

Wait blocks until the call is final, releases its pins, then hands back its result, the same every time it is asked.

[types.go:1111 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L1111)

```go
func (deferred *Deferred[Result]) Wait() (Result, error)
```

##### Struct `ModelDeferredOn`

ModelDeferredOn is the receiver whose verbs submit their calls to an executor and answer a Deferred, offering every verb of ModelOn with the same arguments.8

[model.go:257 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L257)

```go
type ModelDeferredOn struct {
    // contains filtered or unexported fields
}
```

Binding-only.

The library reads a deferred call's inputs until the call is final, so the tapes and slices a verb is handed must not change until then; its arena stays in use until then, as with a blocking verb.

###### `AudioEncode`

AudioEncode submits ModelOn.AudioEncode.

[model.go:283 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L283)

```go
func (on ModelDeferredOn) AudioEncode(
    recordings Tape,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *AudioEncodeConfig,
) (*Deferred[Encoded], error)
```

###### `AudioEncodeSamples`

AudioEncodeSamples submits ModelOn.AudioEncodeSamples.

[model.go:300 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L300)

```go
func (on ModelDeferredOn) AudioEncodeSamples(
    samples Tape,
    sampleRate uint32,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *AudioEncodeConfig,
) (*Deferred[Encoded], error)
```

###### `Describe`

Describe submits ModelOn.Describe.

[model.go:284 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L284)

```go
func (on ModelDeferredOn) Describe() (*Deferred[ModelDescription], error)
```

###### `ImageEncode`

ImageEncode submits ModelOn.ImageEncode.

[model.go:234 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L234)

```go
func (on ModelDeferredOn) ImageEncode(
    images Tape,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *ImageEncodeConfig,
) (*Deferred[Encoded], error)
```

###### `ImageEncodePixels`

ImageEncodePixels submits ModelOn.ImageEncodePixels.

[model.go:251 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L251)

```go
func (on ModelDeferredOn) ImageEncodePixels(
    pixels Tape,
    heights, widths []uint32,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *ImageEncodeConfig,
) (*Deferred[Encoded], error)
```

###### `TextChoose`

TextChoose submits ModelOn.TextChoose.

[model.go:218 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L218)

```go
func (on ModelDeferredOn) TextChoose(
    texts, choices Tape,
    arena *Arena,
    config *TextChooseConfig,
) (*Deferred[TapeView], error)
```

###### `TextEncode`

TextEncode submits ModelOn.TextEncode.

[model.go:201 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L201)

```go
func (on ModelDeferredOn) TextEncode(
    texts Tape,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *TextEncodeConfig,
) (*Deferred[Encoded], error)
```

###### `VideoEncode`

VideoEncode submits ModelOn.VideoEncode.

[model.go:267 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L267)

```go
func (on ModelDeferredOn) VideoEncode(
    videos Tape,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *VideoEncodeConfig,
) (*Deferred[Encoded], error)
```

##### Struct `ModelOn`

ModelOn is the receiver whose verbs block until their call is final: on the calling goroutine when embedded in a Model, and on an executor when Model.On makes it.10

[model.go:247 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L247)

```go
type ModelOn struct {
    // contains filtered or unexported fields
}
```

Binding-only.

###### `AudioEncode`

AudioEncode decodes and encodes WAV, FLAC, MP3 or Opus recordings, resampled to mono.

[model.go:276 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L276)

```go
func (on ModelOn) AudioEncode(
    recordings Tape,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *AudioEncodeConfig,
) (Encoded, error)
```

Calls uform_audio_encode.

###### `AudioEncodeSamples`

AudioEncodeSamples encodes decoded mono ScalarF32 recordings sharing one sampleRate, resampled to the model's rate where it differs.

[model.go:293 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L293)

```go
func (on ModelOn) AudioEncodeSamples(
    samples Tape,
    sampleRate uint32,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *AudioEncodeConfig,
) (Encoded, error)
```

Calls uform_audio_encode_samples.

###### `Deferred`

Deferred is the receiver whose verbs submit their calls to executor, each answering a Deferred from the same arguments.

[model.go:270 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L270)

```go
func (on ModelOn) Deferred(executor *Executor) ModelDeferredOn
```

Binding-only.

###### `Describe`

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

[model.go:278 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L278)

```go
func (on ModelOn) Describe() (ModelDescription, error)
```

Calls uform_model_describe.

###### `ImageEncode`

ImageEncode decodes and encodes JPEG, PNG or WebP files; an undecodable file fails the call with StatusMalformed.

[model.go:227 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L227)

```go
func (on ModelOn) ImageEncode(
    images Tape,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *ImageEncodeConfig,
) (Encoded, error)
```

Calls uform_image_encode.

###### `ImageEncodePixels`

ImageEncodePixels encodes decoded images of interleaved 8-bit RGB, item i holding heights\[i] rows of widths\[i] pixels; an item of another length fails with StatusShapeMismatch.

[model.go:244 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L244)

```go
func (on ModelOn) ImageEncodePixels(
    pixels Tape,
    heights, widths []uint32,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *ImageEncodeConfig,
) (Encoded, error)
```

Calls uform_image_encode_pixels.

###### `On`

On is the receiver whose verbs block on executor, failing StatusContended while another call holds it.

[model.go:263 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L263)

```go
func (on ModelOn) On(executor *Executor) ModelOn
```

Binding-only.

###### `TextChoose`

TextChoose scores each item's legal choices, one byte each, after its UTF-8 state in texts, through one forward, answering one ScalarF32 probability per choice in arena, a softmax over the item's choices alone.

[model.go:212 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L212)

```go
func (on ModelOn) TextChoose(
    texts, choices Tape,
    arena *Arena,
    config *TextChooseConfig,
) (TapeView, error)
```

A model without the byte decoder fails it with StatusUnsupported.

Calls uform_text_choose.

###### `TextEncode`

TextEncode encodes UTF-8 texts through one forward, a token per byte, since models are tokenizer-free, keeping the surfaces outputs names as outputsScalar in arena.

[model.go:194 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L194)

```go
func (on ModelOn) TextEncode(
    texts Tape,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *TextEncodeConfig,
) (Encoded, error)
```

Calls uform_text_encode.

###### `VideoEncode`

VideoEncode decodes and encodes MP4 or WebM clips.

[model.go:260 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L260)

```go
func (on ModelOn) VideoEncode(
    videos Tape,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *VideoEncodeConfig,
) (Encoded, error)
```

Calls uform_video_encode.

##### Enum `Mood`

Mood is what an executor's threads do between a drain and its next call.2

[types.go:591 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L591)

```go
type Mood int32
```

##### Values

| `MoodParked` | | MoodParked sleeps in the kernel until the next call, freeing the cores. |
| - | - | - |
| `MoodSpinning` | | MoodSpinning keeps polling, trading the cores for the lowest wake-up latency. |

###### `MoodFromName`

MoodFromName reads a mood back from the spelling [Mood.String](https://www.unum.cloud/docs/uform/go/errors.md#String) renders.

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

```go
func MoodFromName(name string) (Mood, error)
```

###### `String`

String renders the mood as the library spells it.

[types.go:601 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L601)

```go
func (mood Mood) String() string
```

##### Struct `TrainerDeferredOn`

TrainerDeferredOn is the receiver whose verbs submit their calls and answer a Deferred, offering every verb of TrainerOn with the same arguments.1

[train.go:667 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L667)

```go
type TrainerDeferredOn struct {
    // contains filtered or unexported fields
}
```

Binding-only.

###### `*`

× 2 Save submits TrainerOn.Save.

[train.go:711 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L711)

```go
func (on TrainerDeferredOn) Save(
    path string,
    config *TrainerSaveConfig,
) (*Deferred[struct{}], error)
```

| Symbol |
| - |
| `Save` |
| `Step` |

## Executors

`import "github.com/unum-cloud/uform"` 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.

```go
threads, err := uform.ExecutorForRam(nil, uform.CPUClassUnknown, 8)                  // eight threads, where zero takes 7/8 of the cores
nearby, err := uform.ExecutorForRam([]int32{1}, uform.CPUClassUnknown, 0)            // threads spawned near NUMA node 1
serial, err := uform.ExecutorForRam(nil, uform.CPUClassSerial, 0)                    // dispatches as the portable floor
streams, err := uform.ExecutorForVram([]int32{0, 1}, uform.GPUClassUnknown, nil, uform.CPUClassUnknown, nil, 0)
var local *uform.Executor                                                            // owns nothing, runs on the calling goroutine

err = threads.Drain(uform.MoodSpinning) // waits until no call holds it, then keeps spinning
```

The class arguments are ceilings: calls dispatch as the best class under them the hardware runs, and the zero class sets none. Naming one memory domain spawns the threads near it, while none or several interleave them across the machine. `ExecutorForVram` opens one stream per device, or adopts the caller’s streams, one per named device, and `Close` destroys them; naming no devices drives every listed device of the first vendor with a known class. `uform.GPUDevices(devices)` fills a slice of `GPUDevice` and answers how many GPUs the process can drive, and a device’s position there is the ordinal `ExecutorForVram` and `ModelLoadVram` name it by. An executor runs one call at a time, so two goroutines that genuinely overlap take one apiece. `Close` waits until no call holds the executor, and a closed one refuses every later verb with `StatusUninitialized`.

### API

#### Types

##### `MeshDescription`

MeshDescription is what a mesh reports about itself.

[types.go:343 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L343)

```go
type MeshDescription struct {
    GPUsPerHostDomain      uint
    GPUsPerMultimemDomain  uint
    GPUsPerColocatedDomain uint
    HostDomainIndex        uint
    FirstGPUIndex          uint
    MultimemTier           MultimemTier
    GPUClass               GPUClass
}
```

Mirrors uform_mesh_description_t field for field, so the library writes it in place.

##### `MeshOptions`

MeshOptions is where this process sits among the processes of a run, and how they meet.

[types.go:325 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L325)

```go
type MeshOptions struct {
    HostDomainIndex uint
    HostDomainCount uint
    GPUsPerMultimemDomain uint
    Directory string
    Job string
    TimeoutSeconds float64
}
```

Mirrors uform_mesh_options_t.

##### Fields

| `HostDomainIndex` | `uint` | HostDomainIndex is this process's index among HostDomainCount. |
| - | - | - |
| `HostDomainCount` | `uint` | HostDomainCount is the processes in the run; zero derives one. |
| `GPUsPerMultimemDomain` | `uint` | GPUsPerMultimemDomain is the GPUs one NVLink multicast domain spans; zero derives the host. |
| `Directory` | `string` | Directory is the path every host sees, where processes exchange their facts. |
| `Job` | `string` | Job is the run's unique name, naming one directory inside Directory. |
| `TimeoutSeconds` | `float64` | TimeoutSeconds is how long any wait for a peer lasts; zero derives 120. |

##### Enum `CPUClass`

CPUClass is a CPU family UForm ships tuned variants for, numbered as USearch numbers it; a RAM placement or executor may cap dispatch at one, and the zero value sets no ceiling.2

[types.go:614 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L614)

```go
type CPUClass int32
```

##### Values

| `CPUClassUnknown` | | CPUClassUnknown sets no ceiling, so dispatch may pick any class the machine runs. |
| - | - | - |
| `CPUClassSerial` | | CPUClassSerial is the portable floor, with no SIMD assumptions. |
| `CPUClassMonoversioned` | | CPUClassMonoversioned is the one class of a monoversioned build. |
| `CPUClassIntelHaswell` | | CPUClassIntelHaswell is Haswell-class x86: AVX2 and FMA. |
| `CPUClassIntelSierra` | | CPUClassIntelSierra is Sierra Forest-class x86: AVX-VNNI without AVX-512. |
| `CPUClassIntelSkylake` | | CPUClassIntelSkylake is Skylake-class x86: the AVX-512 foundation. |
| `CPUClassIntelIcelake` | | CPUClassIntelIcelake is Icelake-class x86: AVX-512 VNNI and VPOPCNT. |
| `CPUClassAMDGenoa` | | CPUClassAMDGenoa is Genoa-class x86: native bf16 dot products over AVX-512. |
| `CPUClassIntelSapphire` | | CPUClassIntelSapphire is Sapphire Rapids-class x86: AVX-512 FP16 and the AMX tiles. |
| `CPUClassIntelGranite` | | CPUClassIntelGranite is Granite Rapids-class x86: the AMX-FP16 tiles. |
| `CPUClassIntelDiamond` | | CPUClassIntelDiamond is Diamond Rapids-class x86: AVX10.2's FP8 conversions. |
| `CPUClassAWSG2` | | CPUClassAWSG2 is Graviton2-class Arm: the bare NEON floor. |
| `CPUClassAppleM2` | | CPUClassAppleM2 is Armv8.6 NEON with dot products and bf16. |
| `CPUClassAppleM4` | | CPUClassAppleM4 is Apple M4-class Arm: the SME outer-product tiles. |
| `CPUClassAWSG5` | | CPUClassAWSG5 is Graviton5-class Arm: Armv9.2. |
| `CPUClassNVIDIAVera` | | CPUClassNVIDIAVera is Vera-class Arm: FP8 dot products. |
| `CPUClassAlibabaC930` | | CPUClassAlibabaC930 is Alibaba C930-class RISC-V: RVA23 vectors. |
| `CPUClassIBMPower10` | | CPUClassIBMPower10 is IBM POWER10-class Power: VSX vectors and MMA accumulators. |
| `CPUClassWasm32V128` | | CPUClassWasm32V128 is WebAssembly with fixed-width simd128. |
| `CPUClassWasm64Extended` | | CPUClassWasm64Extended is WebAssembly with relaxed SIMD, threads and 64-bit addressing. |

###### `CPUClassFromName`

CPUClassFromName reads a CPU class back from the spelling [CPUClass.String](https://www.unum.cloud/docs/uform/go/errors.md#String) renders.

[types.go:665 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L665)

```go
func CPUClassFromName(name string) (CPUClass, error)
```

###### `*String`

× 2 String renders the class as the library spells it.

[types.go:660 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L660)

```go
func (class CPUClass) String() string
```

##### Struct `Executor`

Executor owns the host threads or device streams a call runs on, the activation scratch, and the pinned buffers staging passes through, apart from any model.4

[types.go:559 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L559)

```go
type Executor struct {
    // contains filtered or unexported fields
}
```

One executor serves any number of models of its residency, while a model owns only its weights, which is what lets one pool serve several models and keeps the cost of spawning visible at the line that spawns it. Its kind is fixed by the constructor that produced it.

A nil \*Executor is the null executor: it owns nothing, and every call handed it runs on the calling goroutine. One call holds an executor at a time; a second call finding it held finishes StatusContended, and nothing queues.

###### `ExecutorForRam`

ExecutorForRam spawns host threads for RAM-resident models near the one memory domain memoryDomains names, or interleaved across the machine for none or several; the list is the one the models were loaded with, and an empty list derives it from the machine.

[types.go:789 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L789)

```go
func ExecutorForRam(
    memoryDomains []int32,
    cpuClassCeiling CPUClass,
    threads uint,
) (*Executor, error)
```

Zero threads takes seven eighths of the cores those domains carry. A cpuClassCeiling intersects with what the machine runs, so a class the machine lacks narrows rather than refuses.

###### `ExecutorForVram`

ExecutorForVram opens one submission stream on every named device, all driven by the one host thread that calls the verbs, beside host threads on memoryDomains for the decoding the devices leave to the host.

[types.go:810 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L810)

```go
func ExecutorForVram(
    devices []int32,
    gpuClassCeiling GPUClass,
    memoryDomains []int32,
    cpuClassCeiling CPUClass,
    streams []unsafe.Pointer,
    scratchLimit uint,
) (*Executor, error)
```

Streams is empty, or holds one stream per device in devices order: 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. Zero scratchLimit lets scratch grow as batches ask.

###### `Close`

Close waits out the call holding the executor, then releases its threads, rings or streams; every arena it made must be closed first, or it fails with [StatusContended](https://www.unum.cloud/docs/uform/go/errors.md#StatusContended) and frees nothing, so a later Close retries.

[types.go:1168 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L1168)

```go
func (executor *Executor) Close() error
```

It is idempotent; a closed executor must not be used again.

###### `Drain`

Drain waits until no call holds this executor, then adopts mood until the next call; it only waits and never runs a call itself.

[types.go:844 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L844)

```go
func (executor *Executor) Drain(mood Mood) error
```

A failure is the executor's own, such as a lost device, never one of a drained call.

##### Enum `GPUClass`

GPUClass is a GPU family UForm ships tuned variants for, numbered as USearch numbers it; a VRAM placement or executor may cap dispatch at one, and the zero value sets no ceiling.1

[types.go:673 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L673)

```go
type GPUClass int32
```

##### Values

| `GPUClassUnknown` | | GPUClassUnknown sets no ceiling, so dispatch may pick any class every named device loads. |
| - | - | - |
| `GPUClassNVIDIAAmpere` | | GPUClassNVIDIAAmpere is Ampere-class NVIDIA, and every newer GPU whose driver compiles its PTX. |
| `GPUClassNVIDIAAda` | | GPUClassNVIDIAAda is Ada-class NVIDIA: the fp8 conversions. |
| `GPUClassNVIDIAHopper` | | GPUClassNVIDIAHopper is Hopper-class NVIDIA. |
| `GPUClassNVIDIABlackwell` | | GPUClassNVIDIABlackwell is Blackwell-class NVIDIA. |
| `GPUClassNVIDIABlackwellRTX` | | GPUClassNVIDIABlackwellRTX is Consumer Blackwell NVIDIA. |
| `GPUClassNVIDIARubin` | | GPUClassNVIDIARubin is Rubin-class NVIDIA. |
| `GPUClassAMDCDNA3` | | GPUClassAMDCDNA3 is CDNA3 AMD: gfx942. |
| `GPUClassAMDCDNA4` | | GPUClassAMDCDNA4 is CDNA4 AMD: gfx950. |
| `GPUClassAMDCDNA5` | | GPUClassAMDCDNA5 is CDNA5 AMD: gfx1250. |
| `GPUClassAppleMetal7` | | GPUClassAppleMetal7 is Apple7-family GPUs, and every Apple GPU without a class of its own. |
| `GPUClassAppleMetal9` | | GPUClassAppleMetal9 is Apple9-family GPUs. |
| `GPUClassAppleMetal10` | | GPUClassAppleMetal10 is Apple10-family GPUs. |

###### `GPUClassFromName`

GPUClassFromName reads a GPU class back from the spelling [GPUClass.String](https://www.unum.cloud/docs/uform/go/errors.md#String) renders.

[types.go:710 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L710)

```go
func GPUClassFromName(name string) (GPUClass, error)
```

##### Struct `GPUDevice`

GPUDevice is one GPU as UForm numbers it: its position in what GPUDevices fills is the ordinal every VRAM call names.1

[types.go:739 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L739)

```go
type GPUDevice struct {
    Vendor GPUVendor
    VendorOrdinal uint32
    GPUClass GPUClass
    ComputeUnits uint32
    MemoryBytes uint64
    // contains filtered or unexported fields
}
```

Mirrors uform_gpu_device_t field for field, so the library writes it in place.

##### Fields

| `Vendor` | `GPUVendor` | Vendor is the runtime that drives the device. |
| - | - | - |
| `VendorOrdinal` | `uint32` | VendorOrdinal is the device's ordinal in its vendor's runtime. |
| `GPUClass` | `GPUClass` | GPUClass is the newest class whose code runs on it, or GPUClassUnknown where none does. |
| `ComputeUnits` | `uint32` | ComputeUnits counts streaming multiprocessors or compute units. |
| `MemoryBytes` | `uint64` | MemoryBytes is the device memory. |

###### `Name`

Name reports the vendor's own name for the device.

[types.go:754 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L754)

```go
func (device GPUDevice) Name() string
```

##### Enum `GPUVendor`

GPUVendor is the runtime that drives a GPU.1

[types.go:717 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L717)

```go
type GPUVendor int32
```

##### Values

| `GPUVendorUnknown` | | GPUVendorUnknown names no vendor. |
| - | - | - |
| `GPUVendorNVIDIA` | | GPUVendorNVIDIA drives the device through the CUDA driver. |
| `GPUVendorAMD` | | GPUVendorAMD drives the device through the HIP runtime. |
| `GPUVendorApple` | | GPUVendorApple drives the device through Metal. |

###### `String`

String renders the vendor as the library spells it.

[types.go:731 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L731)

```go
func (vendor GPUVendor) String() string
```

##### Struct `Mesh`

Mesh is one process's place among the processes of a run, made once and referred to by every trainer, which must be closed first.3

[train.go:500 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L500)

```go
type Mesh struct {
    // contains filtered or unexported fields
}
```

Mirrors uform_mesh_t; Close calls uform_mesh_free.

###### `MeshBootstrap`

MeshBootstrap joins this process to the run's mesh over executor, a VRAM executor whose devices are this process's members; every process of the run calls it with the same options.

[train.go:508 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L508)

```go
func MeshBootstrap(
    executor *Executor,
    config *MeshOptions,
) (*Mesh, error)
```

Calls uform_mesh_bootstrap, blocking.

###### `Close`

Close leaves the mesh.

[train.go:557 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L557)

```go
func (mesh *Mesh) Close() error
```

It is idempotent, and every trainer made over the mesh must be closed first.

###### `Describe`

Describe reports the mesh's shape and this process's place in it.

[train.go:540 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L540)

```go
func (mesh *Mesh) Describe() (MeshDescription, error)
```

Calls uform_mesh_describe.

##### Enum `MultimemTier`

MultimemTier is how a mesh's NVLink domains reduce.2

[train.go:166 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L166)

```go
type MultimemTier int32
```

##### Values

| `MultimemTierSwitchReduced` | | MultimemTierSwitchReduced reduces through the NVLink switch's multicast memory. |
| - | - | - |
| `MultimemTierPeerRead` | | MultimemTierPeerRead reads every peer in a fixed order, where multicast is absent. |

###### `MultimemTierFromName`

MultimemTierFromName reads a multimem tier back from the spelling [MultimemTier.String](https://www.unum.cloud/docs/uform/go/errors.md#String) renders.

[train.go:181 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L181)

```go
func MultimemTierFromName(name string) (MultimemTier, error)
```

###### `String`

String renders the tier as the library spells it.

[train.go:176 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L176)

```go
func (tier MultimemTier) String() string
```

#### Functions

##### `CapabilitiesAvailable`

CapabilitiesAvailable lists the hardware capabilities the current machine offers at runtime, comma separated.

[uform.go:1273 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/uform.go#L1273)

```go
func CapabilitiesAvailable() string
```

##### `CapabilitiesCompiled`

CapabilitiesCompiled lists the hardware capabilities the linked binary was compiled with, comma separated.

[uform.go:1265 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/uform.go#L1265)

```go
func CapabilitiesCompiled() string
```

##### `GPUDevices`

GPUDevices fills devices with the GPUs this process can drive, NVIDIA first, then AMD, then Apple, and reports how many there are, which may exceed len(devices).

[uform.go:770 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/uform.go#L770)

```go
func GPUDevices(devices []GPUDevice) (uint, error)
```

## Arenas

`import "github.com/unum-cloud/uform"` 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` you pass, and the verb answers views over it without copying. `uform.NewArena(executor)` places it where that executor computes, decided once, and `uform.NewArena(nil)` makes host pages for the calling goroutine. Each call rewinds its arena, so the previous call’s views and every slice they handed out end there, and a steady loop allocates once. A view read after a later call took its arena fails as `Contended`. A slice or segment an accessor returned is valid only until the arena’s next call. 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 `ResidencyVram`; where its `HostAccess` is `HostAccessRefused` no Go code may read it, so a verb given that arena fails with `StatusDevice` before it runs, while managed memory and Apple’s shared memory read like host pages. The Go binding has no pointer accessor or device export that could hand device outputs on unread, so CUDA and HIP device arenas are not usable from Go. An arena never outlives the executor that made it, so `defer executor.Close()` comes before `defer arena.Close()`, and an arena from `uform.NewArena(nil)` lives until it is closed.

```go
arena, err := uform.NewArena(executor)
for _, batch := range batches {
	encoded, err := model.On(executor).TextEncode(batch, uform.EncodeOutputsEmbeddings, uform.ScalarF32, arena, nil)
	if err != nil {
		return err
	}
	consume(encoded.Embeddings) // rewinds next iteration
}
```

`Close` waits for every deferred call naming the arena, and a call naming an arena that serves another call finishes with `StatusContended`.

### API

#### Types

##### `ArenaDescription`

ArenaDescription is where an arena's outputs live, which decides whether Go code may read them.

[types.go:898 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L898)

```go
type ArenaDescription struct {
    Residency Residency
    Device int32
    Vendor GPUVendor
    VendorOrdinal int32
    HostAccess HostAccess
}
```

Mirrors uform_arena_description_t field for field, so the library writes it in place.

##### Fields

| `Residency` | `Residency` | Residency is ResidencyRam for host pages and ResidencyVram for one device's memory. |
| - | - | - |
| `Device` | `int32` | Device is the ordinal of the GPU holding the outputs, as GPUDevices lists it, and -1 for host pages. |
| `Vendor` | `GPUVendor` | Vendor is the vendor whose memory it is, as GPUDevices reports it. |
| `VendorOrdinal` | `int32` | VendorOrdinal is the vendor's own device number, which Arrow and DLPack name, and -1 for host pages. |
| `HostAccess` | `HostAccess` | HostAccess is whether Go code may read the outputs. |

##### Struct `Arena`

Arena is memory the library writes every output whose length scales with a call into, pooled embeddings, per-token states and their offsets alike, reused so a steady loop allocates once.3

[types.go:870 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L870)

```go
type Arena struct {
    // contains filtered or unexported fields
}
```

Every call given an arena rewinds and refills it, so the views of its previous call and every slice they handed out end there, as they do once it is closed; to keep one call's views past the next, give that call another arena. An arena serves one call at a time, and a second overlapping it fails with StatusContended. Deferred verbs hold it as blocking ones do, since Close waits for every deferred call naming it. A verb given an arena whose Describe refuses host access fails with StatusDevice before it runs, since no Go code may read its views.

###### `NewArena`

NewArena makes an empty arena where executor computes, host pages or the memory of its GPU, decided once; a nil executor makes host pages for calls on the calling goroutine.

[types.go:879 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L879)

```go
func NewArena(executor *Executor) (*Arena, error)
```

Nothing is allocated until a call writes into it. An arena must not outlive the executor that made it, so defer [Executor.Close](https://www.unum.cloud/docs/uform/go/training.md#Close) before [Arena.Close](https://www.unum.cloud/docs/uform/go/training.md#Close); one made with a nil executor lives until it is closed. A GPU arena serves only calls on its executor.

###### `Close`

Close releases the memory, waiting for every deferred call naming the arena, and ends every view over it; it comes before the Close of the executor that made the arena.

[types.go:1195 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L1195)

```go
func (arena *Arena) Close() error
```

While an Arrow export of its outputs is unreleased it fails with [StatusContended](https://www.unum.cloud/docs/uform/go/errors.md#StatusContended) and frees nothing, so a later Close retries. It is idempotent, and a closed arena must not be used again.

###### `Describe`

Describe reports where the arena's outputs live, as the executor that made it decided.

[types.go:925 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L925)

```go
func (arena *Arena) Describe() (ArenaDescription, error)
```

##### Enum `HostAccess`

HostAccess is whether Go code may read an arena's outputs.1

[types.go:576 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L576)

```go
type HostAccess int32
```

##### Values

| `HostAccessRefused` | | HostAccessRefused is device memory the host must not read. |
| - | - | - |
| `HostAccessReadable` | | HostAccessReadable is host, pinned and managed memory, and Apple's shared memory. |

###### `String`

String renders the access as the library spells it, "refused" or "readable".

[types.go:586 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L586)

```go
func (access HostAccess) String() string
```

## Encoding

`import "github.com/unum-cloud/uform"` 4.0.0-rc.1 · c58749fe

One verb per input form, each spelled as in C, and each taking its inputs, the `EncodeOutputs` to keep, the scalar every output lands as, the arena, and last a config, nil for none:

- `TextEncode(texts, ..)` takes UTF-8 texts, a byte per token, since models are tokenizer-free.
- `ImageEncode(files, ..)` takes JPEG, PNG or WebP files.
- `ImageEncodePixels(pixels, heights, widths, ..)` takes interleaved 8-bit RGB, `heights[i]` rows of `widths[i]` pixels per item.
- `VideoEncode(files, ..)` takes MP4 or WebM clips.
- `AudioEncode(files, ..)` takes WAV, FLAC, MP3 or Opus recordings.
- `AudioEncodeSamples(samples, sampleRate, ..)` takes mono `float32` samples.

A `Tape` passes the elements and `count + 1` offsets to the library without a copy: `BytesTape(data, offsets)` for texts and files, and `SamplesTape(data, offsets)` for recordings. `TapeOf(items)` gathers separate strings or byte slices into a fresh tape with one copy, and `SamplesOf(recordings)` does so for samples:

```go
tape := uform.BytesTape([]byte("first documentthe second"), []uint{0, 14, 24})
encoded, err := model.TextEncode(tape, uform.EncodeOutputsStates, uform.ScalarBF16, arena, nil)
offsets := encoded.States.Offsets() // item `i` spans rows `offsets[i]` up to `offsets[i + 1]`
second, err := encoded.States.Item(1) // the rows of one item, as `Rows`
```

`EncodeOutputsEmbeddings`, `EncodeOutputsStates` and `EncodeOutputsTokenVectors` join with `|`, and a surface left out answers a zero `Count` 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 `StatusUnsupported`. The config reaches the knobs:

```go
stats := new(uform.TextEncodeStats)
config := &uform.TextEncodeConfig{
	Stats:    stats,
	Progress: func(completed, total uint) bool { return completed*2 < total },
}
encoded, err := model.TextEncode(texts, uform.EncodeOutputsEmbeddings, uform.ScalarF32, arena, config)
```

`Rows` reports its `Count`, `Columns`, `Stride` and `Scalar`, and `uform.RowValues[float32](rows, i)` views one row’s values, refused with `StatusInvalidArgument` when the rows hold another scalar type. `RowsTape` adds the `Offsets` and an `Item` per input. A handler answering false stops the call, which fails with `StatusCancelled` and publishes nothing.

### API

#### Types

##### `AudioEncodeConfig`

AudioEncodeConfig holds the knobs of AudioEncode and AudioEncodeSamples; nil derives every field.

[types.go:162 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L162)

```go
type AudioEncodeConfig struct {
    Progress ProgressCallback
    ProgressSteps uint
    Stats *AudioEncodeStats
}
```

Mirrors the knobs of uform_audio_encode_t and uform_audio_encode_samples_t.

##### Fields

| `Progress` | `ProgressCallback` | Progress hears the items encoded and may stop the call. |
| - | - | - |
| `ProgressSteps` | `uint` | ProgressSteps is the reports the call makes at most; zero derives ten. |
| `Stats` | `*AudioEncodeStats` | Stats is the report the call overwrites, kept by the caller until it is final; nil skips it. |

##### `AudioEncodeStats`

AudioEncodeStats is what an audio call reports beside its outputs, overwritten by the call.

[types.go:108 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L108)

```go
type AudioEncodeStats struct {
    Truncated uint
    Tokens uint
}
```

Mirrors uform_audio_encode_stats_t.

##### Fields

| `Truncated` | `uint` | Truncated counts the items cut at the model's context in frames. |
| - | - | - |
| `Tokens` | `uint` | Tokens counts the frames the call encoded, after truncation. |

##### `E2M3Scalar`

E2M3Scalar holds the six occupied bits of a two-exponent minifloat.

[types.go:250 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L250)

```go
type E2M3Scalar uint8
```

##### `E3M2Scalar`

E3M2Scalar holds the six occupied bits of a three-exponent minifloat.

[types.go:248 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L248)

```go
type E3M2Scalar uint8
```

##### `E4M3Scalar`

E4M3Scalar holds the eight bits of a four-exponent minifloat.

[types.go:246 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L246)

```go
type E4M3Scalar uint8
```

##### `E5M2Scalar`

E5M2Scalar holds the eight bits of a five-exponent minifloat.

[types.go:244 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L244)

```go
type E5M2Scalar uint8
```

##### `Element`

Element constrains the element types rows and tapes may hold, ordered by shrinking dynamic range.

[types.go:260 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L260)

```go
type Element interface {
    float64 | float32 | BFloat16 | Float16 |
        E5M2Scalar | E4M3Scalar | E3M2Scalar | E2M3Scalar |
        int8 | I4x2Scalar | int32 | uint8 | U4x2Scalar | U1x8Scalar
}
```

##### `EncodeOutputs`

EncodeOutputs names the surfaces an encode verb keeps from its one forward, after the C fields they fill; | joins them, and a surface left out costs nothing past the final norm.

[types.go:29 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L29)

```go
type EncodeOutputs uint32
```

Binding-only.

##### Values

| `EncodeOutputsEmbeddings` | `1 &lt;&lt; iota` | EncodeOutputsEmbeddings keeps one pooled embedding per item, past the attention pool and the projection head. |
| - | - | - |
| `EncodeOutputsStates` | | EncodeOutputsStates keeps one final-norm state per token left after truncation. |
| `EncodeOutputsTokenVectors` | | EncodeOutputsTokenVectors keeps one unit vector of the token head per token left after truncation; a model without the head fails the call with StatusUnsupported. |

##### `Encoded`

Encoded is what an encode verb wrote into the arena it was given: the surfaces its EncodeOutputs named, each with a zero Count when left out, and none normalized.

[types.go:44 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L44)

```go
type Encoded struct {
    Embeddings Rows
    States RowsTape
    TokenVectors RowsTape
}
```

Binding-only.

##### Fields

| `Embeddings` | `Rows` | Embeddings holds one pooled embedding of the model's dimensions per item. |
| - | - | - |
| `States` | `RowsTape` | States holds one final-norm state per token left after truncation, item by item. |
| `TokenVectors` | `RowsTape` | TokenVectors holds one unit vector of the model's token width per token left after truncation, item by item. |

##### `Float16`

Float16 holds the sixteen bits of an IEEE half-precision value.

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

```go
type Float16 uint16
```

##### `I4x2Scalar`

I4x2Scalar holds two 4-bit signed integers.

[types.go:252 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L252)

```go
type I4x2Scalar int8
```

##### `ImageEncodeConfig`

ImageEncodeConfig holds the knobs of ImageEncode and ImageEncodePixels; nil derives every field.

[types.go:138 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L138)

```go
type ImageEncodeConfig struct {
    Progress ProgressCallback
    ProgressSteps uint
    Stats *ImageEncodeStats
}
```

Mirrors the knobs of uform_image_encode_t and uform_image_encode_pixels_t.

##### Fields

| `Progress` | `ProgressCallback` | Progress hears the items encoded and may stop the call. |
| - | - | - |
| `ProgressSteps` | `uint` | ProgressSteps is the reports the call makes at most; zero derives ten. |
| `Stats` | `*ImageEncodeStats` | Stats is the report the call overwrites, kept by the caller until it is final; nil skips it. |

##### `ImageEncodeStats`

ImageEncodeStats is what an image call reports beside its outputs, overwritten by the call.

[types.go:88 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L88)

```go
type ImageEncodeStats struct {
    Truncated uint
    Tokens uint
}
```

Mirrors uform_image_encode_stats_t.

##### Fields

| `Truncated` | `uint` | Truncated counts the items whose patch grid was cut at the model's context. |
| - | - | - |
| `Tokens` | `uint` | Tokens counts the patches the call encoded, after truncation. |

##### `TextEncodeConfig`

TextEncodeConfig holds the knobs of TextEncode; nil derives every field.

[types.go:126 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L126)

```go
type TextEncodeConfig struct {
    Progress ProgressCallback
    ProgressSteps uint
    Stats *TextEncodeStats
}
```

Mirrors the knobs of uform_text_encode_t.

##### Fields

| `Progress` | `ProgressCallback` | Progress hears the items encoded and may stop the call. |
| - | - | - |
| `ProgressSteps` | `uint` | ProgressSteps is the reports the call makes at most; zero derives ten. |
| `Stats` | `*TextEncodeStats` | Stats is the report the call overwrites, kept by the caller until it is final; nil skips it. |

##### `TextEncodeStats`

TextEncodeStats is what a text call reports beside its outputs, overwritten by the call.

[types.go:78 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L78)

```go
type TextEncodeStats struct {
    Truncated uint
    Tokens uint
}
```

Mirrors uform_text_encode_stats_t.

##### Fields

| `Truncated` | `uint` | Truncated counts the items cut at the model's context. |
| - | - | - |
| `Tokens` | `uint` | Tokens counts the tokens the call encoded, after truncation. |

##### `U1x8Scalar`

U1x8Scalar holds eight single-bit dimensions.

[types.go:256 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L256)

```go
type U1x8Scalar uint8
```

##### `U4x2Scalar`

U4x2Scalar holds two 4-bit unsigned integers.

[types.go:254 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L254)

```go
type U4x2Scalar uint8
```

##### `VideoEncodeConfig`

VideoEncodeConfig holds the knobs of VideoEncode; nil derives every field.

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

```go
type VideoEncodeConfig struct {
    Progress ProgressCallback
    ProgressSteps uint
    Stats *VideoEncodeStats
}
```

Mirrors the knobs of uform_video_encode_t.

##### Fields

| `Progress` | `ProgressCallback` | Progress hears the items encoded and may stop the call. |
| - | - | - |
| `ProgressSteps` | `uint` | ProgressSteps is the reports the call makes at most; zero derives ten. |
| `Stats` | `*VideoEncodeStats` | Stats is the report the call overwrites, kept by the caller until it is final; nil skips it. |

##### `VideoEncodeStats`

VideoEncodeStats is what a video call reports beside its outputs, overwritten by the call.

[types.go:98 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L98)

```go
type VideoEncodeStats struct {
    Truncated uint
    Tokens uint
}
```

Mirrors uform_video_encode_stats_t.

##### Fields

| `Truncated` | `uint` | Truncated counts the items cut at the model's context in tubes. |
| - | - | - |
| `Tokens` | `uint` | Tokens counts the tubes the call encoded, after truncation. |

##### Struct `Rows`

Rows is a run of rows a call wrote packed into its arena, one per item, readable until the arena serves another call, after which [RowValues](#RowValues) fails with [StatusContended](https://www.unum.cloud/docs/uform/go/errors.md#StatusContended).4

[types.go:312 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L312)

```go
type Rows struct {
    // contains filtered or unexported fields
}
```

A call into an arena the host may not read is refused before it runs.

Mirrors uform_rows_view_t, beside the count the call was given.

###### `Columns`

Columns reports the values per row, the model's dimensions or token width.

[types.go:322 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L322)

```go
func (rows Rows) Columns() uint
```

###### `Count`

Count reports how many rows the call wrote, zero for a surface it did not keep.

[types.go:319 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L319)

```go
func (rows Rows) Count() uint
```

###### `Scalar`

Scalar reports the scalar type the rows were written as.

[types.go:328 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L328)

```go
func (rows Rows) Scalar() Scalar
```

###### `Stride`

Stride reports the bytes between the starts of consecutive rows.

[types.go:325 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L325)

```go
func (rows Rows) Stride() uint
```

##### Struct `RowsTape`

RowsTape is a ragged run of rows a call wrote into its arena, item i spanning the rows between two consecutive [RowsTape.Offsets](#Offsets), readable until the arena serves another call.3

[types.go:352 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L352)

```go
type RowsTape struct {
    // contains filtered or unexported fields
}
```

Mirrors uform_rows_tape_view_t, beside the count the call was given.

###### `Count`

Count reports how many items the call wrote rows for, zero for a surface it did not keep.

[types.go:359 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L359)

```go
func (tape RowsTape) Count() uint
```

###### `Item`

Item views the rows of one item, refused with [StatusInvalidArgument](https://www.unum.cloud/docs/uform/go/errors.md#StatusInvalidArgument) when item is not below [RowsTape.Count](#Count).

[types.go:376 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L376)

```go
func (tape RowsTape) Item(item uint) (Rows, error)
```

###### `Offsets`

Offsets views the Count + 1 offsets into the rows, in rows.

[types.go:363 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L363)

```go
func (tape RowsTape) Offsets() []uint
```

It panics with [StatusContended](https://www.unum.cloud/docs/uform/go/errors.md#StatusContended) once a later call took the arena, as a slice bound does, and the slice is valid only until then.

##### Enum `Scalar`

Scalar names a computed or exchanged scalar type by width and encoding, numbered as USearch numbers it, so a run of embeddings is a run USearch indexes without conversion.2

[types.go:174 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L174)

```go
type Scalar int32
```

Sub-byte kinds pack several dimensions per byte, as their xN suffixes spell.

##### Values

| `ScalarUnknown` | | ScalarUnknown names no scalar: an unset field, which the library refuses. |
| - | - | - |
| `ScalarF64` | | ScalarF64 is 64-bit double precision. |
| `ScalarF32` | | ScalarF32 is 32-bit single precision. |
| `ScalarBF16` | | ScalarBF16 is the brain floating-point format. |
| `ScalarF16` | | ScalarF16 is IEEE half precision. |
| `ScalarE5M2` | | ScalarE5M2 is 8-bit floating point with five exponent bits. |
| `ScalarE4M3` | | ScalarE4M3 is 8-bit floating point with four exponent bits. |
| `ScalarE3M2` | | ScalarE3M2 is 6-bit floating point with three exponent bits. |
| `ScalarE2M3` | | ScalarE2M3 is 6-bit floating point with two exponent bits. |
| `ScalarI8` | | ScalarI8 is an 8-bit signed integer. |
| `ScalarI4x2` | | ScalarI4x2 packs two 4-bit signed integers per byte. |
| `ScalarI32` | | ScalarI32 is a 32-bit signed integer. |
| `ScalarU8` | | ScalarU8 is an 8-bit unsigned integer, the element of UTF-8 text and of encoded files. |
| `ScalarU4x2` | | ScalarU4x2 packs two 4-bit unsigned integers per byte. |
| `ScalarU1x8` | | ScalarU1x8 packs eight single-bit dimensions per byte, the sign of each embedding dimension. |

###### `ScalarFromName`

ScalarFromName reads a scalar back from the spelling [Scalar.String](https://www.unum.cloud/docs/uform/go/errors.md#String) renders.

[types.go:217 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L217)

```go
func ScalarFromName(name string) (Scalar, error)
```

###### `String`

String renders the scalar kind as the library spells it.

[types.go:212 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L212)

```go
func (scalar Scalar) String() string
```

##### Struct `Tape`

Tape views a ragged batch as Apache Arrow lays one out: elements end to end, and one more offset than entries around them, entry i spanning offsets\[i] up to offsets\[i+1].6

[types.go:400 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L400)

```go
type Tape struct {
    // contains filtered or unexported fields
}
```

An element is a byte of UTF-8 text or of an encoded file, or a sample of a recording.

A Tape views and never owns, and the binding pins both slices until each call it crosses is final, so neither may change until then.

###### `BytesTape`

BytesTape views bytes end to end around len(offsets) - 1 texts or files, without a copy.

[types.go:424 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L424)

```go
func BytesTape(data []byte, offsets []uint) Tape
```

Panics when the offsets overrun the bytes, which names a caller's arithmetic mistake rather than a condition the library could report.

###### `SamplesOf`

SamplesOf gathers separate mono recordings end to end into a fresh Tape, one entry apiece.

[types.go:427 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L427)

```go
func SamplesOf(recordings [][]float32) Tape
```

###### `SamplesTape`

SamplesTape views mono samples end to end around len(offsets) - 1 recordings, without a copy.

[types.go:442 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L442)

```go
func SamplesTape(data []float32, offsets []uint) Tape
```

Panics when the offsets overrun the samples.

###### `TapeOf`

TapeOf gathers separate texts or files end to end into a fresh Tape, one entry apiece, copying each once.

[types.go:408 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L408)

```go
func TapeOf[Item ~string | ~[]byte](items []Item) Tape
```

###### `Entries`

Entries reports how many entries the tape spans, zero for the zero Tape.

[types.go:456 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L456)

```go
func (tape Tape) Entries() uint
```

###### `Scalar`

Scalar reports the scalar type the elements hold.

[types.go:464 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L464)

```go
func (tape Tape) Scalar() Scalar
```

##### Struct `TapeView`

TapeView is a ragged batch a call wrote into its arena, readable until the arena serves another call: one probability per choice, item by item, for TextChoose.2

[types.go:483 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L483)

```go
type TapeView struct {
    // contains filtered or unexported fields
}
```

Mirrors uform_tape_view_t, beside the count the call was given.

###### `Entries`

Entries reports how many entries the call wrote.

[types.go:489 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L489)

```go
func (tape TapeView) Entries() uint
```

###### `Scalar`

Scalar reports the scalar type the elements were written as.

[types.go:492 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L492)

```go
func (tape TapeView) Scalar() Scalar
```

#### Functions

##### `RowValues`

RowValues views one row's values in the arena, refused with StatusInvalidArgument when Value is not the scalar type they were written as or row is not below Count, and with StatusContended once a later call took the arena.

[uform.go:333 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/uform.go#L333)

```go
func RowValues[Value Element](
    rows Rows,
    row uint,
) ([]Value, error)
```

The slice is valid only until that call.

##### `TapeEntry`

TapeEntry views one entry's elements in the arena, refused with StatusInvalidArgument when Value is not the scalar type they were written as or entry is not below Entries.

[uform.go:496 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/uform.go#L496)

```go
func TapeEntry[Value Element](
    tape TapeView,
    entry uint,
) ([]Value, error)
```

## Choices

`import "github.com/unum-cloud/uform"` 4.0.0-rc.1 · c58749fe

`TextChoose(texts, choices, ..)` scores each item’s legal choices, one byte each, through one forward, and answers a `TapeView` of one `float32` probability per choice that sums to one per item:

```go
config := &uform.TextChooseConfig{TemperatureGroups: []uint32{0, 1}}
probabilities, err := model.TextChoose(uform.TapeOf([]string{"keep this candidate?", "expand which neighbour?"}),
	uform.TapeOf([]string{"yn", "ABCD"}), arena, config)
expand, err := uform.TapeEntry[float32](probabilities, 1) // the probabilities of 'A' through 'D'
```

Each group is a question type below the model’s `ChoiceTemperatureGroups`, and a model without the byte decoder answers `StatusUnsupported`.

### API

#### Types

##### `Choices`

Choices is the calibrated choices term over the byte decoder; a zero Weight trains none.

[types.go:307 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L307)

```go
type Choices struct {
    Weight      float32
    BrierWeight float32
}
```

Mirrors uform_choices_t field for field.

##### `TextChooseConfig`

TextChooseConfig holds the knobs of TextChoose; nil derives every field.

[types.go:174 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L174)

```go
type TextChooseConfig struct {
    TemperatureGroups []uint32
    Progress ProgressCallback
    ProgressSteps uint
    Stats *TextEncodeStats
}
```

Mirrors the knobs of uform_text_choose_t.

##### Fields

| `TemperatureGroups` | `[]uint32` | TemperatureGroups holds the question type of each item, below the model's ChoiceTemperatureGroups; empty puts every item in group zero. |
| - | - | - |
| `Progress` | `ProgressCallback` | Progress hears the items scored and may stop the call. |
| `ProgressSteps` | `uint` | ProgressSteps is the reports the call makes at most; zero derives ten. |
| `Stats` | `*TextEncodeStats` | Stats is the report the call overwrites, kept by the caller until it is final; nil skips it. |

## Models

`import "github.com/unum-cloud/uform"` 4.0.0-rc.1 · c58749fe

`ModelLoadRam(path, config)` and `ModelLoadVram(path, config)` copy a safetensors checkpoint into host memory or onto GPUs, and `ModelLoadRamBuffer` and `ModelLoadVramBuffer` take the checkpoint’s bytes instead. A nil config loads on the calling goroutine with BFloat16 blocks, and the config reaches the executor, the placement and its class ceiling, `ScalarE4M3` quantization and a progress handler:

```go
model, err := uform.ModelLoadVram("model.safetensors", &uform.ModelLoadVramConfig{
	Executor:     executor,
	Devices:      []int32{0},
	Quantization: uform.ScalarE4M3,
})
description, err := model.Describe() // geometry, placement, classes and heads
```

A description reports the `CPUClass` or `GPUClass` the model dispatched as, and the heads the checkpoint carries: a nonzero `TokenWidth` for token vectors, and a nonzero `ChoiceTemperatureGroups` for choices. Loads always block, and `Close` waits for every deferred call naming the model.

### API

#### Types

##### `ModelDescription`

ModelDescription is what a loaded model reports about itself.

[types.go:29 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L29)

```go
type ModelDescription struct {
    Dimensions uint
    Context uint
    Quantization Scalar
    MemoryUsage uint
    CPUClass CPUClass
    GPUClass GPUClass
    TokenWidth uint
    ChoiceTemperatureGroups uint
}
```

Mirrors uform_model_description_t field for field, so the library writes it in place.

##### Fields

| `Dimensions` | `uint` | Dimensions is the scalars per embedding row; Matryoshka prefixes of it are embeddings too. |
| - | - | - |
| `Context` | `uint` | Context is the tokens one item may span before it is truncated: bytes of text, patches of an image, tubes of a clip, frames of a recording. |
| `Quantization` | `Scalar` | Quantization is the scalar the transformer blocks run in. |
| `MemoryUsage` | `uint` | MemoryUsage is the bytes the model holds; activations are the executor's. |
| `CPUClass` | `CPUClass` | CPUClass is the class a RAM model's tower was packed for, CPUClassUnknown for a VRAM model. |
| `GPUClass` | `GPUClass` | GPUClass is the class every replica of a VRAM model runs as, GPUClassUnknown for a RAM model. |
| `TokenWidth` | `uint` | TokenWidth is the scalars per token vector, zero when the checkpoint carries no token head. |
| `ChoiceTemperatureGroups` | `uint` | ChoiceTemperatureGroups counts the question types the choice temperatures were calibrated over: zero without the byte decoder, one when uncalibrated. |

##### `ModelLoadRamConfig`

ModelLoadRamConfig is how ModelLoadRam and ModelLoadRamBuffer copy a checkpoint into host memory; nil derives every field.

[types.go:54 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L54)

```go
type ModelLoadRamConfig struct {
    Executor *Executor
    MemoryDomains []int32
    CPUClassCeiling CPUClass
    Quantization Scalar
    Progress ProgressCallback
    ProgressSteps uint
}
```

Mirrors uform_model_load_ram_t and uform_model_load_ram_buffer_t beside their path or buffer.

##### Fields

| `Executor` | `*Executor` | Executor is the one the load runs on; nil loads on the calling goroutine. |
| - | - | - |
| `MemoryDomains` | `[]int32` | MemoryDomains are the NUMA nodes to place the weights in; empty derives every node. |
| `CPUClassCeiling` | `CPUClass` | CPUClassCeiling is the newest class to pack and dispatch as; zero sets no ceiling. |
| `Quantization` | `Scalar` | Quantization is the scalar the transformer blocks run in: ScalarBF16 as the checkpoint stores it, or ScalarE4M3 quantized at load; zero keeps ScalarBF16. |
| `Progress` | `ProgressCallback` | Progress hears the tensors placed and may stop the load, which then creates no model. |
| `ProgressSteps` | `uint` | ProgressSteps is the reports the load makes at most; zero derives ten. |

##### `ModelLoadVramConfig`

ModelLoadVramConfig is how ModelLoadVram and ModelLoadVramBuffer copy a checkpoint onto GPUs; nil derives every field.

[types.go:74 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L74)

```go
type ModelLoadVramConfig struct {
    Executor *Executor
    Devices []int32
    GPUClassCeiling GPUClass
    Quantization Scalar
    Progress ProgressCallback
    ProgressSteps uint
}
```

Mirrors uform_model_load_vram_t and uform_model_load_vram_buffer_t beside their path or buffer.

##### Fields

| `Executor` | `*Executor` | Executor is the one the upload runs on, one stream per device; nil uploads on the calling goroutine. |
| - | - | - |
| `Devices` | `[]int32` | Devices are the ordinals GPUDevices lists, each holding a replica; empty places one on every device of the executor. |
| `GPUClassCeiling` | `GPUClass` | GPUClassCeiling is the newest class every device dispatches as; zero sets no ceiling. |
| `Quantization` | `Scalar` | Quantization is the scalar the transformer blocks run in, as for ModelLoadRamConfig. |
| `Progress` | `ProgressCallback` | Progress hears the tensors placed and may stop the load, which then creates no model. |
| `ProgressSteps` | `uint` | ProgressSteps is the reports the load makes at most; zero derives ten. |

##### `Residency`

Residency is where an arena's outputs live, as the executor that made it decided.

[types.go:564 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L564)

```go
type Residency int32
```

##### Values

| `ResidencyUnknown` | | ResidencyUnknown names no residency. |
| - | - | - |
| `ResidencyRam` | | ResidencyRam is host pages, which Go code reads directly. |
| `ResidencyVram` | | ResidencyVram is one GPU's memory, which Go code reads only where HostAccess lets it. |

##### Struct `Model`

Model is a loaded encoder: its weights, their packed copies, and on a GPU the session its attention runs on, shared by every executor of its residency.15

[model.go:111 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L111)

```go
type Model struct {
    ModelOn
    // contains filtered or unexported fields
}
```

Its embedded ModelOn runs every verb on the calling goroutine.

Mirrors uform_model_t; Close calls uform_model_free.

###### `ModelLoadRam`

ModelLoadRam copies a safetensors checkpoint file into host memory and packs it for the CPU.

[model.go:130 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L130)

```go
func ModelLoadRam(
    path string,
    config *ModelLoadRamConfig,
) (*Model, error)
```

The checkpoint carries the model's geometry.

Calls uform_model_load_ram, blocking.

###### `ModelLoadRamBuffer`

ModelLoadRamBuffer copies a checkpoint held in memory into host memory and packs it for the CPU; nothing of buffer is kept.

[model.go:155 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L155)

```go
func ModelLoadRamBuffer(
    buffer []byte,
    config *ModelLoadRamConfig,
) (*Model, error)
```

Calls uform_model_load_ram_buffer, blocking.

###### `ModelLoadVram`

ModelLoadVram copies a checkpoint file onto the named GPUs and packs it there, replicated on each, since a model is small next to the activations it serves.

[model.go:180 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L180)

```go
func ModelLoadVram(
    path string,
    config *ModelLoadVramConfig,
) (*Model, error)
```

Calls uform_model_load_vram, blocking.

###### `ModelLoadVramBuffer`

ModelLoadVramBuffer copies a checkpoint held in memory onto the named GPUs and packs it there.

[model.go:204 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L204)

```go
func ModelLoadVramBuffer(
    buffer []byte,
    config *ModelLoadVramConfig,
) (*Model, error)
```

Calls uform_model_load_vram_buffer, blocking.

###### `Close`

Close frees the model, waiting for every deferred call naming it.

[model.go:227 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L227)

```go
func (model *Model) Close() error
```

It is idempotent, and a closed model refuses every later verb with StatusUninitialized.

###### `AudioEncode`

AudioEncode decodes and encodes WAV, FLAC, MP3 or Opus recordings, resampled to mono.

[model.go:276 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L276)

Inherited from `ModelOn`

```go
func (on Model) AudioEncode(
    recordings Tape,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *AudioEncodeConfig,
) (Encoded, error)
```

Calls uform_audio_encode.

###### `AudioEncodeSamples`

AudioEncodeSamples encodes decoded mono ScalarF32 recordings sharing one sampleRate, resampled to the model's rate where it differs.

[model.go:293 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L293)

Inherited from `ModelOn`

```go
func (on Model) AudioEncodeSamples(
    samples Tape,
    sampleRate uint32,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *AudioEncodeConfig,
) (Encoded, error)
```

Calls uform_audio_encode_samples.

###### `Deferred`

Deferred is the receiver whose verbs submit their calls to executor, each answering a Deferred from the same arguments.

[model.go:270 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L270)

Inherited from `ModelOn`

```go
func (on Model) Deferred(executor *Executor) ModelDeferredOn
```

Binding-only.

###### `Describe`

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

[model.go:278 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L278)

Inherited from `ModelOn`

```go
func (on Model) Describe() (ModelDescription, error)
```

Calls uform_model_describe.

###### `ImageEncode`

ImageEncode decodes and encodes JPEG, PNG or WebP files; an undecodable file fails the call with StatusMalformed.

[model.go:227 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L227)

Inherited from `ModelOn`

```go
func (on Model) ImageEncode(
    images Tape,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *ImageEncodeConfig,
) (Encoded, error)
```

Calls uform_image_encode.

###### `ImageEncodePixels`

ImageEncodePixels encodes decoded images of interleaved 8-bit RGB, item i holding heights\[i] rows of widths\[i] pixels; an item of another length fails with StatusShapeMismatch.

[model.go:244 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L244)

Inherited from `ModelOn`

```go
func (on Model) ImageEncodePixels(
    pixels Tape,
    heights, widths []uint32,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *ImageEncodeConfig,
) (Encoded, error)
```

Calls uform_image_encode_pixels.

###### `On`

On is the receiver whose verbs block on executor, failing StatusContended while another call holds it.

[model.go:263 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L263)

Inherited from `ModelOn`

```go
func (on Model) On(executor *Executor) ModelOn
```

Binding-only.

###### `TextChoose`

TextChoose scores each item's legal choices, one byte each, after its UTF-8 state in texts, through one forward, answering one ScalarF32 probability per choice in arena, a softmax over the item's choices alone.

[model.go:212 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L212)

Inherited from `ModelOn`

```go
func (on Model) TextChoose(
    texts, choices Tape,
    arena *Arena,
    config *TextChooseConfig,
) (TapeView, error)
```

A model without the byte decoder fails it with StatusUnsupported.

Calls uform_text_choose.

###### `TextEncode`

TextEncode encodes UTF-8 texts through one forward, a token per byte, since models are tokenizer-free, keeping the surfaces outputs names as outputsScalar in arena.

[model.go:194 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L194)

Inherited from `ModelOn`

```go
func (on Model) TextEncode(
    texts Tape,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *TextEncodeConfig,
) (Encoded, error)
```

Calls uform_text_encode.

###### `VideoEncode`

VideoEncode decodes and encodes MP4 or WebM clips.

[model.go:260 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/model.go#L260)

Inherited from `ModelOn`

```go
func (on Model) VideoEncode(
    videos Tape,
    outputs EncodeOutputs,
    outputsScalar Scalar,
    arena *Arena,
    config *VideoEncodeConfig,
) (Encoded, error)
```

Calls uform_video_encode.

## Training

`import "github.com/unum-cloud/uform"` 4.0.0-rc.1 · c58749fe

Training is GPU-only. The configuration arrives as structs mirroring the C ones field by field, so a field left at zero is derived by the library:

```go
executor, err := uform.ExecutorForVram([]int32{0, 1}, uform.GPUClassUnknown, nil, uform.CPUClassUnknown, nil, 0)
mesh, err := uform.MeshBootstrap(executor, &uform.MeshOptions{
	HostDomainIndex: rank,
	HostDomainCount: nodes,
	Directory:       "/shared/exchange",
	Job:             "run-17",
})
trainer, err := uform.TrainerInitVram(executor, &uform.TrainerInitVramConfig{
	Mesh:      mesh,
	Depth:     12,
	Hidden:    512,
	Objective: uform.ObjectiveJoint,
	Batch: uform.BatchShape{MaxRowsPerDevice: 64, MaxSegmentsPerDevice: 256, MaxColumnsPerRow: 1024,
		MaxBagsPerDevice: 128, Image: uform.ImageShape{PatchSide: 16}},
	Schedule: uform.Schedule{Steps: 100_000},
	Seed:     42,
})

stats := new(uform.TrainerStepStats)
relations := uform.Relations{Attract: uform.Edges{Offsets: []uint{0, 1, 2, 3, 4}, IDs: []uint32{1, 0, 3, 2}}}
config := &uform.TrainerStepConfig{Bags: []uint32{0, 0, 1, 1}, Relations: relations, Stats: stats}
_, err = trainer.On(executor).Step(modalities, contents, config)
err = trainer.On(executor).Save("checkpoint.safetensors", nil)
```

`BatchShape` nests an `ImageShape`, a `VideoShape` and an `AudioShape`, while `Masking`, `Contrastive`, `LateInteraction`, `Choices` and `Schedule` configure the objectives, and `PairLossForm` picks each contrastive term’s pair loss. `Relations` holds three `Edges` sets as compressed sparse rows, whose offsets and weights the binding checks against the step’s items before the call. A step’s `Sides` give each item a `LateInteractionSide`, and its `Choices` and `ChoiceTargets` give each choice item its legal bytes and their target probabilities as tapes, the shapes `TextChoose` takes and answers. `Step` answers the pooled embeddings the loss scored when its config names an `Arena`, and `Rows` of zero `Count` otherwise. A trainer refers to its mesh, so the mesh outlives every trainer made over it, and `mesh.Describe()` answers a `MeshDescription` whose `MultimemTier` and `GPUClass` describe the run.

### API

#### Types

##### `AudioShape`

AudioShape is the audio slice of a batch envelope; a zero ChunkSamples leaves audio out of the run.

[types.go:219 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L219)

```go
type AudioShape struct {
    ChunkSamples uint
    SampleRate uint
}
```

Mirrors uform_audio_shape_t.

##### Fields

| `ChunkSamples` | `uint` | ChunkSamples is the raw samples per frame. |
| - | - | - |
| `SampleRate` | `uint` | SampleRate is the mono rate every recording is resampled to; zero derives 16000. |

##### `BatchShape`

BatchShape is what one device's step carries at most, whatever the modality mix.

[types.go:229 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L229)

```go
type BatchShape struct {
    MaxRowsPerDevice uint
    MaxSegmentsPerDevice uint
    MaxColumnsPerRow uint
    MaxBagsPerDevice uint
    MaxChoicesPerItem uint
    Image ImageShape
    Video VideoShape
    Audio AudioShape
}
```

Mirrors uform_batch_shape_t field for field.

##### Fields

| `MaxRowsPerDevice` | `uint` | MaxRowsPerDevice is the rows one device's step packs. |
| - | - | - |
| `MaxSegmentsPerDevice` | `uint` | MaxSegmentsPerDevice is the items one device's step carries across all its rows. |
| `MaxColumnsPerRow` | `uint` | MaxColumnsPerRow is the positions one row spans. |
| `MaxBagsPerDevice` | `uint` | MaxBagsPerDevice is the bags one device's step carries; zero keeps every item its own unit. |
| `MaxChoicesPerItem` | `uint` | MaxChoicesPerItem is the legal bytes one item offers at most; zero makes no choices. |
| `Image` | `ImageShape` | Image is the image geometry. |
| `Video` | `VideoShape` | Video is the video geometry. |
| `Audio` | `AudioShape` | Audio is the audio geometry. |

##### `Contrastive`

Contrastive is how the contrastive loss scores the pooled embeddings; every zero derives.

[types.go:268 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L268)

```go
type Contrastive struct {
    MatryoshkaDimensions []uint
    TemperatureGroups uint
    InverseTemperature float32
    Bias float32
    Negatives Negatives
    AmbientRepulsionWeight float32
    MaxEdgesPerDevice uint
    PairLoss PairLossForm
}
```

Mirrors uform_contrastive_t.

##### Fields

| `MatryoshkaDimensions` | `[]uint` | MatryoshkaDimensions are the prefix widths scored, strictly ascending multiples of 8, at most 8 of them; empty scores the full width alone. |
| - | - | - |
| `TemperatureGroups` | `uint` | TemperatureGroups is the learnable pairs of an inverse temperature and a bias; zero derives one. |
| `InverseTemperature` | `float32` | InverseTemperature is the starting inverse temperature of every group. |
| `Bias` | `float32` | Bias is the starting logit bias of every group. |
| `Negatives` | `Negatives` | Negatives is which pairs repel. |
| `AmbientRepulsionWeight` | `float32` | AmbientRepulsionWeight is the weight of every pair no edge names under NegativesAmbient. |
| `MaxEdgesPerDevice` | `uint` | MaxEdgesPerDevice is the edges one device's step names per edge set at most; zero derives. |
| `PairLoss` | `PairLossForm` | PairLoss is the pair loss over each anchor's row. |

##### `Edges`

Edges is one edge set over a step's items as compressed sparse rows: item i links to IDs\[Offsets\[i]] up to IDs\[Offsets\[i+1]].

[types.go:391 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L391)

```go
type Edges struct {
    Offsets []uint
    IDs []uint32
    Weights []float32
}
```

Mirrors uform_edges_view_t.

##### Fields

| `Offsets` | `[]uint` | Offsets holds one more entry than the step's items; empty names no edges. |
| - | - | - |
| `IDs` | `[]uint32` | IDs are indices into the step's items, ascending within each run. |
| `Weights` | `[]float32` | Weights holds one weight per ID; empty weighs every edge one. |

##### `ImageShape`

ImageShape is the image slice of a batch envelope; a zero PatchSide leaves images out of the run.

[types.go:194 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L194)

```go
type ImageShape struct {
    PatchSide uint
    Channels uint
}
```

Mirrors uform_image_shape_t.

##### Fields

| `PatchSide` | `uint` | PatchSide is the square patch side images tile into, in pixels. |
| - | - | - |
| `Channels` | `uint` | Channels is the channels every pixel carries; zero derives four. |

##### `LateInteraction`

LateInteraction is how the late-interaction loss scores per-token vectors; every zero derives.

[types.go:292 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L292)

```go
type LateInteraction struct {
    Weight                     float32
    Width                      uint
    InverseTemperature         float32
    Bias                       float32
    MaxQuerySpan               uint
    MaxQueryTokensPerDevice    uint
    MaxDocumentsPerDevice      uint
    MaxDocumentTokensPerDevice uint
    PairLoss                   PairLossForm
}
```

Mirrors uform_late_interaction_t field for field.

##### `Masking`

Masking is how the masked objective corrupts a batch and weighs its heads; every zero derives.

[types.go:251 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L251)

```go
type Masking struct {
    TokenMaskProbability float32
    TokenMeanSpan        float32
    ReplaceFraction      float32
    RandomFraction       float32
    ImageMaskRatio       float32
    VideoMaskRatio       float32
    AudioMaskRatio       float32
    TextWeight           float32
    ImageWeight          float32
    VideoWeight          float32
    AudioWeight          float32
}
```

Mirrors uform_masking_t field for field.

##### `Relations`

Relations is the contrastive targets of one step.

[types.go:403 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L403)

```go
type Relations struct {
    Attract Edges
    Repel   Edges
    Ignore  Edges
}
```

Mirrors uform_relations_view_t.

##### `Schedule`

Schedule is the learning-rate schedule: a linear warmup to the peak, then a cosine decay.

[types.go:315 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L315)

```go
type Schedule struct {
    LearningRate    float32
    MinLearningRate float32
    WarmupSteps     uint
    Steps           uint
}
```

Mirrors uform_schedule_t field for field.

##### `TrainerInitVramConfig`

TrainerInitVramConfig is the geometry, objectives and schedule of a run; zero fields derive.

[types.go:356 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L356)

```go
type TrainerInitVramConfig struct {
    Resume string
    Depth uint
    Hidden uint
    Batch BatchShape
    Objective Objective
    Masking Masking
    Contrastive Contrastive
    LateInteraction LateInteraction
    Choices Choices
    Schedule Schedule
    Mesh *Mesh
    Seed uint64
    Progress ProgressCallback
    ProgressSteps uint
}
```

Mirrors uform_trainer_init_vram_t.

##### Fields

| `Resume` | `string` | Resume is the path of a checkpoint to continue from; empty starts from Seed. |
| - | - | - |
| `Depth` | `uint` | Depth is the transformer blocks stacked. |
| `Hidden` | `uint` | Hidden is the embedding width, a multiple of 128. |
| `Batch` | `BatchShape` | Batch is what one device's step carries at most. |
| `Objective` | `Objective` | Objective is which losses a step relaxes. |
| `Masking` | `Masking` | Masking configures the masked objective. |
| `Contrastive` | `Contrastive` | Contrastive configures the contrastive loss. |
| `LateInteraction` | `LateInteraction` | LateInteraction configures the late-interaction loss. |
| `Choices` | `Choices` | Choices configures the calibrated choices term. |
| `Schedule` | `Schedule` | Schedule is the learning-rate schedule. |
| `Mesh` | `*Mesh` | Mesh must stay open until the trainer is closed; nil runs this process alone. |
| `Seed` | `uint64` | Seed is the base of every keyed draw. |
| `Progress` | `ProgressCallback` | Progress hears the tensors placed on a resume. |
| `ProgressSteps` | `uint` | ProgressSteps is the reports the call makes at most; zero derives ten. |

##### `TrainerSaveConfig`

TrainerSaveConfig holds the knobs of Save; nil derives every field.

[types.go:453 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L453)

```go
type TrainerSaveConfig struct {
    Progress ProgressCallback
    ProgressSteps uint
}
```

##### Fields

| `Progress` | `ProgressCallback` | Progress hears the tensors written. |
| - | - | - |
| `ProgressSteps` | `uint` | ProgressSteps is the reports the call makes at most; zero derives ten. |

##### `TrainerStepConfig`

TrainerStepConfig holds the per-item inputs and knobs of a step beside its modalities and contents; nil derives every field.

[types.go:431 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L431)

```go
type TrainerStepConfig struct {
    Bags []uint32
    TemperatureGroups []uint32
    Sides []LateInteractionSide
    Choices Tape
    ChoiceTargets Tape
    Relations Relations
    Arena *Arena
    OutputsScalar Scalar
    Stats *TrainerStepStats
}
```

Mirrors uform_trainer_step_t.

##### Fields

| `Bags` | `[]uint32` | Bags holds the bag of each item; empty keeps every item its own bag. |
| - | - | - |
| `TemperatureGroups` | `[]uint32` | TemperatureGroups holds the temperature group of each item; empty puts every item in group zero. |
| `Sides` | `[]LateInteractionSide` | Sides holds the late-interaction side of each item; empty takes none into late interaction. |
| `Choices` | `Tape` | Choices holds each item's legal bytes, as TextChoose takes them; the zero Tape makes none. |
| `ChoiceTargets` | `Tape` | ChoiceTargets holds the target probability of each choice, as TextChoose answers them. |
| `Relations` | `Relations` | Relations holds the attract, repel and ignore edges. |
| `Arena` | `*Arena` | Arena receives the pooled embeddings the loss scored; nil skips the copy. |
| `OutputsScalar` | `Scalar` | OutputsScalar is the scalar the embeddings land as. |
| `Stats` | `*TrainerStepStats` | Stats is the report the step overwrites, kept by the caller until it is final; nil skips it. |

##### `TrainerStepStats`

TrainerStepStats is what a step reports, every loss its world mean.

[types.go:412 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L412)

```go
type TrainerStepStats struct {
    Step                uint
    LearningRate        float32
    Loss                float32
    ContrastiveLoss     float32
    MaskedTextLoss      float32
    MaskedImageLoss     float32
    MaskedVideoLoss     float32
    MaskedAudioLoss     float32
    LateInteractionLoss float32
    ChoicesLoss         float32
    Truncated           uint
    Dropped             uint
}
```

Mirrors uform_trainer_step_stats_t field for field, so the library writes it in place.

##### `VideoShape`

VideoShape is the video slice of a batch envelope; a zero PatchSide leaves video out of the run.

[types.go:204 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L204)

```go
type VideoShape struct {
    PatchSide uint
    TubeFrames uint
    FrameStride uint
    Channels uint
}
```

Mirrors uform_video_shape_t.

##### Fields

| `PatchSide` | `uint` | PatchSide is the square patch side one tube tiles into, in pixels. |
| - | - | - |
| `TubeFrames` | `uint` | TubeFrames is the frames one tube folds ahead of its patch; zero derives two. |
| `FrameStride` | `uint` | FrameStride is the source frames between sampled ones; zero derives one. |
| `Channels` | `uint` | Channels is the channels every pixel carries; zero derives three. |

##### Enum `LateInteractionSide`

LateInteractionSide is which side of a late-interaction score an item takes.2

[train.go:139 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L139)

```go
type LateInteractionSide int32
```

##### Values

| `LateInteractionSideNone` | | LateInteractionSideNone takes no part in late interaction. |
| - | - | - |
| `LateInteractionSideQuery` | | LateInteractionSideQuery scores the documents the item attracts and repels. |
| `LateInteractionSideDocument` | | LateInteractionSideDocument is scored by the queries naming it. |
| `LateInteractionSideQueryAndDocument` | | LateInteractionSideQueryAndDocument plays both sides. |

###### `LateInteractionSideFromName`

LateInteractionSideFromName reads a side back from the spelling [LateInteractionSide.String](https://www.unum.cloud/docs/uform/go/errors.md#String) renders.

[train.go:159 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L159)

```go
func LateInteractionSideFromName(
    name string,
) (LateInteractionSide, error)
```

###### `String`

String renders the side as the library spells it.

[train.go:153 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L153)

```go
func (side LateInteractionSide) String() string
```

##### Enum `Modality`

Modality is what the bytes of one training item hold.2

[train.go:41 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L41)

```go
type Modality int32
```

##### Values

| `ModalityText` | | ModalityText is UTF-8 text, a byte per token. |
| - | - | - |
| `ModalityImage` | | ModalityImage is a JPEG, PNG or WebP file. |
| `ModalityVideo` | | ModalityVideo is an MP4 or WebM file. |
| `ModalityAudio` | | ModalityAudio is a WAV, FLAC, MP3 or Opus file. |

###### `ModalityFromName`

ModalityFromName reads a modality back from the spelling [Modality.String](https://www.unum.cloud/docs/uform/go/errors.md#String) renders.

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

```go
func ModalityFromName(name string) (Modality, error)
```

###### `String`

String renders the modality as the library spells it.

[train.go:55 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L55)

```go
func (modality Modality) String() string
```

##### Enum `Negatives`

Negatives is which pairs the contrastive loss pushes apart.2

[train.go:91 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L91)

```go
type Negatives int32
```

##### Values

| `NegativesAmbient` | | NegativesAmbient repels edges, and every pair no edge names at the ambient weight. |
| - | - | - |
| `NegativesNamed` | | NegativesNamed repels edges alone. |

###### `NegativesFromName`

NegativesFromName reads a negatives policy back from the spelling [Negatives.String](https://www.unum.cloud/docs/uform/go/errors.md#String) renders.

[train.go:106 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L106)

```go
func NegativesFromName(name string) (Negatives, error)
```

###### `String`

String renders the policy as the library spells it.

[train.go:101 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L101)

```go
func (negatives Negatives) String() string
```

##### Enum `Objective`

Objective is which losses a step relaxes, one per combination the engine trains.2

[train.go:67 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L67)

```go
type Objective int32
```

##### Values

| `ObjectiveMasked` | | ObjectiveMasked is masked reconstruction alone, as the Base pretrains. |
| - | - | - |
| `ObjectiveContrastive` | | ObjectiveContrastive is the pairwise contrastive loss alone, as the Embedder trains. |
| `ObjectiveJoint` | | ObjectiveJoint is both, joined at the final-norm states. |

###### `ObjectiveFromName`

ObjectiveFromName reads an objective back from the spelling [Objective.String](https://www.unum.cloud/docs/uform/go/errors.md#String) renders.

[train.go:84 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L84)

```go
func ObjectiveFromName(name string) (Objective, error)
```

###### `String`

String renders the objective as the library spells it.

[train.go:79 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L79)

```go
func (objective Objective) String() string
```

##### Enum `PairLossForm`

PairLossForm is how a contrastive term turns a row of scores into forces.2

[train.go:113 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L113)

```go
type PairLossForm int32
```

##### Values

| `PairLossFormDerived` | | PairLossFormDerived keeps the term's own form: sigmoid for pooled vertices, ranked for tokens. |
| - | - | - |
| `PairLossFormBalanced` | | PairLossFormBalanced normalizes the attract and repel halves of every cell apart. |
| `PairLossFormRanked` | | PairLossFormRanked scores every positive over every negative, where the bias cancels. |
| `PairLossFormSigmoid` | | PairLossFormSigmoid is SigLIP's per-cell sigmoid cross-entropy. |

###### `PairLossFormFromName`

PairLossFormFromName reads a pair loss form back from the spelling [PairLossForm.String](https://www.unum.cloud/docs/uform/go/errors.md#String) renders.

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

```go
func PairLossFormFromName(name string) (PairLossForm, error)
```

###### `String`

String renders the form as the library spells it.

[train.go:127 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L127)

```go
func (form PairLossForm) String() string
```

##### Struct `Trainer`

Trainer is a training run: the tower replicas, gradients, optimizer moments, heads and temperatures on its executor's devices, stepped and saved through that executor.6

[train.go:577 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L577)

```go
type Trainer struct {
    TrainerOn
    // contains filtered or unexported fields
}
```

Its embedded TrainerOn runs every verb on the calling goroutine, and TrainerOn.On on the executor the trainer was made on.

Mirrors uform_trainer_t; Close calls uform_trainer_free.

###### `TrainerInitVram`

TrainerInitVram builds one replica per device of executor and starts or resumes the run; every process of the run calls it with the same geometry, objective and seed.

[train.go:596 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L596)

```go
func TrainerInitVram(
    executor *Executor,
    config *TrainerInitVramConfig,
) (*Trainer, error)
```

Calls uform_trainer_init_vram, blocking.

###### `Close`

Close frees the trainer, waiting for every deferred call naming it.

[train.go:642 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L642)

```go
func (trainer *Trainer) Close() error
```

It is idempotent.

###### `*Deferred`

× 2 Deferred is the receiver whose verbs submit their calls to executor, each answering a Deferred from the same arguments.

[train.go:679 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L679)

Inherited from `TrainerOn`

```go
func (on Trainer) Deferred(executor *Executor) TrainerDeferredOn
```

Binding-only.

###### `*On`

× 2 On is the receiver whose verbs block on executor, the one the trainer was made on.

[train.go:672 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L672)

Inherited from `TrainerOn`

```go
func (on Trainer) On(executor *Executor) TrainerOn
```

Binding-only.

###### `*Save`

× 2 Save writes the weights and the step to a safetensors checkpoint at path, which ModelLoadVram serves and TrainerInitVram resumes; only the process of index zero writes.

[train.go:704 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L704)

Inherited from `TrainerOn`

```go
func (on Trainer) Save(
    path string,
    config *TrainerSaveConfig,
) error
```

Calls uform_trainer_save.

###### `*Step`

× 2 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 the config names an arena, and Rows of zero Count otherwise; every process of the run calls it once per step.

[train.go:689 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L689)

Inherited from `TrainerOn`

```go
func (on Trainer) Step(
    modalities []Modality,
    contents Tape,
    config *TrainerStepConfig,
) (Rows, error)
```

Calls uform_trainer_step.

##### Struct `TrainerOn`

TrainerOn is the receiver whose verbs block until their call is final.

[train.go:661 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/train.go#L661)

```go
type TrainerOn struct {
    // contains filtered or unexported fields
}
```

Binding-only.

## Errors

`import "github.com/unum-cloud/uform"` 4.0.0-rc.1 · c58749fe

Every fallible call answers an `error` whose `*Error` carries a `Status` and the library’s static `Message`, and a bare `Status` is an error too, so `errors.Is` matches either. A failure the binding catches before the call crosses the boundary reports the status the library would have used.

```go
encoded, err := model.On(executor).TextEncode(texts, uform.EncodeOutputsEmbeddings, uform.ScalarF32, arena, nil)
switch {
case errors.Is(err, uform.StatusContended):
	fmt.Println("the arena serves another call")
case err != nil:
	fmt.Println(err)
default:
	fmt.Println(encoded.Embeddings.Count(), "items")
}
```

`Status` carries the C enumerators’ values, and `StatusDeferred` reaches only `Deferred.Status`. `Status`, `Scalar`, `Mood`, `CPUClass`, `GPUClass`, `GPUVendor`, `Modality`, `Objective`, `Negatives`, `MultimemTier`, `PairLossForm` and `LateInteractionSide` print the names the C tables own through `String`, such as `"shape-mismatch"` or `"intel-haswell"`. A panic inside a progress handler crashes the process, since it cannot unwind through the library.

### API

#### Struct `Error`

Error is one failed call: a status every caller can branch on, and the detail the status cannot carry.2

[types.go:132 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L132)

```go
type Error struct {
    Status  Status
    Message string
}
```

Reach the status with errors.Is or errors.As.

##### `Error`

Error implements the error interface.

[types.go:138 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L138)

```go
func (failure *Error) Error() string
```

##### `Unwrap`

Unwrap exposes the status, which is what errors.Is compares.

[types.go:143 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L143)

```go
func (failure *Error) Unwrap() error
```

#### Enum `Status`

Status names what went wrong, numbered as the C header and USearch number it, so one failure carries one identity across both libraries.3

[types.go:69 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L69)

```go
type Status int32
```

Validation performed here before a call crosses reports the status the library would have reported for the same fault.

A Status is an error, so errors.Is(err, uform.StatusUnsupported) matches any failure carrying it.

##### Values

| `StatusSuccess` | | StatusSuccess means the call completed and carries no message. |
| - | - | - |
| `StatusDeferred` | | StatusDeferred means the call was submitted deferred and is not final yet. |
| `StatusOutOfMemory` | | StatusOutOfMemory means device, pinned or host memory could not be allocated. |
| `StatusShapeMismatch` | | StatusShapeMismatch means item counts, a pixel shape or a batch envelope disagree. |
| `StatusUnsupportedLayout` | | StatusUnsupportedLayout means a stride or packing the model cannot read. |
| `StatusUnknownKind` | | StatusUnknownKind means a scalar, modality or name this build does not know. |
| `StatusIO` | | StatusIO means a checkpoint file could not be opened, read or written. |
| `StatusDevice` | | StatusDevice means the driver refused or the device faulted, or the build carries no GPU. |
| `StatusMalformed` | | StatusMalformed means supplied bytes could not be decoded: a checkpoint, an image, a clip or a recording. |
| `StatusInternal` | | StatusInternal means the library reported neither success nor a failure. |
| `StatusOverflow` | | StatusOverflow means a count would pass the largest value its type holds. |
| `StatusUninitialized` | | StatusUninitialized means the handle the call operates on is closed or was never opened. |
| `StatusConfigMismatch` | | StatusConfigMismatch means the request contradicts a frozen configuration. |
| `StatusContended` | | StatusContended means the call was refused rather than waited for: another call holds its executor or arena. |
| `StatusCancelled` | | StatusCancelled means a progress handler asked the call to stop; it unwound and published nothing. |
| `StatusUnsupported` | | StatusUnsupported means the verb is declared but this residency or model does not implement it, like a modality the model was not trained on. |
| `StatusInvalidArgument` | | StatusInvalidArgument means an argument breaks the verb's contract, like a required value left nil. |

###### `StatusFromName`

StatusFromName reads a status back from the spelling [Status.String](#String) renders.

[types.go:121 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L121)

```go
func StatusFromName(name string) (Status, error)
```

###### `Error`

Error implements the error interface, so a bare Status is an errors.Is target.

[types.go:128 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L128)

```go
func (status Status) Error() string
```

###### `String`

String renders the status as the library spells it.

[types.go:116 ↗](https://github.com/unum-cloud/UForm/blob/c58749fe4bb208356cc78a87357ab007041c515b/types.go#L116)

```go
func (status Status) String() string
```

## Design

4.0.0-rc.1 · c58749fe

- **A thin layer over the C ABI.** One file per header, `types.go`, `model.go`, `encode.go` and `train.go`; every name is its C name without `uform_` and `_t` in PascalCase, a verb’s argument struct becomes its `*Config`, and every wrapper’s documentation names the C symbol it calls or says it is binding-only.
- **The receiver chooses, the verb stays.** The model runs a verb on the calling goroutine, `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` and `Wait` blocks through `uform_outcome_wait`, and refusals answer before anything is submitted.
- **No life of its own.** The binding starts no goroutines and keeps no queues, locks or counts; releasing a `Deferred` rides `Close`, which waits for the call first, or the collector’s cleanup, which frees it only once final.
- **Arenas belong to the caller and are reused, never shared.** Every output whose length scales with the call lands in an arena the caller passes, and its views end at the arena’s next call.
- **One pinned frame per call.** A call’s outcome, argument struct, callback handles and result share one allocation holding no unpinned Go pointer, since cgo pins only heap objects.
- **Suites run against the stub library**, and `TestCallsAllocateOnlyTheirFrames` pins the budgets below.

| Path | Go | Rust |
| - | - | - |
| Blocking call | 1 frame | 0 |
| Refusal before the call | 1 `Error` | 1 error |
| Deferred submit and wait | 4: frame, `Deferred`, 2 in `AddCleanup` | 0 |
| Each callback | 1 handle | 0 |
