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 CumMax(operand shapes.Shape, axis int) (output shapes.Shape, err error)
- func CumSum(operand shapes.Shape, axis int) (output shapes.Shape, err error)
- func DeriveGGMLK(opName string, bytesPerRow int, ggmlType compute.GGMLQuantType) (int, error)
- func DotGeneral(lhs shapes.Shape, lhsContractingAxes, lhsBatchAxes []int, rhs shapes.Shape, ...) (shapes.Shape, error)
- func DynamicBroadcastInDim(operand shapes.Shape, broadcastAxes []int, ...) (output shapes.Shape, err error)
- func DynamicIota(dtype dtypes.DType, iotaAxis int, specs []compute.DynamicDimensionSpec, ...) (output shapes.Shape, err error)
- func DynamicPad(operand shapes.Shape, axesConfig ...compute.DynamicPadAxis) (output shapes.Shape, err 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 FusedActivation(x shapes.Shape, cfg compute.ActivationConfig) (shapes.Shape, error)
- func FusedActivationVJP(y, x, dOutput shapes.Shape, cfg compute.ActivationConfig) (shapes.Shape, error)
- func FusedDense(x, weight, bias shapes.Shape, options compute.DenseConfig) (shapes.Shape, error)
- func FusedDenseVJP(x, weight, bias, y, dOutput shapes.Shape, options compute.DenseConfig) (dx, dWeight, dBias shapes.Shape, err error)
- func FusedQuantizedDense(x, weight, bias shapes.Shape, options QuantizedDenseConfigShapes) (shapes.Shape, error)
- func FusedQuantizedDenseVJP(x, weight, bias, y, dOutput shapes.Shape, options QuantizedDenseConfigShapes) (dx, dBias shapes.Shape, err error)
- func FusedRoPE(xShape, cosShape, sinShape shapes.Shape, config compute.FusedRoPEConfig) (shapes.Shape, error)
- func FusedTopK(operand shapes.Shape, k int, cfg compute.FusedTopKConfig) (values, indices shapes.Shape, err error)
- func Gather(operand, startIndices shapes.Shape, indexVectorAxis int, ...) (output shapes.Shape, err error)
- func NonZero(operand shapes.Shape, cfg compute.NonZeroConfig) (shapes.Shape, error)
- func Pad(operand shapes.Shape, axesConfig ...compute.PadAxis) (output shapes.Shape, err error)
- func QuantizedGather(x, indices shapes.Shape, xQuantization *QuantizationShapes) (shapes.Shape, error)
- func RNGBitGenerator(expectedStateShape, stateShape, targetShape shapes.Shape) (newStateShape, valuesShape 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 SelectAndScatter(operand, source shapes.Shape, windowDimensions, windowStrides []int, ...) (shapes.Shape, 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)
- type ActivationParamKind
- type ActivationParamLayout
- type BlockParamLayout
- type QuantizationShapes
- type QuantizedDenseConfigShapes
- type QuantizedDenseInfo
- type QuantizedGatherInfo
Examples ¶
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 DeriveGGMLK ¶ added in v0.1.29
DeriveGGMLK validates a GGMLQuantType and derives the logical element count K from bytesPerRow.
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.
For each axis i in axesConfig:
- If any of StartValue, EndValue, or InteriorValue is non-nil, or if the operand dimension at axis i is already dynamic (shapes.DynamicDim), the output dimension at axis i is shapes.DynamicDim.
- Otherwise, the output dimension is calculated statically: interiorPadding = max(0, operand.Dimensions[i] - 1) * config.Interior output.Dimensions[i] = operand.Dimensions[i] + config.Start + config.End + interiorPadding
Start and End (and StartValue, EndValue) can be negative to truncate/crop elements along that axis (applied after interior padding), as long as the resulting dimension is >= 0. Interior (and InteriorValue) must be non-negative (>= 0).
Examples:
// Static negative padding (cropping) on axis 0 and dynamic padding on axis 1:
operand := shapes.Make(dtypes.Float32, 5, 4)
out, err := shapeinference.DynamicPad(operand,
compute.DynamicPadAxis{Start: -1, End: -1},
compute.DynamicPadAxis{StartValue: dynStart, End: 1, TargetAxisName: "width"},
)
// out has shape (Float32)[3, width=?]
// Combined interior padding and negative edge padding (cropping):
operand2 := shapes.Make(dtypes.Float32, 3)
out2, err := shapeinference.DynamicPad(operand2,
compute.DynamicPadAxis{Start: -1, End: -1, Interior: 1},
)
// Interior adds (3-1)*1 = 2 elements (size 5), then Start=-1, End=-1 crops 2 elements -> (Float32)[3]
Example ¶
operand := shapes.MakeDynamic(dtypes.Float32, []int{shapes.DynamicDim, 5, 3}, []string{"batch", "", ""})
out1, _ := DynamicPad(operand,
compute.DynamicPadAxis{Start: 0, End: 0}, // preserves dynamic "batch"
compute.DynamicPadAxis{Start: -1, End: -1}, // crops axis 1 from 5 to 3
compute.DynamicPadAxis{Start: -1, End: -1, Interior: 1}, // interior: 3 + 2 = 5, crop: 5 - 2 = 3
)
fmt.Println(out1)
Output: (Float32)[batch=?, 3, 3]
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 FusedActivation ¶ added in v0.1.9
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
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 FusedQuantizedDense ¶ added in v0.1.29
func FusedQuantizedDense(x, weight, bias shapes.Shape, options QuantizedDenseConfigShapes) (shapes.Shape, error)
FusedQuantizedDense validates inputs and returns the output shape of FusedQuantizedDense.
func FusedQuantizedDenseVJP ¶ added in v0.1.29
func FusedQuantizedDenseVJP(x, weight, bias, y, dOutput shapes.Shape, options QuantizedDenseConfigShapes) (dx, dBias shapes.Shape, err error)
FusedQuantizedDenseVJP validates inputs and returns the gradient shapes (dx, dBias) for FusedQuantizedDenseVJP.
Memory-saving nil inputs:
- x may be shapes.Invalid() when !options.Activation.Type.VJPRequiresInput(); dx's batch dimensions and float DType are then inferred from dOutput.
- y may be shapes.Invalid() when options.Activation.Type == compute.ActivationNone.
func FusedRoPE ¶ added in v0.1.37
func FusedRoPE(xShape, cosShape, sinShape shapes.Shape, config compute.FusedRoPEConfig) (shapes.Shape, error)
FusedRoPE validates inputs and infers the output shape of FusedRoPE.
Supported cos/sin shapes (with last axis rotaryHalfDim > 0):
- 2D: [seqLen, rotaryHalfDim] (broadcast across all non-seq, non-feature axes)
- (seqAxis+2)D: [b_0, ..., b_{seqAxis-1}, seqLen, rotaryHalfDim] (batched positions)
- Full rank (x.Rank()): [d_0, ..., d_{rank-2}, rotaryHalfDim] (size-1 broadcast axes allowed)
Output shape is identical to xShape.
func FusedTopK ¶ added in v0.1.29
func FusedTopK(operand shapes.Shape, k int, cfg compute.FusedTopKConfig) (values, indices shapes.Shape, err error)
FusedTopK returns the output shapes for selecting k values along cfg.Axis. The selected axis becomes size k; all other dimensions and their names are preserved. Indices are returned as Int32.
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 NonZero ¶ added in v0.1.29
NonZero returns the output shape for NonZero. The output contains one row per nonzero input element and one column per input axis. If cfg.Transpose is set, the output axes are reversed. The nonzero count axis is data-dependent.
func Pad ¶
Pad returns the expected output shape for the Pad operation.
There must be at most `operand.Rank()` axesConfig values; missing trailing axes default to zero padding. For each configured axis i:
- `config.Interior` must be non-negative (`>= 0`).
- `config.Start` and `config.End` can be positive, zero, or negative (negative values truncate/crop the axis).
- The output dimension is `dim + max(dim-1, 0)*config.Interior + config.Start + config.End`, which must be `>= 0`.
Examples:
- `Pad(shapes.Make(F32, 3), PadAxis{Start: 1, End: 2})` -> `(Float32)[6]`
- `Pad(shapes.Make(F32, 3), PadAxis{Start: -1, End: -1})` -> `(Float32)[1]`
- `Pad(shapes.Make(F32, 3), PadAxis{Start: -1, End: -1, Interior: 1})` -> `(Float32)[3]`
Example ¶
// Positive start, end, and interior padding on a 2D shape:
s1, _ := Pad(
shapes.Make(dtypes.Float32, 2, 3),
PadAxis{Start: 1, End: 1},
PadAxis{Start: 0, End: 2, Interior: 1},
)
fmt.Println("Positive and interior:", s1)
// Negative Start/End truncating (cropping) axes, with and without interior padding:
s2, _ := Pad(
shapes.Make(dtypes.Float32, 5, 3),
PadAxis{Start: -1, End: -2}, // 5 - 1 - 2 = 2
PadAxis{Start: -1, End: -1, Interior: 1}, // 3 + (3-1)*1 - 1 - 1 = 3
)
fmt.Println("Negative start/end:", s2)
Output: Positive and interior: (Float32)[4, 7] Negative start/end: (Float32)[2, 3]
func QuantizedGather ¶ added in v0.1.31
func QuantizedGather(x, indices shapes.Shape, xQuantization *QuantizationShapes) (shapes.Shape, error)
QuantizedGather validates inputs and returns the output shape of QuantizedGather.
func RNGBitGenerator ¶ added in v0.1.32
func RNGBitGenerator(expectedStateShape, stateShape, targetShape shapes.Shape) (newStateShape, valuesShape shapes.Shape, err error)
RNGBitGenerator validates the state and target output shapes for an RNGBitGenerator operation and returns the expected (newStateShape, valuesShape).
targetShape must have an unsigned integer bit dtype (Uint8, Uint16, Uint32, or Uint64).
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 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 ¶
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 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 ¶
type ActivationParamKind ¶ added in v0.1.29
type ActivationParamKind uint8
ActivationParamKind classifies how a Scale or ZeroPoint broadcasts over a flattened [M, F] activation/output tensor.
const ( ActParamNone ActivationParamKind = iota ActParamPerTensor ActParamPerColBlock ActParamPerRow ActParamPerRowColBlock )
type ActivationParamLayout ¶ added in v0.1.29
type ActivationParamLayout struct {
Kind ActivationParamKind
ColBlockSize int
NumColBlocks int
}
ActivationParamLayout describes how a Scale or ZeroPoint maps (row m, feature col) on [M, F] (including when M comes from dynamic leading dimensions).
func (ActivationParamLayout) Index ¶ added in v0.1.29
func (l ActivationParamLayout) Index(m, col int) int
Index returns the flat parameter index for (m, col) in [M, F].
func (ActivationParamLayout) Present ¶ added in v0.1.29
func (l ActivationParamLayout) Present() bool
Present reports whether the parameter tensor was provided.
type BlockParamLayout ¶ added in v0.1.29
BlockParamLayout describes how a 2D weight tensor [D0, D1] maps (row, col) coordinates into a flat Scale or ZeroPoint slice:
idx(row, col) = (row / RowBlockSize) * NumColBlocks + (col / ColBlockSize)
func (BlockParamLayout) Index ¶ added in v0.1.29
func (l BlockParamLayout) Index(row, col int) int
Index returns the flat parameter index for (row, col) in [D0, D1].
type QuantizationShapes ¶ added in v0.1.29
type QuantizationShapes struct {
Scheme compute.QuantizationScheme
Scale shapes.Shape // shapes.Invalid() if Scale == nil
ZeroPoint shapes.Shape // shapes.Invalid() if ZeroPoint == nil
BlockAxis int
BlockSize int
GGMLType compute.GGMLQuantType
QuantizedDType dtypes.DType
PackedDType dtypes.DType
}
QuantizationShapes is the shape-only counterpart of compute.Quantization for shape inference.
type QuantizedDenseConfigShapes ¶ added in v0.1.29
type QuantizedDenseConfigShapes struct {
WeightQuantization *QuantizationShapes
XQuantization *QuantizationShapes // nil when x is floating-point
OutputQuantization *QuantizationShapes // nil when output is floating-point
QuantizedMatmul bool
Activation compute.ActivationConfig
WeightLayout compute.DenseLayout
}
QuantizedDenseConfigShapes is the shape-only counterpart of compute.FusedQuantizedDenseConfig.
type QuantizedDenseInfo ¶ added in v0.1.29
type QuantizedDenseInfo struct {
OutputShape shapes.Shape
K int // Logical input-features (contracting) dimension
N int // Logical output-features dimension
FloatComputeDType dtypes.DType
WeightScaleLayout BlockParamLayout
WeightZeroPointLayout BlockParamLayout
XScaleLayout ActivationParamLayout
XZeroPointLayout ActivationParamLayout
OutputScaleLayout ActivationParamLayout
OutputZeroPointLayout ActivationParamLayout
}
QuantizedDenseInfo holds validated dimensions and resolved parameter block layouts for FusedQuantizedDense and FusedQuantizedDenseVJP.
func FusedQuantizedDenseWithInfo ¶ added in v0.1.29
func FusedQuantizedDenseWithInfo(x, weight, bias shapes.Shape, options QuantizedDenseConfigShapes) (QuantizedDenseInfo, error)
FusedQuantizedDenseWithInfo validates inputs and returns both the output shape and resolved layout metadata.
type QuantizedGatherInfo ¶ added in v0.1.31
type QuantizedGatherInfo struct {
OutputShape shapes.Shape
K int // Logical embedding dimension
ScaleLayout BlockParamLayout
ZeroPointLayout BlockParamLayout
}
QuantizedGatherInfo holds validated dimensions and resolved parameter block layouts for QuantizedGather.
func QuantizedGatherWithInfo ¶ added in v0.1.31
func QuantizedGatherWithInfo(x, indices shapes.Shape, xQuantization *QuantizationShapes) (QuantizedGatherInfo, error)
QuantizedGatherWithInfo validates inputs and returns both the output shape and resolved scale/zero-point layouts for QuantizedGather.