nvalchemi.hooks.TorchProfilerHook#
- pydantic model nvalchemi.hooks.TorchProfilerHook[source]#
Capture PyTorch profiler traces through PhysicsNeMo’s profiler wrapper.
TorchProfilerHookdrives PhysicsNeMo’sProfiler(backed byTorchProfileWrapper) so thattorch.profilertraces are collected for an nvalchemi workflow without hand-rolling profiler setup, stepping, and finalization. The same hook attaches to both training and dynamics workflows: it recognizesTrainingStage.BEFORE_TRAINING,BEFORE_BATCH,AFTER_BATCH, andAFTER_TRAINING, plusDynamicsStage.BEFORE_STEPandAFTER_STEP.The profiler starts when the hook enters its context (
__enter__) or, if it is dispatched by a workflow without being used as a context manager, lazily on the first supported start stage. It advances thetorch.profilerschedule once per batch or dynamics step (atAFTER_BATCH/AFTER_STEP) and finalizes traces atAFTER_TRAININGor when the hook context closes. Register it like any other hook by adding it to a strategy’s or dynamics object’shooks=[...]list; for dynamics runs it is also valid to wrap the run in awithblock so start/finalize bracket exactly the profiled region.Outputs are written under
output_dir(named byname). In distributed runs, or wheneverrank_subdirsis set, per-process outputs land inoutput_dir / rank_<global_rank>, and the optionalon_trace_ready_pathTensorBoard handler directory is rank-suffixed the same way. Activity selection accepts eitherProfilerActivityvalues or the string aliases"cpu"/"cuda";Nonelets PhysicsNeMo pick CPU and CUDA when available.Examples
Profile a training run by registering the hook alongside the strategy’s other hooks:
>>> import torch >>> from nvalchemi.hooks.physicsnemo_profiling import TorchProfilerHook >>> from nvalchemi.training import ( ... EnergyMSELoss, OptimizerConfig, TrainingStrategy, default_training_fn, ... ) >>> profiler = TorchProfilerHook( ... output_dir="prof/train", ... activities=("cpu", "cuda"), ... record_shapes=True, ... profile_memory=True, ... with_flops=True, ... ) >>> strategy = TrainingStrategy( ... models=model, ... optimizer_configs=OptimizerConfig( ... optimizer_cls=torch.optim.Adam, optimizer_kwargs={"lr": 1e-3}, ... ), ... training_fn=default_training_fn, ... loss_fn=EnergyMSELoss(), ... num_epochs=1, ... devices=[torch.device("cuda")], ... hooks=[profiler], ... ) >>> strategy.run(train_loader)
For dynamics, use the hook as a context manager so the profiler brackets the exact steps you care about:
>>> hook = TorchProfilerHook(output_dir="prof/md", activities=("cuda",)) >>> with hook: ... dynamics.run(batch, num_steps=100)
Notes
Only one PhysicsNeMo profiler may be active at a time:
_startraises aRuntimeErrorif the globalProfileris already initialized or enabled, so construct and register this hook before any other PhysicsNeMo profiler configuration. The hook is single-use — once finalized it cannot be restarted, and calling it (or re-entering it) aftercloseraises. Finalization happens atAFTER_TRAININGor on context exit; dynamics workflows that never emit anAFTER_TRAININGstage should be run under thewithblock (or haveclosecalled) to flush traces.frequencyis aClassVar-style workflow field, andstageisNonebecause the hook handles multiple stages itself rather than binding to a single one.- field output_dir: Path [Required]#
Root directory for PhysicsNeMo profiler outputs.
- field activities: tuple[ProfilerActivity, ...] | None = None#
PyTorch profiler activities, or None to let PhysicsNeMo choose CPU and CUDA when available.
- field schedule: Callable[[...], Any] | None = None#
Optional torch.profiler schedule.
- field record_shapes: bool = True#
Record input tensor shapes in the trace.
- field profile_memory: bool = True#
Profile memory allocations.
- field with_flops: bool = True#
Estimate FLOPs for supported operations.
- field with_stack: bool = False#
Record Python stack traces.
- field on_trace_ready_path: Path | None = None#
Optional path for PyTorch tensorboard trace handler output.
- field frequency: int = 1#
Run every N workflow steps.
- Constraints:
ge = 1
- field name: str = 'torch'#
PhysicsNeMo profiler output name.
- field rank_subdirs: bool = True#
Write nvalchemi-managed outputs under rank_<global_rank>.