Repository navigation
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
Walkthrough
Merge Risk:
|
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (4)
deepmd/utils/data_system.py (4)
1147-1162: ⚖️ Poor tradeoffRecursive mtime scan may be slow for large source directories.
_source_mtimewalks 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 valueMixed-type detection scans all frames at initialization.
_detect_mixed_typeiterates 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 valueSingle-LMDB fast-path only; consider documenting multi-LMDB limitation.
The LMDB routing only handles the case where
systemsresolves to exactly one LMDB path. If multiple LMDB paths are provided (or conversion produces multiple systems), they fall through toDeepmdDataSystem. 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 tradeoffStale lock files may persist after process crashes.
If a process crashes after creating the lock file (line 1242) but before the
finallyblock runs (e.g., SIGKILL), the.lockfile 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
📒 Files selected for processing (7)
deepmd/pd/entrypoints/main.pydeepmd/pt/entrypoints/main.pydeepmd/pt_expt/entrypoints/main.pydeepmd/utils/argcheck.pydeepmd/utils/data_system.pypyproject.tomlsource/tests/common/test_data_system_conversion.py
Codecov Report❌ Patch coverage is 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. 🚀 New features to boost your workflow:
|
|
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 |
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
|
Possible reviewers based on changed lines, exact file history, and exact-file review history:
No review request was made automatically. Coding agent: Codex |
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
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.
There was a problem hiding this comment.
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.1to 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.
Coding-Agent: Codex Codex-Version: codex-cli 0.144.6 Model: gpt-5.6-sol Reasoning-Effort: xhigh
There was a problem hiding this comment.
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
.lockcan 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'andsystemspoints to a directory (common for existing DeePMD npy/raw datasets),suffixis empty and this returns'auto', which then forces dpdata conversion viaprocess_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 underauto: detect DeePMD directory structure (e.g.,set.*+type_map.raw/type.raw/coord.npy) and skip conversion (setfmt=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 underPath.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., perprocess_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 whenpatternsis 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
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
njzjz-bot
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
iProzd
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
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
left a comment
There was a problem hiding this comment.
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.
Coding-Agent: Codex Codex-Version: codex-cli 0.167.0 Model: gpt-6.1-sol Reasoning-Effort: xhigh
Coding-Agent: Codex Codex-Version: codex-cli 0.167.0 Model: gpt-6.1-sol Reasoning-Effort: xhigh
njzjz-bot
left a comment
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
Coding-Agent: Codex Codex-Version: codex-cli 0.167.0 Model: gpt-6.1-sol Reasoning-Effort: xhigh
|
Pushed 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 ( Local validation:
The other failed check, Paddle C++ setup, stopped at CMake's dependency download with status 18 ( Re-requested review from @wanghan-iapcm; I have not dismissed the existing changes-requested review or merged the PR. |
wanghan-iapcm
left a comment
There was a problem hiding this comment.
One comment below. It concerns how a capability this PR documents is covered by the tests, not a defect in the conversion code itself.
| # 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)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
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
left a comment
There was a problem hiding this comment.
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.
-
A new HDF5 reader can silently return the old energy after a successful refresh. Convert one H atom with energy 1 to
deepmd/hdf5and read its energy viaDPPath. Change only the source energy to 42, callprocess_systemsagain in the same process, and construct a newDPPath. 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. -
A process can silently omit a training system published by another process. Process A converts EXTXYZ to
deepmd/npyand discoversH1. Add anH2frame and let process B complete conversion: B discovers both systems. After B exits, A callsprocess_systemsagain and still gets onlyH1. 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
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
|
The two freshness findings from OutisLi’s review are fixed in |
| "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')))", |
Add automatic training/validation conversion through dpdata
formatandout_format(output_formatalias), defaulting to cacheddeepmd/lmdboutput. 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_systemssignature 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_vecinvariant 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_uniformgives 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:
type_mapfor LMDB.mixed_typeacross every retained source, including separate groups. LMDB is mixed-type; NPY/HDF5 used alongside it must also providereal_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 asse_atten.labeled: true). A labeled read failure never falls back to dropping labels. Only explicitlabeled: falserequests structure-only conversion; it cannot supply supervised targets. Label modes have separate cache keys, and schema 4 invalidates caches from the old implicit fallback.sys_probsalso require another output such asdeepmd/hdf5.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.