shapeinference

package
v0.1.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 13, 2026 License: Apache-2.0 Imports: 9 Imported by: 3 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package shapeinference calculates the shape resulting from operations and validates its inputs.

This can be useful for new backends to test and help plan for buffer space for temporary or output buffers, but otherwise has no real use for someone who only wants to use the `compute` package.

It defines a BinaryOp function for shape inference for the majority of binary functions, using the standard broadcasting rules.

The majority of the unary functions don't change the shape, except those that explicitly say that in their name, like Reshape, etc.

For the remainder ops, it defines one function per OpType.

## Dynamic Shapes

This package supports "dynamic shapes" where one or more dimensions of a tensor are unknown at graph build time. These dimensions are represented by the shapes.DynamicDim sentinel value (-1).

When dynamic shapes are involved, shape inference follows these principles:

  • **Validation Deferral:** Many validation checks that depend on concrete dimension sizes (like checking if a reshape is valid, or if slice indices are within bounds) are deferred. These checks are typically performed by the backend during "shape specialization" once the concrete shapes are known.
  • **Propagation:** Symbolic dimensions propagate through operations. For example, in a BinaryOp, if one operand has a dynamic dimension and the other has a matching static dimension or is also dynamic, the output dimension will be dynamic.
  • **Broadcasting:** During BinaryOp or BroadcastInDim, a dimension of 1 is considered compatible with a shapes.DynamicDim and will be broadcast to it.
  • **Axis Names:** Axis names are used to track and validate symbolic axes across operations. If multiple operands have named axes, shapes.UnifyAxisNames is used to ensure they match and to propagate them to the output.

Index

Constants

This section is empty.

Variables

View Source
var (
	// BooleanOperations take booleans as input, aka. logical operations.
	BooleanOperations = sets.MakeWith(
		compute.OpTypeLogicalAnd,
		compute.OpTypeLogicalOr,
		compute.OpTypeLogicalXor,
		compute.OpTypeLogicalNot,
	)

	// BitwiseOperations operates only on integer (binary) numbers and won't work on floats or complex numbers.
	BitwiseOperations = sets.MakeWith(
		compute.OpTypeBitwiseAnd,
		compute.OpTypeBitwiseOr,
		compute.OpTypeBitwiseXor,
		compute.OpTypeBitwiseNot,
		compute.OpTypeBitCount,
		compute.OpTypeShiftLeft,
		compute.OpTypeShiftRightArithmetic,
		compute.OpTypeShiftRightLogical,
		compute.OpTypeBitCount,
		compute.OpTypeClz,
	)

	// NumberOperations can take any type of number as input: integers, floats, or complex numbers.
	NumberOperations = sets.MakeWith(
		compute.OpTypeAdd,
		compute.OpTypeSub,
		compute.OpTypeMul,
		compute.OpTypeDiv,
		compute.OpTypePow,
		compute.OpTypeRem,

		compute.OpTypeAbs,
		compute.OpTypeSign,

		compute.OpTypeEqual,
		compute.OpTypeNotEqual,
		compute.OpTypeGreaterOrEqual,
		compute.OpTypeGreaterThan,
		compute.OpTypeLessOrEqual,
		compute.OpTypeLessThan,

		compute.OpTypeEqualTotalOrder,
		compute.OpTypeGreaterOrEqualTotalOrder,
		compute.OpTypeGreaterThanTotalOrder,
		compute.OpTypeLessOrEqualTotalOrder,
		compute.OpTypeLessThanTotalOrder,
	)

	SignedNumberOperations = sets.MakeWith(
		compute.OpTypeNeg,
	)

	// FloatOperations operates only on float (and not on complex numbers).
	FloatOperations = sets.MakeWith(
		compute.OpTypeErf,
		compute.OpTypeLogistic,
		compute.OpTypeCos,
		compute.OpTypeSin,
		compute.OpTypeTanh,
	)

	// FloatOrComplexOperations operates only on float or complex numbers and won't work on integer or boolean values.
	FloatOrComplexOperations = sets.MakeWith(
		compute.OpTypeExp,
		compute.OpTypeExpm1,
		compute.OpTypeLog,
		compute.OpTypeLog1p,
		compute.OpTypeCeil,
		compute.OpTypeFloor,
		compute.OpTypeRound,
		compute.OpTypeRsqrt,
		compute.OpTypeSqrt,
		compute.OpTypeIsFinite,
	)

	// ComplexOperations operates only on complex numbers.
	ComplexOperations = sets.MakeWith(
		compute.OpTypeImag,
		compute.OpTypeReal,
		compute.OpTypeConj,
	)

	// StandardBinaryOperations include all operations that have two operands usually named lhs (left-hand-side) and
	// rhs (right-hand-side) and are usually commutative (invariant to order).
	//
	// Implicit broadcasting rules apply to them.
	StandardBinaryOperations = sets.MakeWith(
		compute.OpTypeAdd,
		compute.OpTypeSub,
		compute.OpTypeMul,
		compute.OpTypeDiv,
		compute.OpTypePow,
		compute.OpTypeAtan2,
		compute.OpTypeRem,
		compute.OpTypeBitwiseAnd,
		compute.OpTypeBitwiseOr,
		compute.OpTypeBitwiseXor,
		compute.OpTypeLogicalAnd,
		compute.OpTypeLogicalOr,
		compute.OpTypeLogicalXor,
		compute.OpTypeMax,
		compute.OpTypeMin,
		compute.OpTypeShiftLeft,
		compute.OpTypeShiftRightArithmetic,
		compute.OpTypeShiftRightLogical,
	)

	// AllBinaryOperations include all operations that have two operands and follow the standard implicit broadcasting rules,
	// and the operation is element-wise (output_i dependes only on lhs_i and rhs_i)
	AllBinaryOperations = sets.Union(StandardBinaryOperations, ComparisonOperations)

	// ComparisonOperations include all operations that take two inputs and returns booleans with the results of
	// a comparison.
	//
	// Implicit broadcasting rules apply to them.
	ComparisonOperations = sets.MakeWith(
		compute.OpTypeEqual,
		compute.OpTypeNotEqual,
		compute.OpTypeEqualTotalOrder,
		compute.OpTypeGreaterOrEqual,
		compute.OpTypeGreaterOrEqualTotalOrder,
		compute.OpTypeGreaterThan,
		compute.OpTypeGreaterThanTotalOrder,
		compute.OpTypeLessOrEqual,
		compute.OpTypeLessOrEqualTotalOrder,
		compute.OpTypeLessThan,
		compute.OpTypeLessThanTotalOrder,
	)

	// StandardUnaryOperations include all operations that have a single operand as input, and the return shape is the
	// same as the input (so no reductions).
	//
	// Plus, only operations that are element-wise (output_i dependes only on input_i) are included.
	StandardUnaryOperations = sets.MakeWith(
		compute.OpTypeLogicalNot,
		compute.OpTypeBitwiseNot,
		compute.OpTypeBitCount,
		compute.OpTypeClz,
		compute.OpTypeErf,
		compute.OpTypeExp,
		compute.OpTypeExpm1,
		compute.OpTypeLog,
		compute.OpTypeLog1p,
		compute.OpTypeLogistic,
		compute.OpTypeCeil,
		compute.OpTypeFloor,
		compute.OpTypeRound,
		compute.OpTypeRsqrt,
		compute.OpTypeSqrt,
		compute.OpTypeImag,
		compute.OpTypeReal,
		compute.OpTypeConj,
		compute.OpTypeCos,
		compute.OpTypeSin,
		compute.OpTypeTanh,
		compute.OpTypeAbs,
		compute.OpTypeNeg,
		compute.OpTypeSign,
	)
)

Functions

func ArgMinMax

func ArgMinMax(operand shapes.Shape, axis int, outputDType dtypes.DType) (output shapes.Shape, err error)

ArgMinMax calculates the output shape for an ArgMinMax operation. It will be the shape of the operand minus the "reduce" axis.

func BinaryOp

func BinaryOp(opType compute.OpType, lhsShape, rhsShape shapes.Shape) (output shapes.Shape, err error)

