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
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. ShapedTensor

torch.ShapedTensor

export interface ShapedTensor<S extends Shape = DynamicShape> {
  readonly shape: S;
  readonly dtype: string;
  readonly device: string;
  readonly requires_grad: boolean;

  // Shape-preserving unary operations
  neg(): ShapedTensor<S>;
  abs(): ShapedTensor<S>;
  exp(): ShapedTensor<S>;
  log(): ShapedTensor<S>;
  sqrt(): ShapedTensor<S>;
  relu(): ShapedTensor<S>;
  sigmoid(): ShapedTensor<S>;
  tanh(): ShapedTensor<S>;
  sin(): ShapedTensor<S>;
  cos(): ShapedTensor<S>;
  square(): ShapedTensor<S>;
  clone(): ShapedTensor<S>;

  // Scalar operations preserve shape
  add(scalar: number): ShapedTensor<S>;
  sub(scalar: number): ShapedTensor<S>;
  mul(scalar: number): ShapedTensor<S>;
  div(scalar: number): ShapedTensor<S>;
  pow(scalar: number): ShapedTensor<S>;

  // Tensor binary operations with broadcasting
  add<O extends Shape>(other: ShapedTensor<O>): ShapedTensor<BroadcastShape<S, O>>;
  sub<O extends Shape>(other: ShapedTensor<O>): ShapedTensor<BroadcastShape<S, O>>;
  mul<O extends Shape>(other: ShapedTensor<O>): ShapedTensor<BroadcastShape<S, O>>;
  div<O extends Shape>(other: ShapedTensor<O>): ShapedTensor<BroadcastShape<S, O>>;

  // Matrix operations
  matmul<O extends Shape>(other: ShapedTensor<O>): ShapedTensor<MatmulShape<S, O>>;
  mm<O extends Shape>(other: ShapedTensor<O>): ShapedTensor<Matmul2DShape<S, O>>;
  t(): ShapedTensor<TransposeShape<S>>;
  transpose<D0 extends number, D1 extends number>(
    dim0: D0,
    dim1: D1
  ): ShapedTensor<TransposeDimsShape<S, D0, D1>>;
  permute<P extends readonly number[]>(dims: P): ShapedTensor<PermuteShape<S, P>>;

  // Shape operations
  reshape<const T extends Shape>(...shape: T): ShapedTensor<T>;
  view<const T extends Shape>(...shape: T): ShapedTensor<T>;
  squeeze<D extends number>(dim?: D): ShapedTensor<SqueezeShape<S, D>>;
  unsqueeze<D extends number>(dim: D): ShapedTensor<UnsqueezeShape<S, D>>;
  flatten(): ShapedTensor<FlattenShape<S>>;

  // Reductions
  sum(): ShapedTensor<readonly []>;
  sum<D extends number>(dim: D, keepdim?: false): ShapedTensor<ReduceShape<S, D, false>>;
  sum<D extends number>(dim: D, keepdim: true): ShapedTensor<ReduceShape<S, D, true>>;
  mean(): ShapedTensor<readonly []>;
  mean<D extends number>(dim: D, keepdim?: false): ShapedTensor<ReduceShape<S, D, false>>;
  mean<D extends number>(dim: D, keepdim: true): ShapedTensor<ReduceShape<S, D, true>>;

  // Comparison (returns same shape with bool dtype)
  eq(other: ShapedTensor<S> | number): ShapedTensor<S>;
  ne(other: ShapedTensor<S> | number): ShapedTensor<S>;
  lt(other: ShapedTensor<S> | number): ShapedTensor<S>;
  le(other: ShapedTensor<S> | number): ShapedTensor<S>;
  gt(other: ShapedTensor<S> | number): ShapedTensor<S>;
  ge(other: ShapedTensor<S> | number): ShapedTensor<S>;
}
Sextends Shape
readonlyshape(S)
readonlydtype(string)
readonlydevice(string)
readonlyrequires_grad(boolean)
neg(() => ShapedTensor<S>)
abs(() => ShapedTensor<S>)
exp(() => ShapedTensor<S>)
log(() => ShapedTensor<S>)
sqrt(() => ShapedTensor<S>)
relu(() => ShapedTensor<S>)
sigmoid(() => ShapedTensor<S>)
tanh(() => ShapedTensor<S>)
sin(() => ShapedTensor<S>)
cos(() => ShapedTensor<S>)
square(() => ShapedTensor<S>)
clone(() => ShapedTensor<S>)
add((scalar: number) => ShapedTensor<S>)
sub((scalar: number) => ShapedTensor<S>)
mul((scalar: number) => ShapedTensor<S>)
div((scalar: number) => ShapedTensor<S>)
pow((scalar: number) => ShapedTensor<S>)
add((other: ShapedTensor<O>) => ShapedTensor<BroadcastShape<S, O>>)
sub((other: ShapedTensor<O>) => ShapedTensor<BroadcastShape<S, O>>)
mul((other: ShapedTensor<O>) => ShapedTensor<BroadcastShape<S, O>>)
div((other: ShapedTensor<O>) => ShapedTensor<BroadcastShape<S, O>>)
matmul((other: ShapedTensor<O>) => ShapedTensor<MatmulShape<S, O>>)
mm((other: ShapedTensor<O>) => ShapedTensor<Matmul2DShape<S, O>>)
t(() => ShapedTensor<TransposeShape<S>>)
transpose((dim0: D0, dim1: D1) => ShapedTensor<TransposeDimsShape<S, D0, D1>>)
permute((dims: P) => ShapedTensor<PermuteShape<S, P>>)
reshape((...shape: T) => ShapedTensor<T>)
view((...shape: T) => ShapedTensor<T>)
squeeze((dim?: D) => ShapedTensor<SqueezeShape<S, D>>)
unsqueeze((dim: D) => ShapedTensor<UnsqueezeShape<S, D>>)
flatten(() => ShapedTensor<FlattenShape<S>>)
sum(() => ShapedTensor<readonly []>)
sum((dim: D, keepdim?: false) => ShapedTensor<ReduceShape<S, D, false>>)
sum((dim: D, keepdim: true) => ShapedTensor<ReduceShape<S, D, true>>)
mean(() => ShapedTensor<readonly []>)
mean((dim: D, keepdim?: false) => ShapedTensor<ReduceShape<S, D, false>>)
mean((dim: D, keepdim: true) => ShapedTensor<ReduceShape<S, D, true>>)
eq((other: ShapedTensor<S> | number) => ShapedTensor<S>)
ne((other: ShapedTensor<S> | number) => ShapedTensor<S>)
lt((other: ShapedTensor<S> | number) => ShapedTensor<S>)
le((other: ShapedTensor<S> | number) => ShapedTensor<S>)
gt((other: ShapedTensor<S> | number) => ShapedTensor<S>)
ge((other: ShapedTensor<S> | number) => ShapedTensor<S>)

A tensor with compile-time shape information.

Previous
ShapeCheckedResult
Next
ShapeErrorMessage