Skip to content

Batch cloner ChangeBlock commits - #5461

Closed
ClawLabby wants to merge 4 commits into
isaac-sim:developfrom
ClawLabby:pr/cloner-changeblock-batch
Closed

ClawLabby wants to merge 4 commits into
isaac-sim:developfrom
ClawLabby:pr/cloner-changeblock-batch

Conversation

@ClawLabby

@ClawLabby ClawLabby commented Apr 30, 2026 •

Copy link
Copy Markdown

Summary

This changes USD environment replication to commit smaller batches of cloned env specs instead of committing an entire depth layer in one Sdf.ChangeBlock. The default batch size is one env per ChangeBlock, which reduces startup contention when distributed ranks build Newton scenes concurrently.

Results

With #5215 landed, this PR brings Velocity-Flat-G1 Newton startup for 4 GPUs x 4096 environments/GPU down from 289s to 76s.

@github-actions github-actions Bot added the isaac-lab Related to Isaac Lab team label Apr 30, 2026

@isaaclab-review-bot isaaclab-review-bot 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.

🤖 Isaac Lab Review Bot

Summary

This PR introduces batched Sdf.ChangeBlock commits in usd_replicate() to reduce multi-process contention during distributed training startup. The implementation extracts environment copying into a helper function _replicate_env_batch() and processes environments in configurable chunks (default: 1 env per ChangeBlock). The change is functionally equivalent to the previous single-ChangeBlock-per-depth-layer approach but with finer commit granularity.

Architecture Impact

The change is well-contained within cloner_utils.py. The usd_replicate() function is called from:

  1. clone_from_template() in the same file (lines 74, 84)
  2. External callers via the public API

The new _batch_size parameter is private (underscore-prefixed), so external callers continue using the default behavior. The internal call sites in clone_from_template() don't pass _batch_size, meaning they get the new default of 1 env per ChangeBlock. This should be intentional but warrants verification that the performance regression in single-process scenarios (more ChangeBlock commits = more overhead) is acceptable.

Implementation Verdict

Minor fixes needed

Test Coverage

Good coverage for the new functionality:

  • test_usd_replicate_changeblock_batch_size validates batched replication produces correct results with _batch_size=2
  • test_usd_replicate_rejects_invalid_batch_size validates the error handling for _batch_size=0

Missing coverage:

  • No test for _batch_size < 0 (negative values)
  • No test verifying the number of ChangeBlock commits matches expectations (though this would require deeper mocking)

CI Status

No CI checks available yet — manual validation reported in PR description.

Findings

🟡 Warning: cloner_utils.py:228 — Negative batch sizes bypass validation
The validation if _batch_size < 1 correctly catches zero but the error message and test only cover zero. While negative values are also caught, consider testing _batch_size=-1 for completeness, or adjust the error message to clarify the constraint.

🔵 Improvement: cloner_utils.py:146-191 — Helper function could validate inputs
_replicate_env_batch() assumes wid_list indices are valid for positions and quaternions tensors. If a caller passes inconsistent data (e.g., wid=10 but positions has shape [5, 3]), the error will be an obscure index-out-of-bounds from p = positions[wid]. Consider adding a bounds check or documenting the precondition explicitly.

🔵 Improvement: cloner_utils.py:163-164 — Comment about self-copy was removed
The original code had an explicit comment explaining why src == dp skips CopySpec:

if src == dp:
    pass  # self-copy: CreatePrimInLayer already ensures it exists; CopySpec would be destructive

The new code at line 168-169 silently skips via if src != dp: without the explanatory comment. The test test_usd_replicate_self_copy_skips_copy_spec documents this behavior, but a brief inline comment would aid future maintainability.

🔵 Improvement: cloner_utils.py:205 — Parameter naming convention
The _batch_size parameter uses a leading underscore suggesting it's private/internal, but it's exposed in the public function signature. Either:

  1. Remove the underscore if this is intended to be user-configurable in the future
  2. Add a note in the docstring that this is an internal tuning parameter not part of the stable API

🔵 Improvement: test_cloner.py:156-157 — Test uses float64 positions
The test uses dtype=torch.float64 for positions, which is fine, but the actual runtime typically uses float32. Consider adding a test case with float32 to verify no precision issues in the Gf.Vec3d(float(...)) conversion path, or change the test to use the more common dtype.

🟢 Positive: Depth-ordering preserved
The critical depth-ordering logic (parents replicated before children) is preserved in the refactor. The outer loop still iterates depth_to_indices in sorted order, and the inner batching only affects when ChangeBlocks commit within a depth layer, not the order of prim creation.

@isaaclab-review-bot isaaclab-review-bot 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.

🤖 Isaac Lab Review Bot

Summary

Follow-up review after new commits. The previous concerns have been addressed.

Previous Concerns Addressed

  • ✅ Negative batch size test coverage: test_usd_replicate_rejects_invalid_batch_size now uses @pytest.mark.parametrize("_batch_size", [0, -1]) to cover both zero and negative values.
  • ✅ Self-copy comment: Line 170-171 now includes an explanatory comment: # Self-copy is skipped because CreatePrimInLayer already ensures the prim exists, while CopySpec would overwrite the source spec.
  • ✅ Parameter documentation: The _batch_size parameter now has clear docstring documentation noting it's an "Internal tuning parameter" (lines 228-230).
  • ✅ Test dtype: test_usd_replicate_changeblock_batch_size now uses dtype=torch.float32 (line 161), matching typical runtime usage.

Implementation Verdict

Ship it — all previous concerns addressed, no new issues introduced.

ClawLabby and others added 3 commits May 1, 2026 02:41
In multi-GPU distributed training (e.g., 4-GPU Newton), usd_replicate
spends 226s in scene creation vs 16s single-GPU — a 14x slowdown.

Root cause: Sdf.ChangeBlock commit phase (notifications/recomposition)
serializes across processes. When all GPU processes commit a large
ChangeBlock simultaneously, they contend heavily.

Fix: Break the single large ChangeBlock into small batches (default: 1
env per ChangeBlock). The actual CopySpec work is ~2.5s regardless of
GPU count; only the commit phase contends.

Results on 4-GPU Newton (4096 envs/GPU):
- Before: 226s scene creation
- After:   47s scene creation (4.8x faster)

Single-GPU and PhysX performance is unaffected since contention only
occurs in the multi-process case.
@ClawLabby
ClawLabby force-pushed the pr/cloner-changeblock-batch branch from f90db1c to 7793f2a Compare May 1, 2026 02:44
@ClawLabby
ClawLabby marked this pull request as ready for review May 1, 2026 02:45
@greptile-apps

greptile-apps Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

Refactors usd_replicate in cloner_utils.py to commit USD environment specs in configurable batches (_batch_size, default 1) rather than one monolithic Sdf.ChangeBlock per depth level, reducing lock contention when multiple distributed ranks clone scenes concurrently. The PR reports a 4× speedup for 4-GPU Newton startup (289 s → 76 s).

Confidence Score: 4/5

Safe to merge; only P2 findings, all limited to documentation and pre-existing logic.

No P0 or P1 issues. Two P2 observations: the removed per-depth atomicity guarantee lacks a written rationale, and the xformOpOrder overwrite behavior (pre-existing) is now baked silently into the new named helper. Tests cover the new _batch_size parameter and validation path.

source/isaaclab/isaaclab/cloner/cloner_utils.py — the removed per-depth ChangeBlock comment warrants a brief inline explanation.

Important Files Changed

Filename Overview
source/isaaclab/isaaclab/cloner/cloner_utils.py Refactors usd_replicate to batch Sdf.ChangeBlock commits; introduces _replicate_env_batch helper and _batch_size parameter (default=1); removes the per-depth-level single-ChangeBlock guarantee (pre-existing composition-stability comment removed without documentation).
source/isaaclab/test/sim/test_cloner.py Adds two focused tests: one verifying multi-env batched replication produces correct positions, one verifying invalid batch sizes raise ValueError. Coverage is appropriate for the new parameter.
source/isaaclab/config/extension.toml Patch version bumped from 4.6.25 → 4.6.26, consistent with the changelog entry.
source/isaaclab/docs/CHANGELOG.rst Changelog entry added for 4.6.26, correctly describing the ChangeBlock batching fix.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[usd_replicate called] --> B{_batch_size >= 1?}
    B -- No --> C[raise ValueError]
    B -- Yes --> D[Sort sources by destination path depth]
    D --> E[Group indices by depth]
    E --> F[For each depth level in order]
    F --> G[For each source i at this depth]
    G --> H[Apply mask to wid_list]
    H --> I[Chunk wid_list by _batch_size]
    I --> J[_replicate_env_batch per chunk]
    J --> K[Sdf.ChangeBlock scoped to chunk]
    K --> L[CreatePrimInLayer for each wid]
    L --> M{src == dp?}
    M -- No --> N[CopySpec src to dp]
    M -- Yes --> O[skip self-copy]
    N --> P{positions / quaternions?}
    O --> P
    P -- Yes --> Q[Author xformOp:translate / orient]
    Q --> R[Overwrite xformOpOrder with op_names]
    P -- No --> S[Next wid in chunk]
    R --> S
    S --> T{More chunks?}
    T -- Yes --> I
    T -- No --> U{More sources at depth?}
    U -- Yes --> G
    U -- No --> V{More depths?}
    V -- Yes --> F
    V -- No --> W[Done]
