Skip to content

Let the CUDA allocator honor any power of two alignment - #23446

Merged
shoumikhin merged 1 commit into
pytorch:mainfrom
shoumikhin:cuda-allocator-alignment
Oct 6, 2026
Merged

shoumikhin merged 1 commit into
pytorch:mainfrom
shoumikhin:cuda-allocator-alignment

Conversation

@shoumikhin

@shoumikhin shoumikhin commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Problem

CudaAllocator::allocate refused alignments above 256 bytes. TensorRT asks for 512 bytes when loading an engine, but CUDA guarantees only 256. Accepting larger alignments must not depend on how a GPU packs its allocations.

Change

The allocator now reserves extra memory and rounds the returned pointer up when the requested alignment exceeds 256 bytes.

Requested alignment Before After
Power of two, up to 256 bytes Allocates Allocates without padding
Power of two, above 256 bytes NotSupported Allocates with padding and rounding
Zero or not a power of two InvalidArgument InvalidArgument

Requests above 256 reserve alignment - 1 extra bytes. Rounding consumes at most that many bytes. Size overflow returns InvalidArgument before any CUDA call.

Only pointers changed by rounding are recorded. deallocate retrieves and frees the original pointer. A mutex protects the map; an atomic count keeps deallocation free of that lock when no rounded pointers are live.

For alignments up to 256, the pointer check remains as a safety net. A misaligned block is freed and rejected with NotSupported, instead of MemoryAllocationFailed. Async allocation and memory pools are unchanged. The large alignment tests no longer skip on ROCm.

Validation

20 allocator tests passed on Linux x86_64 with an H100 and CUDA 12.8. They cover 512 and 4096 byte round trips with mixed sizes live over 64 cycles, concurrent allocations, overflow boundaries, and original pointer deallocation through weak CUDA stand ins. Compute Sanitizer reported zero memory errors and zero leaked allocations. Intentional invalid device API errors were excluded from its API error reporting.

The previous allocator fails four regression tests. Restoring this implementation passes the full suite again. ROCm and Windows were not built or run.

@pytorch-bot

pytorch-bot Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/23446

Note: Links to docs will display an error until the docs builds have been completed.

❌ 1 New Failure

As of commit e65f487 with merge base efc7f2e (image):

NEW FAILURE - The following job has failed:

  • Cadence Build & Test / Resolve CI docker image / resolve (gh)
    ##[error]Refusing to check out fork pull request code from a 'pull_request_target' workflow. This workflow runs with the base repository's GITHUB_TOKEN, secrets, default-branch cache scope, and runner access. Fetching and executing a fork's code in that trusted context commonly leads to "pwn request" vulnerabilities. To opt in, review the risks at https://gh.io/securely-using-pull_request_target and set 'allow-unsafe-pr-checkout: true' on the actions/checkout step.

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

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Oct 5, 2026
@shoumikhin
shoumikhin marked this pull request as ready for review October 6, 2026 02:25
Copilot AI balanced review requested due to automatic review settings October 6, 2026 02:25

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@shoumikhin
shoumikhin force-pushed the cuda-allocator-alignment branch from b31f29c to 6c6526a Compare October 6, 2026 02:42
Copilot AI balanced review requested due to automatic review settings October 6, 2026 02:42

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@shoumikhin shoumikhin changed the title Let the CUDA allocator return memory aligned past 256 bytes Let the CUDA allocator return memory aligned to 512 bytes Oct 6, 2026

@digantdesai digantdesai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The reworked version (512 limit, three new tests) looks right to me. Zero is still rejected before the mask, and the limit only applies to the synchronous cudaMalloc path (allocate_async takes no alignment). The device is restored before the alignment check, and a misaligned block is freed. I found no in-tree caller that passes a non-default alignment or depends on the old MemoryAllocationFailed from that path.

Two things before this lands:

ROCm. cuda_allocator.cpp is compiled into aoti_cuda_shims under EXECUTORCH_BUILD_ROCM, and the 512 limit applies there unguarded. .ci/scripts/test-rocm-aoti.sh builds test_cuda_allocator and runs it via ctest -R 'test_cuda_(allocator|mutable_state)'. AllocateWith512ByteAlignmentSucceeds isn't HIP-guarded, but unittest-rocm-gfx950 is skipped on fork PRs, so it hasn't run against hipMalloc. If hipMalloc packs small blocks on 256-byte steps, that job goes red on main after merge. Production stays safe either way, since the post-check returns NotSupported. Could you add ciflow/rocm to get a run, or skip the 512 test under EXECUTORCH_USE_HIP with a TODO until it has run?

Test stand-in pass-through. Once the weak cudaMalloc/cudaFree take effect, every allocation in the test binary goes through them. real comes from dlsym(RTLD_NEXT, ...) without a null check. The "weak keeps the real ones under static cudart" reasoning depends on the archive member holding cudaMalloc being pulled in for other reasons. A linker won't extract a member just to override an existing weak definition. If that ever happens, every test segfaults instead of the misalignment test skipping. A null check that returns cudaErrorUnknown (or aborts with a message) would make that readable.

Minor: the comment at the alignment check repeats the "measured, not documented" point from the comment on the limit just above it. One of them could go.

Copilot AI balanced review requested due to automatic review settings October 6, 2026 04:18
@shoumikhin
shoumikhin force-pushed the cuda-allocator-alignment branch from 6c6526a to 85a45e7 Compare October 6, 2026 04:18

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@Gasoonjia

Gasoonjia commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

My concern is if the 512 alignment will be unified supported in different GPUs, including Nvidia and ROCm gpus.

For example for nvidia gpus: https://docs.nvidia.com/cuda/archive/12.9.0/cuda-c-programming-guide/index.html#device-memory-accesses states that:

Any address of a variable residing in global memory or returned by one of the memory allocation routines from the driver or runtime API is always aligned to at least 256 bytes.

which 512 is not guaranteed.
If possible, I'd prefer allocate more memory and do address round up instead up bump up the alignment

CudaAllocator::allocate refused alignments above 256 bytes. TensorRT asks
for 512 when loading an engine, but CUDA guarantees only 256. Reserve extra
memory and round up so larger alignments do not depend on GPU allocation
packing.

| Requested alignment | Before | After |
| --- | --- | --- |
| Power of two, up to 256 bytes | Allocates | Allocates without padding |
| Power of two, above 256 bytes | NotSupported | Allocates with padding |
| Zero or not a power of two | InvalidArgument | InvalidArgument |

Above 256, reserve alignment minus one extra bytes and round the pointer
up. Reject size overflow with InvalidArgument before any CUDA call. Record
only rounded pointers in a private map, and free their original pointers
on deallocation. A mutex protects the map. An atomic count avoids that
lock when no rounded pointers are live.

Keep the pointer safety check for alignments up to 256. A misaligned block
is freed and rejected with NotSupported instead of MemoryAllocationFailed.
Async allocation and pools are unchanged. Remove the ROCm alignment skip.

Tested on Linux x86_64 with H100 and CUDA 12.8: 20 allocator tests passed,
including mixed live blocks at 512 and 4096 byte alignment over 64 cycles,
concurrent allocation, overflow boundaries, and exact original pointer
frees through weak CUDA stand ins. Compute Sanitizer reported zero memory
errors and leaks, excluding intentional invalid device API error reports.
The previous allocator fails four regression tests; restoring this
implementation passes the full suite. ROCm and Windows were not built or run.
Copilot AI balanced review requested due to automatic review settings October 6, 2026 05:14
@shoumikhin
shoumikhin force-pushed the cuda-allocator-alignment branch from 85a45e7 to e65f487 Compare October 6, 2026 05:14
@shoumikhin shoumikhin changed the title Let the CUDA allocator return memory aligned to 512 bytes Let the CUDA allocator honor any power of two alignment Oct 6, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@shoumikhin

Copy link
Copy Markdown
Contributor Author

The allocator now adds padding and rounds up for alignments above 256 bytes. It remembers the original pointer for deallocation and checks for size overflow before any CUDA call. This removes the 512 byte cap and the dependence on how a GPU packs its blocks. Alignments up to 256 are unchanged.

The 512 and 4096 byte tests pass on H100, and memory checking found no errors or leaks. ROCm has not been run yet.

@Gasoonjia

Copy link
Copy Markdown
Contributor

Thanks it LGTM.
I will defer to @digantdesai for final stamp.

@Gasoonjia

Copy link
Copy Markdown
Contributor

stamp to unblock

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/cuda ciflow/rocm CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. release notes: backends

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants