Skip to content

fix(train): share post-training bias adjustment#5745

Merged
njzjz merged 2 commits into
deepmodeling:masterfrom
njzjz:fix/change-bias-after-training-dpmodel
Jul 10, 2026
Merged

fix(train): share post-training bias adjustment#5745
njzjz merged 2 commits into
deepmodeling:masterfrom
njzjz:fix/change-bias-after-training-dpmodel

Conversation

@njzjz

@njzjz njzjz commented Jul 7, 2026

Copy link
Copy Markdown
Member

Summary

  • add dpmodel shared helpers for post-training output bias adjustment
  • route TF2/JAX/PT/PT-expt change-bias paths through the shared helper
  • enable change_bias_after_training in JAX and pt_expt training and preserve PT wrapper APIs

Tests

  • ruff format . && ruff check .
  • pytest source/tests/common/test_dpmodel_train.py -q
  • pytest source/tests/pt_expt/test_change_bias.py::TestChangeBiasFittingStats -q
  • pytest source/tests/pt/test_training.py::TestModelChangeOutBiasFittingStat::test_fitting_stat_consistency -q

Summary by CodeRabbit

  • New Features
    • Added an optional post-training output-bias adjustment step for supported training workflows.
    • Extended bias updates across both single-task and multi-task models.
    • Exposed shared bias-update helpers as part of the public backend-independent training API.
  • Bug Fixes
    • Ensured updated bias state is propagated correctly in distributed JAX runs and checkpoints are saved after the post-training adjustment.
  • Tests
    • Added coverage for bias-update helper behavior and JAX broadcast during post-training.

Copilot AI review requested due to automatic review settings July 7, 2026 01:32
@dosubot dosubot Bot added the enhancement label Jul 7, 2026

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions github-actions Bot added the Python label Jul 7, 2026
@coderabbitai

coderabbitai Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds shared output-bias adjustment helpers, exports them publicly, and updates pt, pt_expt, tf2, and jax training flows to use them. JAX and pt_expt also add post-training bias adjustment paths, checkpoint saving, and distributed-state synchronization.

Changes

Shared bias-adjustment helper and backend integration

Layer / File(s) Summary
Core helper functions
deepmd/dpmodel/train/__init__.py, deepmd/dpmodel/train/trainer.py, source/tests/common/test_dpmodel_train.py
Adds change_model_out_bias and change_model_out_bias_by_task, exports both names, and covers them with new unit tests.
PT and TF2 delegation
deepmd/pt/train/training.py, deepmd/pt_expt/train/training.py, deepmd/tf2/train/trainer.py
Refactors backend-specific bias adjustment to call the shared helper; pt_expt also adds post-training bias adjustment configuration and checkpoint saving.
JAX post-training bias sync
deepmd/jax/train/trainer.py, source/tests/jax/test_training.py
Adds post-training bias adjustment, wall-clock timing, distributed broadcast of updated model state, and regression tests for chief and peer ranks.

Estimated code review effort: 4 (Complex) | ~45 minutes

Possibly related PRs

Suggested labels: bug

Suggested reviewers: iProzd, wanghan-iapcm

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: shared post-training bias adjustment across training backends.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@deepmd/jax/train/trainer.py`:
- Around line 736-747: The JAX trainer’s run method should not default to
self.training_tasks because that attribute is never set in this path and can
raise AttributeError when tasks is omitted. Update run in the Trainer class to
require an explicit tasks value or otherwise source it from a valid initialized
field, and remove the fallback to self.training_tasks. Keep the existing train()
call site working by passing the task collection explicitly through the run
flow.
- Around line 749-756: The post-training bias adjustment in
_change_bias_after_training currently runs independently on every rank, which
can produce divergent checkpoint state. Update this method to execute
change_model_out_bias_by_task only on rank 0, then broadcast the recomputed
bias/state to all other ranks before saving. Use the existing trainer/JAX rank
utilities around _change_bias_after_training, self.models, and
change_model_out_bias_by_task so the final checkpoint is consistent across
hosts.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: a48da21d-7f31-4b57-ba98-ece2543894f2

📥 Commits

Reviewing files that changed from the base of the PR and between 7b0050f and f361153.

📒 Files selected for processing (7)
  • deepmd/dpmodel/train/__init__.py
  • deepmd/dpmodel/train/trainer.py
  • deepmd/jax/train/trainer.py
  • deepmd/pt/train/training.py
  • deepmd/pt_expt/train/training.py
  • deepmd/tf2/train/trainer.py
  • source/tests/common/test_dpmodel_train.py

Comment thread deepmd/jax/train/trainer.py Outdated
Comment thread deepmd/jax/train/trainer.py
@njzjz njzjz requested a review from wanghan-iapcm July 7, 2026 04:47
@codecov

codecov Bot commented Jul 7, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 64.15094% with 19 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.47%. Comparing base (7b0050f) to head (dc322c6).
⚠️ Report is 4 commits behind head on master.

Files with missing lines Patch % Lines
deepmd/jax/train/trainer.py 57.14% 9 Missing ⚠️
deepmd/pt_expt/train/training.py 30.76% 9 Missing ⚠️
deepmd/tf2/train/trainer.py 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #5745      +/-   ##
==========================================
- Coverage   80.87%   79.47%   -1.41%     
==========================================
  Files        1003     1014      +11     
  Lines      112492   115392    +2900     
  Branches     4236     4274      +38     
==========================================
+ Hits        90981    91709     +728     
- Misses      19986    22139    +2153     
- Partials     1525     1544      +19     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot 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.

🧹 Nitpick comments (1)
source/tests/jax/test_training.py (1)

354-405: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Good coverage of chief vs. peer broadcast paths; consider also covering the single-rank early return.

Both tests correctly exercise the world_size=2 branch of _change_bias_after_training The JAX trainer optionally recomputes output bias on the chief rank, then broadcasts per-model pure state via multihost_utils.broadcast_one_to_all with is_source tied to is_chief and updates nnx models from the broadcasted state., but _bias_sync_trainer always sets world_size=2, so the early-return branch (if self.rank_context.world_size <= 1: return) added in the same change is never exercised — a single-process run would skip broadcasting entirely and this isn't asserted anywhere.

Consider adding a third test with world_size=1 asserting broadcast_one_to_all is not called after change_model_out_bias_by_task runs.

✅ Suggested additional test
+def test_jax_change_bias_after_training_skips_broadcast_single_rank() -> None:
+    """Single-process runs recompute bias without attempting a broadcast."""
+    trainer = _bias_sync_trainer(rank=0)
+    trainer.rank_context = RankContext(rank=0, world_size=1)
+
+    with (
+        patch(
+            "deepmd.jax.train.trainer.change_model_out_bias_by_task",
+        ) as change_model_out_bias_by_task,
+        patch(
+            "jax.experimental.multihost_utils.broadcast_one_to_all",
+        ) as broadcast_one_to_all,
+    ):
+        trainer._change_bias_after_training()
+
+    change_model_out_bias_by_task.assert_called_once()
+    broadcast_one_to_all.assert_not_called()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@source/tests/jax/test_training.py` around lines 354 - 405, Add a test for the
single-rank early return in _change_bias_after_training: create a
_bias_sync_trainer setup with world_size=1, call
trainer._change_bias_after_training(), and assert the method returns without
invoking jax.experimental.multihost_utils.broadcast_one_to_all. Keep the
existing chief/peer tests unchanged, and reuse the same symbols
(_bias_sync_trainer, _change_bias_after_training, change_model_out_bias_by_task,
broadcast_one_to_all) so the new coverage targets the new early-return branch.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@source/tests/jax/test_training.py`:
- Around line 354-405: Add a test for the single-rank early return in
_change_bias_after_training: create a _bias_sync_trainer setup with
world_size=1, call trainer._change_bias_after_training(), and assert the method
returns without invoking jax.experimental.multihost_utils.broadcast_one_to_all.
Keep the existing chief/peer tests unchanged, and reuse the same symbols
(_bias_sync_trainer, _change_bias_after_training, change_model_out_bias_by_task,
broadcast_one_to_all) so the new coverage targets the new early-return branch.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 770746c0-fb81-4b2d-b2c1-56df16865cf0

📥 Commits

Reviewing files that changed from the base of the PR and between f361153 and dc322c6.

📒 Files selected for processing (2)
  • deepmd/jax/train/trainer.py
  • source/tests/jax/test_training.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • deepmd/jax/train/trainer.py

@njzjz njzjz added this pull request to the merge queue Jul 10, 2026
Merged via the queue into deepmodeling:master with commit d884779 Jul 10, 2026
57 checks passed
@njzjz njzjz deleted the fix/change-bias-after-training-dpmodel branch July 10, 2026 21:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants