Go · Training

Training

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

Ask your coding agent about this page, or add the docs server to it

curl -s 'https://www.unum.cloud/docs/uform/go/training.md' | claude -p "How would this fit my code?"

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:

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

AudioShapeAudioShape is the audio slice of a batch envelope; a zero ChunkSamples leaves audio out of the run.
types.go:219 ↗
type AudioShape struct {
    ChunkSamples uint
    SampleRate uint
}

Mirrors uform_audio_shape_t.

Fields

ChunkSamplesuintChunkSamples is the raw samples per frame.
SampleRateuintSampleRate is the mono rate every recording is resampled to; zero derives 16000.
BatchShapeBatchShape is what one device's step carries at most, whatever the modality mix.
types.go:229 ↗
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

MaxRowsPerDeviceuintMaxRowsPerDevice is the rows one device's step packs.
MaxSegmentsPerDeviceuintMaxSegmentsPerDevice is the items one device's step carries across all its rows.
MaxColumnsPerRowuintMaxColumnsPerRow is the positions one row spans.
MaxBagsPerDeviceuintMaxBagsPerDevice is the bags one device's step carries; zero keeps every item its own unit.
MaxChoicesPerItemuintMaxChoicesPerItem is the legal bytes one item offers at most; zero makes no choices.
ImageImageShapeImage is the image geometry.
VideoVideoShapeVideo is the video geometry.
AudioAudioShapeAudio is the audio geometry.
ContrastiveContrastive is how the contrastive loss scores the pooled embeddings; every zero derives.
types.go:268 ↗
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[]uintMatryoshkaDimensions are the prefix widths scored, strictly ascending multiples of 8, at most 8 of them; empty scores the full width alone.
TemperatureGroupsuintTemperatureGroups is the learnable pairs of an inverse temperature and a bias; zero derives one.
InverseTemperaturefloat32InverseTemperature is the starting inverse temperature of every group.
Biasfloat32Bias is the starting logit bias of every group.
NegativesNegativesNegatives is which pairs repel.
AmbientRepulsionWeightfloat32AmbientRepulsionWeight is the weight of every pair no edge names under NegativesAmbient.
MaxEdgesPerDeviceuintMaxEdgesPerDevice is the edges one device's step names per edge set at most; zero derives.
PairLossPairLossFormPairLoss is the pair loss over each anchor's row.
EdgesEdges 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 ↗
type Edges struct {
    Offsets []uint
    IDs []uint32
    Weights []float32
}

Mirrors uform_edges_view_t.

Fields

Offsets[]uintOffsets holds one more entry than the step's items; empty names no edges.
IDs[]uint32IDs are indices into the step's items, ascending within each run.
Weights[]float32Weights holds one weight per ID; empty weighs every edge one.
ImageShapeImageShape is the image slice of a batch envelope; a zero PatchSide leaves images out of the run.
types.go:194 ↗
type ImageShape struct {
    PatchSide uint
    Channels uint
}

Mirrors uform_image_shape_t.

Fields

PatchSideuintPatchSide is the square patch side images tile into, in pixels.
ChannelsuintChannels is the channels every pixel carries; zero derives four.
LateInteractionLateInteraction is how the late-interaction loss scores per-token vectors; every zero derives.
types.go:292 ↗
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.

MaskingMasking is how the masked objective corrupts a batch and weighs its heads; every zero derives.
types.go:251 ↗
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.

RelationsRelations is the contrastive targets of one step.
types.go:403 ↗
type Relations struct {
    Attract Edges
    Repel   Edges
    Ignore  Edges
}

Mirrors uform_relations_view_t.

ScheduleSchedule is the learning-rate schedule: a linear warmup to the peak, then a cosine decay.
types.go:315 ↗
type Schedule struct {
    LearningRate    float32
    MinLearningRate float32
    WarmupSteps     uint
    Steps           uint
}

Mirrors uform_schedule_t field for field.

TrainerInitVramConfigTrainerInitVramConfig is the geometry, objectives and schedule of a run; zero fields derive.
types.go:356 ↗
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

ResumestringResume is the path of a checkpoint to continue from; empty starts from Seed.
DepthuintDepth is the transformer blocks stacked.
HiddenuintHidden is the embedding width, a multiple of 128.
BatchBatchShapeBatch is what one device's step carries at most.
ObjectiveObjectiveObjective is which losses a step relaxes.
MaskingMaskingMasking configures the masked objective.
ContrastiveContrastiveContrastive configures the contrastive loss.
LateInteractionLateInteractionLateInteraction configures the late-interaction loss.
ChoicesChoicesChoices configures the calibrated choices term.
ScheduleScheduleSchedule is the learning-rate schedule.
Mesh*MeshMesh must stay open until the trainer is closed; nil runs this process alone.
Seeduint64Seed is the base of every keyed draw.
ProgressProgressCallbackProgress hears the tensors placed on a resume.
ProgressStepsuintProgressSteps is the reports the call makes at most; zero derives ten.
TrainerSaveConfigTrainerSaveConfig holds the knobs of Save; nil derives every field.
types.go:453 ↗
type TrainerSaveConfig struct {
    Progress ProgressCallback
    ProgressSteps uint
}

Fields

ProgressProgressCallbackProgress hears the tensors written.
ProgressStepsuintProgressSteps is the reports the call makes at most; zero derives ten.
TrainerStepConfigTrainerStepConfig holds the per-item inputs and knobs of a step beside its modalities and contents; nil derives every field.
types.go:431 ↗
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[]uint32Bags holds the bag of each item; empty keeps every item its own bag.
TemperatureGroups[]uint32TemperatureGroups holds the temperature group of each item; empty puts every item in group zero.
Sides[]LateInteractionSideSides holds the late-interaction side of each item; empty takes none into late interaction.
ChoicesTapeChoices holds each item's legal bytes, as TextChoose takes them; the zero Tape makes none.
ChoiceTargetsTapeChoiceTargets holds the target probability of each choice, as TextChoose answers them.
RelationsRelationsRelations holds the attract, repel and ignore edges.
Arena*ArenaArena receives the pooled embeddings the loss scored; nil skips the copy.
OutputsScalarScalarOutputsScalar is the scalar the embeddings land as.
Stats*TrainerStepStatsStats is the report the step overwrites, kept by the caller until it is final; nil skips it.
TrainerStepStatsTrainerStepStats is what a step reports, every loss its world mean.
types.go:412 ↗
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.

VideoShapeVideoShape is the video slice of a batch envelope; a zero PatchSide leaves video out of the run.
types.go:204 ↗
type VideoShape struct {
    PatchSide uint
    TubeFrames uint
    FrameStride uint
    Channels uint
}

Mirrors uform_video_shape_t.

Fields

PatchSideuintPatchSide is the square patch side one tube tiles into, in pixels.
TubeFramesuintTubeFrames is the frames one tube folds ahead of its patch; zero derives two.
FrameStrideuintFrameStride is the source frames between sampled ones; zero derives one.
ChannelsuintChannels is the channels every pixel carries; zero derives three.
EnumLateInteractionSideLateInteractionSide is which side of a late-interaction score an item takes.2
train.go:139 ↗
type LateInteractionSide int32

Values

LateInteractionSideNoneLateInteractionSideNone takes no part in late interaction.
LateInteractionSideQueryLateInteractionSideQuery scores the documents the item attracts and repels.
LateInteractionSideDocumentLateInteractionSideDocument is scored by the queries naming it.
LateInteractionSideQueryAndDocumentLateInteractionSideQueryAndDocument plays both sides.
LateInteractionSideFromNameLateInteractionSideFromName reads a side back from the spelling LateInteractionSide.String renders.
train.go:159 ↗
func LateInteractionSideFromName(
    name string,
) (LateInteractionSide, error)
StringString renders the side as the library spells it.
train.go:153 ↗
func (side LateInteractionSide) String() string
EnumModalityModality is what the bytes of one training item hold.2
train.go:41 ↗
type Modality int32

Values

ModalityTextModalityText is UTF-8 text, a byte per token.
ModalityImageModalityImage is a JPEG, PNG or WebP file.
ModalityVideoModalityVideo is an MP4 or WebM file.
ModalityAudioModalityAudio is a WAV, FLAC, MP3 or Opus file.
ModalityFromNameModalityFromName reads a modality back from the spelling Modality.String renders.
train.go:60 ↗
func ModalityFromName(name string) (Modality, error)
StringString renders the modality as the library spells it.
train.go:55 ↗
func (modality Modality) String() string
EnumNegativesNegatives is which pairs the contrastive loss pushes apart.2
train.go:91 ↗
type Negatives int32

Values

NegativesAmbientNegativesAmbient repels edges, and every pair no edge names at the ambient weight.
NegativesNamedNegativesNamed repels edges alone.
NegativesFromNameNegativesFromName reads a negatives policy back from the spelling Negatives.String renders.
train.go:106 ↗
func NegativesFromName(name string) (Negatives, error)
StringString renders the policy as the library spells it.
train.go:101 ↗
func (negatives Negatives) String() string
EnumObjectiveObjective is which losses a step relaxes, one per combination the engine trains.2
train.go:67 ↗
type Objective int32

Values

ObjectiveMaskedObjectiveMasked is masked reconstruction alone, as the Base pretrains.
ObjectiveContrastiveObjectiveContrastive is the pairwise contrastive loss alone, as the Embedder trains.
ObjectiveJointObjectiveJoint is both, joined at the final-norm states.
ObjectiveFromNameObjectiveFromName reads an objective back from the spelling Objective.String renders.
train.go:84 ↗
func ObjectiveFromName(name string) (Objective, error)
StringString renders the objective as the library spells it.
train.go:79 ↗
func (objective Objective) String() string
EnumPairLossFormPairLossForm is how a contrastive term turns a row of scores into forces.2
train.go:113 ↗
type PairLossForm int32

Values

PairLossFormDerivedPairLossFormDerived keeps the term's own form: sigmoid for pooled vertices, ranked for tokens.
PairLossFormBalancedPairLossFormBalanced normalizes the attract and repel halves of every cell apart.
PairLossFormRankedPairLossFormRanked scores every positive over every negative, where the bias cancels.
PairLossFormSigmoidPairLossFormSigmoid is SigLIP's per-cell sigmoid cross-entropy.
PairLossFormFromNamePairLossFormFromName reads a pair loss form back from the spelling PairLossForm.String renders.
train.go:132 ↗
func PairLossFormFromName(name string) (PairLossForm, error)
StringString renders the form as the library spells it.
train.go:127 ↗
func (form PairLossForm) String() string
StructTrainerTrainer 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 ↗
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.

TrainerInitVramTrainerInitVram 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 ↗
func TrainerInitVram(
    executor *Executor,
    config *TrainerInitVramConfig,
) (*Trainer, error)

Calls uform_trainer_init_vram, blocking.

CloseClose frees the trainer, waiting for every deferred call naming it.
train.go:642 ↗
func (trainer *Trainer) Close() error

It is idempotent.

*Deferred× 2Deferred is the receiver whose verbs submit their calls to executor, each answering a Deferred from the same arguments.
train.go:679 ↗

Inherited from TrainerOn

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

Binding-only.

*On× 2On is the receiver whose verbs block on executor, the one the trainer was made on.
train.go:672 ↗

Inherited from TrainerOn

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

Binding-only.

*Save× 2Save 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 ↗

Inherited from TrainerOn

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

Calls uform_trainer_save.

*Step× 2Step 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 ↗

Inherited from TrainerOn

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

Calls uform_trainer_step.

StructTrainerOnTrainerOn is the receiver whose verbs block until their call is final.
train.go:661 ↗
type TrainerOn struct {
    // contains filtered or unexported fields
}

Binding-only.