For the complete documentation index, see llms.txt. This page is also available as Markdown.

Training

Training SameDiff models — TrainingConfig, fit(), listeners, loss curves, and evaluation

Once you have defined a SameDiff computation graph, training it is a matter of configuring an optimizer and a loss variable, then calling fit(). SameDiff handles the forward pass, backward pass, and parameter updates automatically.

Overview of the Training Flow

  1. Define the graph — declare placeholders, variables, ops, and a scalar loss SDVariable.

  2. Create a TrainingConfig — specify the optimizer, which placeholder names correspond to features and labels, and any listeners.

  3. Attach the config with sd.setTrainingConfig(config).

  4. Call sd.fit() — pass a data iterator and a number of epochs. SameDiff returns a History object with loss and metric values per epoch.

TrainingConfig

TrainingConfig is the single configuration object for a SameDiff training run. It is built with a fluent builder API.

import org.nd4j.autodiff.samediff.TrainingConfig;
import org.nd4j.linalg.learning.config.Adam;
import org.nd4j.linalg.api.buffer.DataType;

TrainingConfig config = TrainingConfig.builder()
    .updater(new Adam(1e-3))                      // optimizer with learning rate
    .dataSetFeatureMapping("input")               // feature array -> placeholder
    .dataSetLabelMapping("labels")                // label array   -> placeholder
    .lossVariables("loss")                        // which SDVariable holds the scalar loss
    .build();

sd.setTrainingConfig(config);

Required settings

Setting
Method
Notes

Optimizer

.updater(IUpdater)

Must always be set

Feature mapping

.dataSetFeatureMapping(String...)

Maps DataSet/MultiDataSet feature arrays to placeholder names (in order)

Label mapping

.dataSetLabelMapping(String...)

Maps label arrays to placeholder names

Loss variable

.lossVariables(String...)

Name of the scalar SDVariable used as the training loss

Optimizer (IUpdater)

SameDiff reuses the same IUpdater implementations as DL4J's MultiLayerNetwork:

All optimizers support a learning rate schedule via LearningRateSchedule:

MultiDataSet mappings

When using MultiDataSetIterator (multiple feature and/or label arrays), list placeholder names in the same order as the arrays:

Data type conversion

If your data iterator produces arrays in a different type than your model's placeholders expect, use .dataSetFeatureMappingDtype() and .dataSetLabelMappingDtype() to request automatic casting:

fit() — Running Training

With a DataSetIterator

Each epoch runs through all batches in trainIter, executes the forward pass, computes the loss, runs the backward pass, and updates all VARIABLE-type parameters.

With a MultiDataSetIterator

The MultiDataSetIterator form is needed when your model has more than one input or output array per sample.

With a validation set

Pass a second iterator to evaluate at the end of every epoch:

Fitting a single batch manually

For custom training loops, drive the iteration yourself:

History and LossCurve

fit() returns a History object that records training progress.

History also exposes raw per-iteration loss values if you need finer-grained monitoring:

If you ran validation, validation losses are available separately:

Listeners

Listeners let you observe and react to events during training. Attach them to the TrainingConfig or directly to the SameDiff instance.

Available built-in listeners

ScoreIterationListener

Prints the loss every N iterations:

SameDiffListener interface

Implement SameDiffListener for fully custom callbacks:

Attach the listener:

CheckpointListener

Save a checkpoint to disk every N epochs or every N minutes:

Adding Evaluation During Training

SameDiff can compute evaluation metrics (accuracy, F1, etc.) automatically at the end of each epoch without writing extra evaluation code.

Specify which output variable and which evaluation to use via TrainingConfig:

For validation evaluations, use .validationEvaluations(...) instead.

After training, retrieve evaluation results from the History object:

Supported evaluation classes include Evaluation, RegressionEvaluation, ROC, ROCMultiClass, and others from the org.nd4j.evaluation package.

End-to-End Training Example

The following is a complete example of training a two-layer classifier on MNIST:

Controlling Which Parameters Are Trained

By default, all VARIABLE-type SDVariable instances in the graph are trained. To freeze specific parameters, convert them to constants before calling fit():

To unfreeze later:

Gradient Clipping

Apply gradient clipping globally via the TrainingConfig:

Available clipping strategies: ClipL2Norm, ClipElementWiseAbsoluteValue.

Last updated

Was this helpful?