Skip to content

comms_logger: honor in-section enabled and bound per-op timer history - #8798

Open
hgdytzyy wants to merge 1 commit into
deepspeedai:masterfrom
hgdytzyy:fix/comms-logger-enabled-flag
Open

hgdytzyy wants to merge 1 commit into
deepspeedai:masterfrom
hgdytzyy:fix/comms-logger-enabled-flag

Conversation

@hgdytzyy

Copy link
Copy Markdown

Summary

Fixes #8797.

The comms logger's enabled flag is currently derived from section presence only:

# deepspeed/comm/config.py
self.comms_logger_enabled = 'comms_logger' in ds_config

# deepspeed/utils/comms_logging.py
def configure(self, comms_config):
    self.enabled = comms_config.comms_logger_enabled

So a user writing "comms_logger": {"enabled": false} (intending to disable the logger) actually enables it. In ZeRO-3 (~1,000 collectives/step) the per-op timers accumulate without reset and every collective walks the full history, producing the linear per-step slowdown reported in #8797 (measured 33.8 → 117.7 s/step over 10 steps; ZeRO-2 unaffected).

Changes

  1. Honor the enabled field inside the section (deepspeed/utils/comms_logging.py):
_inner_logger = getattr(comms_config, "comms_logger", None)
self.enabled = (_inner_logger.enabled if _inner_logger is not None
                else comms_config.comms_logger_enabled)
  1. Bound each op's timer history (deepspeed/utils/timer.py): event_timers is now a deque(maxlen=1024) instead of an unbounded list. timed_op reads the value via elapsed(reset=False) and the records are never otherwise reset; the deque keeps the defensive bound without affecting reset()/mean() usage.

Together these make "comms_logger": {"enabled": false} behave as documented and prevent the O(N²) accumulation even if the logger remains enabled.

Notes

Fixes deepspeedai#8797.

The comms logger enabled flag was derived from section presence only, so a config of "comms_logger": {"enabled": false} enabled the logger. configure() now honors the enabled field inside the section. Additionally bound each op's event_timers to the most recent 1024 records, because timed_op reads elapsed(reset=False) without ever resetting, making every collective walk all past records (O(N^2) step time in ZeRO-3).
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-10T04:17:40.016617Z e763741 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e763741a94

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".


def configure(self, comms_config):
self.enabled = comms_config.comms_logger_enabled
# Honor the `enabled` field inside the comms_logger section instead of

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Add the required Signed-off-by trailer

Inspection of this non-merge commit with git log --format='%b' beccf9cb9a957da9398bf43e69512c33b2264318 shows that its message has no Signed-off-by trailer, so it violates the repository's mandatory commit requirement; recreate the commit with the required sign-off before merging.

AGENTS.md reference: AGENTS.md:L8-L9

Useful? React with 👍 / 👎.

Comment thread deepspeed/utils/timer.py
# elapsed(reset=False) and the records are never otherwise reset, so an
# unbounded list makes every subsequent collective walk all past records
# (O(N^2) step time in ZeRO-3). Keep the most recent records.
self.event_timers = deque(maxlen=1024)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep the generic wall-clock timer's full history

SynchronizedWallClockTimer.Timer.elapsed() sums all records since the last reset, so replacing its shared storage with deque(maxlen=1024) silently drops elapsed time after 1,024 stops. This timer is not communication-specific: PipelineEngine.train_batch adds one TRAIN_BATCH_TIMER record per batch and only resets it at the configurable steps_per_print boundary (deepspeed/runtime/pipe/engine.py:368-380); with steps_per_print=2000, the code sums only 1,024 batches but divides by 2,000, reporting incorrect iteration time and throughput. Keep this generic timer's contract and bound/reset only the communication timer.

Useful? React with 👍 / 👎.

Comment on lines +84 to +85
self.enabled = (_inner_logger.enabled if _inner_logger is not None
else comms_config.comms_logger_enabled)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Load logger options even while disabled

When a config contains enabled: false, the new assignment leaves the existing if self.enabled branch false, so verbose, debug, prof_ops, and prof_all from that section are not copied. If the global logger is then enabled through the public partial-update API deepspeed.comm.configure(enabled=True) (deepspeed/comm/comm.py:77-102), it uses defaults or values left by an earlier engine—for example, configured prof_all: false becomes True—and profiles unintended operations; apply the section's other options independently of its enabled state.

Useful? React with 👍 / 👎.

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.

🟡 Changes recommended

The timer cap breaks shared timer semantics, and disabling logging can remove synchronization required by affected backends.

2 open findings
What changed in this PR

Fixes communication logger configuration and limits timer history growth.

Changes:

  • Honors the nested comms_logger.enabled setting.
  • Bounds timer event history to 1,024 records.
File Description
deepspeed/​utils/​comms_logging.py Reads the nested logger enablement flag.
deepspeed/​utils/​timer.py Replaces unbounded timer storage with a bounded deque.

🧠 Review effort: Balanced


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread deepspeed/utils/timer.py
# elapsed(reset=False) and the records are never otherwise reset, so an
# unbounded list makes every subsequent collective walk all past records
# (O(N^2) step time in ZeRO-3). Keep the most recent records.
self.event_timers = deque(maxlen=1024)
Comment on lines +83 to +85
_inner_logger = getattr(comms_config, "comms_logger", None)
self.enabled = (_inner_logger.enabled if _inner_logger is not None
else comms_config.comms_logger_enabled)
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Oct 27, 2026
…gger.enabled (deepspeedai#8909)

Fixes deepspeedai#8797. With comms logging on, every collective re-read the full
history of its timer, so ZeRO-3 step time grew every step and each
logged latency was the sum of all earlier calls. Separately,
`"comms_logger": {"enabled": false}` turned logging on.

### Root causes
1. **Timer history is never cleared (regression from deepspeedai#7714, v0.18.3).**
Logged latencies are cumulative, which changed the original intent.
2. **The section's `enabled` field is ignored (since deepspeedai#2012).**

### Changes

**`deepspeed/utils/timer.py`**
- `Timer` holds one start/stop event pair, created once and recorded
again for each interval, plus a running total and count. It no longer
keeps a list of every event pair.
- `elapsed()` returns the latest start/stop interval.
- New `elapsed_total()` returns the sum of all intervals since the last
reset.
- `mean()` returns the plain average since the last reset. It used to be
a 10% trimmed mean over the stored records.
- Each interval is measured once, when first needed: on a read or at the
next `start()`. So `stop()` never waits for the device.
- Reading a timer that is still running stops it, with no automatic
restart.
- `SynchronizedWallClockTimer.log()` prints `elapsed_total()`, so every
existing log line is unchanged.
- Cleanups:
  - Removed the now-unused `CudaEventTimer`.
  - Added `NoopTimer.elapsed_total()`.
  - `psutil` is imported only when `ThroughputTimer` monitors memory.

**`deepspeed/comm/config.py`, `deepspeed/comm/comm.py`**
- `comms_logger_enabled` now comes from the section's `enabled` field. A
missing section is parsed with its defaults, the same way the `compile`
section is.
- Inlined `_configure_using_config_file` into
`deepspeed.comm.configure()`.
- Removed an outdated comment ("'elapsed' resets events") and the unused
`timer_summary` global.
- Removed the `config` argument of `deepspeed.init_distributed()`;

### Related PRs

- **deepspeedai#8798** (open, same issue) caps each timer's history at 1,024
records. That changes the shared timer contract: for example, pipeline
iteration time under-reports when `steps_per_print` is above 1024.
Logged latencies also stay cumulative, and steps stay much slower than
without logging. This PR fixes the cause instead. Its config change
addresses the same bug as deepspeedai#8798's.

---------

Signed-off-by: Hongwei Chen <[email protected]>
@auto-pr-labeler-with-jev auto-pr-labeler-with-jev Bot added the skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU. label Nov 14, 2026
banxingmjj pushed a commit to openanolis/DeepSpeed that referenced this pull request Nov 25, 2026
Restore the `Train/Samples/train_loss` monitor event that
`DeepSpeedEngine` stopped writing to TensorBoard, WandB, CSV and Comet
in v0.18.3.

## What breaks

Since deepspeedai#7665 (PyTorch-compatible backward API, first released in
v0.18.3), a run with any monitor backend enabled only gets
`Train/Samples/lr` (and `loss_scale` with fp16). The training loss is
never written, although `docs/_pages/config-json.md` and
`docs/code-docs/source/monitor.rst` still list
`Train/Samples/train_loss` as logged by default. `PipelineEngine` is not
affected because it writes its own loss event in `train_batch()`.

Reproduce: enable `csv_monitor` (or `tensorboard`), train a few steps
with `engine.backward(loss)` and `engine.step()`, and look for
`Train_Samples_train_loss.csv`. It is missing on current master. The
write is present in `engine.backward()` up to v0.18.2 and absent from
v0.18.3 on (checked in the released sources).

## Root cause

deepspeedai#7665 moved the backward prologue into output hooks and removed the
block in `engine.backward()` that summed `loss.mean().detach()` into
`self.losses` and wrote the event at the accumulation boundary.
`self.losses` is still reset in `_take_model_step()`, but nothing writes
to it anymore.

## Fix

- `engine.backward()`: when the monitor is enabled, add the
gradient-accumulation-scaled loss to `self.losses` after
`loss.backward()` and the backward epilogue succeed. The sum is kept in
fp32 so bf16/fp16 losses do not drift over many micro-batches, and a
backward that raises does not leave its loss in the next event.
- `engine.step()`: at the accumulation boundary, write
`("Train/Samples/train_loss", self.losses.item(), self.global_samples)`
on rank 0 right before `_take_model_step()`, which resets the sum and
advances `global_samples`.

This keeps the value and x-axis of the v0.18.2 event (mean micro-batch
loss of the step, at the pre-step `global_samples`). Writing it in
`step()` instead of `backward()` also covers
`managed_gradient_accumulation=false`, where the boundary is only known
inside `step()`. Nothing runs when the monitor is disabled, and the only
added sync is one `.item()` per optimizer step on rank 0 with a monitor
enabled, which matches the old behavior.

Sibling paths checked: `PipelineEngine` calls `super().backward()` and
`_take_model_step()` directly and never `DeepSpeedEngine.step()` (it
raises), so it accumulates and resets `self.losses` but does not write a
second event. `DeepSpeedHybridEngine` inherits the fixed path.

## Tests

New `TestMonitorTrainLoss` in `tests/unit/monitor/test_monitor.py`
trains `SimpleModel` with the CSV monitor (GA=256, 2 optimizer steps)
and checks one event per optimizer step equal to the mean of the
micro-batch losses returned by forward. Cases: managed GA fp32,
unmanaged GA fp32, managed GA bf16 with ZeRO-1 (skipped where bf16 is
unsupported). The bf16 case also fails if the sum is kept in bf16.

Hardware: CPU only, AMD EPYC Genoa (4 vCPU), `DS_ACCELERATOR=cpu`, torch
2.15.0+cpu, Python 3.11.14, pytest 8.3.5. No GPU runs.

```
cd tests && DS_ACCELERATOR=cpu pytest --forked -q unit/monitor/test_monitor.py -k TrainLoss
```

- master (ba0d63c): 3 failed, `AssertionError: Train/Samples/train_loss
was not written to the monitor`
- this PR: 3 passed (also 3 repeated runs, all passed)

Extra local check, not committed: the same loop with both `csv_monitor`
and `tensorboard` across ZeRO 0 fp32, ZeRO 1/2/3 bf16 and ZeRO 2 fp32
(10 cases), comparing the logged values against the forward losses: all
passed. Not validated: fp16 with dynamic loss scaling, CPU/NVMe offload,
multi-rank runs, WandB and Comet (they receive the same event list
through `MonitorMaster`).

## Not covered

Users who call `loss.backward()` directly instead of
`engine.backward(loss)` still get no `train_loss` event, because the
engine never sees the loss value on that path. That path did not exist
before deepspeedai#7665, so this is not a regression, but the docs could say that
`train_loss` is logged for `engine.backward()`. Happy to add that line
or to log from the output hook if you prefer.

## Duplicate check

No open or closed PR or issue mentions the missing event: searched PRs
and issues for `train_loss`, `Train/Samples`, `monitor train loss`,
`tensorboard loss missing`, and checked the open PRs touching the
monitor (deepspeedai#8401, deepspeedai#8065, deepspeedai#8896, deepspeedai#8798), which change other things.

AI assistance was used in preparing this PR; I reviewed and tested every
change.

---------

Signed-off-by: Arunkumar Eli <[email protected]>
Signed-off-by: Masahiro Tanaka <[email protected]>
Co-authored-by: Masahiro Tanaka <[email protected]>

This branch has not been deployed

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

Labels

skip-gpu-test Requires positive evidence that every changed behavior can be validated without a GPU.

Projects

None yet

2 participants