diff --git a/paddle/phi/api/include/compat/ATen/core/TensorBase.h b/paddle/phi/api/include/compat/ATen/core/TensorBase.h index 37659fcb304bc9..107b7b262410ee 100644 --- a/paddle/phi/api/include/compat/ATen/core/TensorBase.h +++ b/paddle/phi/api/include/compat/ATen/core/TensorBase.h @@ -76,11 +76,9 @@ class PADDLE_API TensorBase { } size_t use_count() const { return tensor_.impl().use_count(); } size_t weak_use_count() const { - // TODO(youge325) : In PyTorch, weak pointer is defined and - // implemented in c10/util/intrusive_ptr.h, namely c10::intrusive_ptr; - // but in Paddle, we use std::shared_ptr, so here we just return 0 - // temporarily. - return 0; + // PyTorch exposes an internal self weak-reference on live TensorImpls, so + // the observable weak count starts at 1 even without user-created refs. + return tensor_.defined() ? 1 : 0; } void print() const { diff --git a/test/cpp/compat/c10_ptr_test.cc b/test/cpp/compat/c10_ptr_test.cc index 59cdf84d9c1829..f00bb64211e6db 100644 --- a/test/cpp/compat/c10_ptr_test.cc +++ b/test/cpp/compat/c10_ptr_test.cc @@ -100,16 +100,15 @@ TEST(TensorBaseTest, UseCountAPI) { TEST(TensorBaseTest, WeakUseCountAPI) { // Test weak_use_count() API - // Note: Currently returns 0 as Paddle uses std::shared_ptr instead of - // c10::intrusive_ptr + // Compat exposes PyTorch-visible semantics: live TensorImpl wrappers report + // the self weak-reference count as 1. at::TensorBase tensor1 = at::ones({2, 3}, at::kFloat); - // Should return 0 (not implemented yet) - ASSERT_EQ(tensor1.weak_use_count(), 0); + ASSERT_EQ(tensor1.weak_use_count(), 1); at::TensorBase tensor2 = tensor1; - ASSERT_EQ(tensor1.weak_use_count(), 0); - ASSERT_EQ(tensor2.weak_use_count(), 0); + ASSERT_EQ(tensor1.weak_use_count(), 1); + ASSERT_EQ(tensor2.weak_use_count(), 1); // Test with undefined tensor at::TensorBase undefined_tensor;