Skip to main content
torch.js has not been released yet.
torch.js logotorch.js logotorch.js
PlaygroundContact
Login
Documentation
IntroductionType SafetyTensor ExpressionsTensor IndexingEinsumEinopsAutogradTraining a ModelProfiling & MemoryPyTorch MigrationBest PracticesRuntimesPerformancePyTorch CompatibilityBenchmarksDType Coverage
choleskycholesky_excholesky_inversecholesky_solveCholeskyExOptionsCholeskyInverseOptionsCholeskyOptionsCholeskySolveOptionscondCondOptionscrossCrossOptionsdetdiagonalDiagonalOptionseigeighEighOptionseigvalseigvalshhouseholder_productinvinv_exInvExOptionsldl_factorldl_factor_exldl_solveLdlFactorExOptionsLdlFactorOptionsLdlSolveOptionslobpcgLobpcgOptionslogdetlstsqLstsqOptionslulu_factorlu_factor_exlu_solvelu_unpackLuFactorExOptionsLuFactorOptionsLuOptionsLuSolveOptionsLuUnpackOptionsmatrix_expmatrix_normmatrix_powermatrix_rankMatrixNormOptionsMatrixRankOptionsmulti_dotnormNormOptionspca_lowrankPcaLowrankOptionspinvPinvOptionsqrQrOptionsslogdetsolvesolve_exsolve_triangularSolveExOptionsSolveOptionsSolveTriangularOptionssvdsvd_lowrankSvdLowrankOptionsSvdOptionssvdvalstensorinvTensorinvOptionstensorsolveTensorsolveOptionstracetriangular_solveTriangularSolveOptionsvanderVanderOptionsvecdotVecdotOptionsvector_normVectorNormOptions
absacosacoshAdaptivePool1dShapeAdaptivePool2dShapeaddaddbmmAddbmmOptionsaddcdivAddcdivOptionsaddcmulAddcmulOptionsaddmmAddmmOptionsaddmvAddmvOptionsaddrAddrOptionsadjointallallcloseAllcloseOptionsAlphaBetaOptionsamaxaminaminmaxAminmaxOptionsangleanyapplyOutarangeare_deterministic_algorithms_enabledargmaxargminargsortargwhereas_stridedas_tensorasinasinhAssertNoShapeErrorAssertNotErrorAsStridedOptionsAtat_error_index_out_of_boundsatanatan2atanhatleast_1datleast_2datleast_3dAtShapeautocast_decrement_nestingautocast_increment_nestingautograd_gradient_mismatch_errorautograd_not_registered_errorAutogradConfigAutogradDeviceAutogradDTypeAutogradEntryAutogradHandleAutogradHandleImplAxesRecordBackwardFnbaddbmmBaddbmmOptionsbartlett_windowBaseKernelConfigbatch_dimensions_do_not_match_errorbernoulliBernoulliOptionsBinaryBackwardFnBinaryBroadcastResultBinaryDTypeBinaryKernelConfigCPUBinaryKernelCPUBinaryOpConfigBinaryOpNamesBinaryOpSchemaBinaryOptionsbincountBincountOptionsbitwise_andbitwise_left_shiftbitwise_notbitwise_orbitwise_right_shiftbitwise_xorblackman_windowblock_diagbmmBooleanDTypeRulebroadcast_error_incompatible_dimensionsbroadcast_shapesbroadcast_tensorsbroadcast_toBroadcastShapeBroadcastShapeRulebroadcastShapesbucketizeBucketizeOptionsBufferUsagebuildEinopsErrorbuildErrorMessagecanBroadcastTocartesian_prodcatCatOptionsCatShapeCauchyOptionscdistCdistOptionsceilceluCeluFunctionalOptionschain_matmulCheckShapeErrorCholeskyShapechunkchunk_error_dim_out_of_rangeChunkOptionsclampClampOptionsclear_autocast_cacheclearEinopsCacheclearEinsumCacheclonecolumn_stackcombinationsCombinationsOptionscompiled_with_cxx11_abicomplexconjconj_physicalcontiguousConv1dShapeConv2dShapeConv3dShapeConvTranspose2dShapecopysigncorrcoefcoscoshcount_nonzeroCountNonzeroOptionscovcoverage_reportcoverageReportCoverageReportCovOptionsCPUForwardFnCPUKernelConfigCPUKernelEntryCPUOnlyResultCPUTensorDatacreateCumExtremeResultcreateTorchCreationOpSchemaCumExtremeResultcummaxcummincumprodCumShapecumsumcumulative_trapezoidCumulativeOptionsCumulativeOptionsWithDimdeg2raddetachDeterministicOptionsDetShapeDevicedevice_error_requiresDeviceBufferDeviceCapabilitiesDeviceCheckedResultDeviceConfigDeviceContextDeviceEntryDeviceHandleDeviceInputDeviceOptionsDeviceRegistryDeviceTypediagdiag_embedDiagEmbedOptionsdiagflatDiagflatOptionsDiagFlatOptionsdiagonal_scatterDiagonalOptionsDiagonalScatterOptionsDiagOptionsDiagShapediffDiffOptionsdigammadimension_error_out_of_rangeDispatchConfigdistDistOptionsdivdotDotShapeRuleDoubleDoubleDimdropoutDropoutFunctionalOptionsdsplitdstackDTypedtype_already_registered_errordtype_components_mismatch_errordtype_not_found_errorDTypeComponentsDTypeConfigDTypeCoverageReportDTypeDisplayConfigDTypeEntryDTypeHandleDTypeHandleImplDTypeInfoDTypeRegistryDTypeRuleDTypeSerializationConfigDynamicShapeEigShapeeinops_error_ambiguous_decompositioneinops_error_anonymous_in_outputeinops_error_dimension_mismatcheinops_error_invalid_patterneinops_error_reduce_undefined_outputeinops_error_repeat_missing_sizeeinops_error_undefined_axiseinsumeinsum_error_dimension_mismatcheinsum_error_index_out_of_rangeeinsum_error_invalid_equationeinsum_error_invalid_sublist_elementeinsum_error_operand_count_mismatcheinsum_error_subscript_rank_mismatcheinsum_error_unknown_output_indexEinsumOptionsEinsumOutputShapeEllipsiseluelu_EluFunctionalOptionsembedding_bag_error_requires_2d_inputemptyempty_cacheempty_likeeqequalerferfcerfinvexpexp2expandexpand_asexpand_error_incompatibleExpandShapeexpm1ExponentialOptionseyeEyeOptionsfftFFTOptionsfindKernelWithPredicatefindSimilarPatternsflattenFlattenOptionsFlattenShapeflipflip_error_dim_out_of_rangefliplrFlipShapeflipudfloat_powerFloatDTypeRulefloorfloor_dividefmaxfminfmodformatEquationErrorformatShapefracfrexpfrombufferfullfull_likefunction_already_registered_errorFunctionConfigFunctionEntryFunctionHandlegathergather_error_dim_out_of_rangeGatherShapegcdgegeluGeometricOptionsget_autocast_cpu_dtypeget_autocast_gpu_dtypeget_autocast_ipu_dtypeget_autocast_xla_dtypeget_default_deviceget_default_dtypeget_deterministic_debug_modeget_device_configget_device_contextget_device_moduleget_dtype_infoget_file_pathget_float32_matmul_precisionget_num_interop_threadsget_num_threadsget_op_infoget_printoptionsget_real_dtypeget_rng_stategetAutogradgetDTypegetEinopsCacheSizegetEinsumCacheSizegetFunctiongetKernelgetMethodgetOpInfoGetOpKindGetOpSchemagetScalarKernelgluGluFunctionalOptionsGradContextGradFnGradientsForgtHalfHalfDimhamming_windowhann_windowhardshrinkhardsigmoidhardswishhardtanhhardtanh_HardtanhFunctionalOptionshas_autogradhas_devicehas_dtypehas_kernelhasAutogradhasDTypehasFunctionhasKernelhasMethodhasScalarKernelHasShapeErrorheavisidehistcHistcOptionshistogramHistogramOptionsHistogramResulthsplithstackhypoti0IdentityShapeifftimagindex_addindex_copyindex_fillindex_putindex_reduceindex_selectindex_select_error_dim_out_of_rangeIndexPutOptionsIndexSelectShapeIndexSpecIndicesOptionsIndicesSpecinitialize_deviceInputsForInsertDiminvalid_config_errorinverseInverseShapeirfftis_anomaly_check_nan_enabledis_anomaly_enabledis_autocast_cache_enabledis_autocast_cpu_enabledis_autocast_ipu_enabledis_autocast_xla_enabledis_complexis_complex_dtypeis_cpu_only_modeis_deterministic_algorithms_warn_only_enabledis_floating_pointis_floating_point_dtypeis_inference_mode_enabledis_nonzerois_tensoris_warn_always_enabledis_webgpu_availableIs2DIsAtLeast1DIsBinaryOpIsBinaryOpNameiscloseIscloseOptionsisfiniteisinisinfisnanisneginfisposinfisrealIsReductionOpIsReductionOpNameIsRegistryErrorIsShapeErroristftISTFTOptionsIsUnaryOpIsUnaryOpNameitem_error_not_scalarItemResultkaiser_windowKaiserWindowOptionskernel_not_registered_errorkernel_signature_mismatch_errorKernelConfigKernelConfigWebGPUKernelEntryKernelHandleKernelInfoKernelPredicateKernelRegistryKernelWebGPUkronkthvalueKthvalueOptionslcmldexpleleaky_reluleaky_relu_LeakyReluFunctionalOptionslerplevenshteinDistancelgammalinalg_error_not_square_matrixlinalg_error_requires_2dlinalg_error_requires_at_least_2dlinearlinspacelist_custom_deviceslist_custom_dtypeslist_deviceslist_dtypeslist_functionslist_kernelslist_methodslist_opslistCustomDTypeslistDTypeslistFunctionslistKernelsListKernelsOptionslistMethodslistOpsListOpsOptionsloglog_softmaxlog10log1plog2logaddexplogaddexp2logcumsumexplogical_andlogical_notlogical_orlogical_xorLogitOptionsLogNormalOptionsLogOptionslogsigmoidlogspacelogsumexpLogsumexpOptionsltLUShapeLuSolveOptionsmasked_fillmasked_selectmasked_select_asyncMaskSpecmatmulmatmul_error_inner_dimensions_do_not_matchMatmul2DShapeMatmulShapeMatmulShapeRuleMatrixTransposeShapemaxmaximummeanmedianmemory_statsmemory_summarymeshgridmethod_already_registered_errormethod_dtype_not_supported_errorMethodConfigMethodEntryMethodHandleminminimummishmmMMShapeRulemodemovedimmsortmulmultinomialmultinomial_asyncMultinomialAsyncOptionsMultinomialOptionsMultiplyBymvMVShapeRulenan_to_numnanmeannanmediannanquantileNanReductionOptionsnansumNanToNumOptionsnarrownarrow_copynarrow_error_length_exceeds_boundsnarrow_error_start_out_of_boundsNarrowShapeneneedsBroadcastnegNegativeDimnextafternonzeroNonzeroOptionsnormnormalNormalOptionsNormOptionsnumelonesones_likeop_kind_mismatch_errorop_not_found_errorOpCoverageEntryOpInfoOpKindOpNameOpSchemaOpSchemasouterOuterShapepackPackShapepermutepermute_error_dimension_count_mismatchPermuteShapepoissonpolarPool1dShapePool2dShapePool3dShapepositivepowpreluPrintOptionsprodprofiler_allow_cudagraph_cupti_lazy_reinit_cuda12promote_typesPromoteDTypeRulePutOptionsquantileQuantileOptionsrad2degrandrand_likerandintrandint_likeRandintLikeOptionsRandintOptionsrandnrandn_likeRandomLikeOptionsRandomOptionsrandpermRangeSpecRankravelrealrearrangeRearrangeOptionsRearrangeShapereciprocalreduceReduceOperationReduceOptionsReduceShapeReductionKernelConfigCPUReductionKernelCPUReductionOpNamesReductionOpSchemaReductionOptionsReductionShapeRuleregister_backwardregister_deviceregister_dtyperegister_forwardregister_functionregister_methodregister_scalar_forwardregisterAutogradRegisterBackwardOptionsregisterBinaryOpregisterDTypeRegisterDTypeOptionsRegisteredDTyperegisterFunctionRegisterFunctionOptionsregisterKernelRegisterKernelOptionsregisterMethodRegisterMethodOptionsregisterScalarKernelregisterUnaryOpregistration_failed_errorrelurelu_relu6ReluFunctionalOptionsremainderRemoveDimrepeatrepeat_interleaveRepeatInterleaveOptionsRepeatOptionsRepeatShapeReplaceDimrequireWebGPUreset_peak_memory_statsreshapeReshapeShaperesult_typerfftrollRollOptionsrot90Rot90Optionsroundrrelurrelu_RreluFunctionalOptionsrsqrtSafeExpandShapeSameDTypeRuleSameShapeRuleSaveForBackwardScalarCPUForwardFnScalarCPUKernelConfigScalarKernelEntryScalarKernelHandleScalarWebGPUKernelConfigScaleDimscatterscatter_addscatter_add_scatter_error_dim_out_of_rangescatter_reducescatter_reduce_ScatterReduceOptionsScatterShapesearchsortedSearchSortedOptionsselectselect_error_index_out_of_boundsselect_scatterSelectShapeseluset_default_deviceset_default_tensor_typeset_deterministic_debug_modeset_float32_matmul_precisionset_printoptionsset_warn_alwaysSetupContextFnShapeShapeCheckedResultShapedTensorShapeErrorMessageShapeOpSchemaShapeRulesigmoidsignsignbitsilusinsincsinhSizeOptionsslice_error_out_of_boundsslice_scatterSliceOptionsSliceScatterOptionsSliceShapeSliceSpecsoftmaxsoftmax_error_dim_out_of_rangeSoftmaxShapesoftminSoftminFunctionalOptionssoftplusSoftplusFunctionalOptionssoftshrinksoftsignsortSortOptionssplitsplit_error_dim_out_of_rangeSplitOptionssqrtsquaresqueezeSqueezeOptionsSqueezeShapestackStackOptionsStackShapestdstd_meanStdVarMeanOptionsStdVarOptionsstftSTFTOptionsStrideOptionssubSublistSublistElementSubscriptIndexsumSVDShapeswapaxessym_floatsym_intsym_notttaketake_along_dimTakeAlongDimOptionstantanhtanhshrinktensortensor_splitTensorCreatorTensorDatatensordotTensordotOptionsTensorLikeTensorMetaTensorOptionsTensorStoragethresholdthreshold_tileTileShapeToOptionstopkTopkOptionsTorchtraceTraceShapetransposetranspose_dims_error_out_of_rangetranspose_error_requires_2d_tensorTransposeDimsShapeTransposeDimsShapeCheckedTransposeShapetrapezoidTrapezoidOptionsTriangularOptionstriltril_indicesTriOptionsTripletriutriu_indicestrue_dividetruncTupleOfLengthTypedArrayTypedArrayForTypedStorageTypeOptionsUnaryBackwardFnUnaryDTypeUnaryKernelConfigCPUUnaryKernelCPUUnaryOpConfigUnaryOpFnUnaryOpNamesUnaryOpParamsUnaryOpSchemaUnaryOptionsunbindunbind_error_dim_out_of_rangeUnbindOptionsunflattenUniformOptionsuniqueunique_consecutiveUniqueConsecutiveOptionsUniqueOptionsunpackUnpackShapeunravel_indexunregister_deviceunsqueezeUnsqueezeOptionsUnsqueezeShapeuse_deterministic_algorithmsValidateBatchedSquareMatrixValidateChunkDimValidatedEinsumShapevalidateDeviceValidateDeviceValidatedRearrangeShapeValidatedReduceShapeValidatedRepeatShapevalidateDTypeValidateEinsumValidateOperandCountValidateRanksValidateScalarValidateSplitDimValidateSquareMatrixValidateUnbindDimValueOptionsvar_var_meanvdotviewview_as_complexview_as_realvmapvsplitvstackWebGPUKernelConfigWebGPUOnlyResultWebGPUTensorDatawhereWindowOptionsxlogyzeroszeros_like
torch.js· 2026
LegalTerms of UsePrivacy Policy
/
/
  1. docs
  2. torch.js
  3. torch
  4. linalg
  5. tensorinv

torch.linalg.tensorinv

function tensorinv<S extends Shape, D extends DType, Dev extends DeviceType>(A: Tensor<S, D, Dev>, options?: TensorinvOptions): Tensor<DynamicShape, D, Dev>function tensorinv<S extends Shape, D extends DType, Dev extends DeviceType>(A: Tensor<S, D, Dev>, ind: number, options?: TensorinvOptions): Tensor<DynamicShape, D, Dev>

Computes the multiplicative inverse of a tensor with respect to tensordot operation.

Computes the inverse of a tensor in the sense that if X = tensorinv(A, ind), then tensordot(A, X, dims=[[i for i in range(ind, A.ndim)], [0, ind)]) equals a reshaped identity matrix. This is useful for solving tensor equations and generalizes matrix inversion to higher-order tensors. Essential for:

  • Solving multi-linear systems and tensor equations
  • Inverting multi-linear transformations
  • Tensor decomposition and analysis
  • Higher-order generalizations of linear algebra

Core idea: The ind parameter splits the tensor shape into two parts: the first ind dimensions and the remaining dimensions. The tensor is reshaped into a matrix, inverted, and reshaped back with dimensions permuted. Requires the first ind dimensions to have the same product as the remaining dimensions for inversion to be possible.

How it works:

  1. Split tensor shape at index ind: shape = shape[:ind] + shape[ind:]
  2. Compute prod1 = product of first ind dimensions
  3. Compute prod2 = product of remaining dimensions
  4. Reshape to [prod1, prod2] matrix
  5. Compute matrix inverse
  6. Reshape result back to [shape[ind:] + shape[:ind]]