BinaryOp returns the expected output shape for ops in the StandardBinaryOperations set -- those include all operations that have two operands usually named lhs (left-hand-side) and rhs (right-hand-side), and they are usually commutative (invariant to order).

It returns an error if the data type (shape.DType) is invalid for the operation -- e.g.: non-matching dtypes, or LogicalAnd not having booleans (dtype.Bool) as input.

func Bitcast

func Bitcast(operand shapes.Shape, targetDType dtypes.DType) (output shapes.Shape, err error)

Bitcast calculates the output shape for a Bitcast operation.

func BroadcastInDim

func BroadcastInDim(operand, outputShape shapes.Shape, broadcastAxes []int,
	knownDynamicAxisNames sets.Set[string]) error

BroadcastInDim verifies that the arguments are valid.

The output shape is the same as the input is already known, so nothing is returned.

Dynamic shapes: When broadcasting, an operand axis with a dynamic length cannot be broadcast and must be preserved as dynamic in the output -- their axis names must exactly match in the outputShape. But new dynamic dimensions can be introduced in the output -- either mapping from an axis with dimension 1, or from a newly introduced axis. Notice that introducing new dynamic axis names that are not resolved by any input parameter will result in an error.

func ComparisonOp

func ComparisonOp(opType compute.OpType, lhsShape, rhsShape shapes.Shape) (output shapes.Shape, err error)

ComparisonOp returns the broadcast shape with dtype set to Bool, for comparison operations (Equal, LessThan, GreaterOrEqual, etc.)

func Concatenate

func Concatenate(inputs []shapes.Shape, axis int) (output shapes.Shape, err error)

Concatenate calculates the output shape of a Concatenate operation. It takes a slice of input shapes and the dimension along which to concatenate.

func ConvGeneral

func ConvGeneral(input, kernel shapes.Shape, axes compute.ConvolveAxesConfig,
	strides []int, paddings [][2]int,
	inputDilations, kernelDilations []int,
	channelGroupCount, batchGroupCount int) (shapes.Shape, error)

ConvGeneral returns the expected output shape for the ConvGeneral operation.

func CumSum added in v0.1.5

func CumSum(operand shapes.Shape, axis int) (output shapes.Shape, err error)

CumSum returns the output shape for a CumSum operation.

func DotGeneral

func DotGeneral(
	lhs shapes.Shape, lhsContractingAxes, lhsBatchAxes []int,
	rhs shapes.Shape, rhsContractingAxes, rhsBatchAxes []int,
	config compute.DotGeneralConfig) (shapes.Shape, error)

DotGeneral returns the output shape of a DotGeneral operation given the shapes of the inputs and the axes to contract and batch over.

The resulting shape is [batchIndices..., <lhs cross indices...>, <rhs cross indices...>], the indices come in the order they were provided. The output dtype is by default the same as the input dtype unless config.OutputDType is set.

func DynamicBroadcastInDim added in v0.1.5

func DynamicBroadcastInDim(operand shapes.Shape, broadcastAxes []int, specs []compute.DynamicDimensionSpec, knownDynamicAxisNames sets.Set[string]) (output shapes.Shape, err error)

DynamicBroadcastInDim calculates the output shape resulting from a DynamicBroadcastInDim operation.

DynamicDimensionSpec must be one of:

  • Static: `Static >= 0`, `Name == ""`, `Value == nil`.
  • Dynamic with Value: `Name != ""`, `Value != nil`, `Static == 0`.
  • Dynamic known axis: `Name != ""`, `Value == nil`, `Static == 0` (must match an operand dynamic axis name or known dynamic axis name).

func DynamicIota added in v0.1.5

func DynamicIota(dtype dtypes.DType, iotaAxis int, specs []compute.DynamicDimensionSpec, knownDynamicAxisNames sets.Set[string]) (output shapes.Shape, err error)

DynamicIota calculates the output shape resulting from a DynamicIota operation.

DynamicDimensionSpec must be one of:

  • Static: `Static >= 0`, `Name == ""`, `Value == nil`.
  • Dynamic: `Name != ""`, `Value != nil`, `Static == 0`.
  • Dynamic known axis: `Name != ""`, `Value == nil`, `Static == 0` (known dynamic axis name).

func DynamicPad added in v0.1.5

func DynamicPad(operand shapes.Shape, axesConfig ...compute.DynamicPadAxis) (output shapes.Shape, err error)

DynamicPad calculates the output shape resulting from a DynamicPad operation.

func DynamicReshape added in v0.1.1

func DynamicReshape(operand shapes.Shape, specs []compute.DynamicDimensionSpec) (output shapes.Shape, err error)

DynamicReshape calculates the output shape resulting from a DynamicReshape operation.

DynamicDimensionSpec must be one of:

  • Static: `Static >= 0`, `Name == ""`, `Value == nil`.
  • Dynamic: `Name != ""`, `Value != nil`, `Static == 0`.
  • Inferred: `Name != ""`, `Value == nil`, `Static == 0` (at most one inferred dimension).

Static dimensions cannot be negative (e.g. -1 is invalid for Static).

func DynamicSlice

func DynamicSlice(operand shapes.Shape, sliceSizes []int) (output shapes.Shape, err error)

DynamicSlice calculates the output shape for a DynamicSlice operation.

func DynamicUpdateSlice

func DynamicUpdateSlice(operand, update shapes.Shape) (output shapes.Shape, err error)

DynamicUpdateSlice calculates the output shape for a DynamicUpdateSlice operation.

func FusedActivation added in v0.1.9

func FusedActivation(x shapes.Shape, cfg compute.ActivationConfig) (shapes.Shape, error)

FusedActivation returns the output shape resulting from a FusedActivation operation.

For all standard activations, the output shape is identical to the input shape x. For ActivationSwiGLU, the rank must be >= 1, the last dimension must be even (if static), and the output shape has its last dimension halved: [..., lastDim/2].

func FusedActivationVJP added in v0.1.9

func FusedActivationVJP(y, x, dOutput shapes.Shape, cfg compute.ActivationConfig) (shapes.Shape, error)

FusedActivationVJP returns the output shape (dx) of a FusedActivationVJP operation.

Parameters:

  • y: output of the activation (can be invalid/empty if not provided).
  • x: input to the activation (can be invalid/empty if not provided and not required).
  • dOutput: incoming adjoint gradient (must be valid).
  • cfg: activation configuration.

For SwiGLU, x is required, and the output dx has the same shape as x (double the last dimension of dOutput). For other activations, dx has the same shape as x (if provided) or dOutput / y.

func FusedDense added in v0.1.9

func FusedDense(x, weight, bias shapes.Shape, options compute.DenseConfig) (shapes.Shape, error)

FusedDense returns the output shape of a FusedDense operation.

Inputs:

  • x: [batch..., in_features]
  • weight: [in_features, out_features...] (if WeightLayout is DenseLayoutInputOutputs) or [out_features..., in_features] (if WeightLayout is DenseLayoutOutputsInput)
  • bias: [out_features...] (optional, shapes.Invalid() if unused).
  • options: configuration including activation and weight layout.

Output shape: [batch..., out_features...]

func FusedDenseVJP added in v0.1.9

func FusedDenseVJP(x, weight, bias, y, dOutput shapes.Shape, options compute.DenseConfig) (dx, dWeight, dBias shapes.Shape, err error)

FusedDenseVJP returns the output shapes of the gradients (dx, dWeight, dBias) for a FusedDense operation.

Inputs:

  • x: original input tensor shape [batch..., in_features].
  • weight: weight tensor shape.
  • bias: bias tensor shape (can be invalid if no bias was used).
  • y: output tensor shape of the forward FusedDense.
  • dOutput: incoming adjoint gradient shape with respect to y.
  • options: configuration passed to the forward FusedDense call.

Returns:

  • dx: gradient with respect to x (same shape as x).
  • dWeight: gradient with respect to weight (same shape as weight).
  • dBias: gradient with respect to bias (same shape as bias, or shapes.Invalid() if bias was unused).

