Swift · Encoding

Encoding

import UForm 4.0.0-rc.1 · 3ee5e534

Every verb runs one forward and keeps the surfaces outputs names, deciding which C output pointers the binding passes:

  • .embeddings, the default, lands one pooled row per item as Rows;
  • .states lands the final-norm states, one row per token each item kept after truncation, as RowsTape;
  • .tokenVectors lands the token head’s unit vectors, tokenWidth wide, on the same offsets as the states, and a model without a token head refuses it with unsupported;
  • naming none is refused with invalidArgument.
let encoded = try model.textEncode(texts, outputs: [.embeddings, .states], arena: arena)
let pooled = encoded.embeddings!                  // pooled[i] is item i's row
let states = encoded.states!                      // states[i] is item i's rows, one per byte of its text
print(pooled.columns, pooled.stride, pooled.scalar, states[0].count, encoded.stats.truncated)

The six verbs take one input form each:

try model.textEncode(["a caption"], arena: arena)                                     // UTF-8, a byte per token
try model.imageEncode([jpeg, png], arena: arena)                                      // JPEG, PNG or WebP files
try model.imageEncodePixels([rgb], heights: [480], widths: [640], arena: arena)       // interleaved 8-bit RGB
try model.videoEncode([mp4], arena: arena)                                            // MP4 or WebM files
try model.audioEncode([wav], arena: arena)                                            // WAV, FLAC, MP3 or Opus
try model.audioEncodeSamples([samples], sampleRate: 16_000, arena: arena)             // mono Float samples

EncodeConfig carries the rest: outputsScalar, f32 by default, and a progress handler with its progressSteps. Rows of f32, bf16 and f16 read as Float, and withUnsafeBytes hands any scalar on as stored, such as to a USearch index.

let config = EncodeConfig(outputsScalar: .bf16, progress: { done, total in done < limit ? .continue : .cancel })
let narrow = try model.textEncode(texts, arena: arena, config: config)
narrow.embeddings!.withUnsafeBytes { bytes in index.add(bytes) }

A handler never runs on two threads at once, but may run on whichever thread advanced the work, hence @Sendable; returning .cancel stops the call with cancelled.

API

StructScalarA scalar type a model computes in and its outputs land as, numbered as USearch numbers it, carrying the C enumerator.17
Types.swift:106 ↗
struct Scalar

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

Conforms to

Hashable, Sendable, CustomStringConvertible, Equatable
unknownNo scalar named - an unset field.
Types.swift:111 ↗
static let unknown: Scalar
f64IEEE-754 binary64.
Types.swift:113 ↗
static let f64: Scalar
f32IEEE-754 binary32.
Types.swift:115 ↗
static let f32: Scalar
bf16The brain floating-point format.
Types.swift:117 ↗
static let bf16: Scalar
f16IEEE-754 binary16.
Types.swift:119 ↗
static let f16: Scalar
e5m28-bit floating point with five exponent bits.
Types.swift:121 ↗
static let e5m2: Scalar
e4m38-bit floating point with four exponent bits.
Types.swift:123 ↗
static let e4m3: Scalar
e3m26-bit floating point with three exponent bits.
Types.swift:125 ↗
static let e3m2: Scalar
e2m36-bit floating point with two exponent bits.
Types.swift:127 ↗
static let e2m3: Scalar
i8An 8-bit signed integer.
Types.swift:129 ↗
static let i8: Scalar
i4x2Two 4-bit signed integers per byte.
Types.swift:131 ↗
static let i4x2: Scalar
i32A 32-bit signed integer.
Types.swift:133 ↗
static let i32: Scalar
u8An 8-bit unsigned integer, the element of UTF-8 text and of encoded files.
Types.swift:135 ↗
static let u8: Scalar
u4x2Two 4-bit unsigned integers per byte.
Types.swift:137 ↗
static let u4x2: Scalar
u1x8Eight single-bit dimensions per byte.
Types.swift:139 ↗
static let u1x8: Scalar
descriptionThe kind as the library spells it.
Types.swift:142 ↗
var description: String { get }

Calls uform_scalar_name.

initReads a spelling back, and nil for one no kind carries.
Types.swift:145 ↗
init?(name: String)

Calls uform_scalar_from_name.

StructRowsA run of rows a call wrote packed into its arena, one per item, read in place.7
Types.swift:793 ↗
struct Rows

Mirrors uform_rows_view_t.

Rows of f32, bf16 and f16 read as Float; withUnsafeBytes hands any scalar on as stored, such as to a USearch index.

Conforms to

RandomAccessCollection, BidirectionalCollection, Collection, Sequence
strideBytes between the starts of consecutive rows.
Types.swift:799 ↗
let stride: Int
columnsValues per row, the model's embedding dimensions.
Types.swift:801 ↗
let columns: Int
scalarThe scalar type the rows hold.
Types.swift:803 ↗
let scalar: Scalar
endIndexOne past the last row.
Types.swift:805 ↗
let endIndex: Int
startIndexThe first row's position, which a collection walk starts from.
Types.swift:808 ↗
var startIndex: Int { get }
subscriptOne row's values.
Types.swift:832 ↗
subscript(row: Int) -> Row { get }
withUnsafeBytesLends the rows' bytes as stored to body, which must not keep the buffer past its return.
Types.swift:838 ↗
func withUnsafeBytes<Result, Failure>(
    _ body: (UnsafeRawBufferPointer) throws(Failure) -> Result
) throws(Failure) -> Result where Failure : Error
StructRows.RowOne row of an arena's values, read in place and widened to Float.3
Types.swift:846 ↗
struct Row

Conforms to

RandomAccessCollection, BidirectionalCollection, Collection, Sequence
endIndexOne past the last value in the row.
Types.swift:854 ↗
let endIndex: Int
startIndexThe first value's position, which a collection walk starts from.
Types.swift:857 ↗
var startIndex: Int { get }
subscriptThe value at a position, widened from the row's scalar.
Types.swift:860 ↗
subscript(position: Int) -> Float { get }
StructRowsTapeA ragged run of rows a call wrote into its arena, as many per item as the item had tokens left after truncation, read in place.4
Types.swift:888 ↗
struct RowsTape

Mirrors uform_rows_tape_view_t.

Conforms to

RandomAccessCollection, BidirectionalCollection, Collection, Sequence
rowsEvery item's rows, end to end.
Types.swift:890 ↗
let rows: Rows
endIndexOne past the last item.
Types.swift:894 ↗
let endIndex: Int
startIndexThe first item's position, which a collection walk starts from.
Types.swift:897 ↗
var startIndex: Int { get }
subscriptOne item's rows, one per token it kept.
Types.swift:907 ↗
subscript(item: Int) -> Rows { get }
StructTapeA ragged run of f32 values a call wrote into its arena, as many per item as the item asked for, read in place.3
Types.swift:923 ↗
struct Tape

Mirrors uform_tape_view_t.

Conforms to

RandomAccessCollection, BidirectionalCollection, Collection, Sequence
endIndexOne past the last item.
Types.swift:931 ↗
let endIndex: Int
startIndexThe first item's position, which a collection walk starts from.
Types.swift:934 ↗
var startIndex: Int { get }
subscriptOne item's values.
Types.swift:944 ↗
subscript(item: Int) -> Rows.Row { get }
StructOutputsThe surfaces an encode call keeps from its one forward, each deciding whether the binding passes the C output pointer of the same name; .embeddings alone by default.5
Encode.swift:14 ↗
struct Outputs

Conforms to

OptionSet, Sendable, SetAlgebra, RawRepresentable, Equatable, ExpressibleByArrayLiteral
rawValueThe bits, one per C output pointer the set passes.
Encode.swift:16 ↗
let rawValue: UInt8
initWraps bits, one per C output pointer.
Encode.swift:18 ↗
init(rawValue: UInt8)
embeddingsOne pooled embedding per item, read past the attention pool and the projection head.
Encode.swift:21 ↗
static let embeddings: Outputs
statesThe final-norm states, one row per token each item kept after truncation.
Encode.swift:23 ↗
static let states: Outputs
tokenVectorsThe token head's unit vectors, one row per token each item kept, its prefix included; a model without a token head reports unsupported.
Encode.swift:26 ↗
static let tokenVectors: Outputs
StructEncodeStatsWhat an encode call reports beside its outputs.2
Encode.swift:30 ↗
struct EncodeStats

Mirrors every uform_*_encode_stats_t.

Conforms to

Equatable, Sendable
truncatedItems cut at the model's context.
Encode.swift:32 ↗
var truncated: Int
tokensTokens the call encoded, after truncation: bytes of text, patches, tubes or frames.
Encode.swift:34 ↗
var tokens: Int
StructEncodeConfigThe knobs every encode verb takes beside its inputs, outputs and arena.4
Encode.swift:38 ↗
struct EncodeConfig
outputsScalarThe scalar every output lands as.
Encode.swift:40 ↗
var outputsScalar: Scalar
progressCalled with items encoded.
Encode.swift:42 ↗
var progress: Progress?
progressStepsReports the call makes at most, the last at completion; zero derives to ten.
Encode.swift:44 ↗
var progressSteps: Int
initTakes every knob by name; a zero progressSteps derives ten.
Encode.swift:47 ↗
init(outputsScalar: Scalar = .f32, progress: Progress? = nil, progressSteps: Int = 0)
StructEncodedWhat one encode call wrote into its arena, read in place until the arena's next call.4
Encode.swift:55 ↗
struct Encoded
embeddingsOne row per item, or nil when outputs left the embeddings out.
Encode.swift:57 ↗
let embeddings: Rows?
statesOne run of rows per item, one row per token kept, or nil when outputs left the states out.
Encode.swift:59 ↗
let states: RowsTape?
tokenVectorsOne run of token-width rows per item, one row per token kept, or nil when outputs left them out.
Encode.swift:62 ↗
let tokenVectors: RowsTape?
statsWhat the call counted on the way.
Encode.swift:64 ↗
let stats: EncodeStats