Requires: The two products must be equal (prod1 == prod2) for inversion to exist. The reshaped matrix must be invertible (full rank, non-singular).

tensorinv(A,ind)=reshape(A−1,[shape[ind:],shape[:ind]])where A−1 is computed from A reshaped to [prod(shape[:ind]),prod(shape[ind:])]\begin{aligned} \text{tensorinv}(A, \text{ind}) = \text{reshape}(A^{-1}, [\text{shape}[\text{ind}:], \text{shape}[:\text{ind}]]) \\ \text{where } A^{-1} \text{ is computed from } A \text{ reshaped to } [\text{prod}(\text{shape}[:\text{ind}]), \text{prod}(\text{shape}[\text{ind}:])] \end{aligned}tensorinv(A,ind)=reshape(A−1,[shape[ind:],shape[:ind]])where A−1 is computed from A reshaped to [prod(shape[:ind]),prod(shape[ind:])]​
  • Dimension permutation: Output shape has dimensions from shape[ind:] followed by shape[:ind]
  • Invertibility requirement: The reshaped matrix must be invertible (full rank, non-zero determinant)
  • Dimension product equality: prod(A.shape[:ind]) must equal prod(A.shape[ind:])
  • Index range: ind must satisfy 1 = ind A.ndim
  • Numerical stability: Uses standard matrix inversion (can be ill-conditioned for singular matrices)
  • Computational cost: O((prod1)³) where prod1 = product of first ind dimensions
  • Default ind: Common choice is ind=2 for 4D tensors representing bilinear forms
  • Dimension compatibility: Will throw if prod(shape[:ind]) ≠ prod(shape[ind:])
  • Matrix singularity: Will throw if reshaped matrix is singular (determinant = 0)
  • Numerical precision: Ill-conditioned matrices can produce inaccurate results
  • Memory: Creates temporary reshaped tensors; can be memory-intensive for large tensors