Loading

Reviews (1): Last reviewed commit: "Address cloner batching review comments" | Re-trigger Greptile

Comment on lines 247 to +257
for depth in sorted(depth_to_indices.keys()):
with Sdf.ChangeBlock():
for i in depth_to_indices[depth]:
src = sources[i]
tmpl = destinations[i]
# Select target environments for this source (supports None, [E], or [S, E])
target_envs = env_ids if mask is None else env_ids[mask[i]]
for wid in target_envs.tolist():
dp = tmpl.format(wid)
Sdf.CreatePrimInLayer(rl, dp)
if src == dp:
pass # self-copy: CreatePrimInLayer already ensures it exists; CopySpec would be destructive
else:
Sdf.CopySpec(rl, Sdf.Path(src), rl, Sdf.Path(dp))

if positions is not None or quaternions is not None:
ps = rl.GetPrimAtPath(dp)
op_names = []
if positions is not None:
p = positions[wid]
t_attr = ps.GetAttributeAtPath(dp + ".xformOp:translate")
if t_attr is None:
t_attr = Sdf.AttributeSpec(ps, "xformOp:translate", Sdf.ValueTypeNames.Double3)
t_attr.default = Gf.Vec3d(float(p[0]), float(p[1]), float(p[2]))
op_names.append("xformOp:translate")
if quaternions is not None:
q = quaternions[wid]
o_attr = ps.GetAttributeAtPath(dp + ".xformOp:orient")
if o_attr is None:
o_attr = Sdf.AttributeSpec(ps, "xformOp:orient", Sdf.ValueTypeNames.Quatd)
# xyzw convention: q[3] is w, q[0:3] is xyz
o_attr.default = Gf.Quatd(float(q[3]), Gf.Vec3d(float(q[0]), float(q[1]), float(q[2])))
op_names.append("xformOp:orient")
# Only author xformOpOrder for the ops we actually authored
if op_names:
op_order = ps.GetAttributeAtPath(dp + ".xformOpOrder") or Sdf.AttributeSpec(
ps, UsdGeom.Tokens.xformOpOrder, Sdf.ValueTypeNames.TokenArray
)
op_order.default = Vt.TokenArray(op_names)
for i in depth_to_indices[depth]:
src = sources[i]
tmpl = destinations[i]
target_envs = env_ids if mask is None else env_ids[mask[i]]
wid_list = target_envs.tolist()

# Batch into smaller ChangeBlocks to avoid multi-process commit contention
for start in range(0, len(wid_list), _batch_size):
chunk = wid_list[start : start + _batch_size]
_replicate_env_batch(rl, src, tmpl, chunk, positions, quaternions)

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 Per-depth atomicity guarantee removed without explanation

The original implementation wrapped all sources at the same path depth in a single Sdf.ChangeBlock, and the accompanying comment explicitly said this was to "stabilize composition" and "avoid composition issues for nested or interdependent specs." That comment and the per-depth ChangeBlock envelope were both removed in this PR.

Now each source at depth D is committed in its own series of per-batch ChangeBlocks, interleaved with other sources at depth D. For Isaac Lab's typical case of fully independent environment prims this should be harmless, but the removal of the stated composition-stability guarantee is undocumented. A brief note explaining why per-depth atomicity is no longer needed (or that these sources are always independent at the same depth) would make the intent clear to future reviewers.

Comment on lines +192 to +196
if op_names:
op_order = ps.GetAttributeAtPath(dp + ".xformOpOrder") or Sdf.AttributeSpec(
ps, UsdGeom.Tokens.xformOpOrder, Sdf.ValueTypeNames.TokenArray
)
op_order.default = Vt.TokenArray(op_names)

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 xformOpOrder overwrites ops copied via CopySpec

After Sdf.CopySpec populates the destination prim (including any xformOpOrder from the source), this block unconditionally replaces xformOpOrder.default with only the ops authored in this call (op_names). If the source prim carried additional transform ops (e.g. xformOp:scale or a custom op), those are silently dropped from the order on every replicated copy.

This behaviour is identical to the code it replaced (pre-existing), so this PR doesn't introduce it. Still, since this function is being extracted as a named helper, it's a good moment to document the intentional narrowing — or to change to an append/merge strategy if callers expect source ops to survive replication.

@isaaclab-review-bot isaaclab-review-bot 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.

🤖 Isaac Lab Review Bot

Summary

All previous concerns have been addressed. The new commits added proper test parametrization for invalid batch sizes, clarified the self-copy skip comment, documented the _batch_size parameter, and fixed the test tensor dtype.

Implementation Verdict

Ship it — clean implementation with good test coverage for the batched ChangeBlock optimization.

@kellyguo11
kellyguo11 requested a review from ooctipus May 1, 2026 20:57
@kellyguo11 kellyguo11 moved this to In review in Isaac Lab May 1, 2026

@isaaclab-review-bot isaaclab-review-bot 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.

🤖 Isaac Lab Review Bot

Summary

All previous concerns from the prior review have been addressed. The implementation is clean and the test coverage is thorough for the batched ChangeBlock optimization.

Implementation Verdict

Ship it — the PR correctly implements batched Sdf.ChangeBlock commits to reduce distributed startup contention, with proper validation, documentation, and test coverage.

@kellyguo11 kellyguo11 self-assigned this May 8, 2026
@kellyguo11

Copy link
Copy Markdown
Contributor

Local runs were tested by Octi and we did not observe significant improvements

| Code / mode          | Batch | Per-rank scene creation              |    Mean | Wall time |
|----------------------|------:|--------------------------------------|--------:|----------:|
| Before PR 61c8a9457  | ~4096 | 13.540, 13.855, 14.105, 14.229 s     | 13.932s |   38.06 s |
| PR head              |     1 | 18.470, 18.504, 18.541, 18.567 s     | 18.521s |   41.61 s |
| PR head              |     8 | 13.252, 13.309, 13.366, 13.347 s     | 13.318s |   36.39 s |
| PR head        [best]|    32 | 12.517, 12.594, 12.533, 12.600 s     | 12.561s |   35.52 s |
| PR head              |   128 | 12.559, 12.614, 12.567, 12.610 s     | 12.587s |   35.93 s |
| PR head              |  4096 | 14.364, 14.794, 15.112, 15.312 s     | 14.896s |   38.71 s |

this is done by:

 for b in 1 8 32 128 4096; do
      ISAACLAB_CLONER_BATCH_SIZE=${b} \
      python -m torch.distributed.run --standalone --nnodes=1 --nproc_per_node=4 \
      scripts/reinforcement_learning/rsl_rl/train.py \
      --task=Isaac-Velocity-Flat-G1-v0 \
      --num_envs=4096 \
      --max_iterations=0 \
      --headless \
      --distributed \
      presets=newton
  done

@gavrielstate

gavrielstate commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

I'm still seeing massive startup performance benefits to this change when training DexSuite on a 4-GPU machine with:
NCCL_P2P_DISABLE=1 NCCL_IB_DISABLE=1 python -m torch.distributed.run --nproc_per_node=4 scripts/reinforcement_learning/rsl_rl/train.py --task Isaac-Dexsuite-Kuka-Allegro-Lift-v0 --num_envs 4096 --max_iterations 30 --headless --distributed presets=newton_mjwarp,cube,single_camera,newton_renderer,rgb64

@gavrielstate

Copy link
Copy Markdown
Contributor

I also saw significant performance differences on my 4 GPU test system with the Isaac-Velocity-Flat-G1-v0, so it's not just the DexSuite side of things:

I ran this command on ToT develop both with and without the cloner changes:

time NCCL_P2P_DISABLE=1 NCCL_IB_DISABLE=1 python -m torch.distributed.run --nproc_per_node=4   scripts/reinforcement_learning/rsl_rl/train.py   --task Isaac-Velocity-Flat-G1-v0   --num_envs 4096   --max_iterations 0   --headless   --distributed   presets=newton_mjwarp

With:

[INFO]: Time taken for scene creation Last: 71.520222 s, Mean: 71.520222 s, Std: 0.000000 s, N: 1
...
[INFO]: Time taken for scene creation Last: 74.033036 s, Mean: 74.033036 s, Std: 0.000000 s, N: 1
...
[INFO]: Time taken for scene creation Last: 72.624783 s, Mean: 72.624783 s, Std: 0.000000 s, N: 1
...
[INFO]: Time taken for scene creation Last: 72.831381 s, Mean: 72.831381 s, Std: 0.000000 s, N: 1
...
Training time: 1.4 seconds
Training time: 3.02 seconds
Training time: 3.16 seconds
Training time: 4.05 seconds
...
real 2m5.632s
user 36m35.964s
sys  5m11.357s

Without:

[INFO]: Time taken for scene creation Last: 141.931039 s, Mean: 141.931039 s, Std: 0.000000 s, N: 1
...
[INFO]: Time taken for scene creation Last: 288.149121 s, Mean: 288.149121 s, Std: 0.000000 s, N: 1
...
[INFO]: Time taken for scene creation Last: 290.347562 s, Mean: 290.347562 s, Std: 0.000000 s, N: 1
...
[INFO]: Time taken for scene creation Last: 290.517353 s, Mean: 290.517353 s, Std: 0.000000 s, N: 1
...
Training time: 85.09 seconds
Training time: 1.97 seconds
Training time: 2.85 seconds
Training time: 4.95 seconds
...
real 5m25.028s
user 23m41.655s
sys  125m47.351s

This test was on a Linux server within a docker environment without OV Hub or Isaac Sim installed, so

@AntoineRichard

AntoineRichard commented Aug 25, 2026 •

Copy link
Copy Markdown
Collaborator

Hi @ClawLabby — thank you so much for opening this PR, and for taking the time to contribute to Isaac Lab! 🙏

We're currently doing a big spring-clean of our pull request backlog, which had grown past 400 open PRs. Being honest: at that volume we stopped being able to give every contribution the attention it deserved, and this one is a case where we dropped the ball on getting back to you. That's on us, not on you.

Why this PR is being closed: Here is exactly what we found on this PR when we reviewed the backlog:

Opened 2026-04-30 (about 4 months ago)
Last commit on the branch 2026-05-03
Last activity from the author about 4 months ago
Target branch develop
Review status Never reviewed by a maintainer — nobody on the team got to it. Sorry about that.
Merge status Unknown
Size 4 commit(s), 3 file(s) changed, +131 / -43

It was picked up by the sweep because it has been open for about 4 months. It was then put in the "close" bucket because the author has been silent for about 4 months — which is the signal we used to tell apart pull requests that are still being worked on from ones that have genuinely been set aside.

We deliberately did not close pull requests that were approved and ready to land, or that were small and clearly still fixing a live bug — there were 27 of those, and we are merging them rather than closing them.

To be completely clear — this is not a judgement on the quality or the value of your work. It's purely about getting the queue down to a size where we can actually review things properly and give contributors real, timely feedback.

One thing worth knowing first: Isaac Lab 3.0 has since shipped. develop is now at
3.0.0 while main is still at 2.3.2, and 3.0 restructured a fair amount — quaternion
conventions, actuator collections, data access, and the Isaac Sim extension imports all
changed. The migration guide
is the place to start if you rebase.

It is also the honest reason a lot of these older pull requests stopped applying: the code
they touched moved or was rewritten underneath them.

If this change is still relevant, please reopen this PR or open a fresh one against develop. With the backlog down to a reviewable size, it should get a response a lot sooner than this one did.

Thanks again for contributing to Isaac Lab, and sorry for the long silence! 💚


🤖 This comment was drafted with AI assistance as part of a maintainer-led sweep of the Isaac Lab pull request backlog. A maintainer is behind this cleanup — but if this closure looks wrong, it may well be, so please push back and we'll take another look.

@github-project-automation github-project-automation Bot moved this from In review to Done in Isaac Lab Aug 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

isaac-lab Related to Isaac Lab team

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants