Repository navigation
Conversation
3804227 to
bdb76ef
Compare
What part of the code is specific to FSDP2? It looks pretty generic to me. |
|
yes, you're right. it is actually specific to nccl kernel names, but was tested for FSDP2, maybe works in general. |
tianyu-l
left a comment
There was a problem hiding this comment.
I feel this could be useful, and the code complexity doesn't seem to be crazy.
Meanwhile I would love to see refactor of
- Profiling file into "config build style" following recent refactor, so
ProfilingConfigbecomesProfiler.Config - provide a generic (list of) profile analyzer which this
OverlapAnalyzeris the first example
Let me know if this makes sense or not.
|
@tianyu-l I agree that we can do the quick refractoring for config build style as part of this change. I have updated the PR with this change and added test cases. Let me know if it looks good
|
tianyu-l
left a comment
There was a problem hiding this comment.
Thanks, left some comments.
| self, | ||
| config: "Profiler.Config", | ||
| *, | ||
| analyzers: list[ProfileAnalyzer] | None = None, |
There was a problem hiding this comment.
Let's not put this as part of constructor.
The consistent way to do things is to make OverlapAnalyzer configurable, and have a list of ProfileAnalyzer.Config in Profiler.Config.
We don't have to do it today -- we can just have a singleton self.analyzers list for now.
There was a problem hiding this comment.
I have created a list for now and controlled this via a boolean flag. I have kept the support list[ProfileAnalyzer.Config] in Profiler.Config as TODO for now.
Creating profile analyzers via config leads to cleaner code. In addition to this, having a way for users to control this experimental analysis during execution is helpful too, say via say a CLI flag.
What do you think? We can do this in a followup PR but the current configurable list should be good for now.
| ) as torch_profiler, | ||
| maybe_enable_memory_snapshot( | ||
| config.profiling, | ||
| profiler.enable_memory_snapshot( |
There was a problem hiding this comment.
Instead of calling profiler.enable_profiling and profiler.enable_memory_snapshot, I think we should build the profiler as a container, similar to the LoggerContainer here https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/metrics.py#L178
If this is too much, feel free to leave a TODO here.
There was a problem hiding this comment.
Fixed this so that trainers are simplified
|
@tianyu-l Resolved comments with one TODO |
| Instantiate via ``Profiler.Config.build()`` and use the context-manager | ||
| methods ``maybe_enable_profiling`` and ``maybe_enable_memory_snapshot`` | ||
| in the training loop. |
There was a problem hiding this comment.
I think this solution is over complicated then necessary, as you are trying to reuse the existing context managers, which themselves are already nested.
We should try to flatten everything:
- Profiler itself is a context manager, which defines
__enter__,__exit__, andstep()methods. - torch profiler and memory profiler should be direct children, aka
self.torch_profilerandself.memory_profiler. - Profiler has
build_torch_profilerandbuild_memory_profilerfunctions which return started profiler which we can dostepon. (Here we don't have to use config build style, as they shouldn't change much.)
WDYT? Let me know if you hit difficulties.
There was a problem hiding this comment.
Makes sense. Flattened the structure.
@acisseJZhong Thanks for the suggestion. I indeed missed the overstimation part. To fix both the limitations, I have updated the algorithm to now work on raw events which union the compute and communication time instead of using estimates. This should be accurate and a lot more useful for users. Let me know if this looks good now. I have updated the profiling numbers on 2x H200 using the updated algo. @tianyu-l I have addressed all the comments. Please take a look. (Note: I'll be away from my dev machine for the next 4 weeks, so responses may be delayed.) |
tianyu-l
left a comment
There was a problem hiding this comment.
Thanks, a few more nit comments.
| (distributed run). | ||
| """ | ||
|
|
||
| def __init__(self, config: "Profiler.Config") -> None: |
There was a problem hiding this comment.
| def __init__(self, config: "Profiler.Config") -> None: | |
| def __init__(self, config: Config) -> None: |
|
|
||
| save_memory_snapshot_folder: str = "memory_snapshot" | ||
| """Memory snapshot files location""" | ||
| def active( |
There was a problem hiding this comment.
The existence of active seems unnecessary. Can we merge this into constructor? i.e. constructor would take Config and also the three kwargs here (later we'll do refactor to move them in config as well, don't need to worry about them right now)
There was a problem hiding this comment.
Agreed. Merged active() kwargs into the constructor and removed active().
| ) as memory_profiler, | ||
| ): | ||
| with self.profiler.active( | ||
| global_step=self.step, |
There was a problem hiding this comment.
I don't know why we need global_step, but here it seems a bug that we are sending constant 0.
There was a problem hiding this comment.
Good catch. The construction is now moved after checkpoint load, so self.step reflects the resumed step correctly.
There was a problem hiding this comment.
curious did you not do #2418 (comment) because you wanted to still pass global_step=self.step which is only available at runtime?
I feel it is a previously existing bug to pass global_step=self.step -- what is global_step doing?
There was a problem hiding this comment.
global_step is needed so that when resuming from a checkpoint, trace directories are named correctly (e.g. iteration_100 instead of iteration_0) and
in memoryProfiler the step() method increments step_num and checks step_num % freq != 0 to decide when to dump. Without the correct starting value, snapshot frequency alignment would be wrong after resume
In the current code, self.step is passed after self.checkpointer.load(), so it reflects the loaded checkpoint step correctly.
Does this make sense?
There was a problem hiding this comment.
I see. That makes sense. I didn't know why we need global_step before. Thanks for explaining!
| base_folder=config.dump_folder, | ||
| ) as memory_profiler, | ||
| ): | ||
| with self.profiler.active( |
There was a problem hiding this comment.
continue my last comment, So we can call it
with self.profiler as profiler:
There was a problem hiding this comment.
can we rename to profiler.py, to be consistent with other components.
There was a problem hiding this comment.
Fixed along with the test file
| run_diagnostics = ( | ||
| bool(self._analyzers) | ||
| and torch.distributed.is_initialized() | ||
| and rank == 0 |
There was a problem hiding this comment.
noob question: is it a good decision to only do it for rank 0? e.g. for the MoE case, is it possible that rank_0 overlapping may be very different from some other rank?
If its not overly complex, i wonder if getting histograms/median would be desirable
There was a problem hiding this comment.
Great point. For FSDP2, all ranks do symmetric work so rank 0 is representative. For MoE, per-rank differences would matter. I'll leave a TODO noting this as a future enhancement and keep rank-0-only for now to avoid adding a collective inside the trace handler. Filed as a follow-up.
| from torchtitan.tools.logging import logger | ||
| from torchtitan.tools.utils import device_module | ||
|
|
||
| # how much memory allocation/free ops to record in memory snapshots | ||
| MEMORY_SNAPSHOT_MAX_ENTRIES = 100000 | ||
|
|
||
| _COMM_KEYWORDS: tuple[str, ...] = ("nccl",) | ||
| _COMPUTE_KEYWORDS: tuple[str, ...] = ( |
There was a problem hiding this comment.
sorry, i haven't checked the checked the code deeply, but is it possible that we may be missing (or wrongly adding) some overlap because of the keyword mismatch?
There was a problem hiding this comment.
Kernels that don't match either keyword list are excluded from both categories, so they can't produce a wrong overlap -- they just aren't counted. The main risk is underreporting if a novel kernel type appears. The keyword lists cover the standard PyTorch/CUDA ecosystem. We can extend them as needed. This is called out in the PR "Limitations" section.
|
Has anyone verified the following.
|
I think it's a proxy.
If it doesn't work, maybe you could help |
tianyu-l
left a comment
There was a problem hiding this comment.
People have found https://github.com/facebookresearch/HolisticTraceAnalysis to be rich and battle tested.
I think the Profiler refactor part is still great work. If you'd be able to ship that before your leave, that would be appreciated.
Thanks for understanding!
@tianyu-l Makes sense. I've removed CommsComputeOverlapAnalyzer and will take a deeper look at HTA. The Profiler refactor should be in good shape now. That said, I do think having a lightweight inline signal (e.g. GPU time unutilized) directly in the default profiler output would be useful — it prompts users to start an efficiency investigation without requiring them to download and analyze traces manually. HTA is great for deep offline analysis (Claude code would be fine too), but there's value in a zero-config first signal in the logs. One direction worth exploring: a lightweight HTA integration that runs inline after each trace export and surfaces a summary — users get the immediate signal, and can fall back to full HTA analysis when needed. Happy to file a follow-up issue to track this if that sounds reasonable. |
tianyu-l
left a comment
There was a problem hiding this comment.
lgtm, one nit comment.
One direction worth exploring: a lightweight HTA integration that runs inline after each trace export and surfaces a summary — users get the immediate signal, and can fall back to full HTA analysis when needed. Happy to file a follow-up issue to track this if that sounds reasonable.
This sounds reasonable. cc @felipemello1 if would like to follow up.
| ) as memory_profiler, | ||
| ): | ||
| with self.profiler.active( | ||
| global_step=self.step, |
There was a problem hiding this comment.
I see. That makes sense. I didn't know why we need global_step before. Thanks for explaining!
| with config.profiler.build( | ||
| global_step=self.step, | ||
| base_folder=config.dump_folder, | ||
| ) as prof_session: |
There was a problem hiding this comment.
nit on naming
| ) as prof_session: | |
| ) as profiler: |
There was a problem hiding this comment.
nit: could you address this?
|
hey @pbpatre
I agree that this could be nice as a follow up PR! Should we try to get this one merged first? I think you were going on pto, if you havent yet, can we fix the unit tests + make sure that profiler runs and generates a trace for memory and torch profile? We can merge with those fixes and then chat about HTA. wdyt? |
|
@felipemello1 Makes sense. Can you please help with fixing the failing checks and get this merged? I am on PTO and do not have access to my dev machine so can't fix these and don't want it to get blocked. Let me know if there are any questions. |
|
@tianyu-l I have fixed conflicts with the latest upstream. Can you approve my workflow execution? |
| with config.profiler.build( | ||
| global_step=self.step, | ||
| base_folder=config.dump_folder, | ||
| ) as prof_session: |
There was a problem hiding this comment.
nit: could you address this?
| torch_profiler.step() | ||
| if memory_profiler: | ||
| memory_profiler.step() | ||
| prof_session.step() |
There was a problem hiding this comment.
why do we need this change?
Land #2418 ## Summary Adds an automated compute-communication overlap diagnostic to help identify communication bottlenecks in FSDP2 training. Implements #2408 ## Motivation Achieving high MFU in large-scale training requires effective overlap of compute and NCCL communication. Currently, identifying "communication bubbles" requires manually downloading multi-GB trace files and inspecting them in Chrome Trace Viewer. This feature provides an immediate diagnostic signal directly in the logs. ## Changes ### New Feature: `CommsComputeOverlapAnalyzer` - Analyzes profiler traces to compute overlap efficiency between compute kernels and NCCL operations - Reports Total Compute Time, Total NCCL Time, Total Active Time, Overlap Efficiency, and GPU time unutilized due to NCCL comms - Enabled via `--profiler.enable_overlap_analysis` flag (off by default) ### Implementation Details - Uses `prof.events()` to collect raw CUDA kernel events and their wall-clock time intervals - Classifies kernels by name: `nccl` for communication; `gemm`, `aten`, `cublas`, `cudnn`, `cutlass`, `triton`, `flash` for compute - Computes the union of time intervals per category using interval merging, correctly deduplicating concurrent kernels across CUDA streams - Overlap is derived as `compute_us + comm_us - active_us`, where `active_us` is the union across both categories ## Example Output **Llama 3 8B (8B params) on 2x H200:** ``` [CommsComputeOverlapAnalyzer] Compute-Communication Overlap Report Total Compute Time : 165.12 ms Total NCCL Time : 255.94 ms Total Active Time : 386.52 ms Overlap Efficiency : 13.5 % GPU Unutilized due to NCCL comms : 86.5 % ``` **Debug model (6M params) on 2x H200:** ``` [CommsComputeOverlapAnalyzer] Compute-Communication Overlap Report Total Compute Time : 4.80 ms Total NCCL Time : 19.97 ms Total Active Time : 23.83 ms Overlap Efficiency : 4.7 % GPU Unutilized due to NCCL comms : 95.3 % ``` Both results are expected communication-bound baselines with no overlap optimizations enabled. The debug model is more severely bottlenecked because its compute-to-communication ratio (0.24x) is far lower than the 8B model (0.65x) — there is almost no compute to overlap with. ## Testing Tested on 2x NVIDIA H200 with: - Llama 3 8B: ``` NGPU=2 ./run_train.sh --module llama3 --config llama3_8b \ --hf_assets_path=./tests/assets/tokenizer \ --profiler.enable_profiling --profiler.profile_freq=10 \ --profiler.enable_overlap_analysis --training.steps=20 \ 2>&1 | tee 8B_output.log ``` - Debug model: ``` NGPU=2 ./run_train.sh --module llama3 --config llama3_debugmodel \ --profiler.enable_profiling --profiler.profile_freq=10 \ --profiler.enable_overlap_analysis --training.steps=20 \ 2>&1 | tee 6M_output.log ``` ## Limitations - Only CUDA kernels are considered; CPU-side work is excluded - Kernels not matching the classify patterns (e.g. custom ops) are excluded from both categories and do not affect the reported overlap percentage --------- Co-authored-by: Pratik Patre <[email protected]>
|
since no response for a while and not directly landable, we moved to #3020 to unblock |
Summary
Adds an automated compute-communication overlap diagnostic to help identify communication bottlenecks in FSDP2 training. Implements #2408
Motivation
Achieving high MFU in large-scale training requires effective overlap of compute and NCCL communication. Currently, identifying "communication bubbles" requires manually downloading multi-GB trace files and inspecting them in Chrome Trace Viewer. This feature provides an immediate diagnostic signal directly in the logs.
Changes
New Feature:
CommsComputeOverlapAnalyzer--profiler.enable_overlap_analysisflag (off by default)Implementation Details
prof.events()to collect raw CUDA kernel events and their wall-clock time intervalsncclfor communication;gemm,aten,cublas,cudnn,cutlass,triton,flashfor computecompute_us + comm_us - active_us, whereactive_usis the union across both categoriesExample Output
Llama 3 8B (8B params) on 2x H200:
Debug model (6M params) on 2x H200:
Both results are expected communication-bound baselines with no overlap optimizations enabled. The debug model is more severely bottlenecked because its compute-to-communication ratio (0.24x) is far lower than the 8B model (0.65x) — there is almost no compute to overlap with.
Testing
Tested on 2x NVIDIA H200 with:
Limitations