Repository navigation
Fix FastModuleType tp_setattro segfault on attribute deletion - #122534
AshiteshSingh wants to merge 3 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request adds support for deleting attributes (when value is nullptr) in fast_module_type.cc and ensures the return value of PyObject_GenericSetAttr is propagated. The reviewer pointed out a critical cache inconsistency issue: if PyObject_GenericSetAttr fails after attr_map has already been updated, the cache will be out of sync. A code suggestion was provided to handle this failure and invalidate the cache entry accordingly.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| Py_XDECREF(to_decref); | ||
| PyObject_GenericSetAttr(module, name, value); | ||
| return 0; | ||
| return PyObject_GenericSetAttr(module, name, value); |
There was a problem hiding this comment.
If PyObject_GenericSetAttr fails (returns -1), the attribute is not successfully set on the module. However, attr_map has already been updated with the new value before this call. This leads to cache inconsistency where subsequent lookups of the attribute will incorrectly return the new value from the cache, even though setting it failed.
To prevent this, we should detect if PyObject_GenericSetAttr fails and invalidate/remove the entry from attr_map to keep the cache consistent.
int status = PyObject_GenericSetAttr(module, name, value);
if (status < 0) {
PyObject* key_to_decref = nullptr;
PyObject* val_to_decref = nullptr;
{
absl::MutexLock lock(&fast_module->mutex);
auto& attr_map = fast_module->attr_map;
if (auto it = attr_map.find(name); it != attr_map.end()) {
key_to_decref = it->first;
val_to_decref = it->second;
attr_map.erase(it);
}
}
Py_XDECREF(key_to_decref);
Py_XDECREF(val_to_decref);
}
return status;
sgarciagoogle
left a comment
There was a problem hiding this comment.
Hi @AshiteshSingh, thank you for working on fixing this segfault!
There are two required changes before we can import this into TensorFlow and sync it internally:
1. Fix Cache Inconsistency on Setting Errors (Security & Stability Risk)
Currently, when setting an attribute (value != nullptr), attr_map is updated before calling PyObject_GenericSetAttr. If PyObject_GenericSetAttr fails and returns < 0 (e.g., attribute rejection or dictionary failure), the C++ lookup cache (attr_map) remains desynchronized from the actual Python module state. This stale cache state poses a stability and security risk.
Please check the return status of PyObject_GenericSetAttr when setting attributes and erase/invalidate the cache entry if the operation fails:
int status = PyObject_GenericSetAttr(module, name, value);
if (status < 0) {
PyObject* key_to_decref = nullptr;
PyObject* val_to_decref = nullptr;
{
absl::MutexLock lock(&fast_module->mutex);
auto& attr_map = fast_module->attr_map;
if (auto it = attr_map.find(name); it != attr_map.end()) {
key_to_decref = it->first;
val_to_decref = it->second;
attr_map.erase(it);
}
}
Py_XDECREF(key_to_decref);
Py_XDECREF(val_to_decref);
}
return status;2. Add Unit Tests
Please add unit tests to tensorflow/python/util/fast_module_type_test.py to prevent regressions. Specifically, please add test cases verifying:
- Successful attribute deletion via del module.attr.
- Attempting to delete a non-existent attribute raises an AttributeError.
- Cache consistency when modifications or deletions occur.
Once these updates and tests are added we will be happy to review again!
|
Hi @sgarciagoogle, Thank you for the detailed review! I've addressed both of your requests in the latest commit: 1. Fixed Cache Inconsistency on Setting ErrorsI've updated the 2. Added Unit TestsI've added new unit test cases to
|
|
Hi @AshiteshSingh, |
27d945e to
95c26b2
Compare
|
Hi @sgarciagoogle, Done! I have rebased the PR onto the latest Summary of Current Branch State:
Please let me know if any further changes or test runs are needed. Thank you again for the thorough review! |
Prevents an integer overflow when calculating tensor sizes in `ParameterizedTruncatedNormalOp` by using `int64_t` instead of `int32_t`. This issue could lead to uninitialized memory being returned when using large tensor shapes. Reverts changelist 949495726 FUTURE_COPYBARA_INTEGRATE_REVIEW=#122534 from AshiteshSingh:fix/fast-module-segfault 95c26b2 PiperOrigin-RevId: 942188042
Fixes jax-ml/jax#39257 Commit history for google/XNNPACK (efa2e754 -> 53a1797b): - 0d05b116 Gregory Comer: Add fp32->bf16 rewrite pass - 86776919 Jake Stevens: Add support for avx2 qd8_bf16_qb4w gemm - 49bd3ab2 Jacob Stevens: Merge branch 'google:master' into avx2_bf16_qb4w_gemm - e6f7ecf0 velonica0: [RVV] add rvv f32 kernel for ppmm - cb9c05ad Gregory Comer: Update GN build and fix bf16 sqrt tolerance - 9f2ea13a Gregory Comer: Add :math dep - a3fc80e2 Aizal Khan: reject input channel mismatch in fully-connected reshape - ae5e2eac Quentin Khan: Suppress linter warning for TensorHandle error status implicit construction. - be502dd1 Quentin Khan: Fix allocation behaviour in OwningCpuBuffer::(Copy|Transform). - d0133af8 Volodymyr Kysenko: Add x86 AVX2/FMA3 FP32 GEMV-M dot kernels. - ba90c659 Volodymyr Kysenko: Add benchmarks for various attention cases using ynnpack API to define the graphs. - 7e739a47 Dillon Sharlet: Add 2- and 4-bit 8-way interleaving kernels - 43664800 Dillon Sharlet: Optimize SIMD sub-byte interleave wrappers. - f45b3ea0 Dillon Sharlet: Fix int8 -> uint8 rewrite for dots - 5b5b4a35 Dillon Sharlet: Relax tolerance of sum of squares in YNNPACK - 1890ca2f XNNPACK Team: Merge pull request #10677 from JakeStevens:avx2_bf16_qb4w_gemm - 225cae50 XNNPACK Team: Merge pull request #10700 from aizu-m:fully-connected-input-channel-mismatch - 73658922 Quentin Khan: Add equality operator to int4_t and int2_t. - 64c959c0 Quentin Khan: Implement conversion over ranges of elements. - d5b1ae69 XNNPACK Team: Merge pull request #10629 from GregoryComer:bf16-rewrite - d3f0715a XNNPACK Team: Merge pull request #10690 from velonica0:rvv-ppmm-new - 894aab8e Dillon Sharlet: Add `convert(ternary(...))` and `ternary(convert(...))` fusion rules - 79dc6c43 Quentin Khan: Fix warnings about control reaching the end of a non-void function. - cdbda033 Dillon Sharlet: Update Slinky in XNNPACK - bbc8bb6b Dillon Sharlet: Add concatenated_mixed_dot_bench - 5d9f5ae3 Frank Barchard: xx-pad AVX512SKX microkernel with p64_u128 - fdd1e56 XNNPACK Team: Added option to enable ynnpack integration with litert - a1f8b257 Dillon Sharlet: Update XNNPACK dependencies - 11d93dd0 Volodymyr Kysenko: Move scheduler bounds from producer loop splits to consumer inputs. - 44db2329 Quentin Khan: Fix presubmit checks about unchecked absl::StatusOr access. - 599a1be6 Aizal Khan: validate runtime input channels in convolution reshape paths - f3034661 Dillon Sharlet: Update KleidiAI and Slinky in XNNPACK - 2c59699a Dillon Sharlet: Remove exception for `pack_b` from the constant folding heuristic - 31020912 Dillon Sharlet: Add dynamic shapes to `concatenated_mixed_dot_bench` - e74ee67f Frank Barchard: Fix for fingerprint test - 5fe544df Frank Barchard: Support static FP32 bias for FP16 depthwise convolution 2D in XNNPACK subgraph. - 0de517a4 XNNPACK Team: Fix quantization export to allow explicit q/ dq nodes in the graph - f0fd32b3 Dillon Sharlet: Make B a dynamic value in concatenated_mixed_dot_bench - 79cbaa9a Aizal Khan: Match channel-mismatch reshape error to batch-matrix-multiply wording - b692f911 Quentin Khan: Allow passing a scalar value as the `TensorInit` buffer. - 09767002 Sachin Hambar: Fix LUT fusion treating an already-fused LUT node as a plain unary op - b372ff19 Volodymyr Kysenko: Allow changing the order of the loops when looking for the match to fuse with. - 7647747b Volodymyr Kysenko: Add a transposed decode1 attention benchmark. - a635548f Volodymyr Kysenko: Add a loop fusion test for combining dot steps with LCM. - 66b5f2b0 Quentin Khan: Try keeping buffer and tensor type coherent. - 464e9d3f Dillon Sharlet: Remove deprecated quantization parameters from `ynn_define_convert` - dff8cb5d Quentin Khan: Force `LockedBufferSpan` data access through an lvalue. - b1858faa Frank Barchard: Re-enable packw optimized kernels and refine ISA guards in GEMM configs. - 6d553e89 Frank Barchard: Add xnn_pack_qs8_to_qu8_qc4uw_gemm_gio_w - c8306cee destro4evr-rgb: litert/arithmetic: add axis bounds check in Unpack() - f6d310ea Misha Gutman: Fixed static tensor behavior with ynnpack to match XNNPACK. Old behavior didn't allow for external tensors with static weights. - 1336d27f Dillon Sharlet: Add `YNN_NODE_FLAG_KEEP_SHAPE` flag and implement it in `ynn_define_slice_like` - ff8907d9 Volodymyr Kysenko: Actually provide splits for the pack. - 11f8dc86 Sachin Hambar: Move num_inputs assert past the LUT-fused-node check in is_pure_unary_elementwise - 218bb2e0 Dillon Sharlet: Change x86 uint8 x int2 dot kernels to use tile_k = 8 - 1dfe86ea XNNPACK Team: Merge pull request #10748 from aizu-m:conv-reshape-input-channels - 0e925591 XNNPACK Team: Merge pull request #10756 from sachinhambar:fix/lut-fusion-invalid-unary-node - 9b0e561d XNNPACK Team: Merge pull request #10765 from destro4evr-rgb:fix/litert-unpack-axis-bounds-check - 9fe71df8 destro4evr-rgb: litert/tensor/arithmetic.h: bounds-check axis and index values before vector subscript - 5251854e XNNPACK Team: Merge pull request #10702 from destro4evr-rgb:fix/litert-arithmetic-axis-bounds-checks - 53a1797b Dillon Sharlet: Fix crash due to not allowing internal extra dimensions. Commit history for pytorch/cpuinfo (bc3c01e2 -> ea6b9f1b): - d05fbcd5 Ken Unger: Add riscv half-precision floating point detection (#375) - e829e80f fbarchard: Adding ro.soc.model support to cpuinfo to detect Qualcomm SM8850 SoC (#381) - 3681f0ce Nicolas Pitre: Add Cortex-A320 to MIDR decode table (#384) - ea6b9f1b fbarchard: Add Google Tensor SoC detection. (#382) Commit history for kleidi/kleidiai (51f71905 -> b87ef9c9): - 07809921 Declan Cox: feat: Add SME matmul clamp FP32 <- qsi8d32p x qsi4c32p kernels and supporting RHS packing kernels - 51b3b669 Emil Ohlsson: docs: Indicate deprecated naming - aef56b18 Evie Wright: feat: f32 <- qsi8d32p x qsi4c32p matmul ukernels using advanced SIMD support variable block length - 0e6d26d9 Emil Ohlsson: fix: Make kernel commit ZA - cd569730 Felix Johnny Thomasmathibalan: feat: Skip CI pipelines for draft merge requests - c6b34654 Anitha Raj: feat: Advanced SIMD Matmul Micro-kernels F32 <- QAI8DXP(LHS) x QSU2CXP(RHS) - d01637c3 Felix Johnny Thomasmathibalan: docs: Update documentation in the interface file - 09bcd563 Patryk Kaiser: feat: Add NxK RHS packers for F32 and F16 Adv SIMD kernels - 4581dbcb Patryk Kaiser: chore: Enable overflow protection by default - 1cb4545b James Gross: fix: Fix qai8 SME2 test failures when k=1 - 89a7ef40 Dan Johansson: docs: 3rd party contribution policy - fb22f766 Patryk Kaiser: docs: Update changelog with new packing kernels - 5866364d Viet-Hoa Do: feat: Implement SME2 FP32 GEMV with 4vsx1 RHS format - e3ef8a28 Emil Ohlsson: feat: Add Decomposable GEMM kernels - 158dbabb Felix Johnny Thomasmathibalan: feat: Add depthwise indirect kernels and packing for FP16 SME2 - 147cf38f Emil Ohlsson: chore: Add debug build - 29d3e891 Viet-Hoa Do: feat: Implement SME2 static Int8 GEMM and GEMV kernels - 41560cc9 Emil Ohlsson: fix: Replace invalid clamp ranges in test file - 0b360985 Dan Johansson: fix: Enable random seed for matmul_clamp_f32_qai8dxp_qsi4cxp_test - b6aac192 James Gross: fix: Fix get_lhs/rhs_get_offset API to use mr and nr - 8d6e32ff Emil Ohlsson: fix: Skip unsupported cases - 780a951d Dan Johansson: fix: Reduce scope of public sme1-only testing - 4f32151f John McLoughlin: fix: Update api checker to cater for additional source files - dc50c2e6 Mohammed Suhail Munshi: chore: Bump version to v1.26.0 - ded0f58c Emil Ohlsson: fix: Clean up the use of `clamp_range` - 8e08e0ed Emil Ohlsson: docs: Split kernel naming - e683484a Cathal Lawlor: chore: add electric fence negative CI canary - ae936c0e Aude Vuilliomenet: chore: CI Re-enable API compatibility checker. - 2ff86189 Emil Ohlsson: feat: bf16 LHS packing for SME - f0cac762 Emil Ohlsson: feat: Add SME version of f32_bf16p_bf16p kernel - d96e3f0a Dan Johansson: feat: Add CI job that checks micro-kernel header includes - ea78dad7 Viet-Hoa Do: chore: Rename kernel wrapper registry files - 66135f72 Puneet Matharu: feat: Add experimental ops library - 9bcaee2e John McLoughlin: chore: Bump to release 1.27.0 - 678b268d Emil Ohlsson: fix: Controllable accumulator type - 546ead02 John McLoughlin: chore: Extend the benchmark tool to facilitate kernel & LHS combinations - c8aa2b14 Viet-Hoa Do: chore: Add documentation for micro-kernel API design - b431044a Emil Ohlsson: chore: Add name checker - 45ee3ee2 Emil Ohlsson: chore: Automated naming documentation - 7ca389b8 Emil Ohlsson: chore: trim coverage test output - f6503d33 Dan Johansson: feat: Add fp16 <- qai8dxp x qsi4cxp SME2 GEMM - 2f057318 Aude Vuilliomenet: docs: add vscale information - 142c5852 Suhail M: feat: Add SVE2p1 FP16 Matmul kernels with FP32 Accumulation - b9786177 David Mansell: fix: ops: Remove C-style casts in hybrid kernels. - 1231da54 John McLoughlin: chore: Bump release to 1.28.0 - 8a3aadbc Dan Johansson: fix: Update pack_matmul benchmark suite - 5b8a014c Cathal Lawlor: chore: disable experimental/ops CI for rework - b87ef9c9 Dan Johansson: feat: Add fp16 <- qai8dxp x qsi4cxp SME2 GEMV Commit history for google/pthreadpool (9003ee6c -> 02460584): - 283bff7f Pranav P: Fix endianness issue which fixes deadlock - 6bde301a Gregory Comer: Directly join owned threads on cleanup - 85d1718 Alexander Shaposhnikov: Update googletest, cpuinfo version. - 65eb1fd3 Alexander Shaposhnikov: Add PTHREADPOOL_NO_SANITIZE_FUNCTION macro. - a56dcd79 XNNPACK Team: Merge pull request #92 from GregoryComer:win-cleanup-fix - 02460584 XNNPACK Team: Merge pull request #88 from pranavkaruvally:s390x-fix Commit history for dsharlet/slinky (dad5594 -> 8eda4a05): - 22c8c113 Dillon: Avoid unnecessary body traversals in `depends_on` (#846) - d9b5f83 Dillon: Fix padded aliases with translation (#847) - 50445524 Volodymyr Kysenko: Fix slide_and_fold_storage corrupting sibling crops of a concatenate output. (#850) - 76510c89 Dillon: Fix simplify rules and associated test coverage hole (#853) - 8480fc77 Dillon: Refactor `slide_and_fold_storage` (#854) - 8eda4a05 Dillon: Avoid substituting buffer bounds that are defined in terms of itself (#855) Reverts changelist 949495726 FUTURE_COPYBARA_INTEGRATE_REVIEW=#122534 from AshiteshSingh:fix/fast-module-segfault 95c26b2 PiperOrigin-RevId: 949622824
Previously, Triton would only allow TF32 when precision was DEFAULT. However, cuBLAS allows TF32 when precision is HIGH. This change aligns Triton with cuBLAS behavior, allowing TF32 for both DEFAULT and HIGH precision settings in Triton. HIGHEST precision remains mapped to full F32. Reverts 3136599 FUTURE_COPYBARA_INTEGRATE_REVIEW=#122534 from AshiteshSingh:fix/fast-module-segfault 95c26b2 PiperOrigin-RevId: 949402370
…essages. When floating-point literal comparisons fail, the error message now includes a list of ErrorSpec values (absolute and relative error bounds) that would allow the comparison to pass. These suggestions are derived by tracking the maximum absolute and relative errors encountered for each mismatch and maintaining a set of minimal (abs, rel) pairs. The suggested values are rounded up to one significant figure for readability. Reverts 3136599 FUTURE_COPYBARA_INTEGRATE_REVIEW=#122534 from AshiteshSingh:fix/fast-module-segfault 95c26b2 PiperOrigin-RevId: 947669634
Prevents an integer overflow when calculating tensor sizes in `ParameterizedTruncatedNormalOp` by using `int64_t` instead of `int32_t`. This issue could lead to uninitialized memory being returned when using large tensor shapes. Reverts changelist 949495726 FUTURE_COPYBARA_INTEGRATE_REVIEW=#122534 from AshiteshSingh:fix/fast-module-segfault 95c26b2 PiperOrigin-RevId: 942188042
Prevents an integer overflow when calculating tensor sizes in `ParameterizedTruncatedNormalOp` by using `int64_t` instead of `int32_t`. This issue could lead to uninitialized memory being returned when using large tensor shapes. Reverts changelist 949495726 FUTURE_COPYBARA_INTEGRATE_REVIEW=#122534 from AshiteshSingh:fix/fast-module-segfault 95c26b2 PiperOrigin-RevId: 942188042
…essages. When floating-point literal comparisons fail, the error message now includes a list of ErrorSpec values (absolute and relative error bounds) that would allow the comparison to pass. These suggestions are derived by tracking the maximum absolute and relative errors encountered for each mismatch and maintaining a set of minimal (abs, rel) pairs. The suggested values are rounded up to one significant figure for readability. Reverts 3136599 FUTURE_COPYBARA_INTEGRATE_REVIEW=#122534 from AshiteshSingh:fix/fast-module-segfault 95c26b2 PiperOrigin-RevId: 947669634
…essages. When floating-point literal comparisons fail, the error message now includes a list of ErrorSpec values (absolute and relative error bounds) that would allow the comparison to pass. These suggestions are derived by tracking the maximum absolute and relative errors encountered for each mismatch and maintaining a set of minimal (abs, rel) pairs. The suggested values are rounded up to one significant figure for readability. Reverts 3136599 FUTURE_COPYBARA_INTEGRATE_REVIEW=#122534 from AshiteshSingh:fix/fast-module-segfault 95c26b2 PiperOrigin-RevId: 947669634
…fe in place. Provide a factory for turning an existing buffer into an UndonatableCommonPjRtBuffer, so callers (and tests) no longer construct the hold-free buffer via make_unique with hand-assembled ingredients. MakeUndonatable consumes the input buffer and returns an equivalent hold-free bufer aliasing the same device memory. It reuses the AquireScopedRawBuffer path to snapshot the raw buffer with its definition events, builds the UndonatableCommonPjrtBuffer, then drops the original. Reverts 3136599 FUTURE_COPYBARA_INTEGRATE_REVIEW=#122534 from AshiteshSingh:fix/fast-module-segfault 95c26b2 PiperOrigin-RevId: 949254300
…nt::MakeUndonatable. Provide a factory `MakeUndonatable` for turning an existing buffer into an `UndonatableCommonPjRtBuffer`, it consumes the input buffer and returns an equivalent hold-free buffer aliasing the same device memory. It uses CommonPjRtClient's friend access on CommonPjRtBuffer to donate the tracked buffer, snapshotting the underlying raw buffer along with its definition events to construct UndonatableCommonPjRtBuffer. Static factory `UndonatableCommonPjRtBuffer::Create` is provided as a helper on the buffer class that delegates to `CommonPjRtClient::MakeUndonatable`. Unit tests in `undonatable_common_pjrt_buffer_test.cc` have been updated to use the factory and include null-check verification. Reverts 3136599 FUTURE_COPYBARA_INTEGRATE_REVIEW=#122534 from AshiteshSingh:fix/fast-module-segfault 95c26b2 PiperOrigin-RevId: 949254300
…nt::MakeUndonatable. Provide a factory `MakeUndonatable` for turning an existing buffer into an `UndonatableCommonPjRtBuffer`, it consumes the input buffer and returns an equivalent hold-free buffer aliasing the same device memory. It uses CommonPjRtClient's friend access on CommonPjRtBuffer to donate the tracked buffer, snapshotting the underlying raw buffer along with its definition events to construct UndonatableCommonPjRtBuffer. Static factory `UndonatableCommonPjRtBuffer::Create` is provided as a helper on the buffer class that delegates to `CommonPjRtClient::MakeUndonatable`. Unit tests in `undonatable_common_pjrt_buffer_test.cc` have been updated to use the factory and include null-check verification. Reverts 3136599 FUTURE_COPYBARA_INTEGRATE_REVIEW=#122534 from AshiteshSingh:fix/fast-module-segfault 95c26b2 PiperOrigin-RevId: 949254300
…essages. When floating-point literal comparisons fail, the error message now includes a list of ErrorSpec values (absolute and relative error bounds) that would allow the comparison to pass. These suggestions are derived by tracking the maximum absolute and relative errors encountered for each mismatch and maintaining a set of minimal (abs, rel) pairs. The suggested values are rounded up to one significant figure for readability. Reverts 3136599 FUTURE_COPYBARA_INTEGRATE_REVIEW=#122534 from AshiteshSingh:fix/fast-module-segfault 95c26b2 PiperOrigin-RevId: 947669634
|
Hi @AshiteshSingh, Can you kindly resolve the conflicts ? Thank you! |
95c26b2 to
4b40fda
Compare
|
Hi @nithyak0204, I made a mistake while trying to rebase and resolve the merge conflicts. This caused my branch to temporarily match I have now fully restored my branch to its correct state, and all of my original commits and test cases are intact on Could you please reopen this PR if the system allows it? If GitHub keeps it locked because of the automation, please let me know and I will gladly open a fresh PR from the restored branch. Thank you! |
|
hii @nithyak0204 I have resolved the conflicts and the tests are currently running! |
|
@nithyak0204 all the checks are successfull you can review it, thanks! |
Fixes #121923
Bug
In
tensorflow/python/util/fast_module_type.cc, the customtp_setattroimplementation unconditionally calledPy_INCREF(value). When an attribute is deleted viadel module.attrin Python, the interpreter passesnullptrfor thevalueargument. This causedPy_INCREF(nullptr)to trigger a segmentation fault.Fix
Added a check for
value == nullptrto properly handle attribute deletions. When a deletion occurs:attr_map) if it exists there.PyObject_GenericSetAttr, which correctly removes the attribute from the underlying dictionary and raises anAttributeErrorif the attribute does not exist.