Skip to content

Conversation

Luthaf
Copy link
Contributor

@Luthaf Luthaf commented May 30, 2025

Summary

We split the atomistic models part of metatensor into its own package, called metatomic. This PR updates the interface to use the new package.

Checklist

Before a pull request can be merged, the following items must be checked:

  • Doc strings have been added in the Google docstring format.
    Run ruff on your code.
  • Tests have been added for any new functionality or bug fixes.

We highly recommended installing the pre-commit hooks running in CI locally to speedup the development process. Simply run pip install pre-commit && pre-commit install to install the hooks which will check your code before each commit.

@cla-bot cla-bot bot added the cla-signed Contributor license agreement signed label May 30, 2025
Copy link
Collaborator

@CompRhys CompRhys left a comment

Choose a reason for hiding this comment

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

Looks good to me, I will look at the test failures and then merge after resolving them.

@CompRhys CompRhys merged commit e3a1711 into TorchSim:main Jun 1, 2025
182 of 185 checks passed
janosh added a commit that referenced this pull request Jun 9, 2025
* clean: move pair fn logic into batched model code

* clean: begin to remove unbatched scripts

* clean: update the dynamics scripts, remove old code, refactor the integrators into folder

* fix: all unit tests run

* fix: remove circular import

* wip: address more issues with removing unbatched code

* wip: another attempt to fix examples

* fix: mace needs the shifts? we should add a unit test that needs them as the MaceModel unit tests didn't fail removing them.

* metatensor models have been renamed to metatomic models (#205)

* Fix discrepancies between `FIRE` optimisations in `ASE` and `torch-sim`  (#203)

* fea: use batched vdot

---------

Co-authored-by: Janosh Riebesell <[email protected]>

* clean: remove ai slop

* clean: further attempts to clean but still not matching PR

* fix: dr is vdt rather than fdt

* typing: fix typing issue

* wip: still not sure where the difference is now

* update forces per comment

* Fix ASE pos only implementation

* Initialize velocities to None in the pos-only case, see previous
  changes to the optimizers. (ensures that the correct `dt` is used)

* Change the order of the increase of `n_pos`. Again, this ensures the
  usage of the correct `dt` compared to ASE

* Fix torch-sim ASE-FIRE (Frechet Cell)

* Remove rescaling of positions when updating cell, it's not relevant
* Correctly rescale the positions with respect to the deformation
  gradient
* Consider the `cell_forces` in the convergence when doing cell
  optimizations

* linting

* test: still differ significantly after step 1 for distorted structures

* Fix test comparing ASE and torch-sim optimization

* Include the `cell_forces` in the convergence check
* Fix the number of iterations that are performed. `steps_between_swaps` is set to 1, so the number of iterations is equal to the number of swaps. In the previous version, less iterations would have been performed when reaching the maximum number of swaps. For example, when trying to run 32 steps with `steps_between_swaps=5`, the optimization would have stopped after 30 iterations, i.e., 6 swaps.
* Fix `autobatching.py`. The if statement would have been triggered for `max_attempts=0`, which was the case when running one iteration and `steps_between_swaps=5`

* Fix `optimizers` when using `UnitCellFilter`

* Fix the `None` initialization
* Fix the cell update when using `UnitCellFilter`

* fix test_optimize_fire

* allow FireState.velocities = None since it's being set to None in multiple places

* safer `batched_vdot`: check dimensionality of input tensors `y` and `batch_indices`

- fix stale docstring mentioning is_sum_sq kwarg

* generate_force_convergence_fn raise informative error on needed but missing cell_forces

* pascal case VALID_FIRE_CELL_STATES->AnyFireCellState and fix non-f-string error messages

* fix FireState TypeError: non-default argument 'dt' follows default argument

* allow None but don't set default for state.velocities

* fix bad merge conflict resolution

* tweaks

---------

Co-authored-by: Rhys Goodall <[email protected]>
Co-authored-by: Janosh Riebesell <[email protected]>

* bump pre-commit hooks and fix new errors

* fix MACE examples not using ts.io state conversion utilities

* fix unused shifts_list not torch.cat()-ed in mace.py

* fix examples/scripts/3_Dynamics/3.9_MACE_NVT_staggered_stress.py using nvt_langevin in place of nvt_nose_hoover_invariant

remove debug print in torch_sim/runners.py

* just calc total energy manually in nvt_langevin_invariant in torch_sim/integrators/nvt.py

also fix broadcasting bug in Ornstein-Uhlenbeck (ou_step)

* fix calculate_momenta() in npt_nose_hoover_init

also fix 3.8_MACE_NPT_Nose_Hoover.py broken imports from torch_sim.integrators.npt

* fix unpack of n_particles, dim = state.positions.shape

* fix missing external_pressure in npt_nose_hoover call in 3.8_MACE_NPT_Nose_Hoover.py

* update cell_position in npt_nose_hoover before downstream usage

* refactor (no bug fixes)

* fix npt_nose_hoover transposing cell that's already in column-vector convention

* feat: Add batching support to NPT Nose-Hoover integrator

- Update NPTNoseHooverState cell properties to support batch dimensions

  - reference_cell: [n_batches, 3, 3] instead of [3, 3]

  - cell_position, cell_momentum, cell_mass: [n_batches] instead of scalar

- Fix tensor broadcasting in exp_iL1, exp_iL2 with proper atom-to-batch mapping

- Update compute_cell_force for per-batch kinetic energy and stress calculations

- Fix npt_nose_hoover_init to properly initialize batched cell variables

- Update npt_nose_hoover_invariant for per-batch energy conservation

- Replace pbc_wrap_general with pbc_wrap_batched for proper PBC handling

- Fix example script 3.8_MACE_NPT_Nose_Hoover.py output formatting

Enables multiple independent NPT systems in a single simulation while maintaining backward compatibility for single-batch systems.

* fix: Remove cell dimension squeezing in NVT Nose-Hoover integrator

- Remove problematic cell.squeeze(0) that breaks batching support

- Fix calculate_momenta function call to use correct signature with batch parameter

- Resolves RuntimeError when using MACE with NVT Nose-Hoover thermostat

Fixes example script 3.5_MACE_NVT_Nose_Hoover.py which was failing due to

neighbor list function receiving wrong tensor shapes when cell batch

dimension was incorrectly removed.

* fix: Handle scalar kT and batched stress tensors in NPT Nose-Hoover

- Convert scalar kT to tensor before accessing .ndim attribute in npt_nose_hoover_init and update_cell_mass

- Fix stress tensor trace computation in compute_cell_force to handle 3D batched tensors

- Use torch.diagonal().sum() for batched stress tensors instead of torch.trace()

Fixes Lennard-Jones NPT Nose-Hoover script that was failing with:

- AttributeError: 'float' object has no attribute 'ndim'

- RuntimeError: trace: expected a matrix, but got tensor with dim 3

* fix: Handle batched cell tensors in get_fractional_coordinates

- Replace deprecated .T with .mT for matrix transpose on 3D tensors
- Add support for batched cell tensors with shape [n_batches, 3, 3]
- Extract first batch cell matrix when cell.ndim == 3
- Maintains backward compatibility with 2D cell matrices

Fixes batched silicon workflow script that was failing with:
- UserWarning about deprecated .T usage on >2D tensors
- RuntimeError: linalg.solve: A must be batches of square matrices

The get_fractional_coordinates function now properly handles both
single [3,3] and batched [n_batches,3,3] cell tensors, enabling a2c_silicon_batched.py workflow to run

* replace .transpose(-2, -1) with .mT everywhere

* fix nvt + npt integrators: ensure consistent batch dimensions in kinetic energy calculations

- Add missing `batch=state.batch` parameter to `calc_kinetic_energy` calls in NPT integrator
- Enhance NVT/NPT invariant functions with explicit broadcasting for chain variables
- Replace inefficient manual loops with batch-aware kinetic energy calculation in NPT invariant
- Fix undefined variable reference in NPT invariant function (n_batches → state.n_batches)

Resolves broadcasting issues where scalar kinetic energy was incorrectly combined with
batched energy and temperature tensors, ensuring all energy terms have consistent
batch dimensions before addition.

* fix transforms.py: prevent silent data corruption in get_fractional_coordinates

Replace problematic batched cell handling that only processed the first batch
(cell[0]) with explicit NotImplementedError. This prevents silent data
corruption where multi-batch systems would incorrectly use only the first
batch's cell parameters for all coordinate transformations.

- Raise NotImplementedError for 3D batched cell tensors instead of silently
  ignoring batches 1, 2, ... N
- Preserve existing functionality for 2D cell matrices
- Add clear error message indicating limitation and suggesting workarounds

Breaking change: Code that previously silently failed will now explicitly
error, but this prevents incorrect results in multi-batch scenarios.

* fix nvt_langevin: handle None gamma parameter correctly

* fix npt: missing PBC check in Nose-Hoover position update

- Check state.pbc before applying ts.transforms.pbc_wrap_batched
- Return unwrapped positions when state.pbc is False
- Ensure consistent behavior with NPT Langevin implementation

* Initialize cur_deform_grad to prevent UnboundLocalError

* fix nvt: compute degrees of freedom per batch in Nose-Hoover init

Replace count_dof() with proper batch-aware DOF calculation using
torch.bincount(state.batch) to ensure consistency with invariant function.
Previously ignored batch structure, causing incorrect DOF for batched systems.

* fix /5.1_a2c_silicon_batched.py: restore single-batch cell tensors support in transforms.py's get_fractional_coordinates

- Handle batched cell tensors with shape [1, 3, 3] by auto-squeezing to [3, 3]
- Improve error messages for multi-batch cases to be more informative
- Add comprehensive tests for batched cell tensor scenarios
- Fixes NotImplementedError in examples/scripts/5_Workflow/5.1_a2c_silicon_batched.py:159
- Maintains full backward compatibility with existing 2D cell matrix usage

---------

Signed-off-by: Janosh Riebesell <[email protected]>
Co-authored-by: Janosh Riebesell <[email protected]>
@janosh janosh added fix Bug fix models Model-related issues and PRs labels Jun 10, 2025
Copy link

coderabbitai bot commented Jun 10, 2025

Warning

Rate limit exceeded

@janosh has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 5 minutes and 0 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 2c3a862 and e51ff50.

📒 Files selected for processing (10)
  • .github/workflows/docs.yml (1 hunks)
  • .github/workflows/test.yml (2 hunks)
  • README.md (1 hunks)
  • docs/conf.py (1 hunks)
  • docs/tutorials/index.rst (1 hunks)
  • examples/tutorials/metatomic_tutorial.py (3 hunks)
  • pyproject.toml (2 hunks)
  • tests/models/test_metatensor.py (0 hunks)
  • tests/models/test_metatomic.py (1 hunks)
  • torch_sim/models/metatomic.py (7 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
cla-signed Contributor license agreement signed fix Bug fix models Model-related issues and PRs
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants