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

Operations

Op namespaces — sd.math, sd.nn, sd.cnn, sd.rnn, sd.loss, sd.random — and SDVariable methods

Operations in SameDiff consume one or more SDVariable inputs and produce a new SDVariable output of type ARRAY. They are the edges of the computation graph that connect variable nodes together. The total number of available operations, including overloads, runs into the hundreds — from simple elementwise addition to full LSTM layers.

This page gives an overview of where to find operations, how to use them, and what rules to keep in mind.

Common Properties

Before looking at individual namespaces, there are a few properties that apply to all SameDiff operations:

  • Any variable type is valid as input, as long as the data types match what the operation requires. Most numeric operations require floating-point inputs.

  • All operation outputs are ARRAY-type variables. Operations never return VARIABLE, CONSTANT, or PLACEHOLDER.

  • Variables used in a single operation must all belong to the same SameDiff instance. Mixing variables from different SameDiff objects in one operation is an error.

  • You may optionally name the output variable. Pass the desired name as the first String argument:

SDVariable linear = weights.mmul("matrix_product", input).add(bias);
SDVariable output = sd.nn.sigmoid("output", linear);

Named outputs can be retrieved from the graph later with sd.getVariable(String name). If no name is supplied, a unique one is auto-generated from the operation name (e.g. "mmul:0").

Two Families of Operations

Operations live in two places:

  1. SDVariable instance methods — called directly on a variable, e.g. x.add(y).

  2. SameDiff namespace methods — called via one of six namespace objects on the SameDiff instance.

SDVariable Instance Methods

SDVariable exposes a rich set of methods for common operations. These are the most ergonomic to use because they can be chained:

Linear algebra (BLAS-style)

Method
Description

add(y)

Elementwise addition x + y (broadcasting supported)

sub(y)

Elementwise subtraction x - y

mul(y)

Elementwise multiplication x * y (or scalar scaling)

div(y)

Elementwise division x / y

neg()

Negate all elements

mmul(y)

Matrix multiplication

dot(y, dimension)

Dot product along a dimension

rdiv(y)

Reverse division y / x

rsub(y)

Reverse subtraction y - x

Comparison

Method
Description

gt(y)

Greater than (element vs scalar or element vs element)

gte(y)

Greater than or equal

lt(y)

Less than

lte(y)

Less than or equal

eq(y)

Equal

neq(y)

Not equal

Reductions

Reductions take an optional int... dimensions argument. If omitted, the reduction is over all elements.

Method
Description

sum(dimensions)

Sum of elements

mean(dimensions)

Mean of elements

min(dimensions)

Minimum value

max(dimensions)

Maximum value

norm1(dimensions)

L1 norm

norm2(dimensions)

L2 norm

prod(dimensions)

Product of elements

argmax(dimensions)

Index of maximum element

argmin(dimensions)

Index of minimum element

squaredDifference(y)

Elementwise (x - y)^2

Shape manipulation

Method
Description

reshape(long... shape)

Reshape to specified shape

permute(int... dims)

Permute dimensions (transpose generalisation)

shape()

Returns the shape as an integer SDVariable

Chaining example

SameDiff Namespace Operations

The SameDiff class provides six namespace objects. Access them as fields or method calls (both styles work):

The six namespaces are: math, random, nn, cnn, rnn, and loss.

sd.math — General Mathematical Operations

The math namespace provides a broad collection of mathematical functions, statistics, and linear-algebra primitives.

Power and exponential functions

Trigonometric and hyperbolic functions

Elementwise miscellaneous

Reductions

Distance operations (between two identically-shaped variables)

Matrix operations

Logical operations

Chaining in math

Chaining math ops is slightly more verbose than chaining SDVariable methods:

sd.random — Random Number Generators

The random namespace creates variables whose underlying arrays are filled with random values on each forward pass. These are useful for noise injection, dropout masks, or random initialisation inside the graph.

Fixed-shape random variables

Dynamic-shape random variables

When the shape depends on another variable in the graph (e.g. because the batch size is variable), pass an integer SDVariable as the shape:

The shape variable must have an integer data type.

sd.nn — Neural Network Layers and Activations

The nn namespace covers operations commonly used in general neural networks that are not specific to convolutional or recurrent architectures.

Dense layers

Activation functions

Regularisation

Padding

Full example: two-layer feedforward network

sd.cnn — Convolutional Neural Network Operations

The cnn namespace provides convolution, pooling, and related operations.

Convolution operations

Convolution layers are specified via configuration objects that bundle the many static hyperparameters (kernel size, stride, padding, dilation, data format, bias flag, etc.).

1D convolution:

2D convolution:

Input shape for NCHW format: [batch, channels_in, height, width]. Weight shape: [channels_out, channels_in, kH, kW].

3D convolution:

Depthwise and separable convolutions:

Deconvolution (transposed convolution)

Pooling

Upsampling

Local response normalisation

Full example: simple ConvNet block

sd.rnn — Recurrent Neural Network Operations

The rnn namespace provides modules for sequence modelling.

Simple Recurrent Units (SRU)

LSTM

GRU

All recurrent outputs are ARRAY-type and can be fed into subsequent operations.

sd.loss — Loss Functions

The loss namespace provides standard loss functions for training. Most loss functions share a common signature:

The String name is required (can be null for auto-naming). weights and LossReduce are optional.

Common loss functions

Reduction methods

The LossReduce enum controls how per-sample losses are aggregated over the minibatch:

LossReduce value

Formula

Result shape

NONE

Leave per-sample values as-is

[batchSize]

SUM

sum(weights * loss_i)

scalar

MEAN_BY_WEIGHT

sum(weights * loss_i) / sum(weights)

scalar

MEAN_BY_NONZERO_WEIGHT_COUNT

sum(weights * loss_i) / count(weights != 0)

scalar

When no weights are specified, MEAN_BY_WEIGHT and MEAN_BY_NONZERO_WEIGHT_COUNT are equivalent to plain mean.

Use MEAN_BY_NONZERO_WEIGHT_COUNT when you want to average only over "valid" samples marked with weight=1, ignoring padding positions marked with weight=0.

Weighted loss example

The Don'ts of Operations

A few patterns cause subtle bugs in SameDiff graphs. Avoid them:

Don't mix variables from different SameDiff instances

All variables used in a single op must belong to the same SameDiff.

Don't discard operation results

Every op call creates a new node in the graph. If you call an op without assigning the result to a variable, the node is created but nothing can reference it downstream. This is almost always a bug:

The correct pattern is always to assign the result to a new variable:

Don't redefine existing named variables

If you call sd.var("weights", ...) twice with the same name, you will either get an exception or silently reference the same underlying variable. Always use unique names:

Finding Operations in the Javadoc

The full operation reference is in the SameDiff javadoc. Navigate to:

  • org.nd4j.autodiff.samediff.SDVariable for instance methods.

  • org.nd4j.autodiff.samediff.ops.SDMath, SDRandom, SDNN, SDCNN, SDRNN, SDLoss for namespace ops.

IDE autocompletion is also effective: type sd.nn. and browse the suggestions.

Last updated

Was this helpful?