Skip to content

Separate allocator-internal trace tags from user metadata - #193432

Closed
ezyang wants to merge 1 commit into
gh/ezyang/3560/basefrom
gh/ezyang/3560/head
Closed

ezyang wants to merge 1 commit into
gh/ezyang/3560/basefrom
gh/ezyang/3560/head

Conversation

@ezyang

@ezyang ezyang commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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]

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]
@pytorch-bot

pytorch-bot Bot commented Aug 13, 2026 •

Copy link
Copy Markdown

🔗 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 Failures

As of commit 60c630d with merge base fa4050d (image):
💚 Looks good so far! There are no failures yet. 💚

GREEN LIGHT - PR approved to be merged without human review:

The new shared (non-thread-local) internal_metadata_tag is safely guarded: it is
set at CUDACachingAllocator.cpp:2007 while the unique_lock acquired at :1980 is
held continuously through the tagged region to :2051 (mallocWithAddress reaches
only get_free_block_containing_address/alloc_found_block/free_locked, never the
lock-releasing alloc_block), it is cleared by scope_exit on any exit path, it is
a per-DeviceCachingAllocator instance so other devices are unaffected, and all
ten record_trace call sites hold the same recursive mutex, so no other thread
can pick up the tag. Emission is additive and back-compatible:
internal_metadata_ defaults empty, both snapshot paths (Module.cpp:918,
memory_snapshot.cpp:460) omit the key when empty, TraceEntry has a user-provided
constructor so the new member breaks no aggregate initialization, and the dict
overload of _set_memory_metadata just json.dumps-es before the existing call.
Both new behaviors are covered by test_memory_metadata_dict and
test_resize_storage_with_addr_metadata_tag, the latter asserting no trace
entry's user_metadata is polluted with "mallocWithAddress".

reason: clean
Reviewed commit: 60c630d

Inference job

This comment was automatically generated by Dr. CI and updates every 15 minutes.

Comment thread torch/cuda/memory.py
Comment on lines +1130 to +1132
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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this field always existed but we're now properly documenting it

@ezyang

ezyang commented Aug 31, 2026

Copy link
Copy Markdown
Contributor Author

@claude verify the mutex guarding is complete

@ezyang
ezyang marked this pull request as ready for review August 31, 2026 17:08
@ezyang
ezyang requested a review from ngimel August 31, 2026 17:08
@claude

claude Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Claude finished @ezyang's task in 6m 30s —— View job


Mutex guarding audit for internal_metadata_tag

Verdict: the guarding is complete. Every write and every read of internal_metadata_tag happens with DeviceCachingAllocator::mutex held, and the lock is never dropped inside the tagged region. One cosmetic hole (nested mallocWithAddress) and a comment typo below.

Full analysis

1. Write side — set/clear both under the lock

c10/cuda/CUDACachingAllocator.cpp:1980 takes std::unique_lock<std::recursive_mutex> lock(mutex); the tag is set at :2007 and the scope_exit clearing it is constructed at :2008. Destruction is reverse-construction order, so clear_internal_metadata runs before lock is released — the tag is never observably non-empty by another thread after mallocWithAddress returns. This also holds on the throwing paths (TORCH_INTERNAL_ASSERT in alloc_found_block, C10_CUDA_CHECK in insert_events).

The two early returns (TORCH_CHECK on alignment at :1970, return nullptr at :1992) are both before the tag is set, so no leak there.

2. No lock-release window inside the tagged region

The allocator has exactly three places that drop the lock, and none is reachable from :2007-:2050:

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:

  • :1604 annotateMemory — lock_guard at :1603 ✅
  • :1854 malloc OOM — the lock.unlock() at :1814/:1836 are on the rejection branch that return nullptrs at :1839, so the lock is still held here ✅
  • :2147 alloc_found_block — callers hold ✅
  • :2433 free_locked — free holds at :2478; mallocWithAddress holds ✅
  • :3016 snapshot — lock_guard at :2944 ✅
  • :3453 map_block — only reached via the expandable-segments branch of alloc_block (:3901), which is the branch that does not unlock ✅
  • :3509 free_block ✅
  • :3988 alloc_block SEGMENT_ALLOC — the sg scope_exit re-locks at the end of the if block at :3914-3922, and TORCH_CHECK(lock.owns_lock()) at :3924 asserts it ✅
  • :4125 release_block, :4241 unmap_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.

Fix this →

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::string copy per trace entry (:4459) is a copy of an empty string on the hot path, i.e. no allocation.
  • c10/util/ScopeExit.h is still needed and still used, so no stale include.
  • Read the diff
  • Check mallocWithAddress holds the allocator mutex across the tagged region
  • Check every record_trace caller holds the mutex
  • Check for mutex-release windows inside the tagged region
  • Report findings
    · branch gh/ezyang/3560/head

@ezyang

ezyang commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Sep 2, 2026
@ezyang ezyang added the mergedog mergedog is watching this PR label Sep 2, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: This PR needs a release notes: label
If your changes are user facing and intended to be a part of release notes, please use a label starting with release notes:.

If not, please add the topic: not user facing label.

To add a label, you can comment to pytorchbot, for example
@pytorchbot label "topic: not user facing"

For more information, see
https://github.com/pytorch/pytorch/wiki/PyTorch-AutoLabel-Bot#why-categorize-for-release-notes-and-how-does-it-work.

Details for Dev Infra team Raised by workflow job

@ezyang ezyang added release notes: profiler release notes category topic: bc breaking topic category labels Sep 2, 2026
@ezyang

ezyang commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@ezyang

ezyang commented Sep 2, 2026

Copy link
Copy Markdown
Contributor Author

mergedog handoff

Note

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 @pytorchbot merge.

Current PR head: 60c630d43056c63058c1b51e5ceeb3bb6ec587da.
No mergedog-authored commits were pushed during this run.

No LLM was invoked during this run.

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
…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
@github-actions
github-actions Bot deleted the gh/ezyang/3560/head branch November 4, 2026 01:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/trunk Trigger trunk jobs on your pull request mergedog mergedog is watching this PR mergedX1 release notes: profiler release notes category topic: bc breaking topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants