Repository navigation
Conversation
Add a dedicated `internal_metadata_` field to `TraceEntry` so allocator internals can tag trace entries without mutating the user-set metadata. Previously `malloc_with_address` recorded its "mallocWithAddress" label by temporarily overwriting `user_metadata` (appending to whatever the user had set and restoring it on scope exit). That polluted the user's metadata in the emitted trace entries and, now that metadata may be structured JSON, would have corrupted it. The tag now lives in a separate `internal_metadata_tag` member (guarded by the allocator mutex, held across the tagged region) that is copied into `TraceEntry::internal_metadata_` at record time, leaving `user_metadata_` verbatim what the user set. The new field is surfaced through both snapshot paths (`Module.cpp` and `memory_snapshot.cpp`), emitted only when non-empty, and rendered in MemoryViz.js as a separate "Internal Metadata" section in the event stack. This update also lets `_set_memory_metadata` accept a dict, which is serialized to compact JSON; `_get_memory_metadata` returns the string form, so save/set/restore round-trips without special-casing. The snapshot type stubs in memory.py document both `user_metadata` and the optional `internal_metadata` fields. Tests cover dict metadata round-tripping (`test_memory_metadata_dict`) and verify that `mallocWithAddress` tagging lands in `internal_metadata` while the user's JSON metadata stays intact in `user_metadata` (`test_resize_storage_with_addr_metadata_tag`). [ghstack-poisoned]
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/193432
Note: Links to docs will display an error until the docs builds have been completed. ✅ No FailuresAs of commit 60c630d with merge base fa4050d ( GREEN LIGHT - PR approved to be merged without human review:
reason: This comment was automatically generated by Dr. CI and updates every 15 minutes. |
| user_metadata: str # the calling thread's metadata at the time of | ||
| # the event, as set via _set_memory_metadata (dicts appear as | ||
| # their JSON serialization) |
There was a problem hiding this comment.
this field always existed but we're now properly documenting it
|
@claude verify the mutex guarding is complete |
|
Claude finished @ezyang's task in 6m 30s —— View job Mutex guarding audit for
|
| Site | Reachable from the tagged region? |
|---|---|
malloc OOM-rejection observers (:1814, :1836) |
No — malloc is not on this path |
malloc OOM observers (:1905) |
No |
alloc_block release_lock_on_cudamalloc (:3917-3918) |
No — mallocWithAddress never calls alloc_block; it only uses get_free_block_containing_address (pure lookup) and alloc_found_block (pure bookkeeping/split) |
That last one is the important one, and it's the reason this design is sound rather than accidentally sound: mallocWithAddress operates entirely on an already-found free block, so no cudaMalloc (and therefore no unlock) can occur while the tag is set. free_locked → free_block / insert_events / record_free_markers also never unlock.
Note prepare_for_malloc(context, stream) at :1981 runs before the tag is set, so the FREE_COMPLETED entries that process_events may emit are correctly left untagged.
3. Read side — all record_trace callers hold the lock
record_trace is private, and the class contract at :3267 ("All private methods do not acquire the allocator mutex") means callers must hold it. Checked all nine call sites:
:1604annotateMemory—lock_guardat :1603 ✅:1854mallocOOM — thelock.unlock()at :1814/:1836 are on the rejection branch thatreturn nullptrs at :1839, so the lock is still held here ✅:2147alloc_found_block— callers hold ✅:2433free_locked—freeholds at :2478;mallocWithAddressholds ✅:3016snapshot—lock_guardat :2944 ✅:3453map_block— only reached via the expandable-segments branch ofalloc_block(:3901), which is the branch that does not unlock ✅:3509free_block✅:3988alloc_blockSEGMENT_ALLOC — thesgscope_exit re-locks at the end of theifblock at :3914-3922, andTORCH_CHECK(lock.owns_lock())at :3924 asserts it ✅:4125release_block,:4241unmap_block✅
4. Cross-thread / cross-device reasoning
The tag is a plain per-instance member (not thread_local like user_metadata), which is the right choice here: thread A holds mutex across the whole tagged region, so thread B cannot reach any record_trace on the same device while the tag is set. The interleaving worth spelling out — B unlocks for cudaMalloc at :3918, A grabs the mutex and tags — is safe because B's lock.lock() blocks until A has finished and cleared, so B's SEGMENT_ALLOC at :3988 reads an empty tag. Other devices have their own DeviceCachingAllocator and their own mutex, so there's no cross-device bleed (unlike user_metadata, whose process-wide-per-thread scope is documented at :1529-1534).
5. Minor: clear() vs. save/restore under recursive re-entry
mutex is a std::recursive_mutex, so same-thread re-entry into the allocator is permitted. If a trace_trackers_ callback (record_trace :4462-4464, explicitly documented as "should not include any Pytorch call") or reportMemoryUsageToProfiler (:2176) ever re-entered allocateWithAddress, the inner scope_exit would clear() the tag and the remainder of the outer tagged region would go unlabeled. This is a labeling artifact only — no UB, no lock issue, and it requires a re-entry path that arguably shouldn't exist. Still, save/restore costs nothing and matches what the old code did:
auto saved = std::move(internal_metadata_tag);
internal_metadata_tag = "mallocWithAddress";
auto restore = c10::make_scope_exit(
[this, saved = std::move(saved)]() mutable { internal_metadata_tag = std::move(saved); });Your call whether that's worth the extra lines for a path that probably can't be hit.
6. Comment typo
c10/cuda/CUDACachingAllocator.cpp:1537 says "see malloc_with_address"; the method is mallocWithAddress.
Also confirmed correct (outside the mutex question)
- Both snapshot paths gate on non-empty (
Module.cpp:918,memory_snapshot.cpp:460), so the key is absent rather than""for the overwhelmingly common case — existing snapshot consumers are unaffected. - The extra
std::stringcopy per trace entry (:4459) is a copy of an empty string on the hot path, i.e. no allocation. c10/util/ScopeExit.his still needed and still used, so no stale include.
- Read the diff
- Check
mallocWithAddressholds the allocator mutex across the tagged region - Check every
record_tracecaller holds the mutex - Check for mutex-release windows inside the tagged region
- Report findings
· branchgh/ezyang/3560/head
|
@pytorchbot merge |
Merge failedReason: This PR needs a If not, please add the To add a label, you can comment to pytorchbot, for example For more information, see Details for Dev Infra teamRaised by workflow job |
|
@pytorchbot merge |
mergedog handoffNote This PR is being shepherded by mergedog, an automation tool run by a maintainer. It watches CI and may push fixes; the PR author does not need to act unless a maintainer asks. All CI is green (or skipped). Ready for human review and Current PR head: No LLM was invoked during this run. |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
…3432) Previously `mallocWithAddress` recorded its provenance on the synthetic prefix-block malloc/free pair by temporarily overwriting the calling thread's `user_metadata` (appending `"\nmallocWithAddress"` and restoring on scope exit). This conflated two distinct things: the user-set metadata and an allocator-internal tag. It also corrupted structured metadata -- if the user set JSON via `_set_memory_metadata`, the appended text made the recorded string no longer parse as JSON. This adds a dedicated `internal_metadata_` field on `TraceEntry`. The allocator sets an `internal_metadata_tag` (guarded by the allocator mutex, which is held across the tagged region) and stamps it onto trace entries in `record_trace`, leaving `user_metadata_` verbatim. The field is only emitted in the snapshot (both pybind and pickled paths) when non-empty, and the visualizer renders it under a separate "Internal Metadata" label. `_set_memory_metadata` now also accepts a dict, serialized to compact JSON, so callers can record structured metadata; `_get_memory_metadata` returns the JSON string form, which round-trips back through `_set_memory_metadata`. Test Plan: ``` python test/test_cuda.py -k test_memory_metadata_dict python test/test_cuda.py -k test_resize_storage_with_addr_metadata_tag ``` Authored-with: Claude (Opus 4.8) Co-Authored-By: Claude Opus 4.8 <[email protected]> Pull Request resolved: pytorch#193432 Approved by: https://github.com/pytorchgreenlight, https://github.com/ngimel
Stack from ghstack (oldest at bottom):
Previously
mallocWithAddressrecorded its provenance on the syntheticprefix-block malloc/free pair by temporarily overwriting the calling
thread's
user_metadata(appending"\nmallocWithAddress"and restoringon scope exit). This conflated two distinct things: the user-set metadata
and an allocator-internal tag. It also corrupted structured metadata --
if the user set JSON via
_set_memory_metadata, the appended text madethe recorded string no longer parse as JSON.
This adds a dedicated
internal_metadata_field onTraceEntry. Theallocator sets an
internal_metadata_tag(guarded by the allocator mutex,which is held across the tagged region) and stamps it onto trace entries
in
record_trace, leavinguser_metadata_verbatim. The field is onlyemitted in the snapshot (both pybind and pickled paths) when non-empty,
and the visualizer renders it under a separate "Internal Metadata" label.
_set_memory_metadatanow also accepts a dict, serialized to compact JSON,so callers can record structured metadata;
_get_memory_metadatareturnsthe JSON string form, which round-trips back through
_set_memory_metadata.Test Plan:
Authored-with: Claude (Opus 4.8)
Co-Authored-By: Claude Opus 4.8 [email protected]