DeepSpeed icon indicating copy to clipboard operation
DeepSpeed copied to clipboard

[REQUEST] OPSD Profile and improve HybridEngine rollout performance

Open nathon-lee opened this issue 4 months ago • 19 comments

Is your feature request related to a problem? Please describe.

For OPSD/OPD training, each iteration includes student rollout generation, teacher forward and logit caching, and student forward/distillation loss computation.

The HybridEngine-backed rollout implementation introduced in #8027 provides a useful foundation for on-policy distillation. However, the performance characteristics of the rollout path are not yet well understood. Rollout generation may become a significant part of the total training time, especially with:

  • ZeRO-3
  • Multiple samples per prompt
  • Long prompts or responses
  • HybridEngine inference-cache management
  • Training/inference mode transitions
  • LoRA fuse/unfuse operations

A small and reproducible profiling baseline would help identify the actual bottlenecks before making broader changes to HybridEngine or the OPSD trainer.

This proposal is also related to the OPSD work listed in the Q3 roadmap (#8104).

Describe the solution you'd like

I would like to add a lightweight profiling or benchmark utility for the HybridEngine-backed OPSD rollout path.

The initial benchmark could measure the following components where practical:

  • Prompt expansion
  • Prefill
  • Decode
  • HybridEngine parameter gathering
  • Inference-cache acquisition and release
  • LoRA fuse/unfuse, when enabled
  • Attention-mask construction
  • Rollout output post-processing
  • End-to-end rollout latency

The benchmark could report:

  • End-to-end rollout latency
  • Rollout tokens per second
  • Prefill and decode latency
  • Post-processing latency
  • Cache-management latency
  • Peak memory usage
  • Optionally, total OPSD step time

The first version should remain intentionally small and easy to reproduce. It could use a small causal language model and a limited smoke-test matrix, for example:

Parameter Example values
Batch size 1, 4
Samples per prompt 1, 4
Prompt length 128, 512
Response length 32, 128
Decoding Greedy and sampling
ZeRO stage Stage 0 and Stage 3, if practical

The initial contribution would focus on profiling and benchmarking rather than optimizing multiple components at once. After reviewing the measurements with the maintainers, one measurable bottleneck could be selected for a targeted optimization.

One possible candidate is the post-processing path in HybridEngineRollout.generate(). When n_samples_per_prompt > 1, prompts are expanded with repeat_interleave(), while the prompt portion of the output attention mask is currently populated using a Python loop. If profiling shows that this is a meaningful cost, it may be replaceable with a batched tensor operation.

Any such optimization should preserve:

  • Single-sample behavior
  • Multiple samples per prompt
  • Left-padded prompts
  • Variable prompt attention masks
  • EOS and padding behavior
  • response_start_idx
  • ZeRO-3-backed HybridEngine execution

Correctness tests should cover:

  1. Single-sample rollout
  2. Multiple samples per prompt
  3. Left-padded prompts
  4. Partially masked prompts
  5. Prompt and attention-mask alignment
  6. EOS and padding behavior
  7. Equivalence between the reference and optimized post-processing paths

Describe alternatives you've considered

Rather than modifying HybridEngine broadly without measurements, I would prefer a profiling-first approach.

Potential follow-up areas include:

  • Reusing the HybridEngine inference workspace across compatible rollout calls
  • Reducing unnecessary cache release and re-acquisition operations
  • Avoiding unnecessary gc.collect() or empty_cache() calls on hot paths, where safe
  • Reducing repeated LoRA fuse/unfuse work
  • Improving sampled-decode performance
  • Measuring the complete OPSD training step instead of the rollout path alone

These are possible directions rather than commitments for the initial contribution. I would be happy to narrow the scope based on maintainer feedback.

Additional context

This proposal is intended as a profiling and benchmark follow-up to #8027. A possible incremental implementation plan is:

  1. Add a small profiling or benchmark utility.
  2. Add correctness coverage for relevant rollout edge cases.
  3. Share initial measurements and identify the highest-priority bottleneck.
  4. Implement one targeted optimization, if appropriate.
  5. Add before/after measurements and document the results.

I would appreciate guidance on the following:

  1. Would this profiling-first follow-up to #8027 be useful?
  2. Is there a preferred model and hardware configuration for the initial benchmark?
  3. Should the first contribution focus on the rollout path or the complete OPSD training step?
  4. Are there known HybridEngine bottlenecks that should be prioritized, such as ZeRO-3 parameter gathering or inference-cache management?
  5. Would maintainers prefer standalone benchmark timing or optional instrumentation inside the rollout implementation?

Thank you for considering this proposal. I would be happy to start with the smallest useful benchmark and adjust the scope based on maintainer feedback.

nathon-lee avatar Jul 31 '26 09:07 nathon-lee

Hello, @PKUWZP @delock when you have a chance, could you please review this proposal and let me know whether the profiling-first approach would be useful? I’d be happy to narrow the scope and adjust the implementation based on the maintainers’ feedback.

Thank you for your time and guidance.

nathon-lee avatar Jul 31 '26 09:07 nathon-lee

Hi @nathon-lee , very glad you bring this up. Yes I agree profiling first is a systematic way of performance optimization rather than randomly looking for low hanging fruit. HybridEngineRollout has way to go, and it dominates OPSD time especially when sequence length is long, so I agree to start from HybridEngineRollout.

For your questions:

  1. Model selection: a small dense model <10B might be a good choice as starting point. Models like 0.5B in the example is too small and can only demostrate functionality. Model of size 7/8B would be a viable smallest model.
  2. Profiling in rollout stage might be better than a standalone benchmark, this would be what I preferred.
  3. I think for small model use case, KV cache management is of priority, especially when 1pNr (1 prompt, multiple rollouts) is used in RL pipeline. Zero3 parameter gathering should be the topic when we go to larger models.

@PKUWZP to leave more comments.

Again, very glad to see your proposal and have you to co-work on this! We can discuss in this thread, or discuss on one of our developer meetings hours, let us know which one works for you better, thanks!

delock avatar Aug 01 '26 03:08 delock

Following this one, would be great to see it addressed.

goransh-walia avatar Aug 02 '26 06:08 goransh-walia

Hi @nathon-lee any update on this? If you have some initial data to share that will be great! Let me know if I can help on this.

delock avatar Aug 20 '26 23:08 delock

@delock Hi Delock, sorry for the delay! Work has been quite busy recently, so I haven’t had a chance to make much progress on this. I’ll spend some time on it this weekend and should have some initial data to share with you then. Thanks for checking in, and I really appreciate your offer to help!

nathon-lee avatar Aug 21 '26 02:08 nathon-lee

I implemented an initial profiling-first baseline for the HybridEngine-backed OPSD rollout path.

Implementation branch: https://github.com/nathon-lee/DeepSpeed_woo/tree/perf/opsd-hybridengine-profil

Current scope:

  • Opt-in stage-level profiling in HybridEngineRollout
  • Prompt expansion timing
  • Generation timing
  • Post-processing timing
  • End-to-end rollout latency
  • Tokens-per-second measurement
  • Peak memory reporting
  • A reproducible single-process, single-GPU Stage-0 benchmark
  • Raw profiles plus mean, p50, and p95 summaries

Test environment:

  • GPU: NVIDIA RTX A4500
  • Compute capability: 8.6
  • GPU memory: 20,470 MiB total
  • NVIDIA driver: 580.159.04
  • PyTorch: 2.9.1+cu128
  • CUDA runtime: 12.8
  • Transformers: 4.40.2
  • DeepSpeed checkout: /workspace/DeepSpeed_woo
  • Device: cuda:0
  • World size: 1
  • Model: facebook/opt-6.7b
  • Dtype: fp16
  • ZeRO stage: 0
  • Warmup: 1
  • Iterations: 2 per isolated workload

The following workload combinations completed successfully. Each workload was executed in an isolated process to avoid sharing CUDA and HybridEngine state across different sequence shapes:

  • Samples per prompt: 1, prompt: 128, response: 32
  • Samples per prompt: 1, prompt: 128, response: 128
  • Samples per prompt: 1, prompt: 512, response: 32
  • Samples per prompt: 1, prompt: 512, response: 128
  • Samples per prompt: 4, prompt: 128, response: 32
  • Samples per prompt: 4, prompt: 128, response: 128
  • Samples per prompt: 4, prompt: 512, response: 32
  • Samples per prompt: 4, prompt: 512, response: 128

Observed baseline:

Samples per prompt Prompt length Response length Total latency Throughput Peak memory
1 128 32 1106.34 ms 28.92 tokens/s 12.95 GB
1 128 128 4405.76 ms 29.05 tokens/s 12.95 GB
1 512 32 1214.51 ms 26.35 tokens/s 12.99 GB
1 512 128 4574.83 ms 27.98 tokens/s 12.99 GB
4 128 32 1229.75 ms 104.09 tokens/s 12.99 GB
4 128 128 4614.13 ms 110.96 tokens/s 12.99 GB
4 512 32 1594.82 ms 80.26 tokens/s 13.14 GB
4 512 128 5188.53 ms 98.68 tokens/s 13.14 GB

Initial observations:

  • Generation dominates the end-to-end rollout latency.
  • Prompt expansion and post-processing are currently negligible compared with generation.
  • Increasing samples per prompt improves aggregate throughput substantially.
  • Scaling efficiency decreases with longer prompts, especially when samples per prompt is increased.
  • Peak allocated memory remained approximately 12.95–13.14 GB for these workloads.
  • No standard CUDA out-of-memory error was observed in the successful isolated runs.

One additional behavior needs further investigation. Running the complete workload matrix sequentially in the same process intermittently triggered a CUDA illegal-instruction error, while running each workload in an isolated process succeeded. This means that the current results establish per-workload correctness and performance baselines, but do not yet establish that arbitrary shape transitions are stable within one long-lived HybridEngine process.

Proposed next steps:

  1. Improve benchmark diagnostics by logging each case before execution and persisting completed results incrementally.
  2. Preserve failed-case metadata and traceback instead of discarding all earlier results.
  3. Split generation timing into prefill and decode components.
  4. Measure inference-cache acquisition, release, and reuse overhead.
  5. Re-run the benchmark with longer warmup and more iterations after the diagnostic improvements.
  6. Select one targeted optimization based on the measurements.

The current implementation and measurements cover the single-GPU, ZeRO-0 rollout path only. ZeRO-3 parameter gathering, LoRA fuse/unfuse overhead, inference/training mode transitions, and full OPSD step timing are not covered yet.

At this stage, I would treat this as a profiling and baseline contribution rather than a completed optimization. The data indicates that generation/decode is the first optimization target, while post-processing is not currently a material bottleneck.

nathon-lee avatar Aug 22 '26 04:08 nathon-lee

A follow-up cache-management experiment exposed two additional issues on the same RTX A4500 environment.

With release_inference_cache disabled, the isolated workload (samples_per_prompt=4, prompt=512, response=128, warmup=5, iterations=20) completed with:

  • total latency: 5215.66 ms
  • generation latency: 5215.40 ms
  • throughput: 98.17 tokens/s
  • peak allocated memory: 13144.6 MB

With release_inference_cache enabled, execution failed during the first warmup call in retake_inference_cache(). Accessing self.workspace resulted in recursive DeepSpeedEngine.getattr() calls and eventually a RecursionError. Therefore, a keep-vs-release performance comparison is not available yet.

The same-process multi-shape matrix also reproduced fused-kernel execution error 13, including GEMM shapes with n=512. Since all workloads complete successfully in isolated processes, this appears related to workspace/cache or fused-kernel state across shape transitions rather than a fixed unsupported workload or a standard CUDA OOM.

I plan to add per-case logging and incremental result persistence first, then add a focused regression test for release_inference_cache before attempting a cache-lifecycle fix.

nathon-lee avatar Aug 22 '26 07:08 nathon-lee

Follow-up profiling update:

I completed a formal keep-vs-release inference-cache comparison for the same single-GPU Stage-0 workload.

Test environment:

  • GPU: NVIDIA RTX A4500, 20 GB
  • PyTorch: 2.9.1+cu128
  • CUDA runtime: 12.8
  • Transformers: 4.40.2
  • Model: facebook/opt-6.7b
  • Dtype: FP16
  • World size: 1
  • Batch size: 1
  • Samples per prompt: 4
  • Prompt length: 512
  • Response length: 128
  • Warmup: 5
  • Measured iterations: 20

With inference-cache retention enabled:

  • Mean total latency: 5176.89 ms
  • Mean generation latency: 5176.63 ms
  • Mean throughput: 98.90 tokens/s
  • Peak allocated memory: 13144.6 MB

With inference-cache release enabled:

  • Mean total latency: 5328.75 ms
  • Mean generation latency: 5328.29 ms
  • Mean throughput: 96.09 tokens/s
  • Cache retake: 1.54 ms
  • Cache release: 167.37 ms
  • Peak allocated memory: 13144.6 MB

For this workload, releasing and reacquiring the inference cache adds approximately 151.86 ms per rollout, or 2.93% end-to-end latency. The retake operation is small; most of the cache-management overhead is in the release path.

The measurements also confirm that model generation is the dominant rollout cost, accounting for approximately 97% of end-to-end latency.

The next profiling step is to split generation into prefill and decode timing, and to split cache release into workspace release, Python garbage collection, and allocator cache cleanup. I will use those measurements to select one targeted optimization.

This remains a single-GPU, ZeRO-0 rollout baseline. ZeRO-3 parameter gathering, LoRA fuse/unfuse, and complete OPSD step timing are not covered yet.

The workspace attribute lookup issue discovered during cache-release testing is tracked separately in PR #8288.

nathon-lee avatar Aug 22 '26 09:08 nathon-lee

Hi @nathon-lee thanks for taking your weekend time to work on that. Appreciate!

Agree that rollout time will dominate OPSD profile time and our future optimization shall focus on it. Scaling efficiency decrease with longer prompts (and I see with batch=4) may mean longer prompts take longer time to process (prefill time).

Let me review #8288 first then take a look at your profile branch. Thanks!

delock avatar Aug 22 '26 15:08 delock

Hi @delock, thank you for the encouragement and for taking the time to review this work.

A quick progress update: I have split the work into two clean branches to keep the reviews focused:

  • Profiling baseline: https://github.com/nathon-lee/DeepSpeed_woo/tree/perf/opsd-hybridengine-profil-clean
  • Shared-prefill optimization: https://github.com/nathon-lee/DeepSpeed_woo/tree/feat/opsd-shared-prefill-clean

The preliminary A/B test used an NVIDIA RTX A4500, PyTorch 2.9.1+cu128, Transformers 4.40.2, and OPT-6.7B FP16, with batch size 1, 4 rollouts per prompt, prompt length 512, response length 32, 5 warmup iterations, and 20 measured iterations.

Sharing the prompt prefill across the four rollouts produced:

  • Prefill latency: 443.98 ms → 132.78 ms (-70.1%)
  • End-to-end latency: 1327.07 ms → 1011.62 ms (-23.8%)
  • Throughput: 96.45 → 126.53 tokens/s (+31.2%)
  • Additional peak memory: approximately 34 MiB

The focused test suites are passing locally. I plan to submit the profiling changes as PR #8295 first, followed by the shared-prefill optimization as a separate PR (#8296), so that each change can be reviewed independently.

Thanks again for your guidance!

nathon-lee avatar Aug 23 '26 03:08 nathon-lee

I can contribute an independent multi-GPU evidence extension without touching the profiling or shared-prefill implementation that @nathon-lee owns. I have access to 2–4 NVIDIA A100 80 GB GPUs.

To keep ownership and the comparison boundary clean, I would start from an exact upstream master head only. I would not benchmark or modify #8296 unless its author or a maintainer explicitly asks for that comparison.

Proposed bounded ZeRO-3 baseline:

  • facebook/opt-6.7b, FP16, batch size 1
  • data-parallel world sizes 2 and 4 with inference_tp_size=1 (not TP=world-size)
  • deterministic greedy matrix: samples per prompt {1, 4}, prompt length {128, 512}, response length {32, 128}
  • 5 warmups and 20 measured iterations per isolated cell
  • run the largest effective shape first, matching the HybridEngine workspace first-forward requirement
  • after isolated cells pass, one fixed long-lived shape-transition sequence to probe the previously observed transition-only illegal instruction

I would report only metrics supported by the merged #8295 instrumentation: prompt expansion, generation, post-processing, total latency, throughput, and peak memory. For multi-rank results, total latency would be the maximum rank latency; throughput would use summed generated non-padding positions divided by that max-rank latency, with per-rank values retained. Peak allocated/reserved memory would be reset after warmup and reported as the cross-rank maximum. Prefill/decode and cache-lifecycle breakdowns would remain future work unless the required instrumentation lands first.

Correctness and spend gates:

  • identical deterministic prompts on every rank and an assertion that every rank produces the requested response length before accepting a timing cell
  • 120-second subprocess watchdog; any rank timeout collects all rank logs and stops the matrix
  • do not work around EOS divergence with eos_token_id=None, because that changes generation semantics and overlaps #8264
  • write case metadata before launch and append each result immediately
  • on the first long-lived transition failure, stop and only rerun that transition in isolation
  • record exact DeepSpeed/PyTorch/CUDA/driver versions plus nvidia-smi topo -m; do not combine PCIe and NVLink results
  • first run a 2-GPU gate with a 90-minute wall-clock cap; two failed environment/JIT prewarms or any correctness failure stops before 4 GPUs
  • hard cap of 12 A100 GPU-hours including setup, JIT, and downloads

Would raw exact-head evidence in this issue be most useful, or would you prefer a benchmark-matrix extension only after the measurements? I will keep this evidence-only unless you request otherwise.

FU-max-boop avatar Aug 26 '26 03:08 FU-max-boop

Thanks, @FU-max-boop this would be a useful independent extension. Please start with the raw exact-head evidence and the 2-GPU gate; there is no need to prepare a benchmark-matrix extension yet. Please keep this separate from #8296, since the current shared-prefill path has a different support boundary. Preserving normal EOS behavior and retaining both per-rank results and clearly labeled aggregate DP throughput sounds good. Once the results are available, please share them in this issue. We can review them alongside the current profiling and shared-prefill work, then align the next step with the maintainers.

nathon-lee avatar Aug 26 '26 05:08 nathon-lee

2-GPU gate update: this run produced no performance result.

I ran the fail-closed environment/bootstrap gate on 2x A100 PCIe 40 GB with exact DeepSpeed 92843ad7, DeepSpeedExamples 9311692, and facebook/opt-6.7b at revision a45aa65bbeb77c1558bc99bedc6779195462dab0. Exact checkout/clean-tree verification, model download, offline cache validation, and bootstrap all passed.

Both permitted environment/JIT prewarm attempts then failed before any benchmark cell launched. The base-environment PYTHONPATH caused typing_extensions 4.12.2 to take precedence over the venv copy (4.16.0), so pydantic_core could not import Sentinel. Per the stated contract, I stopped after the second identical prewarm failure:

  • isolated matrix cells run: 0
  • transition probe run: no
  • timing / throughput / memory claims: none
  • 4-GPU escalation: no

The instance was released after 47 minutes, well inside the cap. This is an environment-boundary failure, not evidence about HybridEngine or ZeRO-3 behavior. A future gate needs a clean interpreter boundary plus a preflight that imports pydantic_core and confirms the venv typing_extensions path before DeepSpeed JIT.

FU-max-boop avatar Aug 28 '26 06:08 FU-max-boop

Follow-up to the fail-closed environment result above: after correcting the interpreter boundary, I completed the exact-head 2-GPU gate.

Accepted run: run-20260828T103013Z-formal2 — PASS

  • Hardware: 2 x NVIDIA A100 PCIe 40 GB
  • Model/path: facebook/opt-6.7b, FP16, ZeRO-3 data parallel (world_size=2, inference_tp_size=1), shared-prefill path disabled
  • PyTorch: 2.7.0+cu128
  • DeepSpeed: 92843ad706067f0ab551a06a079a8923dcde27b4
  • DeepSpeedExamples: 931169269a844a44a4c6cb97d9f563b42852d736
  • Matrix: samples per prompt {1, 4} x prompt length {128, 512} x response length {32, 128}, with 5 warmups and 20 measured iterations per isolated cell

The standalone receipt verifier accepted:

  • 8/8 isolated matrix cells
  • 320 rank-level measured-iteration records (8 cells x 20 iterations x 2 ranks)
  • all 8 steps of the long-lived shape-transition sequence
  • fixed response widths and start indices, binary response masks, and rank-to-rank deterministic equality

None of the 320 measured rank records or 16 transition rank records contained a generated EOS (rows_with_eos=0). The verifier includes conditional first-EOS/post-EOS checks, but this A100 run did not empirically exercise those branches.

Mean isolated-cell results are below. DP throughput is summed generated non-padding positions across ranks divided by max-rank total latency; peak memory is the cross-rank maximum after the warmup reset.

samples/prompt prompt response mean total (ms) mean DP tok/s peak allocated (MiB) peak reserved (MiB)
4 512 128 6187.00 165.51 19478.76 19710.00
4 512 32 2167.69 118.10 19478.76 19710.00
4 128 128 6056.85 169.06 19332.29 19382.00
4 128 32 2020.87 126.68 19332.29 19382.00
1 512 128 5998.87 42.67 19332.24 19384.00
1 512 32 2032.37 31.49 19332.24 19384.00
1 128 128 5949.85 43.03 19294.53 19336.00
1 128 32 1990.30 32.16 19294.53 19336.00

The transition sequence completed without reproducing the fused-kernel illegal-instruction failure previously observed on the RTX A4500. This is evidence for this bounded A100 configuration, not a claim that arbitrary HybridEngine shape transitions are universally stable.

The accepted receipt preserved budget accounting from its original start epoch: 4,446.02 seconds (2.47 A100 GPU-hours) and an estimated continuous cost of CNY 6.92 through receipt/verifier completion, within the 5,400-second / CNY 8.40 gate-local execution cap. Including the earlier released 47-minute attempt, this was approximately 4.04 A100 GPU-hours through accepted-receipt completion. These receipt-local figures exclude the later evidence transfer and intentional instance retention for closeout. After the evidence was safely copied and verified, MatrixCloud confirmed release of this formal instance at a final CNY 16.61 for 2 hours 58 minutes; that portal bill is reported separately from gate runtime.

For transparency, within this rerun the first formal attempt failed immediately because the venv preflight could not locate the base-image PyTorch distribution on its sys.path (found 0). It launched no benchmark cells or transition probe and produced no GPU performance data. I corrected the interpreter/environment boundary without resetting the original budget epoch, then ran the complete accepted gate above.

I raised the per-cell subprocess watchdog from the initially proposed 120 seconds to 360 seconds before the accepted run because valid OPT-6.7B cells exceeded 120 seconds; the unchanged 90-minute hard cap still governed the whole gate.

EOS scope is narrower than the verifier's conditional checks: the pinned upstream path—not the harness—passes eos_token_id=None internally for ZeRO-3 collective alignment and post-processes with _pad_after_eos(). Because no recorded output emitted EOS, this gate validates only the no-EOS returned-output branch; it establishes neither actual first-EOS post-processing nor native early-stop compute semantics.

Privacy-reviewed public evidence subset (verifier report, gate contract, all eight per-cell results, and transition result): https://gist.github.com/FU-max-boop/94ed398e43ce672de283f3cd43f71c8e

The original receipt and per-rank JSONL are retained locally but are not mirrored in the public gist because they contain machine-local paths and an obsolete cloud-instance identifier. The original commitments are preserved below; the public subset alone is not sufficient to rerun the full fail-closed verifier. I can provide the complete original tree separately if a maintainer needs a full independent audit.

Evidence hashes:

  • Original raw evidence archive SHA-256: dd9aa8ab4a68a07b33c6ba1019f4e727d503bf63c036c3dca5d1bba6ba5e0e07
  • Accepted receipt.json SHA-256: 24eda7a94367f92ed3257ebe45465eedfc88c2831a1ab136173c216cb57f7019
  • Accepted verification_report.json SHA-256: 8ed0ceb2192ae37e5197a7431d3bd36410a3fb9b936c5107f1d6b6486a09c193

I am treating this as an independent exact-head correctness/stability extension only; it does not benchmark or modify #8296.

FU-max-boop avatar Aug 28 '26 11:08 FU-max-boop

Thanks @FU-max-boop, this is useful independent ZeRO-3 baseline evidence. I’ll treat it as validation of the exact-head ZeRO-3 path only, since shared prefill was disabled and the run did not empirically exercise EOS handling. With #8295 and #8296 now merged, I propose adding one focused, default-off profiling follow-up to split generation into prefill forward, decode forward, and remaining generation overhead. After that, we can use the measurements to decide whether ZeRO-3 shared-prefill support should be a separate follow-up. @delock, does this sound like the right next scope?

nathon-lee avatar Aug 28 '26 11:08 nathon-lee

Hi,@delock. I’ve also been looking at rollout optimizations in vLLM and SGLang. For the current OPSD prototype, I’m wondering whether we should keep StaticCache as the correctness baseline and first focus on profiling, cache lifecycle, and batch-variant kernel optimizations.
Paged/prefix caching, speculative decoding, and low-precision computation seem promising, but they may require broader changes to the cache interface, logprob handling, and weight-update lifecycle. Would this staged direction fit the intended scope of the OPSD rollout work?

nathon-lee avatar Sep 07 '26 08:09 nathon-lee

Additional real-model validation of the existing HybridEngine rollout/profiling implementation at 8950dc33219042995faa96980c25468e2dfd4efd, using one NVIDIA L20:

  • Locally initialized tiny OPT, FP16, actual HybridEngine/native inference kernels, ZeRO-0; Transformers 4.44.2.
  • Eight configurations: samples {1,4}, prompt lengths {128,512}, response limits {32,128}. 112 measured generation calls, including 32 train/eval and shape transitions; 136 total calls including warmups/references.
  • Output tokens and attention masks matched each configuration's profiling-disabled reference exactly. Profiling fields were finite with valid timing ordering. Live allocation across all 32 transitions stayed at 9,876,992 bytes (observed range zero).

Compatibility failures remain: Transformers 5.14.1 fails in injected OPT forward with AttributeError: 'tuple' object has no attribute 'size'; 4.51.3 fails in legacy-cache conversion with ValueError: too many values to unpack (expected 2). Neither is fixed by this validation. Only the 4.44.2 baseline passed.

This exercises repeated tiny-model generation, not hours-long soak testing, full-size model throughput, ZeRO-3 rollout, or LoRA fusion. No duplicate profiling implementation or source patch was added.

Related regression suite: 34 distinct cases passed (33 rollout/profiling cases plus the native FP16 reverse-cache-copy test after supplying the missing CUDA profiler header). This validates the existing work in #8295, #8296, #8350, #8368 and #8494; it is not a new optimization. The unit/native suite used Transformers 5.14.1; the real-model compatibility limitations described above still apply.

0z5a avatar Sep 15 '26 02:09 0z5a

Hi @nathon-lee,

  • Could you have a look on https://github.com/deepspeedai/DeepSpeed/pull/8839, can this help optimize OPSD rollout! Thanks

jinyouzhi avatar Oct 17 '26 06:10 jinyouzhi

Static graph path (use_graph_capture=True) cannot capture on Transformers 4.57.6 + SDPA

On current master (8a47f989), HybridEngineRollout with use_graph_capture=True and greedy sampling fails on the first generate() call when it takes the static path (_generate_graph, i.e. no continuous_batch_size). The captured decode forward receives the 2-D attention_mask. Qwen3 builds its causal mask through masking_utils.create_causal_mask → sdpa_mask_recent_torch → _ignore_causal_mask_sdpa, which evaluates padding_mask.all() on the host. That synchronizes the capturing stream:

  File ".../transformers/masking_utils.py", line 254, in _ignore_causal_mask_sdpa
    padding_mask.all()
torch.AcceleratorError: CUDA error: operation not permitted when stream is capturing
Search for `cudaErrorStreamCaptureUnsupported' ...
...
torch.AcceleratorError: CUDA error: operation failed due to a previous error during capture
Search for `cudaErrorStreamCaptureInvalidated' ...

Repro: one GH200 (96 GB), Qwen3-8B bf16, ZeRO-0, attn_implementation="sdpa", torch 2.14.1+cu130, Transformers 4.57.6. Use HybridEngineRolloutConfig(use_graph_capture=True) and SamplingConfig(temperature=0, max_new_tokens=8) with one 512-token prompt. It failed on both runs, two days apart; with CUDA_LAUNCH_BLOCKING=1 the first failing call is the padding_mask.all() above. The failed capture also poisons the CUDA context, so later calls in the same process fail too: a sweep that reuses one engine reports every cell as failed. Other Transformers versions were not tested.

Why the continuous path is fine: #8732 hands its captured forward a pre-allocated 4-D additive mask, so Transformers' mask construction is skipped. #8602 also rewrites _generate_graph and passes a 4-D (boolean) mask there, so this gets fixed as a side effect when #8602 lands.

Root-cause check: on the same setup, giving the static path's captured forward a pre-built 4-D mask (the #8732 approach) makes capture succeed. All 12 cells of the grid then run: prompts {1, 4, 8} × samples {1, 4} × (prompt, response) {(512, 128), (2048, 256)}, 68–896 tok/s, TPOT 9.7–67.7 ms. These timings include a fresh capture in every generate() call.

Outputs against the eager path:

  • 100 of 130 rows are token-identical.
  • At the 30 first-divergence points, the two candidate tokens differ by a median of 0.08 fp32 logits (max 0.33) at logit values of 10–41. Measured in bf16 rounding steps at that magnitude, that is a median of 0.6 and at most 2. fp32 prefers the eager token 16 times and the graph token 14 times, so these are near ties, not a wrong mask.
  • Duplicate samples of the same prompt already disagree with each other in eager mode. The source is the cuDNN SDPA backend: in the two 8×4 cells we rechecked with torch.backends.cuda.enable_cudnn_sdp(False), duplicates agree in both modes, and the remaining eager-vs-graph differences are deterministic per prompt.

Suggestion: land the _generate_graph mask change with #8602, or split it out as a small standalone fix if #8602 will take a while. @delock, whichever you prefer. Until then, static-path graph capture is unusable on Transformers 4.57.6 + SDPA.

Validation was done with AI assistance (Claude Code); I reviewed the logs and the numbers.

0z5a avatar Oct 26 '26 17:10 0z5a