Parameters

ATensor<S, D, Dev>
The input tensor of shape [...]. Must have ndim = 2. The dimension products around the split point must be equal: prod(shape[:ind]) == prod(shape[ind:])
optionsTensorinvOptionsoptional

Returns

Tensor<DynamicShape, D, Dev>– The inverse tensor with shape [...]. Dimensions are permuted: original shape[:ind] becomes shape[ind:], and original shape[ind:] becomes shape[:ind]

Examples

// Simple 4D tensor: shape [2, 3, 2, 3]
// ind=2: first 2 dims multiply to 2*3=6, last 2 dims multiply to 2*3=6
const A = torch.randn([2, 3, 2, 3]);
const X = torch.linalg.tensorinv(A, 2);
console.log(X.shape);  // [2, 3, 2, 3] (same as input, dimensions rearranged internally)

// Verify inverse property (approximately, due to numerical precision)
// tensordot(A, X, [[2, 3], [0, 1]]) should be close to identity-like structure
// Solving a tensor equation: tensordot(A, X) = B
// If tensordot(A, X, dims) = B, then X = tensordot(B, tensorinv(A))
const A = torch.randn([3, 4, 3, 4]);  // Multi-linear operator
const B = torch.randn([3, 4, 5]);     // Right-hand side

// Compute inverse with ind=2 (first 2 dims vs last 2 dims)
const Ainv = torch.linalg.tensorinv(A, 2);
console.log(Ainv.shape);  // [3, 4, 3, 4] (dimensions rearranged)
// Different ind values split dimensions differently
const A = torch.randn([2, 3, 4, 5, 6]);  // ndim=5

