Skip to content

feat(data): add dpdata format conversion - #5565

Open
njzjz wants to merge 23 commits into
deepmodeling:masterfrom
njzjz:feat/dpdata-auto-conversion
Open

njzjz wants to merge 23 commits into
deepmodeling:masterfrom
njzjz:feat/dpdata-auto-conversion

Conversation

@njzjz

@njzjz njzjz commented Jun 20, 2026 •

Copy link
Copy Markdown
Member

Add automatic training/validation conversion through dpdata format and out_format (output_format alias), defaulting to cached deepmd/lmdb output. Multiple converted paths compose through the native data-group API.

Conversion lives in a loader-independent module, eliminating import cycles between path discovery, data configuration, and LMDB. The legacy data_system.process_systems signature delegates to the common path router.

Conversion tracks file metadata, small-file content, and directory-symlink targets and children, with cycle protection. Owned locks serialize writers, and source changes during conversion prevent publication of a valid cache manifest. Setup failures close readers already acquired for the task or data group.

LMDB adaptations preserve the legacy mixed-type natoms_vec invariant and exactly partition periodic/nonperiodic frames, including rare zero-cell frames outside the optional-label probe. Neighbor-statistics proxies likewise separate periodicity. The legacy adapter uses the common batch iterator for grouped sampling and progress restoration. Bulk key mapping stays in NumPy; availability indexes are reused until the optional tracked key set changes.

The sampling rule follows current master: prob_uniform gives each retained system the same long-run frame share, including unequal automatic batch sizes; it does not promise equal batch counts. Uniform passes remain bounded by the mean system frame count rather than expanding every system to the largest size.

Constraints:

  • Requires dpdata >=1.1.0 and an explicit model type_map for LMDB.
  • TF/TF2/JAX/pt_expt shared statistics adapters require matching mixed_type across every retained source, including separate groups. LMDB is mixed-type; NPY/HDF5 used alongside it must also provide real_atom_types.npy. Fixed composition can use this representation. The native PyTorch loader can combine fixed-type NPY/HDF5 and LMDB directly. Filtering precedes this check, and TensorFlow LMDB additionally needs a mixed-type-capable descriptor such as se_atten.
  • Conversion preserves labels by default (labeled: true). A labeled read failure never falls back to dropping labels. Only explicit labeled: false requests structure-only conversion; it cannot supply supervised targets. Label modes have separate cache keys, and schema 4 invalidates caches from the old implicit fallback.
  • On Windows, LMDB refresh stages a new directory and publishes it with rollback; close old cache readers first. POSIX retains dpdata's transactional overwrite.
  • Paddle rejects converted LMDB in every task's training/validation config before neighbor-stat I/O. Modifiers and explicit sys_probs also require another output such as deepmd/hdf5.
  • Conversion is eager per input path. Parsed arrays and intermediate copies must fit in RAM; split large inputs or preconvert offline. This limit is documented in the input schema and training guide.

Validation:

  • November 17 follow-up (a2ffd4831): 213 common/data/schema tests and 44 subtests, 101 PT/TF tests (including native TF inference), and all 5 real checkpoint/restart training comparisons pass. These include both grouped seed variants, real partially labeled ASE rejection and recovery, explicit structure-only conversion, invalid-cell grouping, and Linux-hosted simulation of the real dpdata Windows overwrite guard. The 57 conversion tests and 14 subtests also pass after the final platform-aware assertion changes. Ruff, formatting, whitespace checks, and commit hooks pass.

  • After the module extraction: 224 data/conversion/LMDB/PT-exportable tests and 38 subtests passed; three fresh-process import orders and real dpdata-to-TensorFlow conversion/neighbor statistics also passed.

  • Latest availability-cache and bulk-key regressions plus the conversion/LMDB suites: 175 tests and 30 subtests passed.

  • Final targeted data/LMDB/PT/PT-exportable run: 269 tests and 28 subtests passed. Earlier broader validation also covered compiled training, task cleanup, and the TensorFlow core inference scenario.

  • Paddle fail-fast cases: 4 passed; JAX setup cleanup: 2 passed; TF2 entrypoint/cleanup: 4 passed.

  • Real dpdata conversion and TensorFlow neighbor statistics passed, including rewriting energy 0 to 42 while restoring the old source mtime.

  • A complete two-step TensorFlow training/validation run from EXTXYZ finished, reduced loss, and saved its checkpoint.

  • Ruff, formatting, whitespace checks, and commit hooks passed.

Closes #5237.

Coding agent: Codex
Codex version: codex-cli 0.167.0
Model: gpt-6.1-sol
Reasoning effort: xhigh

Comment thread deepmd/utils/data_system.py Fixed
Comment thread deepmd/utils/data_system.py Fixed
Comment thread deepmd/utils/data_system.py Fixed
Comment thread deepmd/utils/data_system.py Fixed
@coderabbitai

coderabbitai Bot commented Jun 20, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
Walkthrough

The change adds dpdata-based conversion for configured training and validation inputs, LMDB data adapters and backend routing, and explicit data-system cleanup across training setup and execution paths. It also updates LMDB sampling behavior and adds tests and documentation for these changes.

Changes: Dataset conversion and training data lifecycle

Layer / File(s) Summary
Format configuration and conversion pipeline
deepmd/utils/argcheck.py, deepmd/utils/data_config.py, deepmd/utils/data_path.py, deepmd/utils/data_system.py, deepmd/entrypoints/test.py, pyproject.toml, doc/train/training-advanced.md, source/tests/common/test_data_system_conversion.py
Training and validation groups accept input format and output out_format settings. Non-DeePMD inputs can be converted with dpdata, cached, and resolved through process_systems. The project adds dpdata as a runtime dependency. Tests cover conversion, cache behavior, source changes, locking, and format detection.
LMDB reader, adapter, and statistics
deepmd/dpmodel/utils/lmdb_data.py, deepmd/utils/data_system.py, source/tests/common/dpmodel/test_lmdb_data.py, source/tests/common/test_data_system_conversion.py
Adds a legacy-shaped LMDB data adapter and grouped statistical views. LMDB reads handle box availability, frame inspection, bounded statistics, and cleanup. Block-target calculation validates sampling styles and weights. Tests cover adapter behavior, periodicity grouping, and sampling targets.
Backend routing and seeded LMDB sampling
deepmd/utils/data_system.py, deepmd/pt/utils/dataloader.py, deepmd/pt/utils/lmdb_dataset.py, deepmd/pd/entrypoints/main.py, source/tests/pd/test_conversion_validation.py, source/tests/pt/test_lmdb_dataloader.py, source/tests/pt_expt/test_lmdb_training.py, source/tests/common/test_data_system_conversion.py
Data construction validates backend support and LMDB options, and routes compatible inputs to LMDB readers. Paddle rejects LMDB data. The PyTorch LMDB dataset forwards seeds to its sampler, including list seeds converted with SeedSequence. Tests cover routing and reproducible batch order.
Data-system ownership and cleanup
deepmd/dpmodel/train/data.py, deepmd/tf/entrypoints/train.py, deepmd/tf2/entrypoints/train.py, deepmd/jax/entrypoints/train.py, deepmd/pt_expt/entrypoints/main.py, deepmd/utils/data_system.py, source/tests/common/dpmodel/test_train_data.py, source/tests/tf/test_train_cleanup.py, source/tests/tf2/test_training.py, source/tests/jax/test_training.py, source/tests/pt_expt/test_entrypoint.py
Training and data-construction paths close acquired systems when setup or training raises, and close temporary data after selected operations. Successfully created task maps and trainers retain ownership. Tests exercise cleanup and successful ownership transfer.

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

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant DataConfig
  participant process_systems
  participant dpdata
  participant get_data
  participant LmdbDataSystem
  DataConfig->>process_systems: pass input and output formats
  process_systems->>dpdata: load selected input paths and write converted data
  dpdata-->>process_systems: return converted data paths
  process_systems-->>get_data: provide resolved paths
  get_data->>LmdbDataSystem: construct adapter for LMDB data
Loading

Possibly related PRs

Suggested reviewers: wanghan-iapcm

Merge Risk: Low · previous review d6306

Large LMDB datasets used with TensorFlow, JAX, or TF2 may see slow or memory-heavy setup, because availability scans and index-list construction repeat when requirements are registered. Results and training behavior are not affected. This is a performance follow-up that can be addressed soon, and the PR is mergeable with awareness of it.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title clearly and concisely describes the pull request’s main change: adding automatic dpdata format conversion.
Linked Issues check Passed Issue [#5237] requires automatic conversion of public dataset formats through dpdata. The PR adds format and out_format configuration, format-aware discovery, dpdata conversion, a default `deepmd/…
Out of Scope Changes check Passed The LMDB adapter, backend validation, sampling updates, cache locking, cleanup paths, and related tests support use of converted data across the declared backends. The dependency and documentation cha…
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Full details: Linked Issues check

Explanation

Issue [#5237] requires automatic conversion of public dataset formats through dpdata. The PR adds format and out_format configuration, format-aware discovery, dpdata conversion, a default deepmd/lmdb output, cache invalidation, and conversion tests. The runtime dependency includes dpdata>=1.1.0. The training and test entry points forward the conversion settings. These changes implement automatic external-format conversion and format detection.

Full details: Out of Scope Changes check

Explanation

The LMDB adapter, backend validation, sampling updates, cache locking, cleanup paths, and related tests support use of converted data across the declared backends. The dependency and documentation changes support the same conversion workflow. The available PR evidence does not show a separate unrelated product change.

Finishing Touches

🧪 Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@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: 4

🧹 Nitpick comments (4)
deepmd/utils/data_system.py (4)

1147-1162: ⚖️ Poor tradeoff

Recursive mtime scan may be slow for large source directories.

_source_mtime walks the entire source directory tree to find the latest modification time. For datasets with many files, this could add noticeable latency on every cache freshness check. Consider caching the computed mtime or using a faster heuristic (e.g., only checking top-level directory mtime plus a sample of files).

🤖 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 `@deepmd/utils/data_system.py` around lines 1147 - 1162, The `_source_mtime`
function performs a full recursive directory walk using source.rglob("*") to
find the latest modification time across all files, which becomes inefficient
for large source directories. To improve performance, implement a caching
mechanism to store previously computed mtimes so that repeated calls for the
same source directory do not re-scan the entire tree, or alternatively replace
the full recursive scan with a faster heuristic that only examines the top-level
directory mtime and a representative sample of files rather than traversing
every single file.

786-796: 💤 Low value

Mixed-type detection scans all frames at initialization.

_detect_mixed_type iterates through every frame in the LMDB dataset comparing atom types, which could be slow for very large datasets (thousands of frames). Consider caching this property in the LMDB metadata during conversion, or adding a sampling heuristic for large datasets.

🤖 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 `@deepmd/utils/data_system.py` around lines 786 - 796, The _detect_mixed_type
method iterates through all frames in the dataset to check for mixed atom types,
which is inefficient for large datasets. Implement caching by storing the
detection result as an instance variable after the first call, and consider
adding a sampling heuristic for datasets with many frames such that for very
large datasets (e.g., more than a configurable threshold), only a sample of
frames are checked instead of all frames. Update the method to return the cached
result on subsequent calls and use the sampling strategy to limit iterations
while still maintaining reasonable confidence in the mixed-type detection.

1395-1408: 💤 Low value

Single-LMDB fast-path only; consider documenting multi-LMDB limitation.

The LMDB routing only handles the case where systems resolves to exactly one LMDB path. If multiple LMDB paths are provided (or conversion produces multiple systems), they fall through to DeepmdDataSystem. Consider adding a log warning or updating docstring to clarify this behavior.

🤖 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 `@deepmd/utils/data_system.py` around lines 1395 - 1408, The code currently
only provides optimized handling for a single LMDB system through
LmdbDataSystem, while multiple LMDB systems silently fall through to
DeepmdDataSystem. Add a log warning message when multiple LMDB paths are
detected (when len(systems) > 1 and all are LMDB) to alert users that they will
be handled through the standard DeepmdDataSystem path rather than the optimized
LmdbDataSystem, and update the function's docstring to document this single-LMDB
fast-path behavior and clarify what happens with multiple LMDB inputs.

1219-1277: ⚖️ Poor tradeoff

Stale lock files may persist after process crashes.

If a process crashes after creating the lock file (line 1242) but before the finally block runs (e.g., SIGKILL), the .lock file will remain. Subsequent processes will wait 5 minutes before timing out. Consider adding stale-lock detection using the PID written to the lock file, or a timestamp-based staleness check.

🤖 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 `@deepmd/utils/data_system.py` around lines 1219 - 1277, The
_convert_system_by_dpdata function creates lock files to coordinate between
processes, but if a process crashes after creating the lock file but before the
finally block executes, the lock file persists causing other processes to wait 5
minutes before timing out. Add stale lock detection logic in the except
FileExistsError block before calling _wait_for_conversion. Read the PID from the
existing lock file and check if that process is still running using
platform-appropriate methods (e.g., os.kill with signal 0 on Unix, or process
existence checks). If the process is not running or if the lock file is older
than a reasonable threshold (e.g., 10 minutes), remove the stale lock file and
retry the lock acquisition instead of waiting. This prevents indefinite hangs on
stale locks from crashed processes.
🤖 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/pd/entrypoints/main.py`:
- Around line 123-144: The current LMDB validation checks for both
training_systems and validation_systems only reject LMDB when the result is a
single system (len(...) == 1), but the error messages indicate that Paddle does
not support LMDB data in general. Remove the len(...) == 1 condition from both
the training_systems check (around line 123) and the validation_systems check
(around line 139) so that any LMDB dataset is rejected regardless of whether
it's a single system or multiple systems in the list. This ensures that any
LMDB-resolved dataset triggers the NotImplementedError with a clear message,
preventing less clear failures downstream.

In `@deepmd/pt_expt/entrypoints/main.py`:
- Around line 118-132: The current code in _get_neighbor_stat_data only
validates the single-LMDB case with `if len(systems) == 1 and
is_lmdb(systems[0])`, but when format-based conversion produces multiple LMDB
paths, this check is skipped and execution falls through to get_data() instead
of raising an appropriate error for list-form LMDB systems. Add validation
guards in both _get_neighbor_stat_data and _build_data_system functions to
ensure that after process_systems() is called, if any LMDB systems are returned,
they are validated to not be in list form (similar to what _detect_lmdb_path
does), and raise a clear error before reaching the fallback get_data() or
DeepmdDataSystem paths.

In `@deepmd/pt/entrypoints/main.py`:
- Around line 197-204: Add a validation guard before the existing condition that
checks `len(systems) == 1 and is_lmdb(systems[0])` to prevent multiple LMDB
paths from being passed to DpLoaderSet. The guard should use
`isinstance(systems, list)` combined with `any(isinstance(s, str) and is_lmdb(s)
for s in systems)` to detect when systems is a list containing LMDB paths and
raise a clear ValueError message explaining that LMDB datasets must be passed as
a scalar string rather than as a list.

In `@deepmd/utils/data_system.py`:
- Around line 848-852: Add a defensive check at the beginning of the
`_stack_frames` method to guard against empty frames lists. Before accessing
`frames[0]` at line 864, add validation to check if the frames list is empty and
handle this edge case appropriately, such as raising a more informative error or
returning early. This will prevent IndexError when the sampler yields an empty
batch due to malformed LMDB data, since both `_load_set` and `get_batch` call
this method with frames lists derived from sampler indices.

---

Nitpick comments:
In `@deepmd/utils/data_system.py`:
- Around line 1147-1162: The `_source_mtime` function performs a full recursive
directory walk using source.rglob("*") to find the latest modification time
across all files, which becomes inefficient for large source directories. To
improve performance, implement a caching mechanism to store previously computed
mtimes so that repeated calls for the same source directory do not re-scan the
entire tree, or alternatively replace the full recursive scan with a faster
heuristic that only examines the top-level directory mtime and a representative
sample of files rather than traversing every single file.
- Around line 786-796: The _detect_mixed_type method iterates through all frames
in the dataset to check for mixed atom types, which is inefficient for large
datasets. Implement caching by storing the detection result as an instance
variable after the first call, and consider adding a sampling heuristic for
datasets with many frames such that for very large datasets (e.g., more than a
configurable threshold), only a sample of frames are checked instead of all
frames. Update the method to return the cached result on subsequent calls and
use the sampling strategy to limit iterations while still maintaining reasonable
confidence in the mixed-type detection.
- Around line 1395-1408: The code currently only provides optimized handling for
a single LMDB system through LmdbDataSystem, while multiple LMDB systems
silently fall through to DeepmdDataSystem. Add a log warning message when
multiple LMDB paths are detected (when len(systems) > 1 and all are LMDB) to
alert users that they will be handled through the standard DeepmdDataSystem path
rather than the optimized LmdbDataSystem, and update the function's docstring to
document this single-LMDB fast-path behavior and clarify what happens with
multiple LMDB inputs.
- Around line 1219-1277: The _convert_system_by_dpdata function creates lock
files to coordinate between processes, but if a process crashes after creating
the lock file but before the finally block executes, the lock file persists
causing other processes to wait 5 minutes before timing out. Add stale lock
detection logic in the except FileExistsError block before calling
_wait_for_conversion. Read the PID from the existing lock file and check if that
process is still running using platform-appropriate methods (e.g., os.kill with
signal 0 on Unix, or process existence checks). If the process is not running or
if the lock file is older than a reasonable threshold (e.g., 10 minutes), remove
the stale lock file and retry the lock acquisition instead of waiting. This
prevents indefinite hangs on stale locks from crashed processes.
🪄 Autofix (Beta)

❌ Autofix failed (check again to retry)

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: 54161e1f-c01b-4956-b3a7-a6ab0d33cb04

📥 Commits

Reviewing files that changed from the base of the PR and between 4b6506d and 37b3b76.

📒 Files selected for processing (7)
  • deepmd/pd/entrypoints/main.py
  • deepmd/pt/entrypoints/main.py
  • deepmd/pt_expt/entrypoints/main.py
  • deepmd/utils/argcheck.py
  • deepmd/utils/data_system.py
  • pyproject.toml
  • source/tests/common/test_data_system_conversion.py

Comment thread deepmd/pd/entrypoints/main.py Resolved
Comment thread deepmd/pt_expt/entrypoints/main.py Resolved
Comment thread deepmd/pt/entrypoints/main.py Resolved
Comment thread deepmd/utils/data_system.py Resolved
@codecov

codecov Bot commented Jun 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.21357% with 70 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.88%. Comparing base (d08ba98) to head (66457d1).
⚠️ Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
deepmd/utils/data_conversion.py 90.76% 30 Missing ⚠️
deepmd/utils/data_system.py 94.22% 16 Missing ⚠️
deepmd/tf/entrypoints/train.py 71.11% 13 Missing ⚠️
deepmd/pt/utils/dataloader.py 77.77% 6 Missing ⚠️
deepmd/dpmodel/utils/lmdb_data.py 96.47% 3 Missing ⚠️
deepmd/tf/descriptor/hybrid.py 50.00% 1 Missing ⚠️
deepmd/utils/data_path.py 85.71% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #5565      +/-   ##
==========================================
- Coverage   79.00%   78.88%   -0.13%     
==========================================
  Files        1253     1254       +1     
  Lines      152408   153222     +814     
  Branches     5193     5212      +19     
==========================================
+ Hits       120412   120863     +451     
- Misses      30063    30427     +364     
+ Partials     1933     1932       -1     

☔ 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 commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor

Note

Autofix is a beta feature. Expect some limitations and changes as we gather feedback and continue to improve it.

An unexpected error occurred while generating fixes: Not Found - https://docs.github.com/rest/git/refs#get-a-reference

@njzjz
njzjz marked this pull request as draft June 30, 2026 08:09
Break the LMDB/data-system import cycle, reject ambiguous multi-LMDB results across backends, reject LMDB on Paddle, and guard empty LMDB frame batches with direct regressions.

Coding-Agent: Codex
Codex-Version: codex-cli 0.144.4
Model: gpt-5.6-sol
Reasoning-Effort: xhigh
Resolve the data-loader conflicts while preserving dpdata format conversion, LMDB routing, and the new multi-LMDB validation behavior.

Coding-Agent: Codex
Codex-Version: codex-cli 0.144.4
Model: gpt-5.6-sol
Reasoning-Effort: xhigh
@njzjz

njzjz commented Jul 18, 2026 •

Copy link
Copy Markdown
Member Author

Possible reviewers based on changed lines, exact file history, and exact-file review history:

  • @wanghan-iapcm — 20 commits on changed files; 74 reviews on exact changed files (deepmd/dpmodel/utils/lmdb_data.py, deepmd/pd/entrypoints/main.py, deepmd/pt/entrypoints/main.py, deepmd/pt_expt/entrypoints/main.py, deepmd/utils/argcheck.py, deepmd/utils/data_system.py, pyproject.toml, source/tests/pt_expt/test_lmdb_training.py).
  • @iProzd — 29 commits on changed files (deepmd/dpmodel/utils/lmdb_data.py, deepmd/pt/entrypoints/main.py, deepmd/utils/argcheck.py, deepmd/utils/data_system.py, pyproject.toml).

No review request was made automatically.

Coding agent: Codex
Codex version: codex-cli 0.144.4
Model: gpt-5.6-sol
Reasoning effort: xhigh

Load the dpmodel LMDB helpers only after the legacy data-system module has initialized, preventing backend imports from re-entering a partially initialized module.

Coding-Agent: Codex
Codex-Version: codex-cli 0.144.4
Model: gpt-5.6-sol
Reasoning-Effort: xhigh
@njzjz
njzjz requested review from iProzd and wanghan-iapcm and removed request for iProzd and wanghan-iapcm July 18, 2026 07:24
deepmd.utils.data_system imports is_lmdb inside the validating function
rather than at module scope, so patching the import site no longer
resolves and mock raises AttributeError.
Copilot AI review requested due to automatic review settings July 27, 2026 12:14

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.

Pull request overview

Adds dpdata-backed automatic dataset format conversion (with caching) to the DeePMD-kit training/validation data pipeline, defaulting converted outputs to LMDB and routing those datasets through backend-appropriate data loaders.

Changes:

  • Introduce format / out_format (output_format) options for training/validation datasets and wire them through TF/JAX legacy loaders, PyTorch, and PT-expt entrypoints.
  • Add an LMDB adapter (LmdbDataSystem) plus LMDB-path validation helpers to ensure backends either consume a single LMDB path or raise clear errors (notably for Paddle).
  • Add tests for conversion/caching behavior and LMDB validation, and promote dpdata>=1.0.1 to a runtime dependency.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
source/tests/pt_expt/test_lmdb_training.py Adds PT-expt validation tests ensuring converted LMDB resolves to exactly one path.
source/tests/common/test_data_system_conversion.py New unit tests for dpdata conversion defaults, caching behavior, and LMDB validation errors.
pyproject.toml Adds dpdata>=1.0.1 as a runtime dependency (removes it from test extras).
deepmd/utils/data_system.py Implements dpdata conversion + cache/locking, adds validate_lmdb_systems, and introduces LmdbDataSystem.
deepmd/utils/argcheck.py Documents and registers new format / out_format dataset options.
deepmd/pt/entrypoints/main.py Routes converted datasets through PT dataloaders and LMDB dataset path validation (incl. neighbor-stat path).
deepmd/pt_expt/entrypoints/main.py Adds conversion-aware system processing and LMDB validation for PT-expt training + neighbor-stat.
deepmd/pd/entrypoints/main.py Ensures Paddle rejects LMDB-resolved datasets with a clear error.
deepmd/dpmodel/utils/lmdb_data.py Removes data_system import dependency to avoid cycles by computing prob weights locally.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread deepmd/utils/data_system.py Resolved
Comment thread deepmd/utils/data_system.py Resolved
Comment thread deepmd/utils/data_system.py Resolved
Coding-Agent: Codex
Codex-Version: codex-cli 0.144.6
Model: gpt-5.6-sol
Reasoning-Effort: xhigh
Copilot AI review requested due to automatic review settings August 1, 2026 14:46

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.

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated 2 comments.

Suppressed comments (4)

deepmd/utils/data_system.py:1205

  • If the converting process crashes after creating the lock file, the .lock can persist indefinitely and every future run will wait ~5 minutes and then fail. Consider adding stale-lock recovery: include PID+timestamp in the lock file and, when waiting, remove the lock if it's older than a threshold and the recorded PID is not alive (or the lock mtime is старе than threshold). This avoids permanent failure modes on shared filesystems/cluster retries.
def _wait_for_conversion(source: Path, output: Path, lock_path: Path) -> bool:
    for _ in range(300):
        if not lock_path.exists():
            return _is_conversion_current(source, output)
        if _is_conversion_current(source, output):
            return True
        time.sleep(1.0)
    return False

deepmd/utils/data_system.py:1148

  • When format='auto' and systems points to a directory (common for existing DeePMD npy/raw datasets), suffix is empty and this returns 'auto', which then forces dpdata conversion via process_systems() even though the input may already be valid DeePMD data. This can lead to unexpected conversion attempts or failures. A concrete fix is to treat directory inputs specially under auto: detect DeePMD directory structure (e.g., set.* + type_map.raw/type.raw/coord.npy) and skip conversion (set fmt=None), otherwise fall back to suffix-based inference for files.
def _normalize_dpdata_format(fmt: str, source: Path) -> str:
    fmt = fmt.lower()
    if fmt == "ase":
        return "ase/structure"
    if fmt != "auto":
        return fmt
    suffix = source.suffix.lower().lstrip(".")
    if suffix == "traj":
        return "ase/traj"
    if suffix == "extxyz" or (suffix == "xyz" and _looks_like_extxyz(source)):
        return "extxyz"
    return suffix or fmt

deepmd/utils/data_system.py:40

  • PR description says converted datasets are cached under an absolute path (/home/jzzeng/codes/deepmd-kit/.deepmd_dpdata_cache), but the implementation caches under Path.cwd() / '.deepmd_dpdata_cache'. Please update the PR description to match the implemented behavior, or (if the absolute path is intended) implement/configure the absolute cache location (e.g., via an env var or config key).
_DPDATA_CACHE_DIR = ".deepmd_dpdata_cache"

deepmd/utils/data_system.py:1189

  • For directory sources this walks the entire tree (rglob('*')) to compute freshness, and it can be called repeatedly (e.g., per process_systems() invocation and during lock waits). On large datasets this becomes a noticeable overhead. A more scalable approach is to scope the scan to only the selected conversion inputs (especially when patterns is provided), cache the computed source timestamp per (source, cwd) within the process, or use a cheaper invalidation scheme (e.g., top-level mtime + a manifest hash) to avoid full-tree scans.
def _source_mtime(source: Path, cache_file: Path) -> float:
    if source.is_file():
        return source.stat().st_mtime
    if not source.is_dir():
        return 0.0
    cache_dir = cache_file.parent.resolve(strict=False)
    latest = source.stat().st_mtime
    for item in source.rglob("*"):
        try:
            item_resolved = item.resolve(strict=False)
            if item_resolved == cache_file or cache_dir in item_resolved.parents:
                continue
            latest = max(latest, item.stat().st_mtime)
        except OSError:
            continue
    return latest

Comment thread deepmd/dpmodel/utils/lmdb_data.py Resolved
Comment thread deepmd/utils/data_system.py Resolved
Reject invalid auto-probability weights before normalization and prevent cache cleanup from following directory symlinks. Add focused regression coverage for both validation paths.

Coding-Agent: Codex
Codex-Version: codex-cli 0.144.6
Model: gpt-5.6-sol
Reasoning-Effort: xhigh
Copilot AI review requested due to automatic review settings August 1, 2026 16:23
@njzjz
njzjz requested review from OutisLi and iProzd October 28, 2026 12:09

@njzjz-bot njzjz-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.

Agent: dot

LGTM at 0565191. I reviewed all 27 changed files and their direct conversion/cache, LMDB reader/sampling, legacy data-adapter, and backend entrypoint integration. This is a new complete changed-source review, not an upgrade of the earlier partial-delta receipts based only on green checks.

I reconciled the earlier substantive reviews against the current code: mixed-composition natoms, Paddle rejection before conversion, exact PBC partitioning, symlink-directory cache invalidation, availability-cache reuse, and vectorized frame-key mapping are addressed. The old per-batch prob_uniform objection needs a distinct qualification: current master already intentionally defines equal sampled-frame shares, not equal batch counts. The H1/H32 control gives 128/128 frames and 4/128 batches, consistent with that documented contract; I am not claiming the former batch-uniform behavior was restored. Uniform-pass allocation is now bounded by the documented ceil(N/M) frame quota, and eager conversion explicitly requires parsed arrays and intermediate copies to fit RAM.

Validation on the Git-blob-verified head: 42 committed conversion tests plus 8 subtests; 31 LMDB/task-map tests plus 8 subtests; the committed seed-order regression using real Torch CPU/LMDB; and 26 exact-source backend lifecycle/fail-fast controls all passed. The lifecycle controls use mock model/data objects, not full backend training.

Limits: no full TensorFlow/JAX/Paddle training, physical GPU/multi-GPU, remote-NFS, or large-data memory qualification is claimed. Test Python is still running; both actual CUDA test jobs are skipped despite the successful aggregate. This approval is the source-review verdict, not a replacement for required CI or normal merge protections.

@OutisLi OutisLi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-reviewed commit 0565191.

The earlier rare-PBC partitioning and directory-symlink invalidation issues are addressed in the current implementation. The mixed-type atom-count and early Paddle validation paths also have targeted corrections. My old batch-uniform sampling objection should not be carried forward unchanged: current master explicitly defines prob_uniform by frame shares and bounds a uniform pass by the mean system size. The eager converter's RAM limitation is now documented rather than presented as streaming support.

One reproducible correctness issue still prevents approval: concurrent recovery of a dead local writer's lock can unlink a live successor's lock. The inode check and path deletion are separate operations; see the inline finding. This is a new finding, not a repetition of the resolved cleanup-comment threads.

Validation: 66 focused conversion, LMDB sampling and task-map tests passed, with 11 subtests. Ruff passed for all 25 changed Python files, and whitespace checks passed. A separate two-process probe against the exact conversion module reproduced deletion of the live successor lock, using synchronization only to control the competing processes' interleaving.

Limits: one real dpdata-writer compatibility test was deselected because the available environment has dpdata 1.0.2 rather than the required >=1.1.0. I did not install dependencies or claim end-to-end dpdata 1.1 conversion, full backend training, GPU, remote-NFS or large-data qualification.

Comment thread deepmd/utils/data_conversion.py Resolved

@iProzd iProzd left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I reviewed the exact head 05651917c6ae62a0134ebaca6d838a30bd9ac24e. The previously reported cache, mixed-nloc, Paddle, rare-PBC, and frame-share issues are addressed. One blocker remains in the unresolved OutisLi thread at deepmd/utils/data_conversion.py:395: stale-lock reclamation checks the inode, then unlinks by pathname; a competing waiter can replace the stale lock between those operations, so a live successor lock is deleted and writer exclusion is lost. The exact-source two-thread probe reproduces this. Please make reclamation ownership-safe and add a regression for this interleaving.

@wanghan-iapcm wanghan-iapcm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Re-review at 0565191.

All six threads from the earlier review are addressed at this head: the typing_extensions.Self import, the modifier rejection, Paddle pre-validation, the argcheck documentation, the LMDB natoms_vec contract, and the documented out_format default.

The five findings below are non-blocking and concern the new LMDB path and its interaction with the new conversion default.

Comment thread deepmd/dpmodel/utils/lmdb_data.py Resolved
Comment thread deepmd/utils/data_system.py Resolved
Comment thread deepmd/utils/data_conversion.py Resolved
Comment thread deepmd/utils/data_system.py Resolved
Comment thread deepmd/utils/data_system.py Resolved
Serialize conversion owner-file creation, stale recovery, heartbeat and
release with a cross-process file lock. Prevent cache outputs from joining
native discovery of their ancestor directories.

Partition periodicity on both Torch LMDB paths, pass None for nonperiodic
model cells, and derive full-validation periodicity from each selected view.
Check mixed-type compatibility across legacy readers and count retained LMDB
frames for automatic task weights.

Add a synchronized two-process recovery regression, rare-PBC training and
validation cases, and real TF/TF2/JAX LMDB entrypoint smoke coverage.

Validation: 397 tests and 40 subtests passed across conversion, discovery,
LMDB reader/progress/consistency, Torch adapters/training and TF/TF2/JAX
smoke tests. CPU only; existing native libraries reused. Ruff and whitespace
checks passed.

Coding-Agent: Codex
Codex-Version: codex-cli 0.165.0
Model: gpt-6-astra
Reasoning-Effort: xhigh

@wanghan-iapcm wanghan-iapcm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The five points from my earlier review are addressed on this head, and each has a regression test behind it: the periodicity partition now registers box on both Torch adapters, the mixed-type agreement check includes LMDB children, the conversion cache is excluded from native discovery, the adapter is covered through the TF/TF2/JAX entrypoints, and retained LMDB frames drive the automatic task weights.

The new findings below all sit in the layers this PR adds or newly enables: the automatic dpdata conversion path, and LMDB as a default data source for the legacy backends. Five of them are blocking — two hard failures at startup, one silent hang, one cross-user integrity issue in the conversion cache, and one wrong-result path in dp test.

Comment thread deepmd/utils/data_system.py Resolved
Comment thread deepmd/utils/data_conversion.py Resolved
Comment thread deepmd/utils/data_conversion.py Resolved
Comment thread deepmd/utils/data_conversion.py Resolved
Comment thread deepmd/dpmodel/utils/lmdb_data.py Resolved
Comment thread deepmd/utils/data_system.py Resolved
Coding-Agent: Codex
Codex-Version: codex-cli 0.167.0
Model: gpt-6.1-sol
Reasoning-Effort: xhigh
@njzjz
njzjz requested a review from wanghan-iapcm November 15, 2026 14:08
Coding-Agent: Codex
Codex-Version: codex-cli 0.167.0
Model: gpt-6.1-sol
Reasoning-Effort: xhigh

@njzjz-bot njzjz-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.

Agent: dot

P2: Reconcile the grouped restart fixture with the new mixed-type admission guard.

Python shard 10 fails test_restart_matches_uninterrupted_training[grouped-19] and [grouped-None] at this head: https://github.com/deepmodeling/deepmd-kit/actions/runs/43727331592/job/132852264504 . Both stop in get_data with ValueError: All data systems must agree on mixed_type, before reaching any checkpoint/restart comparison.

In source/tests/pt_expt/test_data_progress_restart.py, grouped mode combines _write_directory (only type.raw, no real_atom_types.npy, hence non-mixed) with the pt_expt LMDB adapter (mixed). The new capability-based guard intentionally rejects this composition. The fixture adjustment in e5aa771 covered the uniform-sampling test, but this existing restart fixture still uses the incompatible combination.

Update this fixture to a supported, consistent mixed-type representation while retaining the cross-format grouped restart comparison, then rerun both seed variants. Do not weaken the production agreement guard just to restore this test. Verified the fixture and the hosted traceback; no independent training run.

@wanghan-iapcm wanghan-iapcm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed the current head. Four points are posted inline, none of them about style: the widened mixed_type check rejects a documented NPY+LMDB composition and breaks an existing test; the new labeled-to-unlabeled fallback turns a partially labeled input into an all-unlabeled cache that trains with zero loss; the zero-cell guard assumes the decoded cell is numeric; and the LMDB write path cannot re-convert a changed source on Windows. Everything else this round was documentation and coverage hygiene.

Comment thread deepmd/utils/data_system.py Resolved
Comment thread deepmd/utils/data_conversion.py Resolved
Comment thread deepmd/dpmodel/utils/lmdb_data.py Resolved
Comment thread deepmd/utils/data_conversion.py Resolved
Coding-Agent: Codex
Codex-Version: codex-cli 0.167.0
Model: gpt-6.1-sol
Reasoning-Effort: xhigh
@njzjz
njzjz requested a review from wanghan-iapcm November 17, 2026 15:27
@njzjz

njzjz commented Nov 17, 2026

Copy link
Copy Markdown
Member Author

Pushed a2ffd4831 and addressed all four new inline threads. The guide and PR constraints now explicitly describe supported mixed-type compositions, label-preserving conversion is the default with no silent unlabeled fallback, invalid/null cells are treated consistently as nonperiodic, and Windows LMDB refresh uses staged publication with rollback.

This also addresses the dot review from @njzjz-bot and the blocking Python shard-10 failures: the grouped restart fixture now uses mixed-type NPY alongside its two LMDB sources, without weakening the production agreement guard. Both grouped seed variants (19 and None) pass, while retaining the real cross-format uninterrupted-vs-restarted training comparison.

Local validation:

  • 213 common/data/schema tests and 44 subtests pass.
  • 101 PT/TF tests pass, including the unmodified NumPy-filter test, both uniform-sampling variants, and the native TensorFlow inference scenario.
  • All 5 real checkpoint/restart training comparisons pass (directory, LMDB, ragged, and grouped with both seeds).
  • After the final platform-aware assertion changes, all 57 conversion tests and 14 subtests pass again.
  • Ruff, formatting, whitespace checks, and all commit hooks pass.

The other failed check, Paddle C++ setup, stopped at CMake's dependency download with status 18 (Transferred a partial file), before compiling this change. I requested a retry; that old-head retry was superseded/cancelled when this fix was pushed. The new head has fresh CI running (27 checks pending/in progress at the latest check, no failures yet), so this is not a claim that hosted CI has finished green. Windows behavior was exercised with the real dpdata writer's Windows guard on Linux, not on a real Windows host.

Re-requested review from @wanghan-iapcm; I have not dismissed the existing changes-requested review or merged the PR.

Coding agent: Codex
Codex version: codex-cli 0.167.0
Model: gpt-6.1-sol
Reasoning effort: xhigh

@wanghan-iapcm wanghan-iapcm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

One comment below. It concerns how a capability this PR documents is covered by the tests, not a defect in the conversion code itself.

Comment thread source/tests/pt/test_lmdb_dataloader.py Outdated
Comment on lines +1940 to +1942
# LMDB is mixed-type even for fixed compositions; both children must
# provide real atom types to share the same statistics contract.
np.save(set_path / "real_atom_types.npy", np.zeros((2, 1), dtype=np.int32))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

What this is about. The PR documents, in the body and in doc/train/training-advanced.md, that "the PyTorch backend's native data loader can combine fixed-type NPY/HDF5 and LMDB directly". The test that used to exercise exactly that combination, test_uniform_group_combines_numpy_and_lmdb_systems, is parametrized over both the pt and pt_expt backends, and this PR adds set.000/real_atom_types.npy to its shared fixture. That file is what DeepmdData._check_mode uses to decide a system is mixed-type, so the NPY child is now mixed-type for both parametrizations. The added line is required by the new mixed_type agreement check in get_data (which is a pt_expt concern here, since the native PyTorch create_dataset path added in this PR has no such check), but it also removes the only committed execution of the fixed-type NPY + LMDB composition on the native PyTorch path. The expected behaviour is that a documented capability keeps an assertion that fails if it stops working.

Trigger. A PyTorch data group containing, in the same group, an NPY/HDF5 system with only type.raw (no set.NNN/real_atom_types.npy) and an LMDB system, iterated through create_dataset/create_dataloader. No test constructs that state at HEAD.

Call chain. TestUniformGroup (test at source/tests/pt/test_lmdb_dataloader.py:1923) -> deepmd.pt.utils.dataloader.create_dataset -> DpLoaderSet (the fixed-type child at the merge base) + LmdbDataset -> GroupedDataset -> create_dataloader; at HEAD the DpLoaderSet child is built from a mixed-type directory instead.

Consequence. If the shared mixed_type agreement check (or a similar constraint) is later applied to the native PyTorch path, the documented fixed-type NPY + LMDB combination would break silently: the suite stays green because its only fixture now carries real_atom_types.npy. It also leaves the new constraint's justification unasserted for pt, since the pt parametrization never needed the fixture change.

Evidence boundary. No tests were run. The conclusion is from the pinned diff, both revisions of the test body, DeepmdData._check_mode (deepmd/utils/data.py) and the native create_dataset/create_dataloader code at HEAD.

Possible resolutions. Scope the real_atom_types.npy write to the pt_expt parametrization, or keep the shared fixture mixed-type and add a pt-only case that combines a fixed-type NPY system with LMDB through create_dataset/create_dataloader.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Addressed in 78a07af39. The native PyTorch case now keeps the NPY fixture fixed-type and verifies sampling from NPY and LMDB through create_dataset and create_dataloader. Only pt_expt writes real_atom_types.npy, as required by the shared statistics path. No production code changed.

Both parametrizations passed, along with the rest of the LMDB loader test file and the TensorFlow single-frame inference test (100 tests total). Ruff checks and formatting also passed.

Coding agent: Codex
Codex version: codex-cli 0.172.0
Model: gpt-6.2-sol
Reasoning effort: xhigh

@OutisLi
OutisLi self-requested a review November 26, 2026 01:27
Keep the native PyTorch regression on fixed-type NPY + LMDB.
Only pt_expt needs mixed-type NPY to satisfy shared statistics.

Coding-Agent: Codex
Codex-Version: codex-cli 0.172.0
Model: gpt-6.2-sol
Reasoning-Effort: xhigh
Preserve JAX batch configuration and data cleanup, the shared NumPy LMDB
adapter, and deterministic native PyTorch LMDB seeding.

Coding-Agent: Codex
Codex-Version: codex-cli 0.172.0
Model: gpt-6.2-sol
Reasoning-Effort: xhigh

@OutisLi OutisLi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I rechecked the updated head af1e755f. The previous merge conflicts are resolved; I am not asking for another conflict-resolution pass. Two data-integrity issues remain. I reproduced both on this head with dpdata 1.1.0 and small labeled EXTXYZ inputs.

  1. A new HDF5 reader can silently return the old energy after a successful refresh. Convert one H atom with energy 1 to deepmd/hdf5 and read its energy via DPPath. Change only the source energy to 42, call process_systems again in the same process, and construct a new DPPath. Opening the published file afresh with h5py returns 42; the new DeePMD reader returns 1. Publication replaces the file at the same pathname, but the reader caches its open handle by pathname and mode. New readers must resolve the newly published file, without globally closing handles that existing readers still own.

  2. A process can silently omit a training system published by another process. Process A converts EXTXYZ to deepmd/npy and discovers H1. Add an H2 frame and let process B complete conversion: B discovers both systems. After B exits, A calls process_systems again and still gets only H1. The fast path validates the current disk manifest but returns a list expanded for an earlier publication. Rediscover the systems on a disk-cache hit, or bind the memoized list to the exact source signature/publication it describes. Clearing only the writer's process-local cache cannot fix another reader.

Please fix freshness in the shared conversion/discovery and reader layers, and add these two public-path regressions. The contract is for new reads after completed publication, not hot-reloading an active training iterator. It should hold for training and validation on every backend that accepts the chosen output format. This does not require a new Paddle LMDB reader: Paddle can use explicit NPY/HDF5; the LMDB and mixed-type restrictions should remain explicit. One regression per distinct cache mechanism is more useful than duplicating the same tests per backend.

@wanghan-iapcm wanghan-iapcm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This review re-checks the current head af1e755f (the 22 threads from my earlier reviews on this PR are all addressed at this commit).

One blocking finding: the conversion-lock liveness probe calls os.kill(pid, 0), which on Windows terminates the process it is supposed to probe. Details in the inline comment.

if expected_start is not None and current_start is not None:
return str(expected_start) == current_start
try:
os.kill(pid, 0)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

On Windows this liveness probe can terminate the process it is meant to observe.

Trigger. Windows with Python 3.10/3.11 (the win_amd64 wheel is cp311 and requires-python is >=3.10), two processes converting the same source. _process_start_time reads /proc/<pid>/stat, which does not exist there, so both the owner's stored token and the current lookup are None; the token comparison above is skipped and this os.kill(pid, 0) runs on the first poll of a live lock. No staleness is involved.

Call chain. deepmd.utils.data_path.process_systems -> _convert_system_by_dpdata (line 541) -> _ConversionLock(lock_path) raises FileExistsError (line 583) -> _wait_for_conversion (line 448) -> _recover_stale_conversion_lock (line 399) -> _lock_owner_is_alive -> os.kill(pid, 0) here.

Consequence. In CPython's Windows os.kill, sig == 0 is CTRL_C_EVENT; when GenerateConsoleCtrlEvent fails for a pid that is not a console process-group leader (the normal case), 3.10/3.11 fall through to TerminateProcess(handle, 0). The waiting process therefore terminates the process that is doing the conversion with exit code 0 -- it looks like a clean exit, but no cache or manifest is published -- and then fails itself; on 3.12+ the same call raises an uncaught OSError in the waiter instead. This is exactly the concurrent-conversion scenario the lock exists for, so the Windows coordination path is destructive rather than serializing.

Evidence boundary. No Windows host was available for this review: the deepmd side is read at af1e755f, and the os.kill semantics come from CPython Modules/posixmodule.c (3.10, 3.11, 3.12, main) plus the Windows SDK's CTRL_C_EVENT == 0, not from a run. A platform-independent liveness decision for this branch (e.g. treating "no start token" as unknown instead of probing with os.kill) would not depend on that semantics.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 66457d103. Liveness probing now calls os.kill(pid, 0) only on POSIX. On Windows, a same-host owner with unknown liveness is left alone; if its heartbeat stalls, the waiter reports an error rather than evicting the lock. The regression exercises both a fresh and an expired heartbeat with the Windows branch enabled and asserts that no signal is sent. This was not run on a native Windows host.

Coding agent: Codex
Codex version: codex-cli 0.172.0
Model: gpt-6.2-sol
Reasoning effort: xhigh

Rediscover systems after any cache publication, reuse HDF5 handles only
for the same file identity, and never signal conversion owners on Windows.

Coding-Agent: Codex
Codex-Version: codex-cli 0.172.0
Model: gpt-6.2-sol
Reasoning-Effort: xhigh
@njzjz

njzjz commented Nov 27, 2026

Copy link
Copy Markdown
Member Author

The two freshness findings from OutisLi’s review are fixed in 66457d103. A new HDF5 path reuses a handle only if it names the same file identity; paths derived from an existing reader stay on that reader’s snapshot. Conversion now rediscovers NPY/HDF5 systems on disk-cache hits rather than returning a process-local list. The public-path tests cover an energy refresh from 1 to 42 while the old reader remains open, and an independent process publishing H1 plus H2. The conversion, path, statistics-file, and TensorFlow single-frame tests passed (98 tests and 10 subtests).

Coding agent: Codex
Codex version: codex-cli 0.172.0
Model: gpt-6.2-sol
Reasoning effort: xhigh

Comment on lines +1054 to +1056
"import json, sys; from deepmd.utils.data_path import process_systems; "
"print(json.dumps(process_systems(sys.argv[1], fmt='extxyz', "
"out_fmt='deepmd/npy')))",

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Automatic Format Conversion in dp using dpdata

7 participants