Skip to content

Initial version of mixed precision optimizers - #175230

Closed
vivekgoe wants to merge 8 commits into
pytorch:mainfrom
vivekgoe:mixed_prec_optimizer
Closed

vivekgoe wants to merge 8 commits into
pytorch:mainfrom
vivekgoe:mixed_prec_optimizer

Conversation

@vivekgoe

@vivekgoe vivekgoe commented Feb 18, 2026 •

Copy link
Copy Markdown
Contributor

Added Mixed precision optimizer Fused kernels for Adam/AdamW. Continuation of POC work done by @janeyx99 [Refer to https://github.com//issues/146542#issuecomment-2836583889 for more details].
Motivation for adding these kernels is to provide a path to users to initialize optimizer states for Adam/AdamW in low-precision from user code and use these Fused kernels to achieve reduced device memory foot-print. TorchTitan example here pytorch/torchtitan#2732

Co-authored-by: Jane (Yuan) Xu

@pytorch-bot

pytorch-bot Bot commented Feb 18, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

❌ 2 New Failures

As of commit d5a4e6a with merge base 018bf86 (image):

NEW FAILURES - The following jobs have failed:

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

@vivekgoe

Copy link
Copy Markdown
Contributor Author

Results for DeepSeek-V3-671B training shared here #146542 (comment)

Comment thread torch/optim/optimizer.py Resolved

@crcrpar crcrpar left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I'm not sure AT_DISPATCH macro in mixed precision is necessary

@guangyey guangyey mentioned this pull request Mar 30, 2026
4 tasks
@janeyx99

Copy link
Copy Markdown
Contributor

@claude please review this PR!

@claude

claude Bot commented Mar 30, 2026 •

Copy link
Copy Markdown

Claude finished @janeyx99's task in 5m 14s —— View job


PR Review: #175230

Summary

This PR adds mixed-precision fused CUDA kernels for Adam/AdamW that allow optimizer states (exp_avg, exp_avg_sq, max_exp_avg_sq) to be stored in bfloat16 while params/grads remain in float32, reducing device memory footprint. The approach uses a pre-step hook pattern for state initialization rather than a built-in dtype policy API. The kernel implementation is structurally sound but has several issues worth addressing around code duplication, unnecessary dispatch macros, and restrictiveness.


Code Quality

  1. Massive code duplication across 4 impl files. The mixed-precision branch in fused_adam_impl.cu, fused_adamw_impl.cu, fused_adam_amsgrad_impl.cu, and fused_adamw_amsgrad_impl.cu all contain nearly identical TORCH_CHECK validation blocks (5 checks each, repeated twice per file for the scalar-lr and tensor-lr overloads = 8 copies total). This is the kind of repeated boilerplate that should be extracted into a shared validation function, e.g.:

    void validate_mixed_precision_dtypes(
        TensorList params, TensorList grads,
        TensorList exp_avgs, TensorList exp_avg_sqs,
        const char* op_name);

    Fix this →

  2. Redundant AT_DISPATCH in mixed-precision branches (as @crcrpar and @janeyx99 noted). The TORCH_CHECK immediately above already guarantees params[0].scalar_type() == at::kFloat, so AT_DISPATCH_FLOATING_TYPES_AND2(kHalf, kBFloat16, params[0].scalar_type(), ...) will always resolve to float. The dispatch is dead code for kHalf and kBFloat16. Consider using AT_DISPATCH_SWITCH/AT_DISPATCH_CASE dispatching on the state dtype instead (as the author proposed in the review thread), which would:

    • Make the dispatch meaningful (dispatching on what actually varies)
    • Make it straightforward to add float16 state support later
    • Remove the misleading impression that params can be half/bf16 in this path

    Affected files: fused_adam_impl.cu:51, fused_adam_impl.cu:145, fused_adamw_impl.cu:51, fused_adamw_impl.cu:145, fused_adam_amsgrad_impl.cu:60, fused_adam_amsgrad_impl.cu:163, fused_adamw_amsgrad_impl.cu:60, fused_adamw_amsgrad_impl.cu:163

  3. FusedAdamMathFunctorMP aligned-path code is verbose. The aligned path (fused_adam_utils.cuh:295-430) repeats the pattern if constexpr (!std::is_same_v<scalar_type, X>) { cast element-by-element; load_store } else { load_store } for every tensor type, both for loading and storing. This pattern appears ~10 times. Consider a small template helper that does the cast-and-load-store in one call, which would cut the aligned-path code roughly in half.

Infrastructure

  1. Hardcoded BFloat16 in _group_tensors_by_first_tensors_device_and_dtype (ForeachUtils.h:333). This change allows BFloat16 tensors to be grouped with tensors of any other dtype. This is overly broad — it means any optimizer using this grouping function now silently accepts bf16 tensors mixed in, not just the fused Adam/AdamW kernels. If someone passes bf16 states to an optimizer that doesn't support mixed-precision, the grouping won't catch it. Consider either:

    • Making this configurable (accept a set of allowed state dtypes)
    • At minimum, adding Float16 alongside BFloat16 for consistency (float16 is conspicuously absent)
  2. skip_dtype_check=true disables all dtype validation in check_fast_path_restrictions (FusedAdamKernel.cu:34, FusedAdamWKernel.cu:34). The new overload of check_fast_path_restrictions in ForeachUtils.h:203-208 passes through to _check_tensors_share_device_and_dtype which, when skip_dtype_check=true, skips dtype checking entirely for all tensor lists. This means the fast-path check no longer validates that e.g. all params share the same dtype, or all grads share the same dtype. The validation relies entirely on the TORCH_CHECK in the impl files, which only checks [0] element. If a user passes a mix of float32 and float16 params, the [0]-only check would pass but the kernel would silently misinterpret memory. Consider checking dtype consistency within each tensor list while allowing across-list dtype differences.

API Design

  1. No float16 state support despite the kernel being fully capable. The FusedAdamMathFunctorMP is templated and handles arbitrary type combinations via std::is_same_v checks. The TORCH_CHECK restricts states to bfloat16 only, but there's no technical reason float16 states couldn't work. This is a design choice that should be documented — either extend support to float16 or add a comment explaining why bfloat16-only is intentional.

  2. Hook-based approach puts burden on users. The PR removes the dtype_policy API (per commit e171d41) and replaces it with a pattern where users must manually register a pre-step hook (_bf16_state_init_hook). This is simpler internally but means:

    • Every user must write/copy the hook code
    • There's no built-in discoverability (no API docs to find)
    • The hook is defined only in the test file, not exposed as a utility

    If this is the intended long-term API, consider at minimum exposing the hook as a utility function (e.g., torch.optim.mixed_precision_state_hook or similar) rather than leaving it as test-only code.

Testing

  1. Missing @parametrize for amsgrad. test_fused_mixed_precision_state_init and test_fused_mixed_precision_hook_skips_existing_state both manually loop over amsgrad in (False, True). Use @parametrize("amsgrad", [False, True]) for proper test isolation and naming. If one amsgrad variant fails, the current loop approach makes it harder to identify which variant failed.

  2. Mutable kwargs modification. In test_fused_mixed_precision_numerics (around the optim_inputs loop), kwargs["fused"] = True mutates the original kwargs dict from optim_input. Use kwargs = {**optim_input.kwargs, "fused": True} to avoid side effects on shared state.

  3. 600 parameters unexplained. test_fused_mixed_precision_numerics creates 600 parameters. If this is a stress test for the multi-tensor apply batching, it should be documented. Otherwise 5-10 params would suffice for numerical correctness testing.

  4. Only [0] dtype is validated in C++ kernels. The TORCH_CHECK blocks only validate params[0].scalar_type(), grads[0].scalar_type(), etc. If a user passes a heterogeneous list (e.g., some params float32, others float16), only the first element is checked. The remaining elements could silently produce incorrect results. Consider checking all elements or at least documenting this assumption.

Backward Compatibility

  1. Relaxed grouping in ForeachUtils.h affects all fused optimizers. The change at ForeachUtils.h:331-333 that adds BFloat16 to the dtype allowlist affects _group_tensors_by_first_tensors_device_and_dtype globally. This could change grouping behavior for existing fused optimizer code paths (SGD, Adadelta, etc.) that call this function. The change is likely safe (bf16 tensors won't appear in non-Adam optimizers without user action), but it's a shared-infrastructure change that deserves scrutiny.

  2. Relaxed fast-path restrictions. Changing check_fast_path_restrictions to skip_dtype_check=true for all fused Adam/AdamW calls means the dtype validation is permanently weakened for the non-mixed-precision path too (the else branch). Previously, the check ensured all tensors had matching dtypes. Now it only checks device/stride/size alignment.

Performance

  1. Element-by-element casting in aligned path. In FusedAdamMathFunctorMP's aligned path (fused_adam_utils.cuh:299-306), values are cast one-by-one in a scalar loop before being passed to load_store. For the aligned case, vectorized loads (float4/__nv_bfloat162) followed by batch conversion could be more efficient, though this is an optimization that can be deferred.

Recommendation

Request Changes

Key issues to resolve before merge:

  • Fix the overly permissive skip_dtype_check=true that weakens validation for all paths (item 5)
  • Address the redundant AT_DISPATCH macro usage (item 2) — this was already flagged by reviewers
  • Reduce code duplication across the 4 impl files (item 1)
  • Decide on the user-facing API story: if hooks are the answer, expose the hook as a proper utility (item 7)

@vivekgoe

Copy link
Copy Markdown
Contributor Author

@janeyx99 I have addressed 3/4 changes requested by Claude, regarding 4th I am not sure if we want to expose hook as a proper utility, since in longer term I assume we will have a proper front-end interface. Review comment from @crcrpar is also addressed as part of these changes.

Regarding some other comments listed by Claude,

  • Hardcoded BFloat16 in _group_tensors_by_first_tensors_device_and_dtype
    => we can potentially provide a list of allowed dtypes by passing another argument, but this will need changes in multiple files, some related to torch compile which makes change bit risky, therefore I suggest we skip this in this PR. If it makes sense, I can pick it up in a follow-up PR.
  • FusedAdamMathFunctorMP aligned-path code is verbose
    => I can add this if it makes sense to you.
  • Element-by-element casting in aligned path
    => I can add this if you think this will give any performance benefit.

@vivekgoe
vivekgoe marked this pull request as ready for review March 31, 2026 14:44
janeyx99
janeyx99 previously approved these changes Mar 31, 2026

@janeyx99 janeyx99 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.

thank you! looks good overall, please link benchmark results for memory and perf!

Comment thread aten/src/ATen/native/ForeachUtils.h Resolved
Comment thread test/test_optim.py Resolved
Comment thread test/test_optim.py Resolved
Comment thread test/test_optim.py Resolved
Comment thread test/test_optim.py Resolved
Comment thread test/test_optim.py Resolved
@janeyx99

Copy link
Copy Markdown
Contributor
  • Hardcoded BFloat16 in _group_tensors_by_first_tensors_device_and_dtype: can optimize later, lowpri from my pov
  • FusedAdamMathFunctorMP aligned-path code is verbose: can improve as a followup
  • Element-by-element casting in aligned path: do in followup with benchmarks, this one is the highest pri out of this list

also, please ensure lint and tests pass. It would be nice once this lands to document how to use this in torchtitan to widen visibility

@vivekgoe

vivekgoe commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor Author

@janeyx99 Uploaded another patch with changes as suggested in review comments. 1 of the tests test_fused_mixed_precision_hook_skips_existing_state has been refactored to align more closely to original intent of the test.

Adding some plots giving a picture of Peformance, memory usage and convergence with float32 vs bfloat16 optimize r states for DeepSeek-V3-16B.
optimizer_states_comparison

Please help trigger CI if everything looks ok to you. Thanks.

Comment thread test/test_optim.py
p.grad = torch.rand_like(p)

optim = optim_cls(
[{"params": g1_params}, {"params": g2_params}],

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.

great!

just curious, if this had been one group, i expect there'd be errors because our current group by device + dtype is unaware + wouldn't separate them based on the types of exp_avg+exp_avg_sq, right?

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.

Yes, if this had been 1 group it would have triggered an assert because we do not allow mixed dtypes within a tensorlist (but allow mixing dtypes across tensorlists).

@janeyx99

janeyx99 commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor

Still a bit confusing to me that it appears the code is slower for bf16 vs fp32 in TFLOPs. Did you end up investigating why?

I think the memory perf win is good enough to have this land but it'd be good to understand why it's not faster, even if just slightly

@vivekgoe

vivekgoe commented Apr 3, 2026 •

Copy link
Copy Markdown
Contributor Author

@janeyx99 In the TFlops plot, orange (bfloat16) is always same or slightly higher than blue (float32), it will be difficult to see anything better than this from end-to-end TFlops plots because optimizer is only a small part of compute during an iteration. I will try to take some torch traces to extract optimizer compute times, that will give a better picture.

Some of the CI jobs are failing, does not look related to changes in PR, can you please help confirm it? If there is an issue due to change in PR I will work on fixing it.

@janeyx99

janeyx99 commented Apr 3, 2026 •

Copy link
Copy Markdown
Contributor

@vivekgoe can you rebase? CI failures do not look related/are about calculating docker images which this PR shouldn;t be touching.

And yes it would be good to confirm that the optim step is faster, though yes, slightly higher TFLOPs is a good sign (I had been dumb earlier and misinterpreted the axes)

@vivekgoe

vivekgoe commented Apr 3, 2026 •

Copy link
Copy Markdown
Contributor Author

@janeyx99 I extracted average time for optimizer.step from torch traces (on 8xH100). For float32 it takes 20.59ms whereas for bfloat16 it reduces to 15.29ms, so there is a ~25% reduction, which means we do gain in terms of perf. as well. It's just that for this workload optimizer is not a significant enough contributor to overall compute, therefore it does not show up clearly in end-to-end TFLOP numbers.

Rebased PR now. Thanks.

@vivekgoe
vivekgoe force-pushed the mixed_prec_optimizer branch from a403149 to 34662f8 Compare April 3, 2026 16:17
@janeyx99

janeyx99 commented Apr 3, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Apr 3, 2026
@janeyx99

janeyx99 commented Apr 3, 2026

Copy link
Copy Markdown
Contributor

@vivekgoe can you share the benchmark script in a gist or just a code snippet here?

@atalman

atalman commented Apr 10, 2026

Copy link
Copy Markdown
Collaborator

@pytorchmergebot rebase -b main

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/main. Check the current status here

Introduced a pre-hook to initialize optimizer states in bfloat16 format, allowing for efficient mixed-precision training. Updated tests to verify the correct behavior of the new hook, ensuring it skips already-populated states and maintains dtype consistency across optimizer parameters. Renamed test methods for clarity and improved structure.
Removed the dtype policy logic from the Adam optimizer, streamlining the initialization of state tensors. This change enhances clarity and reduces complexity by directly using the parameter's dtype for state tensors. Additionally, unnecessary dtype checks during the update step have been eliminated, improving performance and maintainability.
Added checks to ensure that parameters and gradients are in float32 while optimizer states are in bfloat16 for mixed-precision training. Updated the fast path restriction checks to allow for mixed-precision states and improved error messages for clarity. Refactored the fused Adam and AdamW implementations to handle these requirements, ensuring compatibility with the new mixed-precision initialization hook. Updated tests to verify the correct behavior of these changes.
Updated the FusedAdam and FusedAdamW implementations to support mixed-precision training by adding a new max_exp_avg_sq_type parameter. Improved state initialization and handling for mixed-precision scenarios, ensuring compatibility with the new requirements. Enhanced tests to verify the correct behavior of mixed-precision state initialization, including checks for max_exp_avg_sq in the optimizer states. Updated error messages for clarity and consistency.
    - Replace redundant AT_DISPATCH_FLOATING_TYPES_AND2 on params dtype with
      AT_DISPATCH_V2 dispatching on state dtype in all 8 mixed-precision sites
      across 4 impl files, since params are already validated as float32
    - Extract shared validate_mixed_precision_dtypes() helper into
      fused_adam_utils.cuh to deduplicate TORCH_CHECK blocks across impl files
    - Rename skip_dtype_check to skip_cross_list_dtype_check and enforce
      within-list dtype homogeneity even in mixed-precision mode; only skip
      cross-list dtype check conditionally when is_mixed_precision is true
    - Fix mutable kwargs bug in test_fused_mixed_precision_numerics
    - Use @parametrize for amsgrad in state_init and hook_skips tests
    - Reduce test params from 600 to 10 in numerics test
    - Document bfloat16-only restriction and [0]-only validation assumption
    - Add TBD comment for making grouping dtypes configurable per optimizer
…W kernels

- Updated the error messages in the TORCH_CHECK statements to clarify requirements for parameter and gradient types.
- Enhanced the check_fast_path_restrictions function by adding a new parameter for skipping cross-list dtype checks.
- Improved documentation regarding the mixed-precision configuration for optimizer states.
- Cleaned up the test cases for mixed-precision state initialization, ensuring consistency and clarity in assertions.
- Updated the test for mixed-precision optimizers to handle two parameter groups with different state dtypes.
- Ensured that the state initialization hook correctly skips already-populated states and initializes others in bfloat16.
- Improved clarity in assertions regarding dtype consistency for both parameter groups during optimizer steps.
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased mixed_prec_optimizer onto refs/remotes/origin/main, please pull locally before adding more changes (for example, via git checkout mixed_prec_optimizer && git pull --rebase)

@pytorch-bot pytorch-bot Bot removed ciflow/binaries Trigger all binary build and upload jobs on the PR ciflow/trunk Trigger trunk jobs on your pull request labels Apr 10, 2026
bobrenjc93 pushed a commit to bobrenjc93/pytorch that referenced this pull request Apr 10, 2026
Added Mixed precision optimizer Fused kernels for Adam/AdamW. Continuation of POC work done by @janeyx99 [Refer to pytorch#146542 (comment) for more details].
Motivation for adding these kernels is to provide a path to users to initialize optimizer states for Adam/AdamW in low-precision from user code and use these Fused kernels to achieve reduced device memory foot-print. TorchTitan example here pytorch/torchtitan#2732

Co-authored-by: Jane (Yuan) Xu <janeyx99>
Pull Request resolved: pytorch#175230
Approved by: https://github.com/janeyx99
@janeyx99

Copy link
Copy Markdown
Contributor

@pytorchbot merge -f "CI failures look preexisting and irrelevant"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged immediately since you used the force (-f) flag, bypassing any CI checks (ETA: 1-5 minutes). Please use -f as last resort and instead consider -i/--ignore-current to continue the merge ignoring current failures. This will allow currently pending tests to finish and report signal before the merge.

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

gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
Added Mixed precision optimizer Fused kernels for Adam/AdamW. Continuation of POC work done by @janeyx99 [Refer to pytorch#146542 (comment) for more details].
Motivation for adding these kernels is to provide a path to users to initialize optimizer states for Adam/AdamW in low-precision from user code and use these Fused kernels to achieve reduced device memory foot-print. TorchTitan example here pytorch/torchtitan#2732

Co-authored-by: Jane (Yuan) Xu <janeyx99>
Pull Request resolved: pytorch#175230
Approved by: https://github.com/janeyx99
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
Added Mixed precision optimizer Fused kernels for Adam/AdamW. Continuation of POC work done by @janeyx99 [Refer to pytorch#146542 (comment) for more details].
Motivation for adding these kernels is to provide a path to users to initialize optimizer states for Adam/AdamW in low-precision from user code and use these Fused kernels to achieve reduced device memory foot-print. TorchTitan example here pytorch/torchtitan#2732

Co-authored-by: Jane (Yuan) Xu <janeyx99>
Pull Request resolved: pytorch#175230
Approved by: https://github.com/atalman
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Added Mixed precision optimizer Fused kernels for Adam/AdamW. Continuation of POC work done by @janeyx99 [Refer to pytorch#146542 (comment) for more details].
Motivation for adding these kernels is to provide a path to users to initialize optimizer states for Adam/AdamW in low-precision from user code and use these Fused kernels to achieve reduced device memory foot-print. TorchTitan example here pytorch/torchtitan#2732

Co-authored-by: Jane (Yuan) Xu <janeyx99>
Pull Request resolved: pytorch#175230
Approved by: https://github.com/janeyx99
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
Added Mixed precision optimizer Fused kernels for Adam/AdamW. Continuation of POC work done by @janeyx99 [Refer to pytorch#146542 (comment) for more details].
Motivation for adding these kernels is to provide a path to users to initialize optimizer states for Adam/AdamW in low-precision from user code and use these Fused kernels to achieve reduced device memory foot-print. TorchTitan example here pytorch/torchtitan#2732

Co-authored-by: Jane (Yuan) Xu <janeyx99>
Pull Request resolved: pytorch#175230
Approved by: https://github.com/atalman
@vivekgoe
vivekgoe deleted the mixed_prec_optimizer branch October 27, 2026 10:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

6 participants