// ind=1: split at 1 → [2] vs [3,4,5,6]
// prod1 = 2, prod2 = 3*4*5*6 = 360 (not equal, would fail)

// ind=2: split at 2 → [2,3] vs [4,5,6]
// prod1 = 6, prod2 = 120 (not equal, would fail)

// ind=3: split at 3 → [2,3,4] vs [5,6]
// prod1 = 24, prod2 = 30 (not equal, would fail)

// For this to work, need compatible dimensions
const A_compat = torch.randn([2, 3, 4, 2, 3, 4]);  // prod1=24, prod2=24
const X = torch.linalg.tensorinv(A_compat, 3);
console.log(X.shape);  // [2, 3, 4, 2, 3, 4] (same shape, dimensions rearranged)
// Shape transformation: dimensions are permuted
const A = torch.randn([2, 3, 2, 3]);
const X = torch.linalg.tensorinv(A, 2);

// Input shape: [2, 3, 2, 3]
// Split: [2, 3] vs [2, 3]
// Output shape: [2, 3, 2, 3] (rearranged, but same in this case)
// For A with shape [3, 4, 3, 4], output would be [3, 4, 3, 4]

See Also

  • PyTorch torch.linalg.tensorinv
  • torch.linalg.inv - Standard matrix inversion for 2D tensors
  • torch.linalg.tensorsolve - Solve tensor equations (uses tensorinv internally)
  • torch.tensordot - Tensor contraction operation (inverse defined w.r.t. this)
  • torch.linalg.matrix_power - Compute integer powers of matrices
Previous
svdvals
Next
TensorinvOptions