Skip to content

Document and type distributed utils; fix pad_helper padding the wrong dim - #1697

Open
harshaa765 wants to merge 13 commits into
NVIDIA:mainfrom
harshaa765:add-type-annotations-distributed-utils
Open

harshaa765 wants to merge 13 commits into
NVIDIA:mainfrom
harshaa765:add-type-annotations-distributed-utils

Conversation

@harshaa765

@harshaa765 harshaa765 commented Jun 5, 2026 •

Copy link
Copy Markdown

PhysicsNeMo Pull Request

Description

This PR adds type annotations and NumPy-style docstrings to the helpers in physicsnemo/distributed/utils.py, which resolves the # TODO this also needs more docstrings note at the top of that file. While writing tests for the documented behavior, I found that pad_helper padded the wrong dimension, so this PR also includes that fix.

Documentation and typing (no behavior change)

  • Adds docstrings to compute_split_shapes, get_memory_format, pad_helper, truncate_helper, split_tensor_along_dim, distributed_transpose, _reduce, and _split, and a Returns section to reduce_loss.
  • Adds type annotations to all of these helpers, including the review suggestions (Literal["zero", "conj"] for mode, built-in tuple[...]/list[...] return types).
  • Removes the now-documented compute_split_shapes and split_tensor_along_dim entries from the interrogate baseline.

Fix: pad_helper padded the last dimension regardless of dim

  • F.pad lists its (left, right) padding pairs starting from the last dimension. pad_helper always wrote the pad amount at index 1, which is the right-hand side of the last dimension.
  • As a result, pad_helper(x, dim=1, ...) on a 3-D tensor padded dimension 2 instead, and mode="conj" then raised an error.
  • The fix writes the pad amount to the final entry of the list. For the last dimension, both indices are the same slot, so the existing callers in distributed/fft.py behave as before.
  • pad_helper and truncate_helper now index with tuples. Indexing with a list is deprecated in PyTorch and currently emits a warning.
  • The "too few elements" error in split_tensor_along_dim was missing its f prefix and printed literal {dim} placeholders. It is now an f-string.

Update since the previous review round

  • Merged main.
  • Fixed ruff errors: an unused Tuple import and two signatures that needed reformatting.
  • Fixed the list[torch.Tensor, ...] annotation from the applied suggestion. list takes a single type argument, so it is now list[torch.Tensor].
  • Added CHANGELOG entries.

Tests

  • New test/distributed/test_utils_helpers.py with single-process tests for:
    • compute_split_shapes
    • pad_helper, in both modes, along every dimension
    • truncate_helper
    • split_tensor_along_dim
  • 6 of the new tests fail on main and pass with this change.
  • pytest test/distributed: 174 passed, 48 skipped. I ran this on CPU only, so the multi-GPU tests are among the skipped ones.
  • ruff check/format and the docstring-coverage hook pass.

Checklist

  • I am familiar with the Contributing Guidelines.
  • New or existing tests cover these changes.
  • The documentation is up to date with these changes.
  • The CHANGELOG.md is up to date with these changes.
  • An issue is linked to this pull request. (No issue; this PR addresses the TODO in distributed/utils.py.)
  • If I am implementing a new model or modifying any existing model, I have followed the Models Implementation Coding Standards. (Not applicable.)

Dependencies

None.

Addresses the TODO at line 17 requesting improved docstrings.
Adds full PEP 484 type annotations and NumPy-style docstrings to all
previously untyped functions: get_memory_format, pad_helper,
truncate_helper, split_tensor_along_dim, distributed_transpose,
_reduce, and _split. Also adds the missing Optional[float] return
type to reduce_loss. No logic changes.
@harshaa765
harshaa765 requested a review from coreyjadams as a code owner June 5, 2026 11:18
@copy-pr-bot

copy-pr-bot Bot commented Jun 5, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@greptile-apps

greptile-apps Bot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Retrigger

The PR appears safe to merge; no blocking or non-blocking actionable defects remain.

Findings

  1. P2 The TODO comment the PR explicitly states it is addressing is still present. Since the docstrings have been added, the comment should be removed to keep the file tidy. ▶

Summary

This PR documents and types the distributed tensor utilities while correcting pad_helper so it pads the requested dimension rather than always padding the last dimension.

  • Adds NumPy-style docstrings and type annotations to distributed helpers.
  • Corrects dimension-specific padding and replaces deprecated list-based tensor indexing with tuple indexing.
  • Fixes interpolation in the split error message.
  • Adds focused CPU tests and updates the documentation baseline and changelog.

Reviews (2) · Last reviewed commit: "fix(distributed): pad the requested dim ..."

Comment thread physicsnemo/distributed/utils.py Outdated
Comment on lines +17 to +18
# TODO this also needs more docstrings
from typing import List, Optional
from typing import List, Optional, Tuple

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.

P2 The TODO comment the PR explicitly states it is addressing is still present. Since the docstrings have been added, the comment should be removed to keep the file tidy.

Suggested change
# TODO this also needs more docstrings
from typing import List, Optional
from typing import List, Optional, Tuple
from typing import List, Optional, Tuple

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Comment thread physicsnemo/distributed/utils.py Resolved
Updates the docstring to correctly state "is greater than or equal to" instead of "exceeds" to accurately reflect the 0-indexed tensor dimension check.

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Comment thread physicsnemo/distributed/utils.py Outdated
def pad_helper(tensor, dim, new_size, mode="zero"):
"""Util for padding tensors"""
def pad_helper(
tensor: torch.Tensor, dim: int, new_size: int, mode: str = "zero"

@peterdsharpe peterdsharpe Jun 5, 2026 •

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.

Suggested change
tensor: torch.Tensor, dim: int, new_size: int, mode: str = "zero"
tensor: torch.Tensor, dim: int, new_size: int, mode: Literal["zero", "conj"] = "zero"

+ add from typing import Literal up top

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good suggestion — applied in 84947d1. Narrowed mode from str to Literal["zero", "conj"] and added Literal to the typing imports. Updated the docstring parameter type to match as well.

Comment thread physicsnemo/distributed/utils.py Resolved
Comment thread physicsnemo/distributed/utils.py Resolved
peterdsharpe and others added 4 commits June 5, 2026 09:36
Replace `str` with `Literal["zero", "conj"]` for the mode parameter
in pad_helper, as those are the only two valid values. Also adds
Literal to the typing imports and updates the docstring to match.

Addresses reviewer suggestion from peterdsharpe.
- Remove the resolved TODO comment (docstrings have now been added)
- Add missing Returns section to reduce_loss, documenting that
  non-destination ranks receive None
@github-actions

github-actions Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

This pull request is stale because it has been open for 90 days with no activity. Remove the stale label or comment to keep it open, otherwise this will be closed in 14 days.

@github-actions github-actions Bot added the stale label Sep 6, 2026
Harshdeep Sharma added 3 commits September 17, 2026 09:18
Signed-off-by: Harshdeep Sharma <harsh.sharma52@gmail.com>
- Drop the now-unused `Tuple` import (ruff F401) and apply ruff format
  to the `pad_helper` and `reduce_loss` signatures.
- `list` takes a single type argument: annotate `distributed_transpose`
  as returning `tuple[list[torch.Tensor], dist.Work | None]` and match
  the Returns sections to the built-in generics used in the signatures.
- Document `compute_split_shapes`, the last undocumented helper, and
  drop both functions from the interrogate baseline.
- Add a CHANGELOG entry.

Signed-off-by: Harshdeep Sharma <harsh.sharma52@gmail.com>
pad_helper always wrote the pad amount to index 1 of the F.pad list,
which is the right-hand side of the last dimension, so padding any other
dimension silently padded the last one instead (and mode="conj" then
failed). F.pad lists pairs from the last dimension backwards, so the
right-hand padding of `dim` is the final entry. Existing callers only pad
the last dimension, where both indices coincide, so their behavior is
unchanged.

Also index with tuples instead of lists in pad_helper and
truncate_helper (list indexing is deprecated in PyTorch), make the
split_tensor_along_dim error message an f-string, and add single-process
tests for the tensor helpers.

Signed-off-by: Harshdeep Sharma <harsh.sharma52@gmail.com>
@harshaa765 harshaa765 changed the title feat(distributed): add type annotations and docstrings to utils.py Document and type distributed utils; fix pad_helper padding the wrong dim Sep 17, 2026
@harshaa765

Copy link
Copy Markdown
Author

@greptileai please re-review. Since the last review: merged main, fixed the ruff failures and the list[torch.Tensor, ...] annotation, documented compute_split_shapes, and fixed pad_helper padding the last dimension instead of dim (06a86c3, with new CPU tests).

Harshdeep Sharma added 2 commits September 17, 2026 18:32
Signed-off-by: Harshdeep Sharma <harsh.sharma52@gmail.com>
Signed-off-by: Harshdeep Sharma <harsh.sharma52@gmail.com>
@github-actions github-actions Bot removed the stale label Sep 20, 2026
Signed-off-by: Harshdeep Sharma <harshsharma52@gmail.com>
@harshaa765

Copy link
Copy Markdown
Author

Synced with main (only CHANGELOG.md conflicted). @coreyjadams @ktangsali @negin513 could you take a look when you have a moment?

Only CHANGELOG.md conflicted. Both entries move to the unreleased 2.4.0
section now that 2.3.0 is released.

Signed-off-by: Harshdeep Sharma <harsh.sharma52@gmail.com>
@harshaa765

Copy link
Copy Markdown
Author

Synced with main again and moved the CHANGELOG entries to 2.4.0. @peterdsharpe your suggestions from June are in. Could you review this, or point me to the right reviewer?

I also have #1701 (EnsembleMSE/EnsembleRMSE) and #1999 (AeroJEPA mask fix) waiting on a first review, if you know who should look at those. All three need /ok to test to run CI. Maintainers can push to the branches if the CHANGELOG conflicts come back.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants