Rust · Training

Training

use uform::AudioShape;use uform::BatchShape;use uform::Contrastive;use uform::Edges;use uform::ImageShape;use uform::LateInteraction;use uform::LateInteractionSide;use uform::Masking;use uform::Modality;use uform::Negatives;use uform::Objective;use uform::PairLossForm;use uform::Relations;use uform::Schedule;use uform::TrainVerbs;use uform::Trainer;use uform::TrainerInitVramConfig;use uform::TrainerSave;use uform::TrainerSaveConfig;use uform::TrainerStep;use uform::TrainerStepConfig;use uform::TrainerStepStats;use uform::VideoShape; 4.0.0-rc.1 · 3ee5e534

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

let executor = unsafe { Executor::for_vram(&[0, 1], None, &[], None, &[], 0)? };
let mesh = Mesh::bootstrap(&executor, &MeshOptions {
    host_domain_index: rank,
    host_domain_count: nodes,
    directory: Path::new("/shared/exchange"),
    job: "run-17",
    ..MeshOptions::default()
})?;
let trainer = Trainer::init_vram(&executor, TrainerInitVramConfig {
    mesh: Some(&mesh),
    depth: 12,
    hidden: 512,
    objective: Objective::Joint,
    batch: BatchShape { max_rows_per_device: 64, max_segments_per_device: 256, max_columns_per_row: 1024,
                        max_bags_per_device: 128, image: ImageShape { patch_side: 16, channels: 0 },
                        ..BatchShape::default() },
    schedule: Schedule { steps: 100_000, ..Schedule::default() },
    seed: 42,
    ..TrainerInitVramConfig::default()
})?;

let mut stats = TrainerStepStats::default();
let relations = Relations { attract: Edges { offsets: &[0, 1, 2, 3, 4], ids: &[1, 0, 3, 2], weights: &[] },
                            ..Relations::default() };
let config = TrainerStepConfig { bags: &[0, 0, 1, 1], relations, stats: Some(&mut stats), ..TrainerStepConfig::default() };
trainer.on(&executor).step(&modalities, &contents, config)?;
trainer.on(&executor).save("checkpoint.safetensors")?;

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, which the binding checks against the step’s items before the call. A step’s sides give each item a LateInteractionSide, and its choices and choice_targets give each choice item its legal bytes and their target probabilities as (data, offsets) tapes, the shapes text_choose takes and answers, checked the same way. Paths cross as the OS’s bytes on Unix, not necessarily UTF-8, while the mesh’s job is a name and a &str. step answers the pooled embeddings the loss scored when its config names an arena, and None otherwise. A trainer borrows its mesh, so the mesh outlives every trainer made over it, and mesh.describe() answers a MeshDescription whose multimem_tier is a MultimemTier and whose gpu_class is the GPUClass every GPU of the run dispatches as.

API

StructAudioShapeThe audio slice of a batch envelope; a zero chunk_samples leaves audio out of the run.
train.rs:449 ↗
pub struct AudioShape

Mirrors uform_audio_shape_t.

Fields

chunk_samplesusizeRaw samples per frame, the fan-in of the learned frontend.
sample_rateusizeThe mono rate every recording is resampled to; zero derives 16000.

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Eq, Debug, Default
StructBatchShapeWhat one device's step carries at most, whatever the modality mix: capacity fixed at creation.
train.rs:462 ↗
pub struct BatchShape

Text always takes part; a media modality takes part when its slice is live.

Mirrors uform_batch_shape_t.

Fields

max_rows_per_deviceusizeRows one device's step packs.
max_segments_per_deviceusizeItems one device's step carries across all its rows, which is also its pooling axis.
max_columns_per_rowusizePositions one row spans, the sequence length.
max_bags_per_deviceusizeBags one device's step carries; zero keeps every item its own routing unit.
max_choices_per_itemusizeLegal bytes one item offers to choose from at most; zero makes no choices.
imageImageShapeThe image geometry.
videoVideoShapeThe video geometry.
audioAudioShapeThe audio geometry.

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Eq, Debug, Default
StructContrastiveHow the contrastive loss scores the pooled embeddings; every zero derives the default the C header names.
train.rs:517 ↗
pub struct Contrastive<'config>

Mirrors uform_contrastive_t.

Fields

matryoshka_dimensions&'config [usize]Matryoshka prefix widths, strictly ascending, each a multiple of 8, at most 8 of them, every one scored; empty scores the full width alone. Copied, not borrowed.
temperature_groupsusizeLearnable inverse temperature and bias pairs, one per group a step's items select; one.
inverse_temperaturef32The starting inverse temperature of every group; 10 under the sigmoid form, SigLIP's, else 1.
biasf32The starting logit bias of every group; −10 under the sigmoid form, SigLIP's, else zero.
negativesNegativesWhich pairs repel.
ambient_repulsion_weightf32The weight of every pair no edge names, under Negatives::Ambient; 1.
max_edges_per_deviceusizeEdges one device's step names per edge set at most; max_segments_per_device.
pair_lossPairLossFormThe pair loss over each anchor's row; sigmoid.

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Debug, Default
StructEdgesOne edge set over a step's items, as compressed sparse rows; empty offsets name no edges.
train.rs:711 ↗
pub struct Edges<'config>

Mirrors uform_edges_view_t.

Fields

offsets&'config [usize]The step's count plus one non-decreasing offsets into ids.
ids&'config [u32]Item i links to items ids[offsets[i]..offsets[i + 1]], indices into the step's items, ascending within each run.
weights&'config [f32]The weight of each edge, paired with ids; empty weighs every edge one.

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Debug, Default
StructImageShapeThe image slice of a batch envelope; a zero patch_side leaves images out of the run.
train.rs:421 ↗
pub struct ImageShape

Mirrors uform_image_shape_t.

Fields

patch_sideusizeThe square patch side images tile into, in pixels.
channelsusizeChannels every pixel carries; zero derives four, RGBA end to end.

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Eq, Debug, Default
StructLateInteractionHow the late-interaction loss scores the per-token vectors of query and document items; every zero derives the default the C header names.
train.rs:563 ↗
pub struct LateInteraction

Mirrors uform_late_interaction_t.

Fields

weightf32The loss weight; zero trains no token head.
widthusizeThe token vectors' width, a multiple of 8; 128.
inverse_temperaturef32The starting inverse temperature of every contrastive group; 1.
biasf32The starting logit bias of every contrastive group; zero is zero.
max_query_spanusizeTokens one query item contributes at most, its first past the prefix; 64.
max_query_tokens_per_deviceusizeQuery token rows one device's step holds at most; max_query_span of every item.
max_documents_per_deviceusizeDocument items one device's step holds at most; max_segments_per_device.
max_document_tokens_per_deviceusizeDocument token rows one device's step holds at most; the batch's tokens per device.
pair_lossPairLossFormThe pair loss over each query's row of hard MaxSim scores; ranked.

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Debug, Default
EnumLateInteractionSideWhich side of a late-interaction score an item takes: a query's tokens score a document's, and a symmetric pair plays both.
train.rs:400 ↗
pub enum LateInteractionSide

Mirrors uform_late_interaction_side_t.

Values

None0The item takes no part in late interaction.
Query1The item's tokens score the documents it attracts and repels.
Document2The item's tokens are scored by the queries naming it.
QueryAndDocument3The item plays both sides.

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Eq, Debug, Default, Hash
StructMaskingHow the masked objective corrupts a batch and weighs its heads; every zero derives the default the C header names.
train.rs:487 ↗
pub struct Masking

Mirrors uform_masking_t.

Fields

token_mask_probabilityf32Fraction of text positions covered by spans; 0.15.
token_mean_spanf32Mean geometric span length in bytes; 16.
replace_fractionf32Of covered positions, the share shown as MASK; 0.8.
random_fractionf32Of covered positions, the share replaced by a random byte, the rest kept clean; 0.1.
image_mask_ratiof32Fraction of image patches masked; 0.75.
video_mask_ratiof32Fraction of video tubes masked, tubed across time; 0.75.
audio_mask_ratiof32Fraction of audio frames masked; 0.75.
text_weightf32The weight of the text head; 1.
image_weightf32The weight of the image head; 1.
video_weightf32The weight of the video head; 1.
audio_weightf32The weight of the audio head; 1.

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Debug, Default
EnumModalityWhat the bytes of one training item hold.
train.rs:202 ↗
pub enum Modality

Mirrors uform_modality_t.

Values

Text0UTF-8 text, a byte per token.
Image1A JPEG, PNG or WebP file.
Video2An MP4 or WebM file.
Audio3A WAV, FLAC, MP3 or Opus file.

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Eq, Debug, Hash, Display, FromStr
EnumNegativesWhich pairs the contrastive loss pushes apart.
train.rs:293 ↗
pub enum Negatives

Mirrors uform_negatives_t.

Values

Ambient0Repel edges, and every pair no edge names, at the ambient repulsion weight.
Named1Repel edges alone.

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Eq, Debug, Default, Hash, Display, FromStr
EnumObjectiveWhich losses a step relaxes, one enumerator per combination the engine trains.
train.rs:246 ↗
pub enum Objective

Mirrors uform_objective_t.

Values

Masked0Masked reconstruction alone, as the Base pretrains.
Contrastive1The pairwise contrastive loss alone, as the Embedder trains.
Joint2Both, joined at the final-norm states.

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Eq, Debug, Default, Hash, Display, FromStr
EnumPairLossFormHow a contrastive term turns a row of scores into forces.
train.rs:381 ↗
pub enum PairLossForm

Mirrors uform_pair_loss_form_t.

Values

Derived0The term's own form: sigmoid for pooled vertices, ranked for token vectors.
Balanced1The sigmoid cross-entropy of every cell, its attract and repel halves normalized apart.
Ranked2The sigmoid cross-entropy of every positive's score over every negative's, where the bias cancels.
Sigmoid3SigLIP's sigmoid cross-entropy of every cell, each repel weighed like an attract.

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Eq, Debug, Default, Hash
StructRelationsThe contrastive targets of one step, resolved per pair in this order: a pair ignore names is skipped, one attract names pulls together, one repel names pushes apart, and every other pair follows the run's Negatives.
train.rs:766 ↗
pub struct Relations<'config>

Mirrors uform_relations_view_t.

Fields

attractEdges<'config>Pairs pulled together.
repelEdges<'config>Pairs pushed apart.
ignoreEdges<'config>Pairs skipped, like known false negatives; their weights are not read.

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Debug, Default, From<Relations<'config>>
StructScheduleThe learning-rate schedule: a linear warmup to the peak, then a cosine decay to the floor.
train.rs:603 ↗
pub struct Schedule

Mirrors uform_schedule_t.

Fields

learning_ratef32The peak learning rate; zero derives 5e-4.
min_learning_ratef32The floor the cosine settles at; zero derives 1e-5.
warmup_stepsusizeSteps from zero to the peak; zero derives a tenth of steps, at most 400.
stepsusizeSteps the run takes across resumes, which the cosine spans; zero is refused.

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Debug, Default
TraitTrainVerbsEvery trainer verb, written once for both receivers of Trainer::on and Trainer::deferred, which run on the executor the trainer was made on.4
train.rs:1118 ↗
pub trait TrainVerbs<'trainer>: Copy

Rust-only.

Implementors

  • impl<'trainer, Completion: Completion> TrainVerbs<'trainer> for On<'trainer, Trainer<'_>, Completion>
CompletionBlocking or Deferring.
train.rs:1120 ↗
type Completion: Completion;
handlesThe trainer this receiver reaches and the executor its calls run on.
train.rs:1123 ↗
fn handles(&self) -> Handles
stepApplies one optimizer step over this process's items and every peer's: forward, losses, backward, the world gradient reduction, and the update.
train.rs:1132 ↗
fn step<'config, 'arena, Modalities: AsRef<[Modality]>, Contents: TapeView<u8>>(
    self,
    modalities: Modalities,
    contents: Contents,
    config: impl Into<TrainerStepConfig<'config, 'arena>>,
) -> <<Self as TrainVerbs<'trainer>>::Completion as Completion>::Answer<'trainer, TrainerStep<'config, 'arena, Modalities, Contents>>
where
    Self::Completion: Accepts<Modalities> + Accepts<Contents> + Accepts<TrainerStepConfig<'config, 'arena>>,

Every process of the run calls it once per step, with one modality per item and each item's bytes in contents.

Answers the pooled embeddings when the config names an arena.

Calls uform_trainer_step.

saveWrites the weights and the step, which the model loads serve and Trainer::init_vram resumes; only the process of index zero writes, the rest return at once.
train.rs:1156 ↗
fn save<'config, Location: AsRef<Path>>(
    self,
    config: impl Into<TrainerSaveConfig<'config, Location>>,
) -> <<Self as TrainVerbs<'trainer>>::Completion as Completion>::Answer<'trainer, TrainerSave<'config, Location>>
where
    Self::Completion: Accepts<TrainerSaveConfig<'config, Location>>,

Calls uform_trainer_save.

StructTrainerA training run: the tower replicas, gradients, optimizer moments, heads, temperatures and the collectives sized by them, on its executor's devices, whose verbs come from TrainVerbs.3
train.rs:1030 ↗
pub struct Trainer<'mesh>
use uform::*;

let executor = unsafe { Executor::for_vram(&[0], None, &[], None, &[], 0, 0)? };
let trainer = Trainer::init_vram(&executor, TrainerInitVramConfig {
    depth: 12,
    hidden: 512,
    batch: BatchShape { max_rows_per_device: 64, max_segments_per_device: 256, max_columns_per_row: 1024,
                        ..BatchShape::default() },
    schedule: Schedule { steps: 100_000, ..Schedule::default() },
    seed: 42,
    ..TrainerInitVramConfig::default()
})?;
let mut stats = TrainerStepStats::default();
let config = TrainerStepConfig { stats: Some(&mut stats), ..TrainerStepConfig::default() };
trainer.on(&executor).step([Modality::Text], ["a caption"], config)?;
trainer.on(&executor).save("checkpoint.safetensors")?;

Mirrors uform_trainer_t; dropping it calls uform_trainer_free. 'mesh is the borrow of the Mesh it was made over.

Implements

Debug, Send, Drop
init_vramBuilds one replica per device of executor, the NVLink domain its consumers reserve over the mesh, and starts or resumes the run; every process of the run calls it with the same geometry, objective and seed.
train.rs:1048 ↗
pub fn init_vram<'config>(
    executor: &Executor,
    config: impl Into<TrainerInitVramConfig<'config, 'mesh>>,
) -> Result<Self>

Calls uform_trainer_init_vram.

onThe receiver whose verbs block on executor, the one the trainer was made on.
train.rs:1088 ↗
pub fn on<'trainer>(&'trainer self, executor: &'trainer Executor) -> On<'trainer, Trainer<'mesh>>

Rust-only.

deferredThe receiver whose verbs submit their calls to executor, answering a Deferred from the same verbs given owned arguments.
train.rs:1100 ↗
pub fn deferred<'trainer>(
    &'trainer self,
    executor: &'trainer Executor,
) -> On<'trainer, Trainer<'mesh>, Deferring>

Rust-only.

StructTrainerInitVramConfigThe geometry, objective and starting point of a run; see Trainer::init_vram.
train.rs:673 ↗
pub struct TrainerInitVramConfig<'config, 'mesh>

Mirrors uform_trainer_init_vram_t.

Fields

resumeOption<&'config Path>The checkpoint to continue from, at its saved step; None starts from seed.
depthusizeTransformer blocks stacked.
hiddenusizeEmbedding width, a multiple of 128.
batchBatchShapeWhat one device's step carries at most.
objectiveObjectiveWhich losses a step relaxes.
maskingMaskingThe masked objective's corruption and weights, read unless the objective is contrastive alone.
contrastiveContrastive<'config>The contrastive loss's scoring, read unless the objective is masked alone.
late_interactionLateInteractionThe late-interaction loss beside the pooled one, read when its weight is positive.
choicesChoicesThe calibrated choices beside every other term, read when its weight is positive, which needs the batch's max_choices_per_item.
scheduleScheduleThe learning-rate schedule.
meshOption<&'mesh Mesh>The mesh made over the same executor, borrowed until the trainer drops; None runs this process alone.
seedu64The base of every keyed draw: initialization, corruption and the shuffle.
progressOption<&'config mut ProgressCallback<'config>>Reports the tensors placed on a resume and stops wherever it says to.
progress_stepsusizeReports the call makes at most, the last at completion; zero derives to ten.

Implements

Default
StructTrainerSaveA checkpoint write; see TrainVerbs::save.
train.rs:1281 ↗
pub struct TrainerSave<'config, Location>

Calls uform_trainer_save.

StructTrainerSaveConfigThe path a checkpoint is written to and the handler counting its tensors; see TrainVerbs::save.
train.rs:898 ↗
pub struct TrainerSaveConfig<'config, Location>

Mirrors uform_trainer_save_t.

Fields

pathLocationDestination of the safetensors checkpoint, written whole and renamed into place.
progressOption<&'config mut ProgressCallback<'config>>Reports the tensors written and stops wherever it says to.
progress_stepsusizeReports the call makes at most, the last at completion; zero derives to ten.

Implements

From<Location>
StructTrainerStepOne optimizer step; see TrainVerbs::step.
train.rs:1188 ↗
pub struct TrainerStep<'config, 'arena, Modalities, Contents>

Calls uform_trainer_step.

StructTrainerStepConfigThe routing, targets and reports of TrainVerbs::step.
train.rs:840 ↗
pub struct TrainerStepConfig<'config, 'arena>

Mirrors uform_trainer_step_t.

Fields

bags&'config [u32]The bag of each item, items sharing a bag landing on one device; empty keeps every item its own bag.
temperature_groups&'config [u32]The temperature group of each item, each below the run's temperature_groups; empty puts every item in group zero.
sides&'config [LateInteractionSide]The late-interaction side of each item; empty makes every item LateInteractionSide::None.
choices(&'config [u8], &'config [usize])Each item's legal choices, one byte each, as a (data, offsets) tape like the one text_choose takes; empty offsets make no choices. Read when the run trains them: a text item offering any is the state its answer follows, and the call appends the mask byte, cutting a state longer than a row at its head.
choice_targets(&'config [f32], &'config [usize])The target probability of each choice, a (data, offsets) tape whose entries are as long as those of choices and sum to one, as text_choose answers its probabilities.
relationsRelations<'config>The contrastive targets, read unless the objective is masked alone.
arenaOption<&'arena mut Arena>The arena the pooled embeddings land in, as the contrastive loss scored them before the update; None skips the copy, and the step answers no rows.
outputs_scalarScalarThe scalar type the embeddings land as, read only with an arena.
statsOption<&'config mut TrainerStepStats>Where the losses land, overwritten by the call; None skips their readback too.

Implements

Default, From<Relations<'config>>
StructTrainerStepStatsWhat a step reports, every loss its world mean, overwritten by the call.
train.rs:781 ↗
pub struct TrainerStepStats

Mirrors uform_trainer_step_stats_t.

Fields

stepusizeThe optimizer step the call applied, counted from one across resumes.
learning_ratef32The learning rate it applied.
lossf32The total loss the step minimized.
contrastive_lossf32The contrastive term; zero when the objective is masked alone.
masked_text_lossf32The text reconstruction term, before its weight; zero when absent.
masked_image_lossf32The image reconstruction term, before its weight; zero when absent.
masked_video_lossf32The video reconstruction term, before its weight; zero when absent.
masked_audio_lossf32The audio reconstruction term, before its weight; zero when absent.
late_interaction_lossf32The late-interaction term, weighted; zero when absent.
choices_lossf32The choices term over the items that made a choice, before its weight; zero when absent.
truncatedusizeItems cut at a row's width.
droppedusizeSegments dropped whole because the batch had no room for them, since the last step that read its stats.

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Debug, Default
StructVideoShapeThe video slice of a batch envelope; a zero patch_side leaves video out of the run.
train.rs:433 ↗
pub struct VideoShape

Mirrors uform_video_shape_t.

Fields

patch_sideusizeThe square patch side one tube tiles into, in pixels.
tube_framesusizeFrames one tube folds ahead of its patch; zero derives two.
frame_strideusizeSource frames between sampled ones; zero derives one, every frame.
channelsusizeChannels every pixel carries; zero derives three.

Implements

Clone, Copy, StructuralPartialEq, PartialEq, Eq, Debug, Default