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 ¶
- Variables
- func ArgMinMax(operand shapes.Shape, axis int, outputDType dtypes.DType) (output shapes.Shape, err error)
- func BinaryOp(opType compute.OpType, lhsShape, rhsShape shapes.Shape) (output shapes.Shape, err error)
- func Bitcast(operand shapes.Shape, targetDType dtypes.DType) (output shapes.Shape, err error)
- func BroadcastInDim(operand, outputShape shapes.Shape, broadcastAxes []int, ...) error
- func ComparisonOp(opType compute.OpType, lhsShape, rhsShape shapes.Shape) (output shapes.Shape, err error)
- func Concatenate(inputs []shapes.Shape, axis int) (output shapes.Shape, err error)
- func ConvGeneral(input, kernel shapes.Shape, axes compute.ConvolveAxesConfig, strides []int, ...) (shapes.Shape, error)
- func DotGeneral(lhs shapes.Shape, lhsContractingAxes, lhsBatchAxes []int, rhs shapes.Shape, ...) (shapes.Shape, error)
- func DynamicReshape(operand shapes.Shape, specs []compute.DynamicDimensionSpec) (output shapes.Shape, err error)
- func DynamicSlice(operand shapes.Shape, sliceSizes []int) (output shapes.Shape, err error)
- func DynamicUpdateSlice(operand, update shapes.Shape) (output shapes.Shape, err error)
- func Gather(operand, startIndices shapes.Shape, indexVectorAxis int, ...) (output shapes.Shape, err error)
- func Pad(operand shapes.Shape, axesConfig ...compute.PadAxis) (output shapes.Shape, err error)
- func Reduce(operand shapes.Shape, axes []int) (output shapes.Shape, err error)
- func ReduceWindow(operand shapes.Shape, ...) (shapes.Shape, error)
- func Reshape(operand shapes.Shape, dims []int) (output shapes.Shape, err error)
- func Scatter(operand, indices, updates shapes.Shape, indexVectorAxis int, ...) (output shapes.Shape, err error)
- func Slice(operand shapes.Shape, starts, limits, strides []int) (output shapes.Shape, err error)
- func Transpose(operand shapes.Shape, permutations []int) (output shapes.Shape, err error)
- func UnaryOp(opType compute.OpType, operand shapes.Shape) (output shapes.Shape, err error)
- func Where(condition, onTrue, onFalse shapes.Shape) (output shapes.Shape, err error)
Constants ¶
This section is empty.
Variables ¶
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 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 ¶
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 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 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 ¶
DynamicSlice calculates the output shape for a DynamicSlice operation.
func DynamicUpdateSlice ¶
DynamicUpdateSlice calculates the output shape for a DynamicUpdateSlice operation.
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 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 ¶
Reshape to the given dimensions: trivial output shape, but this function also checks that the sizes are the same.
This version of reshape doesn't support reshaping dynamic dimensions (axes with shapes.DynamicDim). Any dynamic dimensions in the input must be matched by dynamic dimensions in the output, and their axis names are preserved. If new axes are created, the dynamic axis in the input x and dimensions are matched in order.
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 Slice ¶
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 ¶
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 ¶
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 ¶
Where returns the shape resulting from the Where operation.
Shape constraints for the operation:
- The onTrue and onFalse must have the exact same dtype.
- The onTrue and onFalse must have the exact same shape, or one can be a scalar.
- 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 to a common dtype before calling Where.
Types ¶
This section is empty.