Note: FusedDenseVJP only works for activations where ActivationType.VJPRequiresInput() is false. If the activation requires input (e.g. GELU, SiLU), FusedDense without activation followed by FusedActivation should be used instead.

func Gather

func Gather(operand, startIndices shapes.Shape, indexVectorAxis int, offsetOutputAxes, collapsedSliceAxes,
	startIndexMap, sliceSizes []int, indicesAreSorted bool) (output shapes.Shape, err error)

Gather returns the output shape of a Gather operation.

func Pad

func Pad(operand shapes.Shape, axesConfig ...compute.PadAxis) (output shapes.Shape, err error)

Pad returns the expected output shape for the Pad operation.

func Reduce

func Reduce(operand shapes.Shape, axes []int) (output shapes.Shape, err error)

Reduce works for the ReduceMax, ReduceMin, ReduceSum and ReduceProduct ops.

func ReduceWindow

func ReduceWindow(operand shapes.Shape, windowDimensions, strides, baseDilations, windowDilations []int, paddings [][2]int) (shapes.Shape, error)

ReduceWindow returns the expected output shape for the operation.

Notice it doesn't take as input the reductionType parameter, since it doesn't affect the output shape.

func Reshape

func Reshape(operand shapes.Shape, dims []int) (output shapes.Shape, err error)

Reshape to the given dimensions: trivial output shape, but this function also checks that the sizes are the same.

This operation only supports concrete (static) shapes. For dynamic shapes, use DynamicReshape.

func Scatter

func Scatter(operand, indices, updates shapes.Shape, indexVectorAxis int, updateWindowAxes, insertedWindowAxes, scatterAxesToOperandAxes []int) (output shapes.Shape, err error)

Scatter checks that the parameters are consistent. The output shape returned is the unchanged operand -- the scattered updates are applied to the operand, but its shape is unchanged.

The Scatter operations indicesAreSorted and uniqueIndices don't play a role in this.

func SelectAndScatter added in v0.1.3

func SelectAndScatter(operand, source shapes.Shape, windowDimensions, windowStrides []int, paddings [][2]int) (shapes.Shape, error)

SelectAndScatter returns the expected output shape for SelectAndScatter operations (SelectAndScatterMax and SelectAndScatterMin). The output shape is equal to the operand shape.

func Slice

func Slice(operand shapes.Shape, starts, limits, strides []int) (output shapes.Shape, err error)

Slice calculates the output shape for a Slice operation. It checks that starts, limits, and strides have the correct length (matching operand rank), and that the slice parameters are valid for the operand's dimensions. Strides must be positive.

func Transpose

func Transpose(operand shapes.Shape, permutations []int) (output shapes.Shape, err error)

Transpose all axes of the operand. There must be one value in permutations for each axis in the operand. The output will have: output.Shape.Dimension[ii] = operand.Shape.Dimension[permutations[i]].

func UnaryOp

func UnaryOp(opType compute.OpType, operand shapes.Shape) (output shapes.Shape, err error)

UnaryOp checks the validity of the data type for StandardUnaryOperations and returns either an error or the output shape, which is the same as the operand.

func Where

func Where(condition, onTrue, onFalse shapes.Shape) (output shapes.Shape, err error)

Where returns the shape resulting from the Where operation.

Shape constraints for the operation:

  1. The onTrue and onFalse must have the exact same dtype.
  2. The onTrue and onFalse must have the exact same shape, or one can be a scalar.
  3. The condition must either be a scalar or match the shape of onTrue or onFalse, except for the DType that must be Bool.

Note: If you need to select between values of different dtypes, use ConvertDType to convert them Where returns the shape resulting from the Where operation.

The condition must be of boolean dtype. The onTrue and onFalse must have the same dtype.

Standard implicit broadcasting rules apply across all three operands:

  • Scalar operands are implicitly broadcast to the shape of the other operands.
  • Non-scalar operands must have the same rank, and for each axis, their dimensions must either match or be 1. Dimension 1 is broadcast to the larger dimension.
  • The resulting shape has dimension max(dim_condition, dim_onTrue, dim_onFalse) on each axis, and the dtype of onTrue/onFalse.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL