diff --git a/.github/actions/combine-results/action.yml b/.github/actions/combine-results/action.yml deleted file mode 100644 index 8ed66e3b4603..000000000000 --- a/.github/actions/combine-results/action.yml +++ /dev/null @@ -1,103 +0,0 @@ -# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). -# All rights reserved. -# -# SPDX-License-Identifier: BSD-3-Clause - -name: 'Combine XML Test Results' -description: 'Combines multiple XML test result files into a single file' - -inputs: - tests-dir: - description: 'Directory containing test result files' - default: 'tests' - required: false - output-file: - description: 'Output combined XML file path' - required: true - reports-dir: - description: 'Directory to store the combined results' - default: 'reports' - required: false - -runs: - using: composite - steps: - - name: Combine XML Test Results - shell: sh - run: | - # Function to combine multiple XML test results - combine_xml_results() { - local tests_dir="$1" - local output_file="$2" - local reports_dir="$3" - - echo "Combining test results from: $tests_dir" - echo "Output file: $output_file" - echo "Reports directory: $reports_dir" - - # Check if reports directory exists - if [ ! -d "$reports_dir" ]; then - echo "⚠️ Reports directory does not exist: $reports_dir" - mkdir -p "$reports_dir" - fi - - # Check if tests directory exists - if [ ! -d "$tests_dir" ]; then - echo "⚠️ Tests directory does not exist: $tests_dir" - echo "Creating fallback XML..." - echo 'Tests directory was not found' > "$output_file" - return - fi - - # Find all XML files in the tests directory - echo "Searching for XML files in: $tests_dir" - xml_files=$(find "$tests_dir" -name "*.xml" -type f 2>/dev/null | sort) - - if [ -z "$xml_files" ]; then - echo "⚠️ No XML files found in: $tests_dir" - echo "Creating fallback XML..." - echo 'No XML test result files were found' > "$output_file" - return - fi - - # Count XML files found - file_count=$(echo "$xml_files" | wc -l) - echo "✅ Found $file_count XML file(s):" - echo "$xml_files" | while read -r file; do - echo " - $file ($(wc -c < "$file") bytes)" - done - - # Create combined XML - echo "🔄 Combining $file_count XML files..." - echo '' > "$output_file" - echo '' >> "$output_file" - - # Process each XML file - combined_count=0 - echo "$xml_files" | while read -r file; do - if [ -f "$file" ]; then - echo " Processing: $file" - # Remove XML declaration and outer testsuites wrapper from each file - # Remove first line (XML declaration) and strip outer / tags - sed '1d; s/^//; s/<\/testsuites>$//' "$file" >> "$output_file" 2>/dev/null || { - echo " ⚠️ Warning: Could not process $file, skipping..." - } - combined_count=$((combined_count + 1)) - fi - done - - echo '' >> "$output_file" - echo "✅ Successfully combined $combined_count files into: $output_file" - - # Verify output file was created - if [ -f "$output_file" ]; then - echo "✅ Final output file created: $output_file" - echo "📊 Output file size: $(wc -c < "$output_file") bytes" - else - echo "❌ Failed to create output file: $output_file" - exit 1 - fi - } - - # Call the function with provided parameters - combine_xml_results "${{ inputs.tests-dir }}" "${{ inputs.output-file }}" "${{ inputs.reports-dir }}" diff --git a/.github/actions/ecr-build-push-pull/action.yml b/.github/actions/ecr-build-push-pull/action.yml index b9b8d4378594..b661d4b9fd62 100644 --- a/.github/actions/ecr-build-push-pull/action.yml +++ b/.github/actions/ecr-build-push-pull/action.yml @@ -37,11 +37,6 @@ inputs: description: Tag used for the ECR layer cache image (e.g. "cache-base", "cache-curobo"). required: false default: 'cache' - overlay-dockerfile-path: - description: 'Thin overlay Dockerfile applied on top of a deps cache hit.' - required: false - default: 'docker/Dockerfile.overlay' - runs: using: composite steps: @@ -67,15 +62,15 @@ runs: export DOCKER_CONFIG="${DOCKER_CONFIG_DIR}" if [ -n "${{ env.NGC_API_KEY }}" ]; then - echo "🟢 Logging into nvcr.io..." + echo "🔵 Logging into nvcr.io..." docker login -u \$oauthtoken -p ${{ env.NGC_API_KEY }} nvcr.io else - echo "🟠 NGC_API_KEY not set — skipping nvcr.io login (normal for fork PRs)" + echo "🟠 NGC_API_KEY not set - skipping nvcr.io login (normal for fork PRs)" fi ##### 2: Resolve ECR URL ##### - # Tries: explicit input → ECR_CACHE_URL env var → SSM parameter on EC2. + # Tries: explicit input >> ECR_CACHE_URL env var >> SSM parameter on EC2. # Exports ECR_URL to GITHUB_ENV and sets output `available`. - name: Resolve ECR URL @@ -87,13 +82,13 @@ runs: ECR_URL="${INPUT_ECR_URL:-}" if [ -z "${ECR_URL}" ]; then - echo "🟢 ecr-url input not set, trying ECR_CACHE_URL env var..." + echo "🔵 ecr-url input not set, trying ECR_CACHE_URL env var..." ECR_URL="${ECR_CACHE_URL:-}" [ -n "${ECR_URL}" ] && echo "🟢 Using ECR_CACHE_URL env var: ${ECR_URL}" fi if [ -z "${ECR_URL}" ]; then - echo "🟢 ECR_CACHE_URL env var not set, trying SSM..." + echo "🔵 ECR_CACHE_URL env var not set, trying SSM..." IMDS_TOKEN=$(curl -sf -X PUT "http://169.254.169.254/latest/api/token" \ -H "X-aws-ec2-metadata-token-ttl-seconds: 21600") || true INSTANCE_ID=$(curl -sf -H "X-aws-ec2-metadata-token: ${IMDS_TOKEN}" \ @@ -109,10 +104,10 @@ runs: if [ -n "${ECR_URL}" ]; then echo "🟢 Resolved ECR URL from SSM (/github-runner/${INSTANCE_ID}/ecr-cache-url): ${ECR_URL}" else - echo "🟢 SSM parameter not found for instance ${INSTANCE_ID}" + echo "🔵 SSM parameter not found for instance ${INSTANCE_ID}" fi else - echo "🟢 Not running on EC2 or IMDS unavailable, skipping SSM lookup" + echo "🔵 Not running on EC2 or IMDS unavailable, skipping SSM lookup" fi fi @@ -136,7 +131,7 @@ runs: AWS_REGION=$(echo "${REGISTRY}" | sed 's/.*\.dkr\.ecr\.\(.*\)\.amazonaws\.com/\1/') if [ "${AWS_REGION}" = "${REGISTRY}" ]; then - echo "🔴 Invalid ECR URL — cannot extract AWS region: ${ECR_URL}" + echo "🔴 Invalid ECR URL - cannot extract AWS region: ${ECR_URL}" echo "🔴 Expected format: .dkr.ecr..amazonaws.com/" exit 1 fi @@ -148,39 +143,55 @@ runs: echo "ECR_IMAGE=${ECR_IMAGE}" >> "$GITHUB_ENV" echo "CACHE_IMAGE=${CACHE_IMAGE}" >> "$GITHUB_ENV" - echo "🟢 Logging into ECR registry..." + echo "🔵 Logging into ECR registry..." aws ecr get-login-password --region "${AWS_REGION}" | \ docker login --username AWS --password-stdin "${REGISTRY}" - ##### 4: Pull exact image from ECR ##### + ##### 4: Check if exact image exists in ECR ##### - # If the exact per-commit image already exists in ECR, pull and tag it locally. - # Sets output `hit: true` to skip all subsequent build/push steps. + # Lightweight manifest check - fetches only the image manifest (~KB), + # not the actual layers. If the exact per-commit image already exists + # in ECR, sets output `hit: true` to skip all subsequent build/push steps. - - name: Pull exact image from ECR + - name: Check exact image in ECR id: pull-exact if: steps.resolve-ecr.outputs.available == 'true' shell: bash run: | - echo "🟢 Trying to pull commit-tagged ${ECR_IMAGE} from ECR..." - if docker pull "${ECR_IMAGE}" 2>/dev/null; then - docker tag "${ECR_IMAGE}" "${{ inputs.image-tag }}" - echo "🟢 Commit-tagged image pulled, skipping build!" + echo "🔵 Checking if commit-tagged image exists in ECR >> ${ECR_IMAGE}" + if docker manifest inspect "${ECR_IMAGE}" >/dev/null 2>&1; then + echo "🟢 Commit-tagged image found in ECR, skipping build!" echo "hit=true" >> "$GITHUB_OUTPUT" else echo "🟠 Image ${ECR_IMAGE} not found in ECR, will try deps-cache strategy..." fi - ##### 5: Compute deps hash and try overlay ##### + # Pull the image when the manifest check succeeded but the image is not + # available locally (test jobs need it for `docker run`). Build jobs + # that only push to ECR will already have the image or don't need it. + - name: Pull exact image from ECR + if: steps.pull-exact.outputs.hit == 'true' + shell: bash + run: | + if docker image inspect "${{ inputs.image-tag }}" >/dev/null 2>&1; then + echo "🟢 Image already available locally, skipping pull" + else + echo "🔵 Pulling ${ECR_IMAGE} from ECR..." + docker pull "${ECR_IMAGE}" + docker tag "${ECR_IMAGE}" "${{ inputs.image-tag }}" + echo "🟢 Image pulled and tagged as ${{ inputs.image-tag }}" + fi + + ##### 5: Check deps cache ##### # Hashes installation-relevant files + the base image digest to produce a stable - # deps- ECR tag. If it exists, builds only the thin final-COPY overlay - # (seconds) instead of the full image (40-60 min). + # deps- ECR tag. If the image exists in ECR, the build job succeeds + # immediately and test jobs pull the deps image with a source volume mount. # Edit DEPS_FILES or DEPS_MANIFEST_PATTERN when install # inputs change (new packages, new manifests, etc.). - - name: Compute deps hash and try overlay + - name: Check deps cache id: deps-cache if: steps.resolve-ecr.outputs.available == 'true' && steps.pull-exact.outputs.hit != 'true' shell: bash @@ -208,36 +219,26 @@ runs: BASE_IMAGE_UNIQ_ID="${{ inputs.isaacsim-base-image }}:${{ inputs.isaacsim-version }}" fi - echo "🟢 Base image ID: ${BASE_IMAGE_UNIQ_ID}" + echo "🔵 Base image ID: ${BASE_IMAGE_UNIQ_ID}" MANIFEST_FILES=$(git ls-files | grep -E "${DEPS_MANIFEST_PATTERN}" || true) FILE_HASH=$(git ls-files -s "${DEPS_FILES[@]}" ${MANIFEST_FILES} 2>/dev/null \ | sha256sum | cut -c1-16) DEPS_HASH=$(printf '%s %s' "${FILE_HASH}" "${BASE_IMAGE_UNIQ_ID}" | sha256sum | cut -c1-16) DEPS_ECR_IMAGE="${ECR_URL}:deps-${DEPS_HASH}" - echo "🟢 Deps hash: ${DEPS_HASH}" - echo "🟢 Trying to pull deps image ${DEPS_ECR_IMAGE} from ECR..." - - if docker pull "${DEPS_ECR_IMAGE}" 2>/dev/null; then - echo "🟢 Deps cache HIT!!! Building thin overlay (final COPY only)..." - OVERLAY_BUILDER="ci-builder-overlay-${{ github.run_id }}-${{ github.job }}" - docker buildx create --use --driver docker-container --name "${OVERLAY_BUILDER}" \ - || docker buildx use "${OVERLAY_BUILDER}" - trap 'docker buildx rm "${OVERLAY_BUILDER}" || true' EXIT - docker buildx build \ - --progress=plain \ - --platform linux/amd64 \ - -f "${{ inputs.overlay-dockerfile-path }}" \ - --build-arg "DEPS_IMAGE=${DEPS_ECR_IMAGE}" \ - --build-arg "ISAACLAB_PATH_ARG=/workspace/isaaclab" \ - -t "${{ inputs.image-tag }}" \ - --load \ - . - echo "🟢 Overlay build complete!" - docker tag "${{ inputs.image-tag }}" "${ECR_IMAGE}" - echo "🟢 Pushing overlay image ${ECR_IMAGE} to ECR for future reuse..." - docker push "${ECR_IMAGE}" - echo "overlay-built=true" >> "$GITHUB_OUTPUT" + echo "🔵 Deps hash: ${DEPS_HASH}" + echo "🔵 Checking if deps image ${DEPS_ECR_IMAGE} exists in ECR..." + + # Lightweight manifest check - fetches only the image manifest (~KB), + # not the actual layers, so this completes in seconds. + if docker manifest inspect "${DEPS_ECR_IMAGE}" >/dev/null 2>&1; then + echo "🟢 Deps cache HIT!!! Image exists in ECR: ${DEPS_ECR_IMAGE}" + # Create a commit-tagged alias pointing to the same manifest (registry-side, + # no layer download). Test jobs will pull this tag normally. + echo "🔵 Tagging as commit image ${ECR_IMAGE}..." + docker buildx imagetools create -t "${ECR_IMAGE}" "${DEPS_ECR_IMAGE}" + echo "🟢 Tagged ${ECR_IMAGE} >> ${DEPS_ECR_IMAGE}" + echo "deps-cache-hit=true" >> "$GITHUB_OUTPUT" else echo "🟠 Deps cache MISS 😿😿😿 (${DEPS_HASH}). Will build now. 🐢🐢🐢" echo "DEPS_ECR_IMAGE=${DEPS_ECR_IMAGE}" >> "$GITHUB_ENV" @@ -246,11 +247,11 @@ runs: ##### 6: Full build ##### - # Runs when neither the exact image nor the deps-overlay was available. + # Runs when neither the exact image nor the deps cache was available. # Uses ECR layer cache (--cache-from/--cache-to) when ECR is available. - name: Full build - if: steps.pull-exact.outputs.hit != 'true' && steps.deps-cache.outputs.overlay-built != 'true' + if: steps.pull-exact.outputs.hit != 'true' && steps.deps-cache.outputs.deps-cache-hit != 'true' shell: bash run: | BUILD_ARGS=( @@ -277,7 +278,7 @@ runs: || docker buildx use "${BUILDER_NAME}" trap 'docker buildx rm "${BUILDER_NAME}" || true' EXIT - echo "🟢 Building ${{ inputs.image-tag }}..." + echo "🔵 Building ${{ inputs.image-tag }}..." docker buildx build --load "${BUILD_ARGS[@]}" . ##### 7: Push to ECR ##### @@ -289,10 +290,10 @@ runs: if: > steps.resolve-ecr.outputs.available == 'true' && steps.pull-exact.outputs.hit != 'true' && - steps.deps-cache.outputs.overlay-built != 'true' + steps.deps-cache.outputs.deps-cache-hit != 'true' shell: bash run: | - echo "🟢 Pushing ${ECR_IMAGE} to ECR..." + echo "🔵 Pushing ${ECR_IMAGE} to ECR..." docker push "${ECR_IMAGE}" echo "🟢 Pushed ${ECR_IMAGE}" @@ -305,7 +306,7 @@ runs: if: env.PUSH_DEPS_IMAGE == 'true' shell: bash run: | - echo "🟢 Pushing deps image for future cache hits: ${DEPS_ECR_IMAGE}" + echo "🔵 Pushing deps image for future cache hits: ${DEPS_ECR_IMAGE}" docker tag "${{ inputs.image-tag }}" "${DEPS_ECR_IMAGE}" docker push "${DEPS_ECR_IMAGE}" diff --git a/.github/actions/run-package-tests/action.yml b/.github/actions/run-package-tests/action.yml new file mode 100644 index 000000000000..cb32d46d4c6b --- /dev/null +++ b/.github/actions/run-package-tests/action.yml @@ -0,0 +1,128 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +name: 'Run Package Tests' +description: > + Pulls the Docker image from ECR, runs pytest inside the container, uploads + results as an artifact, and fails fork PRs on test failures. + NOTE: The calling job must check out the code before using this action. + +inputs: + image-tag: + description: 'Docker image tag' + required: true + isaacsim-base-image: + description: 'IsaacSim base image' + required: true + isaacsim-version: + description: 'IsaacSim version' + required: true + dockerfile-path: + description: 'Path to Dockerfile' + default: 'docker/Dockerfile.base' + required: false + cache-tag: + description: 'ECR cache tag' + default: 'cache-base' + required: false + filter-pattern: + description: 'Pattern to filter test files (e.g., isaaclab_tasks)' + default: '' + required: false + shard-index: + description: 'Zero-based shard index' + default: '' + required: false + shard-count: + description: 'Total number of shards' + default: '' + required: false + curobo-only: + description: 'Run only cuRobo and SkillGen tests' + default: 'false' + required: false + quarantined-only: + description: 'Run only quarantined tests' + default: 'false' + required: false + include-files: + description: 'Comma-separated list of specific test files to include' + default: '' + required: false + pytest-options: + description: 'Additional pytest options' + default: '' + required: false + container-name: + description: 'Docker container name prefix (run-id is appended automatically)' + required: true +runs: + using: composite + steps: + - name: Record pull start time + id: pull-start + shell: bash + run: echo "time=$(date +%s)" >> "$GITHUB_OUTPUT" + + - name: Pull image from ECR + uses: ./.github/actions/ecr-build-push-pull + with: + image-tag: ${{ inputs.image-tag }} + isaacsim-base-image: ${{ inputs.isaacsim-base-image }} + isaacsim-version: ${{ inputs.isaacsim-version }} + dockerfile-path: ${{ inputs.dockerfile-path }} + cache-tag: ${{ inputs.cache-tag }} + + - name: Report pull duration + if: always() + shell: bash + run: | + start_time="${{ steps.pull-start.outputs.time }}" + if [ -z "$start_time" ]; then + echo "🟠 Could not calculate pull duration (start time not recorded)" >> "$GITHUB_STEP_SUMMARY" + exit 0 + fi + elapsed=$(( $(date +%s) - start_time )) + printf "🔵 Image pull took %dm %ds\n" $((elapsed/60)) $((elapsed%60)) + echo "🔵 Docker Image Pulled in ${elapsed}s" >> "$GITHUB_STEP_SUMMARY" + + - name: Run Tests + uses: ./.github/actions/run-tests + with: + test-path: "tools" + result-file: "${{ github.job }}-report.xml" + container-name: "${{ inputs.container-name }}-${{ github.run_id }}-${{ github.run_attempt }}" + image-tag: ${{ inputs.image-tag }} + pytest-options: ${{ inputs.pytest-options }} + filter-pattern: ${{ inputs.filter-pattern }} + shard-index: ${{ inputs.shard-index }} + shard-count: ${{ inputs.shard-count }} + curobo-only: ${{ inputs.curobo-only }} + quarantined-only: ${{ inputs.quarantined-only }} + include-files: ${{ inputs.include-files }} + volume-mount-source: ${{ github.workspace }} + + - name: Check Test Results + if: always() + shell: bash + run: | + if [ -f "reports/${{ github.job }}-report.xml" ]; then + if grep -qE 'failures="[1-9][0-9]*"' reports/${{ github.job }}-report.xml || grep -qE 'errors="[1-9][0-9]*"' reports/${{ github.job }}-report.xml; then + echo "Tests failed for PR from fork. The test report is in the logs. Failing the job." + exit 1 + fi + else + echo "No test results file found. This might indicate test execution failed." + exit 1 + fi + + - name: Kill container on cancellation + if: cancelled() + shell: bash + run: | + CONTAINER="${{ inputs.container-name }}-${{ github.run_id }}-${{ github.run_attempt }}" + echo "🟠 Workflow cancelled, force-killing container ${CONTAINER}..." + docker kill "${CONTAINER}" 2>/dev/null || true + docker rm -f "${CONTAINER}" 2>/dev/null || true diff --git a/.github/actions/run-tests/action.yml b/.github/actions/run-tests/action.yml index f760de638da1..dc95acda7a5c 100644 --- a/.github/actions/run-tests/action.yml +++ b/.github/actions/run-tests/action.yml @@ -35,22 +35,26 @@ inputs: description: 'Run only cuRobo and SkillGen tests (requires the cuRobo Docker image)' default: 'false' required: false - cuda-issue-only: - description: 'Run only tests with known CUDA issues (isolated from general tests)' - default: 'false' - required: false - flaky-only: - description: 'Run only clearly flaky tests (<60% pass rate); these are skipped in normal jobs' - default: 'false' - required: false - slightly-flaky-only: - description: 'Run only mildly flaky tests (96%+ pass rate); these are skipped in normal jobs' + quarantined-only: + description: 'Run only tests listed in QUARANTINED_TESTS (skipped in normal jobs)' default: 'false' required: false include-files: description: 'Comma-separated list of specific test file paths to include (e.g., source/pkg/test/test_a.py,source/pkg/test/test_b.py)' default: '' required: false + shard-index: + description: 'Zero-based index of this shard (used with shard-count to split tests across parallel jobs)' + default: '' + required: false + shard-count: + description: 'Total number of shards (used with shard-index to split tests across parallel jobs)' + default: '' + required: false + volume-mount-source: + description: 'Host path to bind-mount at /workspace/isaaclab (for deps-cache-hit mode)' + default: '' + required: false runs: using: composite @@ -68,10 +72,11 @@ runs: local pytest_options="$6" local filter_pattern="$7" local curobo_only="$8" - local cuda_issue_only="$9" - local include_files="${10}" - local flaky_only="${11}" - local slightly_flaky_only="${12}" + local include_files="$9" + local quarantined_only="${10}" + local shard_index="${11}" + local shard_count="${12}" + local volume_mount_source="${13}" echo "Running tests in: $test_path" if [ -n "$pytest_options" ]; then @@ -83,12 +88,12 @@ runs: if [ "$curobo_only" = "true" ]; then echo "cuRobo-only mode enabled: running only cuRobo and SkillGen tests" fi - if [ "$cuda_issue_only" = "true" ]; then - echo "cuda-issue-only mode enabled: running only CUDA issue tests" - fi if [ -n "$include_files" ]; then echo "Include files: $include_files" fi + if [ -n "$shard_index" ] && [ -n "$shard_count" ]; then + echo "Shard: $shard_index of $shard_count" + fi # Create reports directory mkdir -p "$reports_dir" @@ -112,19 +117,9 @@ runs: echo "Setting TEST_CUROBO_ONLY=true" fi - if [ "$cuda_issue_only" = "true" ]; then - docker_env_vars="$docker_env_vars -e TEST_CUDA_ISSUE_ONLY=true" - echo "Setting TEST_CUDA_ISSUE_ONLY=true" - fi - - if [ "$flaky_only" = "true" ]; then - docker_env_vars="$docker_env_vars -e TEST_FLAKY_ONLY=true" - echo "Setting TEST_FLAKY_ONLY=true" - fi - - if [ "$slightly_flaky_only" = "true" ]; then - docker_env_vars="$docker_env_vars -e TEST_SLIGHTLY_FLAKY_ONLY=true" - echo "Setting TEST_SLIGHTLY_FLAKY_ONLY=true" + if [ "$quarantined_only" = "true" ]; then + docker_env_vars="$docker_env_vars -e TEST_QUARANTINED_ONLY=true" + echo "Setting TEST_QUARANTINED_ONLY=true" fi if [ -n "$include_files" ]; then @@ -135,9 +130,15 @@ runs: echo "Setting TEST_INCLUDE_FILES=$include_files_compact" fi + if [ -n "$shard_index" ] && [ -n "$shard_count" ]; then + docker_env_vars="$docker_env_vars -e TEST_SHARD_INDEX=$shard_index -e TEST_SHARD_COUNT=$shard_count" + echo "Setting TEST_SHARD_INDEX=$shard_index TEST_SHARD_COUNT=$shard_count" + fi + if [ -n "$filter_pattern" ]; then - if [[ "$filter_pattern" == not* ]]; then - # Handle "not pattern" case + if [[ "$filter_pattern" == "not "* ]]; then + # Handle "not " case - note the trailing space to avoid + # matching words that happen to start with "not". exclude_pattern="${filter_pattern#not }" docker_env_vars="$docker_env_vars -e TEST_EXCLUDE_PATTERN=$exclude_pattern" echo "Setting exclude pattern: $exclude_pattern" @@ -152,9 +153,22 @@ runs: echo "Docker environment variables: '$docker_env_vars'" - # Run tests in container with error handling - echo "🚀 Starting Docker container for tests..." - if docker run --name $container_name \ + # Volume mount for deps-cache-hit mode: bind-mount the checked-out + # source code over /workspace/isaaclab instead of baking it into the image. + docker_volume_args="" + if [ -n "$volume_mount_source" ]; then + docker_volume_args="-v ${volume_mount_source}:/workspace/isaaclab" + echo "🔵 Volume-mounting ${volume_mount_source} >> /workspace/isaaclab" + fi + + # Run tests in a detached container and follow logs. Running detached + # means the container lifecycle is independent of the shell - if the + # runner kills this step on cancellation, the `if: always()` cleanup + # step can still `docker kill` the container reliably. + # `docker logs -f` is the foreground process and is trivially killable. + echo "🔵 Starting Docker container for tests..." + docker run -d --name $container_name \ + --init --stop-timeout 5 \ --entrypoint bash --gpus all --network=host \ --security-opt=no-new-privileges:true \ --memory=$(echo "$(free -m | awk '/^Mem:/{print $2}') * 0.9 / 1" | bc)m \ @@ -162,6 +176,7 @@ runs: --oom-kill-disable=false \ --ulimit nofile=65536:65536 \ --ulimit nproc=4096:4096 \ + $docker_volume_args \ $docker_env_vars \ $image_tag \ -c " @@ -169,51 +184,118 @@ runs: cd /workspace/isaaclab mkdir -p tests echo 'Starting pytest with path: $test_path' - /isaac-sim/python.sh -m pytest --ignore=tools/conftest.py $test_path $pytest_options -v --junitxml=tests/$result_file || echo 'Pytest completed with exit code: $?' - "; then - echo "✅ Docker container completed successfully" + /isaac-sim/python.sh -m pytest --ignore=tools/conftest.py $test_path $pytest_options -v --junitxml=tests/$result_file + " + + # Stream container logs to CI output (this is the killable foreground process). + docker logs -f $container_name & + local logs_pid=$! + + # Wait for the container to exit and capture its exit code. + DOCKER_EXIT=$(docker wait $container_name) || DOCKER_EXIT=1 + + # Stop following logs. + kill $logs_pid 2>/dev/null || true + wait $logs_pid 2>/dev/null || true + + if [ $DOCKER_EXIT -eq 0 ]; then + echo "🟢 Docker container completed successfully" else - echo "⚠️ Docker container failed, but continuing to copy results..." + echo "🟠 Docker container failed (exit $DOCKER_EXIT), but continuing to copy results..." fi - # Copy test results with error handling - echo "📋 Attempting to copy test results..." - if docker cp $container_name:/workspace/isaaclab/tests/$result_file "$reports_dir/$result_file" 2>/dev/null; then - echo "✅ Test results copied successfully to $reports_dir/$result_file" + # Copy test results with error handling. + # When volume-mounted, test output lands on the host filesystem directly + # (docker cp cannot see bind-mounted paths after the container stops). + echo "🔵 Attempting to copy test results..." + if [ -n "$volume_mount_source" ] && [ -f "${volume_mount_source}/tests/$result_file" ]; then + cp "${volume_mount_source}/tests/$result_file" "$reports_dir/$result_file" + echo "🟢 Test results copied from volume mount to $reports_dir/$result_file" + elif cp_err=$(docker cp $container_name:/workspace/isaaclab/tests/$result_file "$reports_dir/$result_file" 2>&1); then + echo "🟢 Test results copied successfully to $reports_dir/$result_file" else - echo "❌ Failed to copy specific result file, trying to copy all test results..." - if docker cp $container_name:/workspace/isaaclab/tests/ "$reports_dir/" 2>/dev/null; then - echo "✅ All test results copied successfully to $reports_dir/" + echo "🔴 Failed to copy specific result file: $cp_err" + echo "🔴 Trying to copy all test results..." + if cp_err=$(docker cp $container_name:/workspace/isaaclab/tests/ "$reports_dir/" 2>&1); then + echo "🟢 All test results copied successfully to $reports_dir/" # Look for any XML files and use the first one found if [ -f "$reports_dir/full_report.xml" ]; then mv "$reports_dir/full_report.xml" "$reports_dir/$result_file" - echo "✅ Found and renamed full_report.xml to $result_file" - elif [ -f "$reports_dir/test-reports-"*".xml" ]; then - # Combine individual test reports if no full report exists - echo "📊 Combining individual test reports..." - echo '' > "$reports_dir/$result_file" + echo "🟢 Found and renamed full_report.xml to $result_file" + elif ls "$reports_dir"/test-reports-*.xml 1>/dev/null 2>&1; then + # Combine individual test reports if no full report exists. + # Extract each block intact to produce valid JUnit XML. + echo "🔵 Combining individual test reports..." + echo '' > "$reports_dir/$result_file" + echo '' >> "$reports_dir/$result_file" for xml_file in "$reports_dir"/test-reports-*.xml; do if [ -f "$xml_file" ]; then echo " Processing: $xml_file" - sed '1d; /^> "$reports_dir/$result_file" 2>/dev/null || true + # Copy everything between and (inclusive) + sed -n '//p' "$xml_file" >> "$reports_dir/$result_file" || echo "🟠 Warning: failed to extract testsuite from $xml_file" fi done echo '' >> "$reports_dir/$result_file" - echo "✅ Combined individual test reports into $result_file" + echo "🟢 Combined individual test reports into $result_file" else - echo "❌ No test result files found, creating fallback" + echo "🔴 No test result files found, creating fallback" echo "Container may have failed to generate any results" > "$reports_dir/$result_file" fi else - echo "❌ Failed to copy any test results, creating fallback" + echo "🔴 Failed to copy any test results, creating fallback" echo "Container may have failed to generate results" > "$reports_dir/$result_file" fi fi + # Copy comparison images (saved by test_rendering_correctness.py). + local img_dir="$reports_dir/comparison-images" + if [ -n "$volume_mount_source" ] && [ -d "${volume_mount_source}/tests/comparison-images" ]; then + cp -r "${volume_mount_source}/tests/comparison-images" "$img_dir" + echo "🟢 Comparison images copied to $img_dir" + elif docker cp "$container_name:/workspace/isaaclab/tests/comparison-images" "$img_dir" 2>/dev/null; then + echo "🟢 Comparison images copied from container to $img_dir" + fi + # Clean up container - echo "🧹 Cleaning up Docker container..." - docker rm $container_name 2>/dev/null || echo "⚠️ Container cleanup failed, but continuing..." + echo "🔵 Cleaning up Docker container..." + docker rm $container_name 2>/dev/null || echo "🟠 Container cleanup failed, but continuing..." + + return $DOCKER_EXIT } # Call the function with provided parameters - run_tests "${{ inputs.test-path }}" "${{ inputs.result-file }}" "${{ inputs.container-name }}" "${{ inputs.image-tag }}" "${{ inputs.reports-dir }}" "${{ inputs.pytest-options }}" "${{ inputs.filter-pattern }}" "${{ inputs.curobo-only }}" "${{ inputs.cuda-issue-only }}" "${{ inputs.include-files }}" "${{ inputs.flaky-only }}" "${{ inputs.slightly-flaky-only }}" + run_tests "${{ inputs.test-path }}" "${{ inputs.result-file }}" "${{ inputs.container-name }}" "${{ inputs.image-tag }}" "${{ inputs.reports-dir }}" "${{ inputs.pytest-options }}" "${{ inputs.filter-pattern }}" "${{ inputs.curobo-only }}" "${{ inputs.include-files }}" "${{ inputs.quarantined-only }}" "${{ inputs.shard-index }}" "${{ inputs.shard-count }}" "${{ inputs.volume-mount-source }}" + + - name: Write job summary + if: always() + shell: bash + run: | + report="${{ inputs.reports-dir }}/${{ inputs.result-file }}" + if [ ! -f "$report" ]; then + echo "🟠 No test report found" >> "$GITHUB_STEP_SUMMARY" + exit 0 + fi + + # Parse JUnit XML and produce a markdown summary. + # Exit code 2 means the report was corrupt/unreadable - surface the + # error in the summary but don't mask the real test exit code. + if ! python3 .github/actions/run-tests/junit_summary.py "$report" >> "$GITHUB_STEP_SUMMARY"; then + echo "::warning::junit_summary.py failed to parse $report - test results may be missing from the summary" + fi + + - name: Upload comparison images + if: always() + uses: actions/upload-artifact@v7 + with: + name: comparison-images-${{ inputs.container-name }} + path: ${{ inputs.reports-dir }}/comparison-images/ + if-no-files-found: ignore + retention-days: 7 + + - name: Clean up Docker container + if: always() + shell: bash + run: | + echo "🔵 Cleaning up Docker container..." + docker kill "${{ inputs.container-name }}" 2>/dev/null || true + docker rm -f "${{ inputs.container-name }}" 2>/dev/null || true diff --git a/.github/actions/run-tests/junit_summary.py b/.github/actions/run-tests/junit_summary.py new file mode 100755 index 000000000000..70480acccf71 --- /dev/null +++ b/.github/actions/run-tests/junit_summary.py @@ -0,0 +1,134 @@ +#!/usr/bin/env python3 +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Parse a JUnit XML report and print a markdown summary (for $GITHUB_STEP_SUMMARY).""" + +import sys +import xml.etree.ElementTree as ET + +if len(sys.argv) < 2: + print("Usage: junit_summary.py ", file=sys.stderr) + sys.exit(1) + +try: + tree = ET.parse(sys.argv[1]) + root = tree.getroot() +except ET.ParseError as exc: + print(f"🔴 Failed to parse test report: {exc}") + sys.exit(0) # non-fatal so the step summary still renders +except OSError as exc: + print(f"🔴 Failed to read test report: {exc}") + sys.exit(0) + +passed, failed, errored, skipped = [], [], [], [] +# Keyed by (test_name, label) -> {"diff_pct": str, "ssim": str, "passed": bool} +comparison_scores = {} +total_time = 0.0 + + +def safe_float(val, default=0.0): + try: + return float(val) + except (ValueError, TypeError): + return default + + +for tc in root.iter("testcase"): + classname = tc.get("classname", "") + tc_name = tc.get("name", "unknown") + name = f"{classname}.{tc_name}" if classname else tc_name + t = safe_float(tc.get("time", 0)) + total_time += t + tc_failed = tc.find("failure") is not None + tc_errored = tc.find("error") is not None + if tc_failed: + failed.append((name, t, tc.find("failure").get("message", ""))) + elif tc_errored: + errored.append((name, t, tc.find("error").get("message", ""))) + elif (skip_el := tc.find("skipped")) is not None: + skipped.append((name, t, skip_el.get("message", ""))) + else: + passed.append((name, t)) + + # Collect diff_pct:*, ssim:*, and img_*:* properties emitted by test_rendering_correctness. + props = tc.find("properties") + if props is not None: + for prop in props.findall("property"): + prop_name = prop.get("name", "") + for prefix in ("diff_pct:", "ssim:", "threshold:", "img_result:", "img_golden:"): + if prop_name.startswith(prefix): + label = prop_name[len(prefix) :] + key = (name, label) + if key not in comparison_scores: + comparison_scores[key] = { + "diff_pct": "", + "ssim": "", + "threshold": "", + "passed": not (tc_failed or tc_errored), + "img_result": "", + "img_golden": "", + } + field = prefix.rstrip(":") + comparison_scores[key][field] = prop.get("value", "") + +mins, secs = divmod(total_time, 60) +time_str = f"{int(mins)}m:{secs:.0f}s" + + +def sanitize_msg(msg, max_len=300): + """Collapse newlines, escape pipe characters, and truncate for markdown tables.""" + return msg.replace("\n", " ").replace("\r", "").replace("|", "\\|")[:max_len] + + +def fmt_name(name): + """Format a test name for markdown: strip ``source.`` prefix, allow word-breaking.""" + if name.startswith("source."): + name = name[len("source.") :] + # Insert zero-width spaces after dots and brackets so tables can wrap. + return name.replace(".", ".\u200b").replace("[", "[\u200b").replace("]", "]\u200b") + + +if failed or errored: + print(f"🔴 {len(failed) + len(errored)} FAILED, {len(passed)} PASSED ({time_str})") +elif not passed and not skipped: + print("🟠 No test cases found in report") + +if failed or errored: + print("") + print("| Status | Test | Time | Message |") + print("|--------|------|------|---------|") + for name, t, msg in sorted(failed, key=lambda x: x[1], reverse=True): + print(f"| ASSERTION | {fmt_name(name)} | {t:.1f}s | {sanitize_msg(msg)} |") + for name, t, msg in sorted(errored, key=lambda x: x[1], reverse=True): + print(f"| ERROR | {fmt_name(name)} | {t:.1f}s | {sanitize_msg(msg)} |") + +if passed: + print(f"\n
🟢 {len(passed)} PASSED ({time_str})") + print("") + print("
") + print("") + print("| Test | Time |") + print("|------|------|") + for name, t in sorted(passed, key=lambda x: x[1], reverse=True): + print(f"| {fmt_name(name)} | {t:.1f}s |") + print("") + print("
") + +if skipped: + print(f"\n
🟠 {len(skipped)} SKIPPED") + print("") + print("
") + print("") + print("| Test | Reason |") + print("|------|--------|") + for name, t, msg in skipped: + print(f"| {fmt_name(name)} | {sanitize_msg(msg)} |") + print("") + print("
") + +if comparison_scores: + print("\n") + print("🔵 GOLDEN vs ACTUAL report is attached as artifact (at the bottom of this page).") diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 2a09001d9451..07e054ba8a15 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -3,6 +3,67 @@ # # SPDX-License-Identifier: BSD-3-Clause +# Test job gating summary +# +# +------------------------------------+-----------------------------------------------------+ +# | Job | Gate (any match triggers the job) | +# +------------------------------------+-----------------------------------------------------+ +# | test-isaaclab-tasks (x3 shards) | isaaclab-tasks | isaaclab-core | infra | +# | test-isaaclab-core (x3 shards) | isaaclab-core | infra | +# | test-isaaclab-rl | isaaclab-rl | isaaclab-core | infra | +# | test-isaaclab-mimic | isaaclab-mimic | isaaclab-core | infra | +# | test-isaaclab-contrib | isaaclab-contrib | isaaclab-core | infra | +# | test-isaaclab-teleop | isaaclab-teleop | isaaclab-core | infra | +# | test-isaaclab-visualizers | isaaclab-visualizers | isaaclab-core | infra | +# | test-isaaclab-assets | isaaclab-assets | isaaclab-core | infra | +# | test-isaaclab-newton | isaaclab-newton | isaaclab-core | infra | +# | test-isaaclab-physx | isaaclab-physx | isaaclab-core | infra | +# | test-isaaclab-ov | isaaclab-ov | isaaclab-core | infra | +# | test-environments-training | isaaclab-tasks | isaaclab-core | infra | +# | test-curobo (needs build-curobo) | isaaclab-mimic | isaaclab-core | infra | +# | test-skillgen (needs build-curobo) | isaaclab-mimic | isaaclab-tasks | isaaclab-core | +# | | | infra | +# | test-quarantined | vars.RUN_QUARANTINED_TESTS == "true" | +# | build-curobo | isaaclab-mimic | isaaclab-tasks | isaaclab-core | +# | | | infra | +# +------------------------------------+-----------------------------------------------------+ +# +# ============================================================================= +# CI DEBUGGING TIPS +# ============================================================================= +# +# 1. DISABLE A TEST JOB (to isolate a specific job): +# Change the job's `if:` clause to `if: false` +# Example: +# test-isaaclab-tasks: +# ... +# if: false # TEMP: Disabled for debugging +# +# 2. RUN ONLY SPECIFIC TEST FILES (within a job): +# Add `include-files:` parameter to run-package-tests action +# Example: +# - uses: ./.github/actions/run-package-tests +# with: +# ... +# include-files: "test_rigid_object_collection.py" # Comma-separated +# +# 3. SKIP CONCURRENCY WAIT (run immediately without waiting for other runs): +# Comment out the concurrency block: +# # concurrency: +# # group: ${{ github.workflow }}-${{ github.ref }} +# # cancel-in-progress: true +# +# 4. TEST LOCALLY LIKE CI: +# docker run -it --rm --gpus all --network=host --entrypoint bash \ +# -e OMNI_KIT_ACCEPT_EULA=yes -e ACCEPT_EULA=Y -e ISAAC_SIM_HEADLESS=1 \ +# -e TEST_FILTER_PATTERN="isaaclab_physx" \ +# -e TEST_INCLUDE_FILES="test_rigid_object_collection.py" \ +# -v "$PWD":/workspace/isaaclab isaac-lab-base:latest \ +# -c 'cd /workspace/isaaclab && /isaac-sim/python.sh -m pytest tools -v' +# +# Remember to REVERT all temporary changes before merging! +# ============================================================================= + name: Docker + Tests on: @@ -19,6 +80,7 @@ on: - main - develop - 'release/**' + workflow_dispatch: # Concurrency control to prevent parallel runs on the same PR concurrency: @@ -37,14 +99,156 @@ env: ISAACSIM_BASE_IMAGE: 'nvcr.io/nvidian/isaac-sim' # ${{ vars.ISAACSIM_BASE_IMAGE || 'nvcr.io/nvidia/isaac-sim' }} ISAACSIM_BASE_VERSION: 'latest-develop' # ${{ vars.ISAACSIM_BASE_VERSION || '6.0.0' }} DOCKER_IMAGE_TAG: isaac-lab-dev:${{ github.event_name == 'pull_request' && format('pr-{0}', github.event.pull_request.number) || github.ref_name }}-${{ github.sha }} + # To run quarantined tests, create a GitHub repo variable named + # RUN_QUARANTINED_TESTS and set it to 'true'. The test-quarantined + # job is skipped when the variable is absent or not 'true'. jobs: + detect-changes: + name: Detect Changes + runs-on: ubuntu-latest + outputs: + isaaclab-core: ${{ steps.check.outputs.isaaclab-core }} + isaaclab-physx: ${{ steps.check.outputs.isaaclab-physx }} + isaaclab-newton: ${{ steps.check.outputs.isaaclab-newton }} + isaaclab-tasks: ${{ steps.check.outputs.isaaclab-tasks }} + isaaclab-rl: ${{ steps.check.outputs.isaaclab-rl }} + isaaclab-mimic: ${{ steps.check.outputs.isaaclab-mimic }} + isaaclab-contrib: ${{ steps.check.outputs.isaaclab-contrib }} + isaaclab-teleop: ${{ steps.check.outputs.isaaclab-teleop }} + isaaclab-visualizers: ${{ steps.check.outputs.isaaclab-visualizers }} + isaaclab-assets: ${{ steps.check.outputs.isaaclab-assets }} + isaaclab-ov: ${{ steps.check.outputs.isaaclab-ov }} + infra: ${{ steps.check.outputs.infra }} + steps: + - name: Checkout Code + uses: actions/checkout@v6 + with: + fetch-depth: 1 + + - name: Detect changed files and packages + id: check + run: | + set -euo pipefail + + # For non-PR events, run all tests + if [ "${{ github.event_name }}" != "pull_request" ]; then + for pkg in isaaclab-core isaaclab-physx isaaclab-newton isaaclab-tasks \ + isaaclab-rl isaaclab-mimic isaaclab-contrib isaaclab-teleop \ + isaaclab-visualizers isaaclab-assets isaaclab-ov infra; do + echo "$pkg=true" >> "$GITHUB_OUTPUT" + done + exit 0 + fi + + # Fetch the PR base branch tip to diff against + git fetch --depth=1 origin "${{ github.event.pull_request.base.ref }}" + changed=$(git diff --name-only FETCH_HEAD HEAD) + + if [ -z "$changed" ]; then + echo "::warning::No changed files detected between FETCH_HEAD and HEAD - running all tests as a safety measure" + for pkg in isaaclab-core isaaclab-physx isaaclab-newton isaaclab-tasks \ + isaaclab-rl isaaclab-mimic isaaclab-contrib isaaclab-teleop \ + isaaclab-visualizers isaaclab-assets isaaclab-ov infra; do + echo "$pkg=true" >> "$GITHUB_OUTPUT" + done + exit 0 + fi + + has() { + echo "$changed" | grep -qE "$1" + local rc=$? + if [ $rc -eq 0 ]; then echo true + elif [ $rc -eq 1 ]; then echo false + else + echo "::error::grep failed with exit $rc for pattern: $1" + exit 1 + fi + } + + # Detect per-package changes + core=$(has '^source/isaaclab/') + physx=$(has '^source/isaaclab_physx/') + newton=$(has '^source/isaaclab_newton/') + tasks=$(has '^source/isaaclab_tasks/') + + # Changes in apps/ trigger: core, physx, newton, tasks + apps=$(has '^apps/') + if [ "$apps" = "true" ]; then + core=true + physx=true + newton=true + tasks=true + fi + + echo "isaaclab-core=$core" >> "$GITHUB_OUTPUT" + echo "isaaclab-physx=$physx" >> "$GITHUB_OUTPUT" + echo "isaaclab-newton=$newton" >> "$GITHUB_OUTPUT" + echo "isaaclab-tasks=$tasks" >> "$GITHUB_OUTPUT" + echo "isaaclab-rl=$(has '^source/isaaclab_rl/')" >> "$GITHUB_OUTPUT" + echo "isaaclab-mimic=$(has '^source/isaaclab_mimic/')" >> "$GITHUB_OUTPUT" + echo "isaaclab-contrib=$(has '^source/isaaclab_contrib/')" >> "$GITHUB_OUTPUT" + echo "isaaclab-teleop=$(has '^source/isaaclab_teleop/')" >> "$GITHUB_OUTPUT" + echo "isaaclab-visualizers=$(has '^source/isaaclab_visualizers/')" >> "$GITHUB_OUTPUT" + echo "isaaclab-assets=$(has '^source/isaaclab_assets/')" >> "$GITHUB_OUTPUT" + echo "isaaclab-ov=$(has '^source/isaaclab_ov/')" >> "$GITHUB_OUTPUT" + echo "infra=$(has '^(\.github/|docker/|tools/|scripts/)')" >> "$GITHUB_OUTPUT" + + echo "" + echo "CHANGED FILES:" + echo "$changed" | while IFS= read -r f; do + case "$f" in + source/isaaclab/*) echo "$f (isaaclab-core)" ;; + source/isaaclab_physx/*) echo "$f (isaaclab-physx)" ;; + source/isaaclab_newton/*) echo "$f (isaaclab-newton)" ;; + source/isaaclab_tasks/*) echo "$f (isaaclab-tasks)" ;; + source/isaaclab_rl/*) echo "$f (isaaclab-rl)" ;; + source/isaaclab_mimic/*) echo "$f (isaaclab-mimic)" ;; + source/isaaclab_contrib/*) echo "$f (isaaclab-contrib)" ;; + source/isaaclab_teleop/*) echo "$f (isaaclab-teleop)" ;; + source/isaaclab_visualizers/*) echo "$f (isaaclab-visualizers)" ;; + source/isaaclab_assets/*) echo "$f (isaaclab-assets)" ;; + source/isaaclab_ov/*) echo "$f (isaaclab-ov)" ;; + .github/*|docker/*|tools/*|scripts/*) echo "$f (infra)" ;; + apps/*) echo "$f (apps - core/physx/newton/tasks)" ;; + *) echo "$f" ;; + esac + done + echo "" + echo "CHANGED PACKAGES:" + cat "$GITHUB_OUTPUT" + + # Write job summary visible on the GH Actions UI + { + echo "| File | Package |" + echo "|------|---------|" + echo "$changed" | while IFS= read -r f; do + case "$f" in + source/isaaclab/*) echo "| \`$f\` | isaaclab-core |" ;; + source/isaaclab_physx/*) echo "| \`$f\` | isaaclab-physx |" ;; + source/isaaclab_newton/*) echo "| \`$f\` | isaaclab-newton |" ;; + source/isaaclab_tasks/*) echo "| \`$f\` | isaaclab-tasks |" ;; + source/isaaclab_rl/*) echo "| \`$f\` | isaaclab-rl |" ;; + source/isaaclab_mimic/*) echo "| \`$f\` | isaaclab-mimic |" ;; + source/isaaclab_contrib/*) echo "| \`$f\` | isaaclab-contrib |" ;; + source/isaaclab_teleop/*) echo "| \`$f\` | isaaclab-teleop |" ;; + source/isaaclab_visualizers/*) echo "| \`$f\` | isaaclab-visualizers |" ;; + source/isaaclab_assets/*) echo "| \`$f\` | isaaclab-assets |" ;; + source/isaaclab_ov/*) echo "| \`$f\` | isaaclab-ov |" ;; + .github/*|docker/*|tools/*|scripts/*) echo "| \`$f\` | infra |" ;; + apps/*) echo "| \`$f\` | apps - core/physx/newton/tasks |" ;; + *) echo "| \`$f\` | - |" ;; + esac + done + } >> "$GITHUB_STEP_SUMMARY" + build: - name: Build Base Docker image + name: Build Base Docker Image runs-on: [self-hosted, gpu] + needs: [detect-changes] steps: - name: Checkout Code - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: fetch-depth: 1 lfs: true @@ -58,17 +262,19 @@ jobs: dockerfile-path: docker/Dockerfile.base cache-tag: cache-base - # ECR images must be pruned with a lifecycle policy. - - name: Clean up stale Docker images - if: always() - run: docker image prune -f --filter "until=24h" || true build-curobo: - name: Build cuRobo Docker image + name: Build cuRobo Docker Image runs-on: [self-hosted, gpu] + needs: [detect-changes] + if: >- + needs.detect-changes.outputs.isaaclab-mimic == 'true' || + needs.detect-changes.outputs.isaaclab-tasks == 'true' || + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' steps: - name: Checkout Code - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: fetch-depth: 1 lfs: true @@ -82,695 +288,499 @@ jobs: dockerfile-path: docker/Dockerfile.curobo cache-tag: cache-curobo - # ECR images must be pruned with a lifecycle policy. - - name: Clean up stale Docker images - if: always() - run: docker image prune -f --filter "until=24h" || true + # Each test job checks out code, then calls run-package-tests which handles + # ECR pull, pytest in Docker, artifact upload, and fork-PR checks. + test-isaaclab-tasks: - name: IsaacLab Tasks Tests 1/2 + name: isaaclab_tasks [1/3] runs-on: [self-hosted, gpu] timeout-minutes: 180 continue-on-error: true - needs: build - + needs: [build, detect-changes] + if: >- + always() && needs.build.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-tasks == 'true' || + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) steps: - - name: Checkout Code - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: fetch-depth: 1 lfs: true - - - name: Pull image from ECR - uses: ./.github/actions/ecr-build-push-pull + - uses: ./.github/actions/run-package-tests with: image-tag: ${{ env.DOCKER_IMAGE_TAG }} isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} - dockerfile-path: docker/Dockerfile.base - cache-tag: cache-base - - - name: Run IsaacLab Tasks Tests 1/2 - uses: ./.github/actions/run-tests - with: - test-path: "tools" - result-file: "${{ github.job }}-report.xml" - container-name: "isaac-lab-tasks-test-${{ github.run_id }}-${{ github.run_attempt }}" - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - pytest-options: "" filter-pattern: "isaaclab_tasks" - include-files: >- - test_multi_agent_environments.py, - test_pickplace_stack_environments.py, - test_environments.py, - test_factory_environments.py, - test_cartpole_showcase_environments.py, - test_teleop_environments.py - - - name: Upload IsaacLab Tasks Test Results - uses: actions/upload-artifact@v4 - if: always() - with: - name: isaaclab-tasks-test-results - path: reports/${{ github.job }}-report.xml - retention-days: 1 - compression-level: 9 - - - name: Check Test Results for Fork PRs - if: github.event.pull_request.head.repo.full_name != github.repository - run: | - if [ -f "reports/${{ github.job }}-report.xml" ]; then - # Check if the test results contain any failures - if grep -q 'failures="[1-9]' reports/${{ github.job }}-report.xml || grep -q 'errors="[1-9]' reports/${{ github.job }}-report.xml; then - echo "Tests failed for PR from fork. The test report is in the logs. Failing the job." - exit 1 - fi - else - echo "No test results file found. This might indicate test execution failed." - exit 1 - fi + shard-index: "0" + shard-count: "3" + container-name: isaac-lab-tasks-1-test - # ECR images must be pruned with a lifecycle policy. - - name: Clean up stale Docker images - if: always() - run: docker image prune -f --filter "until=24h" || true test-isaaclab-tasks-2: - name: IsaacLab Tasks Tests 2/2 + name: isaaclab_tasks [2/3] runs-on: [self-hosted, gpu] timeout-minutes: 180 continue-on-error: true - needs: build - + needs: [build, detect-changes] + if: >- + always() && needs.build.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-tasks == 'true' || + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) steps: - - name: Checkout Code - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: fetch-depth: 1 lfs: true - - - name: Pull image from ECR - uses: ./.github/actions/ecr-build-push-pull + - uses: ./.github/actions/run-package-tests with: image-tag: ${{ env.DOCKER_IMAGE_TAG }} isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} - dockerfile-path: docker/Dockerfile.base - cache-tag: cache-base + filter-pattern: "isaaclab_tasks" + shard-index: "1" + shard-count: "3" + container-name: isaac-lab-tasks-2-test + - - name: Run IsaacLab Tasks Tests 2/2 - uses: ./.github/actions/run-tests + test-isaaclab-tasks-3: + name: isaaclab_tasks [3/3] + runs-on: [self-hosted, gpu] + timeout-minutes: 180 + continue-on-error: true + needs: [build, detect-changes] + if: >- + always() && needs.build.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-tasks == 'true' || + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 1 + lfs: true + - uses: ./.github/actions/run-package-tests with: - test-path: "tools" - result-file: "${{ github.job }}-report.xml" - container-name: "isaac-lab-tasks-2-test-${{ github.run_id }}-${{ github.run_attempt }}" image-tag: ${{ env.DOCKER_IMAGE_TAG }} - pytest-options: "" + isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} + isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} filter-pattern: "isaaclab_tasks" - include-files: >- - test_teleop_environments_with_stage_in_memory.py, - test_lift_teddy_bear.py, - test_environment_determinism.py, - test_hydra.py, - test_rl_device_separation.py, - test_cartpole_showcase_environments_with_stage_in_memory.py, - test_environments_with_stage_in_memory.py - - - name: Upload IsaacLab Tasks 2 Test Results - uses: actions/upload-artifact@v4 - if: always() - with: - name: isaaclab-tasks-2-test-results - path: reports/${{ github.job }}-report.xml - retention-days: 1 - compression-level: 9 - - - name: Check Test Results for Fork PRs - if: github.event.pull_request.head.repo.full_name != github.repository - run: | - if [ -f "reports/${{ github.job }}-report.xml" ]; then - # Check if the test results contain any failures - if grep -q 'failures="[1-9]' reports/${{ github.job }}-report.xml || grep -q 'errors="[1-9]' reports/${{ github.job }}-report.xml; then - echo "Tests failed for PR from fork. The test report is in the logs. Failing the job." - exit 1 - fi - else - echo "No test results file found. This might indicate test execution failed." - exit 1 - fi + shard-index: "2" + shard-count: "3" + container-name: isaac-lab-tasks-3-test - # ECR images must be pruned with a lifecycle policy. - - name: Clean up stale Docker images - if: always() - run: docker image prune -f --filter "until=24h" || true - test-general: - name: General Tests + test-isaaclab-core: + name: isaaclab (core) [1/3] runs-on: [self-hosted, gpu] timeout-minutes: 180 - needs: build - + needs: [build, detect-changes] + if: >- + always() && needs.build.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) steps: - - name: Checkout Code - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: fetch-depth: 1 lfs: true - - - name: Pull image from ECR - uses: ./.github/actions/ecr-build-push-pull + - uses: ./.github/actions/run-package-tests with: image-tag: ${{ env.DOCKER_IMAGE_TAG }} isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} - dockerfile-path: docker/Dockerfile.base - cache-tag: cache-base + filter-pattern: "not isaaclab_" + shard-index: "0" + shard-count: "3" + container-name: isaac-lab-core-1-test - - name: Run General Tests - id: run-general-tests - uses: ./.github/actions/run-tests - with: - test-path: "tools" - result-file: "${{ github.job }}-report.xml" - container-name: "isaac-lab-general-test-${{ github.run_id }}-${{ github.run_attempt }}" - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - pytest-options: "" - filter-pattern: "not isaaclab_tasks,isaaclab_newton,isaaclab_physx" - - name: Upload General Test Results - uses: actions/upload-artifact@v4 - if: always() + test-isaaclab-core-2: + name: isaaclab (core) [2/3] + runs-on: [self-hosted, gpu] + timeout-minutes: 180 + needs: [build, detect-changes] + if: >- + always() && needs.build.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) + steps: + - uses: actions/checkout@v6 with: - name: general-test-results - path: reports/${{ github.job }}-report.xml - retention-days: 1 - compression-level: 9 - - - name: Check Test Results for Fork PRs - if: github.event.pull_request.head.repo.full_name != github.repository - run: | - if [ -f "reports/${{ github.job }}-report.xml" ]; then - # Check if the test results contain any failures - if grep -q 'failures="[1-9]' reports/${{ github.job }}-report.xml || grep -q 'errors="[1-9]' reports/${{ github.job }}-report.xml; then - echo "Tests failed for PR from fork. The test report is in the logs. Failing the job." - exit 1 - fi - else - echo "No test results file found. This might indicate test execution failed." - exit 1 - fi + fetch-depth: 1 + lfs: true + - uses: ./.github/actions/run-package-tests + with: + image-tag: ${{ env.DOCKER_IMAGE_TAG }} + isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} + isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + filter-pattern: "not isaaclab_" + shard-index: "1" + shard-count: "3" + container-name: isaac-lab-core-2-test - # ECR images must be pruned with a lifecycle policy. - - name: Clean up stale Docker images - if: always() - run: docker image prune -f --filter "until=24h" || true - test-newton: + test-isaaclab-core-3: + name: isaaclab (core) [3/3] runs-on: [self-hosted, gpu] timeout-minutes: 180 - needs: build - + needs: [build, detect-changes] + if: >- + always() && needs.build.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) steps: - - name: Checkout Code - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: fetch-depth: 1 lfs: true - - - name: Pull image from ECR - uses: ./.github/actions/ecr-build-push-pull + - uses: ./.github/actions/run-package-tests with: image-tag: ${{ env.DOCKER_IMAGE_TAG }} isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} - dockerfile-path: docker/Dockerfile.base - cache-tag: cache-base + filter-pattern: "not isaaclab_" + shard-index: "2" + shard-count: "3" + container-name: isaac-lab-core-3-test - - name: Run Newton Tests - uses: ./.github/actions/run-tests - with: - test-path: "tools" - result-file: "${{ github.job }}-report.xml" - container-name: "isaac-lab-newton-test-${{ github.run_id }}-${{ github.run_attempt }}" - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - pytest-options: "" - filter-pattern: "isaaclab_newton" - - name: Upload Newton Test Results - uses: actions/upload-artifact@v4 - if: always() + test-isaaclab-rl: + name: isaaclab_rl + runs-on: [self-hosted, gpu] + timeout-minutes: 180 + needs: [build, detect-changes] + if: >- + always() && needs.build.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-rl == 'true' || + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) + steps: + - uses: actions/checkout@v6 with: - name: newton-test-results - path: reports/${{ github.job }}-report.xml - retention-days: 1 - compression-level: 9 - - - name: Check Test Results for Fork PRs - if: github.event.pull_request.head.repo.full_name != github.repository - run: | - if [ -f "reports/${{ github.job }}-report.xml" ]; then - # Check if the test results contain any failures - if grep -q 'failures="[1-9]' reports/${{ github.job }}-report.xml || grep -q 'errors="[1-9]' reports/${{ github.job }}-report.xml; then - echo "Tests failed for PR from fork. The test report is in the logs. Failing the job." - exit 1 - fi - else - echo "No test results file found. This might indicate test execution failed." - exit 1 - fi + fetch-depth: 1 + lfs: true + - uses: ./.github/actions/run-package-tests + with: + image-tag: ${{ env.DOCKER_IMAGE_TAG }} + isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} + isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + filter-pattern: "isaaclab_rl" + container-name: isaac-lab-rl-test - # ECR images must be pruned with a lifecycle policy. - - name: Clean up stale Docker images - if: always() - run: docker image prune -f --filter "until=24h" || true - test-physx: + test-isaaclab-mimic: + name: isaaclab_mimic runs-on: [self-hosted, gpu] timeout-minutes: 180 - needs: build - + needs: [build, detect-changes] + if: >- + always() && needs.build.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-mimic == 'true' || + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) steps: - - name: Checkout Code - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: fetch-depth: 1 lfs: true - - - name: Pull image from ECR - uses: ./.github/actions/ecr-build-push-pull + - uses: ./.github/actions/run-package-tests with: image-tag: ${{ env.DOCKER_IMAGE_TAG }} isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} - dockerfile-path: docker/Dockerfile.base - cache-tag: cache-base + filter-pattern: "isaaclab_mimic" + container-name: isaac-lab-mimic-test - - name: Run PhysX Tests - uses: ./.github/actions/run-tests - with: - test-path: "tools" - result-file: "${{ github.job }}-report.xml" - container-name: "isaac-lab-physx-test-${{ github.run_id }}-${{ github.run_attempt }}" - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - pytest-options: "" - filter-pattern: "isaaclab_physx" - - name: Upload PhysX Test Results - uses: actions/upload-artifact@v4 - if: always() + test-isaaclab-contrib: + name: isaaclab_contrib + runs-on: [self-hosted, gpu] + timeout-minutes: 180 + needs: [build, detect-changes] + if: >- + always() && needs.build.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-contrib == 'true' || + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) + steps: + - uses: actions/checkout@v6 with: - name: physx-test-results - path: reports/${{ github.job }}-report.xml - retention-days: 1 - compression-level: 9 - - - name: Check Test Results for Fork PRs - if: github.event.pull_request.head.repo.full_name != github.repository - run: | - if [ -f "reports/${{ github.job }}-report.xml" ]; then - # Check if the test results contain any failures - if grep -q 'failures="[1-9]' reports/${{ github.job }}-report.xml || grep -q 'errors="[1-9]' reports/${{ github.job }}-report.xml; then - echo "Tests failed for PR from fork. The test report is in the logs. Failing the job." - exit 1 - fi - else - echo "No test results file found. This might indicate test execution failed." - exit 1 - fi + fetch-depth: 1 + lfs: true + - uses: ./.github/actions/run-package-tests + with: + image-tag: ${{ env.DOCKER_IMAGE_TAG }} + isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} + isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + filter-pattern: "isaaclab_contrib" + container-name: isaac-lab-contrib-test - # ECR images must be pruned with a lifecycle policy. - - name: Clean up stale Docker images - if: always() - run: docker image prune -f --filter "until=24h" || true - test-curobo: - name: cuRobo and SkillGen Tests + test-isaaclab-teleop: + name: isaaclab_teleop runs-on: [self-hosted, gpu] - timeout-minutes: 120 - continue-on-error: true - needs: build-curobo - + timeout-minutes: 180 + needs: [build, detect-changes] + if: >- + always() && needs.build.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-teleop == 'true' || + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) steps: - - name: Checkout Code - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: fetch-depth: 1 lfs: true - - - name: Pull cuRobo image from ECR - uses: ./.github/actions/ecr-build-push-pull + - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }}-curobo + image-tag: ${{ env.DOCKER_IMAGE_TAG }} isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} - dockerfile-path: docker/Dockerfile.curobo - cache-tag: cache-curobo + filter-pattern: "isaaclab_teleop" + container-name: isaac-lab-teleop-test - - name: Run cuRobo and SkillGen Tests - uses: ./.github/actions/run-tests - with: - test-path: "tools" - result-file: "${{ github.job }}-report.xml" - container-name: "isaac-lab-curobo-test-${{ github.run_id }}-${{ github.run_attempt }}" - image-tag: ${{ env.DOCKER_IMAGE_TAG }}-curobo - pytest-options: "" - filter-pattern: "" - curobo-only: "true" - - name: Upload cuRobo Test Results - uses: actions/upload-artifact@v4 - if: always() + test-isaaclab-visualizers: + name: isaaclab_visualizers + runs-on: [self-hosted, gpu] + timeout-minutes: 180 + needs: [build, detect-changes] + if: >- + always() && needs.build.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-visualizers == 'true' || + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) + steps: + - uses: actions/checkout@v6 with: - name: curobo-test-results - path: reports/${{ github.job }}-report.xml - retention-days: 1 - compression-level: 9 - - - name: Check Test Results for Fork PRs - if: github.event.pull_request.head.repo.full_name != github.repository - run: | - if [ -f "reports/${{ github.job }}-report.xml" ]; then - # Check if the test results contain any failures - if grep -q 'failures="[1-9]' reports/${{ github.job }}-report.xml || grep -q 'errors="[1-9]' reports/${{ github.job }}-report.xml; then - echo "Tests failed for PR from fork. The test report is in the logs. Failing the job." - exit 1 - fi - else - echo "No test results file found. This might indicate test execution failed." - exit 1 - fi + fetch-depth: 1 + lfs: true + - uses: ./.github/actions/run-package-tests + with: + image-tag: ${{ env.DOCKER_IMAGE_TAG }} + isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} + isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + filter-pattern: "isaaclab_visualizers" + container-name: isaac-lab-visualizers-test - # ECR images must be pruned with a lifecycle policy. - - name: Clean up stale Docker images - if: always() - run: docker image prune -f --filter "until=24h" || true - test-flaky: - name: "⚠️ Very Flaky Tests" + test-isaaclab-assets: + name: isaaclab_assets runs-on: [self-hosted, gpu] timeout-minutes: 180 - continue-on-error: true - needs: build - + needs: [build, detect-changes] + if: >- + always() && needs.build.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-assets == 'true' || + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) steps: - - name: Checkout Code - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: fetch-depth: 1 lfs: true - - - name: Pull image from ECR - uses: ./.github/actions/ecr-build-push-pull + - uses: ./.github/actions/run-package-tests with: image-tag: ${{ env.DOCKER_IMAGE_TAG }} isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} - dockerfile-path: docker/Dockerfile.base - cache-tag: cache-base + filter-pattern: "isaaclab_assets" + container-name: isaac-lab-assets-test - - name: Run Flaky Tests - uses: ./.github/actions/run-tests - with: - test-path: "tools" - result-file: "${{ github.job }}-report.xml" - container-name: "isaac-lab-flaky-test-${{ github.run_id }}-${{ github.run_attempt }}" - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - pytest-options: "" - filter-pattern: "" - flaky-only: "true" - - name: Upload Flaky Test Results - uses: actions/upload-artifact@v4 - if: always() + test-isaaclab-newton: + name: isaaclab_newton + runs-on: [self-hosted, gpu] + timeout-minutes: 180 + needs: [build, detect-changes] + if: >- + always() && needs.build.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-newton == 'true' || + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) + steps: + - uses: actions/checkout@v6 with: - name: flaky-test-results - path: reports/${{ github.job }}-report.xml - retention-days: 1 - compression-level: 9 - - - name: Check Test Results for Fork PRs - if: github.event.pull_request.head.repo.full_name != github.repository - run: | - if [ -f "reports/${{ github.job }}-report.xml" ]; then - if grep -q 'failures="[1-9]' reports/${{ github.job }}-report.xml || grep -q 'errors="[1-9]' reports/${{ github.job }}-report.xml; then - echo "Tests failed for PR from fork. The test report is in the logs. Failing the job." - exit 1 - fi - else - echo "No test results file found. This might indicate test execution failed." - exit 1 - fi + fetch-depth: 1 + lfs: true + - uses: ./.github/actions/run-package-tests + with: + image-tag: ${{ env.DOCKER_IMAGE_TAG }} + isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} + isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + filter-pattern: "isaaclab_newton" + container-name: isaac-lab-newton-test - # ECR images must be pruned with a lifecycle policy. - - name: Clean up stale Docker images - if: always() - run: docker image prune -f --filter "until=24h" || true - test-slightly-flaky: - name: "⚠️ Less Flaky Tests" + test-isaaclab-physx: + name: isaaclab_physx runs-on: [self-hosted, gpu] - timeout-minutes: 60 - continue-on-error: true - needs: build - + timeout-minutes: 180 + needs: [build, detect-changes] + if: >- + always() && needs.build.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-physx == 'true' || + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) steps: - - name: Checkout Code - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: fetch-depth: 1 lfs: true - - - name: Pull image from ECR - uses: ./.github/actions/ecr-build-push-pull + - uses: ./.github/actions/run-package-tests with: image-tag: ${{ env.DOCKER_IMAGE_TAG }} isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} - dockerfile-path: docker/Dockerfile.base - cache-tag: cache-base + filter-pattern: "isaaclab_physx" + container-name: isaac-lab-physx-test - - name: Run Slightly Flaky Tests - uses: ./.github/actions/run-tests - with: - test-path: "tools" - result-file: "${{ github.job }}-report.xml" - container-name: "isaac-lab-slightly-flaky-test-${{ github.run_id }}-${{ github.run_attempt }}" - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - pytest-options: "" - filter-pattern: "" - slightly-flaky-only: "true" - - name: Upload Slightly Flaky Test Results - uses: actions/upload-artifact@v4 - if: always() + test-isaaclab-ov: + name: isaaclab_ov + runs-on: [self-hosted, gpu] + timeout-minutes: 180 + needs: [build, detect-changes] + if: >- + always() && needs.build.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-ov == 'true' || + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) + steps: + - uses: actions/checkout@v6 with: - name: slightly-flaky-test-results - path: reports/${{ github.job }}-report.xml - retention-days: 1 - compression-level: 9 - - - name: Check Test Results for Fork PRs - if: github.event.pull_request.head.repo.full_name != github.repository - run: | - if [ -f "reports/${{ github.job }}-report.xml" ]; then - if grep -q 'failures="[1-9]' reports/${{ github.job }}-report.xml || grep -q 'errors="[1-9]' reports/${{ github.job }}-report.xml; then - echo "Tests failed for PR from fork. The test report is in the logs. Failing the job." - exit 1 - fi - else - echo "No test results file found. This might indicate test execution failed." - exit 1 - fi + fetch-depth: 1 + lfs: true + - uses: ./.github/actions/run-package-tests + with: + image-tag: ${{ env.DOCKER_IMAGE_TAG }} + isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} + isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + filter-pattern: "isaaclab_ov" + container-name: isaac-lab-ov-test - # ECR images must be pruned with a lifecycle policy. - - name: Clean up stale Docker images - if: always() - run: docker image prune -f --filter "until=24h" || true - test-environments-training: - name: "⚠️ test_environments_training.py" + test-curobo: + name: test-curobo runs-on: [self-hosted, gpu] - timeout-minutes: 300 + timeout-minutes: 120 continue-on-error: true - needs: build - + needs: [build-curobo, detect-changes] + if: >- + always() && needs.build-curobo.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-mimic == 'true' || + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) steps: - - name: Checkout Code - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: fetch-depth: 1 lfs: true - - - name: Pull image from ECR - uses: ./.github/actions/ecr-build-push-pull + - uses: ./.github/actions/run-package-tests with: - image-tag: ${{ env.DOCKER_IMAGE_TAG }} + image-tag: ${{ env.DOCKER_IMAGE_TAG }}-curobo isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} - dockerfile-path: docker/Dockerfile.base - cache-tag: cache-base + dockerfile-path: docker/Dockerfile.curobo + cache-tag: cache-curobo + include-files: "test_curobo_planner_franka.py,test_curobo_planner_cube_stack.py,test_pink_ik.py" + container-name: isaac-lab-curobo-test - - name: Run Environments Training Tests - uses: ./.github/actions/run-tests - with: - test-path: "tools" - result-file: "${{ github.job }}-report.xml" - container-name: "isaac-lab-environments-training-test-${{ github.run_id }}-${{ github.run_attempt }}" - image-tag: ${{ env.DOCKER_IMAGE_TAG }} - pytest-options: "" - filter-pattern: "isaaclab_tasks" - include-files: "test_environments_training.py" - - name: Upload Environments Training Test Results - uses: actions/upload-artifact@v4 - if: always() + test-skillgen: + name: test-skillgen + runs-on: [self-hosted, gpu] + timeout-minutes: 120 + continue-on-error: true + needs: [build-curobo, detect-changes] + if: >- + always() && needs.build-curobo.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-mimic == 'true' || + needs.detect-changes.outputs.isaaclab-tasks == 'true' || + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) + steps: + - uses: actions/checkout@v6 with: - name: environments-training-test-results - path: reports/${{ github.job }}-report.xml - retention-days: 1 - compression-level: 9 - - - name: Check Test Results for Fork PRs - if: github.event.pull_request.head.repo.full_name != github.repository - run: | - if [ -f "reports/${{ github.job }}-report.xml" ]; then - if grep -q 'failures="[1-9]' reports/${{ github.job }}-report.xml || grep -q 'errors="[1-9]' reports/${{ github.job }}-report.xml; then - echo "Tests failed for PR from fork. The test report is in the logs. Failing the job." - exit 1 - fi - else - echo "No test results file found. This might indicate test execution failed." - exit 1 - fi - - # ECR images must be pruned with a lifecycle policy. - - name: Clean up stale Docker images - if: always() - run: docker image prune -f --filter "until=24h" || true - - combine-results: - needs: [build, build-curobo, test-isaaclab-tasks, test-isaaclab-tasks-2, test-general, test-newton, test-physx, test-curobo, test-flaky, test-slightly-flaky, test-environments-training] - runs-on: ubuntu-latest - if: always() - name: Combine Results + fetch-depth: 1 + lfs: true + - uses: ./.github/actions/run-package-tests + with: + image-tag: ${{ env.DOCKER_IMAGE_TAG }}-curobo + isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} + isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + dockerfile-path: docker/Dockerfile.curobo + cache-tag: cache-curobo + include-files: "test_generate_dataset_skillgen.py,test_environments_skillgen.py,test_environments_automate.py" + container-name: isaac-lab-skillgen-test + + + # test-quarantined: + # name: "Quarantined Tests" + # runs-on: [self-hosted, gpu] + # timeout-minutes: 180 + # continue-on-error: true + # needs: [build, detect-changes] + # if: >- + # always() && needs.build.result == 'success' && + # vars.RUN_QUARANTINED_TESTS == 'true' + # steps: + # - uses: actions/checkout@v6 + # with: + # fetch-depth: 1 + # lfs: true + # - uses: ./.github/actions/run-package-tests + # with: + # image-tag: ${{ env.DOCKER_IMAGE_TAG }} + # isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} + # isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + # quarantined-only: "true" + # container-name: isaac-lab-quarantined-test + test-environments-training: + name: "environments_training" + runs-on: [self-hosted, gpu] + timeout-minutes: 300 + continue-on-error: true + needs: [build, detect-changes] + if: >- + always() && needs.build.result == 'success' && ( + needs.detect-changes.outputs.isaaclab-tasks == 'true' || + needs.detect-changes.outputs.isaaclab-core == 'true' || + needs.detect-changes.outputs.infra == 'true' + ) steps: - - name: Checkout Code - uses: actions/checkout@v4 + - uses: actions/checkout@v6 with: fetch-depth: 1 - lfs: false - sparse-checkout: .github/actions - sparse-checkout-cone-mode: true - - - name: Create Reports Directory - run: | - mkdir -pv reports - - - name: Download Test Results - uses: actions/download-artifact@v4 + lfs: true + - uses: ./.github/actions/run-package-tests with: - name: isaaclab-tasks-test-results - path: reports/ - continue-on-error: true - - - name: Download IsaacLab Tasks 2 Test Results - uses: actions/download-artifact@v4 - with: - name: isaaclab-tasks-2-test-results - path: reports/ - continue-on-error: true - - - name: Download General Test Results - if: always() - uses: actions/download-artifact@v4 - with: - name: general-test-results - path: reports/ - continue-on-error: true - - - name: Download Newton Test Results - uses: actions/download-artifact@v4 - with: - name: newton-test-results - path: reports/ - continue-on-error: true - - - name: Download PhysX Test Results - uses: actions/download-artifact@v4 - with: - name: physx-test-results - path: reports/ - continue-on-error: true - - - name: Download cuRobo Test Results - uses: actions/download-artifact@v4 - with: - name: curobo-test-results - path: reports/ - continue-on-error: true - - - name: Download Flaky Test Results - uses: actions/download-artifact@v4 - with: - name: flaky-test-results - path: reports/ - continue-on-error: true - - - name: Download Slightly Flaky Test Results - uses: actions/download-artifact@v4 - with: - name: slightly-flaky-test-results - path: reports/ - continue-on-error: true - - - name: Download Environments Training Test Results - uses: actions/download-artifact@v4 - with: - name: environments-training-test-results - path: reports/ - continue-on-error: true - - - name: Combine All Test Results - if: always() - uses: ./.github/actions/combine-results - with: - tests-dir: "reports" - output-file: "reports/combined-results.xml" - - - name: Upload Combined Test Results - uses: actions/upload-artifact@v4 - if: always() - with: - name: pr-${{ github.event.pull_request.number }}-combined-test-results - path: reports/combined-results.xml - retention-days: 7 - compression-level: 9 - - - name: Comment on Test Results - id: test-reporter - if: github.event.pull_request.head.repo.full_name == github.repository - uses: EnricoMi/publish-unit-test-result-action@v2 - with: - files: "reports/combined-results.xml" - check_name: "Tests Summary" - comment_mode: changes - comment_title: "Test Results Summary" - report_individual_runs: false - deduplicate_classes_by_file_name: true - compare_to_earlier_commit: true - fail_on: errors - action_fail_on_inconclusive: true - - - name: Report Test Results - if: github.event.pull_request.head.repo.full_name == github.repository - uses: dorny/test-reporter@v1 - with: - name: IsaacLab Build and Test Results - path: reports/combined-results.xml - reporter: java-junit - fail-on-error: true - only-summary: false - max-annotations: '50' - report-title: "IsaacLab Test Results - ${{ github.workflow }}" + image-tag: ${{ env.DOCKER_IMAGE_TAG }} + isaacsim-base-image: ${{ env.ISAACSIM_BASE_IMAGE }} + isaacsim-version: ${{ env.ISAACSIM_BASE_VERSION }} + filter-pattern: "isaaclab_tasks" + include-files: "test_environments_training.py" + container-name: isaac-lab-environments-training-test diff --git a/.github/workflows/check-links.yml b/.github/workflows/check-links.yml index d77832d3f481..2251222a569b 100644 --- a/.github/workflows/check-links.yml +++ b/.github/workflows/check-links.yml @@ -32,7 +32,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: fetch-depth: 2 filter: tree:0 @@ -42,7 +42,7 @@ jobs: run: | # Get the files changed by this PR/commit. # For PRs: HEAD is the merge commit, HEAD^1 is the base branch tip. - # Diffing HEAD^1..HEAD shows exactly what the PR introduces — files only + # Diffing HEAD^1..HEAD shows exactly what the PR introduces - files only # changed on the base branch (not by the PR) are identical in both and # won't appear. Works for push events too (last commit vs its parent). CHANGED=$(git diff --name-only HEAD^1 HEAD || true) diff --git a/.github/workflows/daily-compatibility.yml b/.github/workflows/daily-compatibility.yml index bb2845f18252..8e9dcba23a81 100644 --- a/.github/workflows/daily-compatibility.yml +++ b/.github/workflows/daily-compatibility.yml @@ -70,7 +70,7 @@ jobs: steps: - name: Checkout Code - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: fetch-depth: 1 lfs: true @@ -101,7 +101,7 @@ jobs: fi - name: Upload IsaacLab Tasks Test Results - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 if: always() with: name: isaaclab-tasks-compat-results-${{ matrix.isaacsim_version }} @@ -127,7 +127,7 @@ jobs: steps: - name: Checkout Code - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: fetch-depth: 1 lfs: true @@ -158,7 +158,7 @@ jobs: fi - name: Upload General Test Results - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 if: always() with: name: general-tests-compat-results-${{ matrix.isaacsim_version }} @@ -173,7 +173,7 @@ jobs: steps: - name: Checkout Code - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: fetch-depth: 1 lfs: false @@ -185,7 +185,7 @@ jobs: mkdir -p reports - name: Download All Test Results - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v8 with: pattern: '*-compat-results-*' path: reports/ @@ -199,7 +199,7 @@ jobs: output-file: "reports/combined-compat-results.xml" - name: Upload Combined Test Results - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 if: always() with: name: daily-compat-${{ github.run_id }}-combined-test-results @@ -208,7 +208,7 @@ jobs: compression-level: 9 - name: Report Test Results - uses: dorny/test-reporter@v1 + uses: dorny/test-reporter@v2.6.0 if: always() with: name: IsaacLab Compatibility Test Results (${{ github.event_name }}) @@ -224,7 +224,7 @@ jobs: steps: - name: Checkout Code - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: fetch-depth: 1 lfs: false @@ -253,7 +253,7 @@ jobs: echo "*This report was generated automatically by the daily compatibility workflow.*" >> compatibility-report.md - name: Upload Compatibility Report - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 if: always() with: name: compatibility-report-${{ github.run_id }} diff --git a/.github/workflows/docs.yaml b/.github/workflows/docs.yaml index ef91a54c94c5..2469a838eea5 100644 --- a/.github/workflows/docs.yaml +++ b/.github/workflows/docs.yaml @@ -43,7 +43,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup python uses: actions/setup-python@v5 @@ -60,7 +60,7 @@ jobs: run: make current-docs - name: Upload docs artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: docs-html path: ./docs/_build @@ -74,7 +74,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v6 - name: Setup python uses: actions/setup-python@v5 @@ -102,7 +102,7 @@ jobs: make multi-docs - name: Upload docs artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: docs-html path: ./docs/_build @@ -116,13 +116,13 @@ jobs: steps: - name: Download docs artifact - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v8 with: name: docs-html path: ./docs/_build - name: Deploy to gh-pages - uses: peaceiris/actions-gh-pages@v3 + uses: peaceiris/actions-gh-pages@v4 with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./docs/_build diff --git a/.github/workflows/license-check.yaml b/.github/workflows/license-check.yaml index 9e1914121779..4a27eb9b1493 100644 --- a/.github/workflows/license-check.yaml +++ b/.github/workflows/license-check.yaml @@ -19,7 +19,7 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: filter: tree:0 diff --git a/.github/workflows/postmerge-ci.yml b/.github/workflows/postmerge-ci.yml index f78461de10c2..ef3ea68a545b 100644 --- a/.github/workflows/postmerge-ci.yml +++ b/.github/workflows/postmerge-ci.yml @@ -41,7 +41,7 @@ jobs: steps: - name: Checkout Code - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: fetch-depth: 1 lfs: true @@ -111,6 +111,8 @@ jobs: # Combine repo short name and branch name for the tag COMBINED_TAG="${REPO_SHORT_NAME}-${SAFE_BRANCH_NAME}-${IMAGE_BASE_VERSION}" BUILD_TAG="${COMBINED_TAG}-b${{ github.run_number }}" + COMMIT_TAG="${COMBINED_TAG}-${{ github.sha }}" + SHORT_COMMIT_TAG="${COMBINED_TAG}-${GITHUB_SHA::7}" # Determine if multiarch is supported by inspecting the base image manifest echo "Checking if base image supports multiarch..." @@ -151,12 +153,14 @@ jobs: echo "Base image: $BASE_IMAGE_FULL" echo "Target platforms: $BUILD_PLATFORMS" - # Build Docker image once with both tags for multiple architectures + # Build Docker image once with all tags for multiple architectures docker buildx build \ --platform $BUILD_PLATFORMS \ --progress=plain \ -t ${{ env.ISAACLAB_IMAGE_NAME }}:$COMBINED_TAG \ -t ${{ env.ISAACLAB_IMAGE_NAME }}:$BUILD_TAG \ + -t ${{ env.ISAACLAB_IMAGE_NAME }}:$COMMIT_TAG \ + -t ${{ env.ISAACLAB_IMAGE_NAME }}:$SHORT_COMMIT_TAG \ --build-arg ISAACSIM_BASE_IMAGE_ARG=${{ env.ISAACSIM_BASE_IMAGE }} \ --build-arg ISAACSIM_VERSION_ARG=$IMAGE_BASE_VERSION \ --build-arg ISAACSIM_ROOT_PATH_ARG=/isaac-sim \ @@ -169,4 +173,6 @@ jobs: echo "✅ Successfully built and pushed: ${{ env.ISAACLAB_IMAGE_NAME }}:$COMBINED_TAG (platforms: $BUILD_PLATFORMS)" echo "✅ Successfully built and pushed: ${{ env.ISAACLAB_IMAGE_NAME }}:$BUILD_TAG (platforms: $BUILD_PLATFORMS)" + echo "✅ Successfully built and pushed: ${{ env.ISAACLAB_IMAGE_NAME }}:$COMMIT_TAG (platforms: $BUILD_PLATFORMS)" + echo "✅ Successfully built and pushed: ${{ env.ISAACLAB_IMAGE_NAME }}:$SHORT_COMMIT_TAG (platforms: $BUILD_PLATFORMS)" done diff --git a/.github/workflows/pre-commit.yaml b/.github/workflows/pre-commit.yaml index 983e2429b310..aa3a38daffff 100644 --- a/.github/workflows/pre-commit.yaml +++ b/.github/workflows/pre-commit.yaml @@ -13,7 +13,7 @@ jobs: pre-commit: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v6 - uses: actions/setup-python@v5 with: python-version: "3.12" diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index d97b86cf88b2..318e1106c688 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -184,6 +184,7 @@ Guidelines for modifications: * Yohan Choi * Yujian Zhang * Yun Liu +* YuTeh Shen * Zehao Wang * Zijian Li * Ziqi Fan diff --git a/docker/Dockerfile.overlay b/docker/Dockerfile.overlay deleted file mode 100644 index cd9c4bea3d51..000000000000 --- a/docker/Dockerfile.overlay +++ /dev/null @@ -1,17 +0,0 @@ -# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). -# All rights reserved. -# -# SPDX-License-Identifier: BSD-3-Clause - -# Thin overlay: apply the final file copy on top of a pre-built deps image. -# Used by ecr-build-push-pull when a deps cache hit is found in ECR, -# skipping the expensive pip/apt installation steps. -ARG DEPS_IMAGE -FROM ${DEPS_IMAGE} - -ARG ISAACLAB_PATH_ARG=/workspace/isaaclab -ENV ISAACLAB_PATH=${ISAACLAB_PATH_ARG} - -# Overwrite with the current working tree (mirrors the final COPY in Dockerfile.base/curobo) -COPY ../ ${ISAACLAB_PATH}/ -WORKDIR ${ISAACLAB_PATH} diff --git a/docs/source/experimental-features/newton-physics-integration/installation.rst b/docs/source/experimental-features/newton-physics-integration/installation.rst index 0cd53178e75e..7ac2fa12bb70 100644 --- a/docs/source/experimental-features/newton-physics-integration/installation.rst +++ b/docs/source/experimental-features/newton-physics-integration/installation.rst @@ -53,8 +53,7 @@ Ensure pip is up to date: .. code-block:: bash - uv pip install "isaacsim[all,extscache]==6.0.0" --extra-index-url https://pypi.nvidia.com - + uv pip install "isaacsim[all,extscache]==6.0.0" --extra-index-url https://pypi.nvidia.com --index-strategy unsafe-best-match --prerelease=allow Install the correct version of torch and torchvision: @@ -76,4 +75,4 @@ To verify that the installation was successful, run the following command from t .. code-block:: bash - ./isaaclab.sh -p scripts/environments/zero_agent.py --task Isaac-Cartpole-Direct-v0 --num_envs 128 + ./isaaclab.sh -p scripts/environments/zero_agent.py --task Isaac-Cartpole-Direct-v0 --num_envs 128 --viz newton presets=newton diff --git a/docs/source/setup/installation/isaaclab_pip_installation.rst b/docs/source/setup/installation/isaaclab_pip_installation.rst index 77b309df0654..d3070fd51f50 100644 --- a/docs/source/setup/installation/isaaclab_pip_installation.rst +++ b/docs/source/setup/installation/isaaclab_pip_installation.rst @@ -61,14 +61,15 @@ Isaac Lab sub-packages: uv pip install isaaclab==3.0.0 # specific version # Isaac Lab + Isaac Sim - uv pip install "isaaclab[isaacsim]" + uv pip install "isaaclab[isaacsim]" --index-strategy unsafe-best-match --prerelease=allow # Isaac Lab + specific sub-package(s) + # Note: flags above are only needed when installing the isaacsim extra uv pip install "isaaclab[assets]" uv pip install "isaaclab[rl,tasks]" # Isaac Lab + Isaac Sim + all sub-packages - uv pip install "isaaclab[isaacsim,all]" + uv pip install "isaaclab[isaacsim,all]" --index-strategy unsafe-best-match --prerelease=allow .. tab-item:: pip @@ -79,14 +80,15 @@ Isaac Lab sub-packages: pip install isaaclab==3.0.0 # specific version # Isaac Lab + Isaac Sim - pip install "isaaclab[isaacsim]" --extra-index-url https://pypi.nvidia.com + pip install "isaaclab[isaacsim]" --extra-index-url https://pypi.nvidia.com --pre # Isaac Lab + specific sub-package(s) + # Note: flags above are only needed when installing the isaacsim extra pip install "isaaclab[assets]" pip install "isaaclab[rl,tasks]" # Isaac Lab + Isaac Sim + all Isaac Lab sub-packages - pip install "isaaclab[isaacsim,all]" --extra-index-url https://pypi.nvidia.com + pip install "isaaclab[isaacsim,all]" --extra-index-url https://pypi.nvidia.com --pre Installing dependencies ~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/source/setup/installation/pip_installation.rst b/docs/source/setup/installation/pip_installation.rst index 22481e8e4a72..a45a66d1de3d 100644 --- a/docs/source/setup/installation/pip_installation.rst +++ b/docs/source/setup/installation/pip_installation.rst @@ -51,7 +51,7 @@ Installing dependencies .. code-block:: bash - uv pip install "isaacsim[all,extscache]==6.0.0" --extra-index-url https://pypi.nvidia.com + uv pip install "isaacsim[all,extscache]==6.0.0" --extra-index-url https://pypi.nvidia.com --index-strategy unsafe-best-match --prerelease=allow - Install a CUDA-enabled PyTorch build that matches your system architecture: diff --git a/docs/source/setup/quickstart.rst b/docs/source/setup/quickstart.rst index 54fb0378f366..4ebdcd024046 100644 --- a/docs/source/setup/quickstart.rst +++ b/docs/source/setup/quickstart.rst @@ -98,7 +98,7 @@ and now we can install the Isaac Sim packages. .. code-block:: bash - uv pip install "isaacsim[all,extscache]==6.0.0" --extra-index-url https://pypi.nvidia.com + uv pip install "isaacsim[all,extscache]==6.0.0" --extra-index-url https://pypi.nvidia.com --index-strategy unsafe-best-match --prerelease=allow Finally, we can install Isaac Lab. To start, clone the repository using the following diff --git a/pyproject.toml b/pyproject.toml index 7f77a42ddf2a..b34726f1eaed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -146,3 +146,15 @@ markers = [ [[tool.uv.index]] url = "https://pypi.nvidia.com" explicit = false + +# Some Isaac Sim dependencies (e.g. mujoco-usd-converter, tinyobjloader) have +# mismatched versions across pypi.nvidia.com and PyPI. unsafe-best-match lets uv +# resolve the correct version from any index, and prerelease=allow covers packages +# that only publish pre-release wheels (e.g. tinyobjloader==2.0.0rc13). +[tool.uv] +index-strategy = "unsafe-best-match" +prerelease = "allow" + +[tool.uv.pip] +index-strategy = "unsafe-best-match" +prerelease = "allow" diff --git a/scripts/reinforcement_learning/rsl_rl/play.py b/scripts/reinforcement_learning/rsl_rl/play.py index cb60206bdf99..224ff1e5493c 100644 --- a/scripts/reinforcement_learning/rsl_rl/play.py +++ b/scripts/reinforcement_learning/rsl_rl/play.py @@ -20,6 +20,7 @@ from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg from isaaclab.utils.assets import retrieve_file_path from isaaclab.utils.dict import print_dict +from isaaclab.utils.string import list_intersection, string_to_callable from isaaclab_rl.rsl_rl import ( RslRlBaseRunnerCfg, @@ -60,14 +61,27 @@ help="Use the pre-trained checkpoint from Nucleus.", ) parser.add_argument("--real-time", action="store_true", default=False, help="Run in real-time, if possible.") +parser.add_argument("--external_callback", default=None, help="Fully qualified path to an externally defined callback.") cli_args.add_rsl_rl_args(parser) add_launcher_args(parser) -args_cli, hydra_args = parser.parse_known_args() +args_cli, remaining_args = parser.parse_known_args() if args_cli.video: args_cli.enable_cameras = True -sys.argv = [sys.argv[0]] + hydra_args + +# Call an external callback if requested. This gives opportunity to external code to register the environments +# The function is expected to return a list of arguments that were not consumed by the callback. +remaining_args_env_registration = None +if args_cli.external_callback: + external_callback_function = string_to_callable(args_cli.external_callback, separator=".") + remaining_args_env_registration = external_callback_function() + +# clear out sys.argv for Hydra +# The remaining arguments are the arguments that were not consumed by both this scripts +# argparser and (optionally) the external callback function. +remaining_args = list_intersection(remaining_args, remaining_args_env_registration) +sys.argv = [sys.argv[0]] + remaining_args # Check for installed RSL-RL version installed_version = metadata.version("rsl-rl-lib") diff --git a/scripts/reinforcement_learning/rsl_rl/train.py b/scripts/reinforcement_learning/rsl_rl/train.py index a0f29e7d8a52..da865153b398 100644 --- a/scripts/reinforcement_learning/rsl_rl/train.py +++ b/scripts/reinforcement_learning/rsl_rl/train.py @@ -23,6 +23,7 @@ from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg from isaaclab.utils.dict import print_dict from isaaclab.utils.io import dump_yaml +from isaaclab.utils.string import list_intersection, string_to_callable from isaaclab_rl.rsl_rl import RslRlBaseRunnerCfg, RslRlVecEnvWrapper, handle_deprecated_rsl_rl_cfg @@ -65,14 +66,27 @@ parser.add_argument( "--ray-proc-id", "-rid", type=int, default=None, help="Automatically configured by Ray integration, otherwise None." ) +parser.add_argument("--external_callback", default=None, help="Fully qualified path to an externally defined callback.") cli_args.add_rsl_rl_args(parser) add_launcher_args(parser) -args_cli, hydra_args = parser.parse_known_args() +args_cli, remaining_args = parser.parse_known_args() if args_cli.video: args_cli.enable_cameras = True -sys.argv = [sys.argv[0]] + hydra_args + +# Call an external callback if requested. This gives opportunity to external code to register the environments +# The function is expected to return a list of arguments that were not consumed by the callback. +remaining_args_env_registration = None +if args_cli.external_callback: + external_callback_function = string_to_callable(args_cli.external_callback, separator=".") + remaining_args_env_registration = external_callback_function() + +# clear out sys.argv for Hydra +# The remaining arguments are the arguments that were not consumed by both this scripts +# argparser and (optionally) the external callback function. +remaining_args = list_intersection(remaining_args, remaining_args_env_registration) +sys.argv = [sys.argv[0]] + remaining_args # -- check RSL-RL version ---------------------------------------------------- installed_version = metadata.version("rsl-rl-lib") diff --git a/source/isaaclab/config/extension.toml b/source/isaaclab/config/extension.toml index d6e20b221327..fec90f0de8ae 100644 --- a/source/isaaclab/config/extension.toml +++ b/source/isaaclab/config/extension.toml @@ -1,7 +1,7 @@ [package] # Note: Semantic Versioning is used: https://semver.org/ -version = "4.5.22" +version = "4.5.24" # Description title = "Isaac Lab framework for Robot Learning" diff --git a/source/isaaclab/docs/CHANGELOG.rst b/source/isaaclab/docs/CHANGELOG.rst index 11524c3b3182..8274b1d14210 100644 --- a/source/isaaclab/docs/CHANGELOG.rst +++ b/source/isaaclab/docs/CHANGELOG.rst @@ -1,6 +1,45 @@ Changelog --------- +4.5.24 (2026-03-25) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added support for absolute named imports (``from pkg import a, b``) in + ``.pyi`` stubs processed by :func:`~isaaclab.utils.module.lazy_export`. + Previously only relative imports and absolute wildcard fallbacks were + handled; explicit names from absolute packages are now eagerly resolved + and re-exported. + +Fixed +^^^^^ + +* Fixed incorrect mass matrix and gravity compensation force indexing for + floating-base robots in :class:`~isaaclab.envs.mdp.actions.OperationalSpaceControllerAction`. + The method ``_compute_dynamic_quantities()`` used ``self._joint_ids`` to index into PhysX + generalized quantities, which does not account for the 6 virtual base DOFs prepended by PhysX + for floating-base articulations. Replaced with ``self._jacobi_joint_idx`` which correctly + applies the +6 offset for floating-base robots and is identical to ``self._joint_ids`` for + fixed-base robots. + + +4.5.23 (2026-03-16) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed flaky tests in ``test_mock_data_properties`` caused by use-after-free in + mock asset data properties. Warp view properties (e.g. :attr:`root_com_lin_vel_w`) + created pointer aliases into locally-scoped temporary arrays; when those temporaries + were freed by CPython's reference counter before the view was consumed, subsequent + reads produced garbage. Fixed by caching default arrays in the backing attribute + (``self._root_link_vel_w``, ``self._root_com_vel_w``, ``self._body_com_vel_w``, + etc.) so the backing memory remains alive for the lifetime of the mock object. + + 4.5.22 (2026-03-16) ~~~~~~~~~~~~~~~~~~~ diff --git a/source/isaaclab/isaaclab/envs/mdp/actions/task_space_actions.py b/source/isaaclab/isaaclab/envs/mdp/actions/task_space_actions.py index 648502d55a8c..99ee2e5cfb55 100644 --- a/source/isaaclab/isaaclab/envs/mdp/actions/task_space_actions.py +++ b/source/isaaclab/isaaclab/envs/mdp/actions/task_space_actions.py @@ -646,12 +646,20 @@ def _resolve_nullspace_joint_pos_targets(self): raise ValueError("Invalid value for nullspace joint pos targets.") def _compute_dynamic_quantities(self): - """Computes the dynamic quantities for operational space control.""" + """Computes the dynamic quantities for operational space control. + + Note: For floating-base robots, PhysX prepends 6 virtual DOFs (base position and orientation) + to the generalized mass matrix and gravity compensation forces. We use ``self._jacobi_joint_idx`` + (which applies the +6 offset for floating-base robots) instead of ``self._joint_ids`` to correctly + index into these quantities. For fixed-base robots, the two are identical. + """ self._mass_matrix[:] = wp.to_torch(self._asset.root_view.get_generalized_mass_matrices())[ - :, self._joint_ids, : - ][:, :, self._joint_ids] - self._gravity[:] = wp.to_torch(self._asset.root_view.get_gravity_compensation_forces())[:, self._joint_ids] + :, self._jacobi_joint_idx, : + ][:, :, self._jacobi_joint_idx] + self._gravity[:] = wp.to_torch(self._asset.root_view.get_gravity_compensation_forces())[ + :, self._jacobi_joint_idx + ] def _compute_ee_jacobian(self): """Computes the geometric Jacobian of the ee body frame in root frame. diff --git a/source/isaaclab/isaaclab/managers/observation_manager.py b/source/isaaclab/isaaclab/managers/observation_manager.py index a1bde0266f4b..ee017cd87de7 100644 --- a/source/isaaclab/isaaclab/managers/observation_manager.py +++ b/source/isaaclab/isaaclab/managers/observation_manager.py @@ -580,15 +580,15 @@ def _prepare_terms(self): for mod_cfg in term_cfg.modifiers: # check if class modifier and initialize with observation size when adding if isinstance(mod_cfg, modifiers.ModifierCfg): - # to list of modifiers + # to list of modifiers - instantiate class-based modifiers if inspect.isclass(mod_cfg.func): - if not issubclass(mod_cfg.func, modifiers.ModifierBase): + mod_cfg.func = mod_cfg.func(cfg=mod_cfg, data_dim=obs_dims, device=self._env.device) + # verify the instance is the correct type + if not isinstance(mod_cfg.func, modifiers.ModifierBase): raise TypeError( f"Modifier function '{mod_cfg.func}' for observation term '{term_name}'" - f" is not a subclass of 'ModifierBase'. Received: '{type(mod_cfg.func)}'." + f" is not an instance of 'ModifierBase'. Received: '{type(mod_cfg.func)}'." ) - mod_cfg.func = mod_cfg.func(cfg=mod_cfg, data_dim=obs_dims, device=self._env.device) - # add to list of class modifiers self._group_obs_class_instances.append(mod_cfg.func) else: @@ -622,16 +622,15 @@ def _prepare_terms(self): # prepare noise model classes if term_cfg.noise is not None and isinstance(term_cfg.noise, noise.NoiseModelCfg): - noise_model_cls = term_cfg.noise.class_type - if not issubclass(noise_model_cls, noise.NoiseModel): - raise TypeError( - f"Class type for observation term '{term_name}' NoiseModelCfg" - f" is not a subclass of 'NoiseModel'. Received: '{type(noise_model_cls)}'." - ) - # initialize func to be the noise model class instance - term_cfg.noise.func = noise_model_cls( + term_cfg.noise.func = term_cfg.noise.class_type( term_cfg.noise, num_envs=self._env.num_envs, device=self._env.device ) + # verify the instance is the correct type + if not isinstance(term_cfg.noise.func, noise.NoiseModel): + raise TypeError( + f"Noise model for observation term '{term_name}' is not an instance of 'NoiseModel'." + f" Received: '{type(term_cfg.noise.func)}'." + ) self._group_obs_class_instances.append(term_cfg.noise.func) # create history buffers and calculate history term dimensions diff --git a/source/isaaclab/isaaclab/physics/physics_manager.py b/source/isaaclab/isaaclab/physics/physics_manager.py index 5b94ede481d5..5676fa8ef02b 100644 --- a/source/isaaclab/isaaclab/physics/physics_manager.py +++ b/source/isaaclab/isaaclab/physics/physics_manager.py @@ -265,6 +265,17 @@ def step(cls) -> None: """Step physics simulation by one timestep (physics only, no rendering).""" pass + @classmethod + def pre_render(cls) -> None: + """Sync deferred physics state to the rendering backend. + + Called by :meth:`~isaaclab.sim.SimulationContext.render` before cameras + and visualizers read scene data. The default implementation is a no-op. + Backends that defer transform writes (e.g. Newton's dirty-flag pattern) + should override this to flush pending updates. + """ + pass + @classmethod def close(cls) -> None: """Clean up physics resources. diff --git a/source/isaaclab/isaaclab/sim/simulation_context.py b/source/isaaclab/isaaclab/sim/simulation_context.py index 27e41f69a8b8..91cee7d0be46 100644 --- a/source/isaaclab/isaaclab/sim/simulation_context.py +++ b/source/isaaclab/isaaclab/sim/simulation_context.py @@ -669,6 +669,7 @@ def render(self, mode: int | None = None) -> None: every physics step). Camera sensors drive their configured renderer when fetching data, so this method remains backend-agnostic. """ + self.physics_manager.pre_render() self.update_visualizers(self.get_rendering_dt()) # Call render callbacks diff --git a/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_articulation.py b/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_articulation.py index c4a033e75176..ddbee003152c 100644 --- a/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_articulation.py +++ b/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_articulation.py @@ -170,7 +170,9 @@ def default_root_pose(self) -> wp.array: def default_root_vel(self) -> wp.array: """Default root velocity. dtype=wp.spatial_vectorf, shape: (N,).""" if self._default_root_vel is None: - return wp.zeros((self._num_instances, 6), dtype=wp.float32, device=self.device).view(wp.spatial_vectorf) + self._default_root_vel = wp.zeros((self._num_instances, 6), dtype=wp.float32, device=self.device).view( + wp.spatial_vectorf + ) return self._default_root_vel @property @@ -362,7 +364,9 @@ def root_link_pose_w(self) -> wp.array: def root_link_vel_w(self) -> wp.array: """Root link velocity in world frame. dtype=wp.spatial_vectorf, shape: (N,).""" if self._root_link_vel_w is None: - return wp.zeros((self._num_instances, 6), dtype=wp.float32, device=self.device).view(wp.spatial_vectorf) + self._root_link_vel_w = wp.zeros((self._num_instances, 6), dtype=wp.float32, device=self.device).view( + wp.spatial_vectorf + ) return self._root_link_vel_w @property @@ -403,14 +407,14 @@ def root_link_ang_vel_w(self) -> wp.array: def root_com_pose_w(self) -> wp.array: """Root CoM pose in world frame. dtype=wp.transformf, shape: (N,).""" if self._root_com_pose_w is None: - return wp.clone(self.root_link_pose_w, self.device) + self._root_com_pose_w = wp.clone(self.root_link_pose_w, self.device) return self._root_com_pose_w @property def root_com_vel_w(self) -> wp.array: """Root CoM velocity in world frame. dtype=wp.spatial_vectorf, shape: (N,).""" if self._root_com_vel_w is None: - return wp.clone(self.root_link_vel_w, self.device) + self._root_com_vel_w = wp.clone(self.root_link_vel_w, self.device) return self._root_com_vel_w @property @@ -467,9 +471,9 @@ def body_link_pose_w(self) -> wp.array: def body_link_vel_w(self) -> wp.array: """Body link velocities in world frame. dtype=wp.spatial_vectorf, shape: (N, num_bodies).""" if self._body_link_vel_w is None: - return wp.zeros((self._num_instances, self._num_bodies, 6), dtype=wp.float32, device=self.device).view( - wp.spatial_vectorf - ) + self._body_link_vel_w = wp.zeros( + (self._num_instances, self._num_bodies, 6), dtype=wp.float32, device=self.device + ).view(wp.spatial_vectorf) return self._body_link_vel_w @property @@ -510,14 +514,14 @@ def body_link_ang_vel_w(self) -> wp.array: def body_com_pose_w(self) -> wp.array: """Body CoM poses in world frame. dtype=wp.transformf, shape: (N, num_bodies).""" if self._body_com_pose_w is None: - return wp.clone(self.body_link_pose_w, self.device) + self._body_com_pose_w = wp.clone(self.body_link_pose_w, self.device) return self._body_com_pose_w @property def body_com_vel_w(self) -> wp.array: """Body CoM velocities in world frame. dtype=wp.spatial_vectorf, shape: (N, num_bodies).""" if self._body_com_vel_w is None: - return wp.clone(self.body_link_vel_w, self.device) + self._body_com_vel_w = wp.clone(self.body_link_vel_w, self.device) return self._body_com_vel_w @property @@ -538,9 +542,9 @@ def body_state_w(self) -> wp.array: def body_com_acc_w(self) -> wp.array: """Body CoM accelerations in world frame. dtype=wp.spatial_vectorf, shape: (N, num_bodies).""" if self._body_com_acc_w is None: - return wp.zeros((self._num_instances, self._num_bodies, 6), dtype=wp.float32, device=self.device).view( - wp.spatial_vectorf - ) + self._body_com_acc_w = wp.zeros( + (self._num_instances, self._num_bodies, 6), dtype=wp.float32, device=self.device + ).view(wp.spatial_vectorf) return self._body_com_acc_w @property diff --git a/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_rigid_object.py b/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_rigid_object.py index 05652e7cf51b..9d2543e14bdc 100644 --- a/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_rigid_object.py +++ b/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_rigid_object.py @@ -104,7 +104,9 @@ def default_root_pose(self) -> wp.array: def default_root_vel(self) -> wp.array: """Default root velocity. dtype=wp.spatial_vectorf, shape: (N,).""" if self._default_root_vel is None: - return wp.zeros((self._num_instances, 6), dtype=wp.float32, device=self.device).view(wp.spatial_vectorf) + self._default_root_vel = wp.zeros((self._num_instances, 6), dtype=wp.float32, device=self.device).view( + wp.spatial_vectorf + ) return self._default_root_vel @property @@ -129,7 +131,9 @@ def root_link_pose_w(self) -> wp.array: def root_link_vel_w(self) -> wp.array: """Root link velocity in world frame. dtype=wp.spatial_vectorf, shape: (N,).""" if self._root_link_vel_w is None: - return wp.zeros((self._num_instances, 6), dtype=wp.float32, device=self.device).view(wp.spatial_vectorf) + self._root_link_vel_w = wp.zeros((self._num_instances, 6), dtype=wp.float32, device=self.device).view( + wp.spatial_vectorf + ) return self._root_link_vel_w @property @@ -171,14 +175,14 @@ def root_link_ang_vel_w(self) -> wp.array: def root_com_pose_w(self) -> wp.array: """Root CoM pose in world frame. dtype=wp.transformf, shape: (N,).""" if self._root_com_pose_w is None: - return wp.clone(self.root_link_pose_w, self.device) + self._root_com_pose_w = wp.clone(self.root_link_pose_w, self.device) return self._root_com_pose_w @property def root_com_vel_w(self) -> wp.array: """Root CoM velocity in world frame. dtype=wp.spatial_vectorf, shape: (N,).""" if self._root_com_vel_w is None: - return wp.clone(self.root_link_vel_w, self.device) + self._root_com_vel_w = wp.clone(self.root_link_vel_w, self.device) return self._root_com_vel_w @property @@ -236,7 +240,9 @@ def body_link_pose_w(self) -> wp.array: def body_link_vel_w(self) -> wp.array: """Body link velocity in world frame. dtype=wp.spatial_vectorf, shape: (N, 1).""" if self._body_link_vel_w is None: - return wp.zeros((self._num_instances, 1, 6), dtype=wp.float32, device=self.device).view(wp.spatial_vectorf) + self._body_link_vel_w = wp.zeros((self._num_instances, 1, 6), dtype=wp.float32, device=self.device).view( + wp.spatial_vectorf + ) return self._body_link_vel_w @property @@ -278,14 +284,14 @@ def body_link_ang_vel_w(self) -> wp.array: def body_com_pose_w(self) -> wp.array: """Body CoM pose in world frame. dtype=wp.transformf, shape: (N, 1).""" if self._body_com_pose_w is None: - return wp.clone(self.body_link_pose_w, self.device) + self._body_com_pose_w = wp.clone(self.body_link_pose_w, self.device) return self._body_com_pose_w @property def body_com_vel_w(self) -> wp.array: """Body CoM velocity in world frame. dtype=wp.spatial_vectorf, shape: (N, 1).""" if self._body_com_vel_w is None: - return wp.clone(self.body_link_vel_w, self.device) + self._body_com_vel_w = wp.clone(self.body_link_vel_w, self.device) return self._body_com_vel_w @property @@ -306,7 +312,9 @@ def body_state_w(self) -> wp.array: def body_com_acc_w(self) -> wp.array: """Body CoM acceleration in world frame. dtype=wp.spatial_vectorf, shape: (N, 1).""" if self._body_com_acc_w is None: - return wp.zeros((self._num_instances, 1, 6), dtype=wp.float32, device=self.device).view(wp.spatial_vectorf) + self._body_com_acc_w = wp.zeros((self._num_instances, 1, 6), dtype=wp.float32, device=self.device).view( + wp.spatial_vectorf + ) return self._body_com_acc_w @property diff --git a/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_rigid_object_collection.py b/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_rigid_object_collection.py index 354c78c2e467..c9533ba2fc5c 100644 --- a/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_rigid_object_collection.py +++ b/source/isaaclab/isaaclab/test/mock_interfaces/assets/mock_rigid_object_collection.py @@ -96,16 +96,16 @@ def default_body_pose(self) -> wp.array: if self._default_body_pose is None: pose_np = np.zeros((self._num_instances, self._num_bodies, 7), dtype=np.float32) pose_np[..., 6] = 1.0 # identity quat qw=1, transformf layout - return wp.array(pose_np, dtype=wp.float32, device=self.device).view(wp.transformf) + self._default_body_pose = wp.array(pose_np, dtype=wp.float32, device=self.device).view(wp.transformf) return self._default_body_pose @property def default_body_vel(self) -> wp.array: """Default body velocities. dtype=wp.spatial_vectorf, shape: (N, num_bodies).""" if self._default_body_vel is None: - return wp.zeros((self._num_instances, self._num_bodies, 6), dtype=wp.float32, device=self.device).view( - wp.spatial_vectorf - ) + self._default_body_vel = wp.zeros( + (self._num_instances, self._num_bodies, 6), dtype=wp.float32, device=self.device + ).view(wp.spatial_vectorf) return self._default_body_vel @property @@ -130,9 +130,9 @@ def body_link_pose_w(self) -> wp.array: def body_link_vel_w(self) -> wp.array: """Body link velocities in world frame. dtype=wp.spatial_vectorf, shape: (N, num_bodies).""" if self._body_link_vel_w is None: - return wp.zeros((self._num_instances, self._num_bodies, 6), dtype=wp.float32, device=self.device).view( - wp.spatial_vectorf - ) + self._body_link_vel_w = wp.zeros( + (self._num_instances, self._num_bodies, 6), dtype=wp.float32, device=self.device + ).view(wp.spatial_vectorf) return self._body_link_vel_w @property @@ -173,14 +173,14 @@ def body_link_ang_vel_w(self) -> wp.array: def body_com_pose_w(self) -> wp.array: """Body CoM poses in world frame. dtype=wp.transformf, shape: (N, num_bodies).""" if self._body_com_pose_w is None: - return wp.clone(self.body_link_pose_w, self.device) + self._body_com_pose_w = wp.clone(self.body_link_pose_w, self.device) return self._body_com_pose_w @property def body_com_vel_w(self) -> wp.array: """Body CoM velocities in world frame. dtype=wp.spatial_vectorf, shape: (N, num_bodies).""" if self._body_com_vel_w is None: - return wp.clone(self.body_link_vel_w, self.device) + self._body_com_vel_w = wp.clone(self.body_link_vel_w, self.device) return self._body_com_vel_w @property @@ -194,9 +194,9 @@ def body_com_state_w(self) -> wp.array: def body_com_acc_w(self) -> wp.array: """Body CoM accelerations in world frame. dtype=wp.spatial_vectorf, shape: (N, num_bodies).""" if self._body_com_acc_w is None: - return wp.zeros((self._num_instances, self._num_bodies, 6), dtype=wp.float32, device=self.device).view( - wp.spatial_vectorf - ) + self._body_com_acc_w = wp.zeros( + (self._num_instances, self._num_bodies, 6), dtype=wp.float32, device=self.device + ).view(wp.spatial_vectorf) return self._body_com_acc_w @property diff --git a/source/isaaclab/isaaclab/utils/module.py b/source/isaaclab/isaaclab/utils/module.py index a1138bb6f875..3c3fcdc35bfc 100644 --- a/source/isaaclab/isaaclab/utils/module.py +++ b/source/isaaclab/isaaclab/utils/module.py @@ -18,11 +18,14 @@ import lazy_loader as lazy -def _parse_stub(stub_file: str) -> tuple[str | None, list[str], list[str]]: +def _parse_stub( + stub_file: str, +) -> tuple[str | None, list[str], list[str], dict[str, list[str]]]: """Parse a ``.pyi`` stub in a single AST pass. Returns: - A 3-tuple of ``(filtered_path, fallback_packages, relative_wildcards)``. + A 4-tuple ``(filtered_path, fallback_packages, relative_wildcards, + absolute_named)``. *filtered_path* is a temporary ``.pyi`` containing only explicit relative imports (what ``lazy_loader`` can handle), or ``None`` when @@ -36,6 +39,9 @@ def _parse_stub(stub_file: str) -> tuple[str | None, list[str], list[str]]: *relative_wildcards* lists submodule names extracted from relative wildcard imports (``from .mod import *``). + + *absolute_named* maps fully-qualified package names to the list of + explicit names imported from them (``from pkg import a, b``). """ with open(stub_file) as f: source = f.read() @@ -44,6 +50,7 @@ def _parse_stub(stub_file: str) -> tuple[str | None, list[str], list[str]]: fallback_packages: list[str] = [] relative_wildcards: list[str] = [] + absolute_named: dict[str, list[str]] = {} filtered_body: list[ast.stmt] = [] needs_filter = False @@ -57,18 +64,21 @@ def _parse_stub(stub_file: str) -> tuple[str | None, list[str], list[str]]: fallback_packages.append(node.module) elif node.level == 1 and is_star and node.module: relative_wildcards.append(node.module) + elif node.level == 0 and not is_star and node.module: + names = [alias.name for alias in node.names] + absolute_named.setdefault(node.module, []).extend(names) needs_filter = True else: filtered_body.append(node) if not needs_filter: - return None, fallback_packages, relative_wildcards + return None, fallback_packages, relative_wildcards, absolute_named filtered = ast.Module(body=filtered_body, type_ignores=[]) with tempfile.NamedTemporaryFile(mode="w", suffix=".pyi", delete=False) as tmp: tmp.write(ast.unparse(filtered)) - return tmp.name, fallback_packages, relative_wildcards + return tmp.name, fallback_packages, relative_wildcards, absolute_named def lazy_export( @@ -84,6 +94,8 @@ def lazy_export( local submodule (existing ``lazy_loader`` behaviour). * ``from .rewards import *`` — eagerly imports the submodule and re-exports all of its public names at ``lazy_export()`` time. + * ``from isaaclab.envs.mdp import foo, bar`` — eagerly re-exports + specific names from an absolute package. * ``from isaaclab.envs.mdp import *`` — sets up a lazy fallback so that any name not found locally is resolved from the specified package. @@ -123,9 +135,10 @@ def lazy_export( fallback_packages: list[str] = list(packages) if packages else [] relative_wildcards: list[str] = [] + absolute_named: dict[str, list[str]] = {} if has_stub: - filtered_path, stub_fallbacks, relative_wildcards = _parse_stub(stub_file) + filtered_path, stub_fallbacks, relative_wildcards, absolute_named = _parse_stub(stub_file) if stub_fallbacks: fallback_packages = list(dict.fromkeys(fallback_packages + stub_fallbacks)) @@ -138,6 +151,14 @@ def lazy_export( mod = sys.modules[package_name] + # -- Eagerly resolve absolute named imports (from pkg import a, b) ----- + for abs_pkg, names in absolute_named.items(): + pkg_mod = importlib.import_module(abs_pkg) + for name in names: + mod.__dict__[name] = getattr(pkg_mod, name) + if name not in __all__: + __all__.append(name) + # -- Eagerly resolve relative wildcard imports (from .X import *) ------ for rel_mod_name in relative_wildcards: fq_name = f"{package_name}.{rel_mod_name}" diff --git a/source/isaaclab/isaaclab/utils/string.py b/source/isaaclab/isaaclab/utils/string.py index 8506da848196..21c5cd58e77f 100644 --- a/source/isaaclab/isaaclab/utils/string.py +++ b/source/isaaclab/isaaclab/utils/string.py @@ -105,11 +105,12 @@ def is_lambda_expression(name: str) -> bool: return False -def callable_to_string(value: Callable) -> str: +def callable_to_string(value: Callable, separator: str = ":") -> str: """Converts a callable object to a string. Args: value: A callable object. + separator: The separator between the module path and the function name. Defaults to ":". Raises: ValueError: When the input argument is not a callable object. @@ -132,15 +133,16 @@ def callable_to_string(value: Callable) -> str: module_name = value.__module__ function_name = value.__name__ # return the string - return f"{module_name}:{function_name}" + return f"{module_name}{separator}{function_name}" -def string_to_callable(name: str) -> Callable: +def string_to_callable(name: str, separator: str = ":") -> Callable: """Resolves the module and function names to return the function. Args: name: The function name. The format should be 'module:attribute_name' or a lambda expression of format: 'lambda x: x'. + separator: The separator between the module path and the function name. Defaults to ":". Raises: ValueError: When the resolved attribute is not a function. @@ -153,7 +155,7 @@ def string_to_callable(name: str) -> Callable: if is_lambda_expression(name): callable_object = eval(name) else: - mod_name, attr_name = name.split(":") + mod_name, attr_name = name.rsplit(separator, 1) mod = importlib.import_module(mod_name) callable_object = getattr(mod, attr_name) # check if attribute is callable @@ -484,3 +486,22 @@ def find_root_prim_path_from_regex(prim_path_regex: str) -> tuple[str, int]: root_prim_path = "/".join(prim_paths_list[:root_idx]) tree_level = root_idx return root_prim_path, tree_level + + +def list_intersection(list1: list[Any], list2: list[Any] | None) -> list[Any]: + """Return the intersection of two lists. + + The returned list has elements that are in both input lists. + + Args: + list1: The first list. + list2: The second list. + + Returns: + A new list containing elements that are in both input lists. + + """ + if list2 is None: + return list1 + set2 = set(list2) + return [x for x in list1 if x in set2] diff --git a/source/isaaclab/test/controllers/test_operational_space.py b/source/isaaclab/test/controllers/test_operational_space.py index 771cde6e5c04..3b9eb1a2c5a0 100644 --- a/source/isaaclab/test/controllers/test_operational_space.py +++ b/source/isaaclab/test/controllers/test_operational_space.py @@ -19,12 +19,26 @@ from isaacsim.core.cloner import GridCloner +import isaaclab.envs.mdp as mdp import isaaclab.sim as sim_utils from isaaclab.assets import Articulation +from isaaclab.assets.articulation import ArticulationCfg from isaaclab.controllers import OperationalSpaceController, OperationalSpaceControllerCfg + +## +# Pre-defined configs +## +from isaaclab.envs import ManagerBasedEnv, ManagerBasedEnvCfg +from isaaclab.envs.mdp.actions.actions_cfg import OperationalSpaceControllerActionCfg +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.managers import ObservationTermCfg as ObsTerm +from isaaclab.managers import SceneEntityCfg from isaaclab.markers import VisualizationMarkers from isaaclab.markers.config import FRAME_MARKER_CFG +from isaaclab.scene import InteractiveSceneCfg from isaaclab.sensors import ContactSensor, ContactSensorCfg +from isaaclab.terrains import TerrainImporterCfg +from isaaclab.utils import configclass as lab_configclass from isaaclab.utils.math import ( apply_delta_pose, combine_frame_transforms, @@ -35,10 +49,7 @@ subtract_frame_transforms, ) -## -# Pre-defined configs -## -from isaaclab_assets import FRANKA_PANDA_CFG # isort:skip +from isaaclab_assets import FRANKA_PANDA_CFG, G1_29DOF_CFG # isort:skip @pytest.fixture @@ -1258,6 +1269,146 @@ def test_franka_taskframe_hybrid_with_nullspace_centering(sim): ) +## +# Floating-base regression test configs (PR #5107) +## + +_G1_ARM_JOINT_NAMES = [ + "left_shoulder_pitch_joint", + "left_shoulder_roll_joint", + "left_shoulder_yaw_joint", + "left_elbow_joint", +] + + +@lab_configclass +class _FloatingBaseOscSceneCfg(InteractiveSceneCfg): + """Minimal scene with a floating-base G1 humanoid.""" + + terrain = TerrainImporterCfg(prim_path="/World/ground", terrain_type="plane", debug_vis=False) + robot: ArticulationCfg = G1_29DOF_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") + + def __post_init__(self): + super().__post_init__() + self.robot.spawn.articulation_props.fix_root_link = False + self.robot.spawn.rigid_props.disable_gravity = True + + +@lab_configclass +class _FloatingBaseOscActionsCfg: + arm_action: OperationalSpaceControllerActionCfg = OperationalSpaceControllerActionCfg( + asset_name="robot", + joint_names=_G1_ARM_JOINT_NAMES, + body_name="left_elbow_link", + controller_cfg=OperationalSpaceControllerCfg( + target_types=["pose_abs"], + impedance_mode="fixed", + inertial_dynamics_decoupling=True, + gravity_compensation=False, + motion_stiffness_task=500.0, + motion_damping_ratio_task=1.0, + ), + ) + + +@lab_configclass +class _FloatingBaseOscObsCfg: + @lab_configclass + class _PolicyCfg(ObsGroup): + joint_pos = ObsTerm(func=mdp.joint_pos, params={"asset_cfg": SceneEntityCfg("robot")}) + + policy: _PolicyCfg = _PolicyCfg() + + +@lab_configclass +class _FloatingBaseOscEnvCfg(ManagerBasedEnvCfg): + scene: _FloatingBaseOscSceneCfg = _FloatingBaseOscSceneCfg(num_envs=4, env_spacing=4.0) + actions: _FloatingBaseOscActionsCfg = _FloatingBaseOscActionsCfg() + observations: _FloatingBaseOscObsCfg = _FloatingBaseOscObsCfg() + decimation: int = 1 + sim: sim_utils.SimulationCfg = sim_utils.SimulationCfg(dt=0.01) + + +@pytest.mark.isaacsim_ci +def test_floating_base_osc_action_term_indexing(): + """Regression test for #4999 / PR #5107: verify OperationalSpaceControllerAction uses correct + indices for mass matrix and gravity on floating-base robots. + + For floating-base robots, PhysX prepends 6 virtual DOFs to the generalized mass matrix and + gravity vectors. The action term's ``_compute_dynamic_quantities()`` must use + ``_jacobi_joint_idx`` (with +6 offset) instead of ``_joint_ids``. This test instantiates the + real action term via a ManagerBasedEnv, triggers ``_compute_dynamic_quantities()``, and verifies + the extracted mass matrix and gravity match a manual extraction using the correct PhysX indices. + + If someone reverts ``_jacobi_joint_idx`` back to ``_joint_ids`` in ``_compute_dynamic_quantities``, + this test will fail. + """ + env_cfg = _FloatingBaseOscEnvCfg() + env_cfg.sim.device = "cuda:0" + env = ManagerBasedEnv(cfg=env_cfg) + num_envs = env.num_envs + + try: + robot: Articulation = env.scene["robot"] + + # --- 1. Verify the robot is floating-base --- + assert not robot.is_fixed_base, "G1_29DOF_CFG must be floating-base for this test" + + # --- 2. Get the action term --- + action_term = env.action_manager._terms["arm_action"] + num_arm_joints = action_term._num_DoF + + # --- 3. Step the env to populate physics buffers --- + zero_actions = torch.zeros(num_envs, action_term.action_dim, device=env.device) + action_term.process_actions(zero_actions) + action_term.apply_actions() + + # --- 4. The action term's _mass_matrix and _gravity are now populated --- + term_mass = action_term._mass_matrix.clone() + term_gravity = action_term._gravity.clone() + + # --- 5. Manually extract using the CORRECT indices (what the fix does) --- + jacobi_joint_idx = action_term._jacobi_joint_idx + full_mass_matrix = wp.to_torch(robot.root_view.get_generalized_mass_matrices()) + full_gravity = wp.to_torch(robot.root_view.get_gravity_compensation_forces()) + + manual_mass = full_mass_matrix[:, jacobi_joint_idx, :][:, :, jacobi_joint_idx] + manual_gravity = full_gravity[:, jacobi_joint_idx] + + # --- 6. KEY ASSERTION: action term output must match manual extraction with correct indices --- + torch.testing.assert_close(term_mass, manual_mass, atol=1e-5, rtol=0) + torch.testing.assert_close(term_gravity, manual_gravity, atol=1e-5, rtol=0) + + # --- 7. Verify the full PhysX tensor has +6 virtual DOFs --- + expected_physx_dofs = robot.num_joints + 6 + assert full_mass_matrix.shape[1] == expected_physx_dofs, ( + f"Mass matrix should have {expected_physx_dofs} DOFs, got {full_mass_matrix.shape[1]}" + ) + + # --- 8. Verify correct indices differ from raw joint_ids (the old bug) --- + # Reconstruct the original joint_ids before any slice(None) optimization + original_joint_ids, _ = robot.find_joints(_G1_ARM_JOINT_NAMES) + buggy_mass = full_mass_matrix[:, original_joint_ids, :][:, :, original_joint_ids] + assert not torch.allclose(term_mass, buggy_mass, atol=1e-6), ( + "Action term mass matrix should NOT match extraction with raw joint_ids (no +6 offset)" + ) + + # --- 9. Verify physically reasonable values --- + diag = torch.diagonal(term_mass, dim1=-2, dim2=-1) + assert (diag > 0).all(), f"Mass matrix diagonal must be positive, got min={diag.min().item():.6f}" + assert diag.max().item() < 100.0, ( + f"Mass matrix diagonal too large ({diag.max().item():.1f}), possibly contaminated by base DOFs" + ) + assert torch.allclose(term_mass, term_mass.transpose(-2, -1), atol=1e-5), "Mass matrix should be symmetric" + + # --- 10. Verify shapes --- + assert term_mass.shape == (num_envs, num_arm_joints, num_arm_joints) + assert term_gravity.shape == (num_envs, num_arm_joints) + + finally: + env.close() + + def _run_op_space_controller( robot: Articulation, osc: OperationalSpaceController, diff --git a/source/isaaclab/test/deps/isaacsim/check_camera.py b/source/isaaclab/test/deps/isaacsim/check_camera.py index 28f23ed1ef43..27a0dfdfca99 100644 --- a/source/isaaclab/test/deps/isaacsim/check_camera.py +++ b/source/isaaclab/test/deps/isaacsim/check_camera.py @@ -168,12 +168,6 @@ def main(): initial_joint_pos = view.get_joint_positions() initial_joint_vel = view.get_joint_velocities() - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - world.step(render=True) - # Counter count = 0 prev_im = None diff --git a/source/isaaclab/test/envs/test_env_rendering_logic.py b/source/isaaclab/test/envs/test_env_rendering_logic.py index 3a5531165109..0b04143f9537 100644 --- a/source/isaaclab/test/envs/test_env_rendering_logic.py +++ b/source/isaaclab/test/envs/test_env_rendering_logic.py @@ -145,7 +145,7 @@ def callback(dt): @pytest.mark.parametrize("env_type", ["manager_based_env", "manager_based_rl_env", "direct_rl_env"]) -@pytest.mark.parametrize("render_interval", [1, 2, 4, 8, 10]) +@pytest.mark.parametrize("render_interval", [1, 4, 10]) def test_env_rendering_logic(env_type, render_interval, physics_callback, render_callback): """Test the rendering logic of the different environment workflows.""" physics_cb, get_physics_stats = physics_callback @@ -204,7 +204,7 @@ def wrapped_step(dt): actions = torch.zeros((env.num_envs, 0), device=env.device) # run the environment and check the rendering logic - for i in range(50): + for i in range(10): # apply zero actions env.step(action=actions) diff --git a/source/isaaclab/test/envs/test_manager_based_rl_env_obs_spaces.py b/source/isaaclab/test/envs/test_manager_based_rl_env_obs_spaces.py index 5901d7806408..66a14739897b 100644 --- a/source/isaaclab/test/envs/test_manager_based_rl_env_obs_spaces.py +++ b/source/isaaclab/test/envs/test_manager_based_rl_env_obs_spaces.py @@ -115,11 +115,11 @@ def test_non_concatenated_obs_groups_contain_all_terms(device): ) @pytest.mark.parametrize("device", ["cpu", "cuda"]) def test_obs_space_follows_clip_contraint(env_cfg_cls, device): - """Ensure curriculum terms apply correctly after the fallback and replacement.""" + """Ensure observation space bounds reflect the clip constraint on each term.""" # new USD stage sim_utils.create_new_stage() - # configure the cartpole env + # configure the env env_cfg = env_cfg_cls() env_cfg.scene.num_envs = 2 # keep num_envs small for testing env_cfg.observations.policy.concatenate_terms = False diff --git a/source/isaaclab/test/managers/test_observation_manager.py b/source/isaaclab/test/managers/test_observation_manager.py index 86e77c571a42..4c44bfd00ba5 100644 --- a/source/isaaclab/test/managers/test_observation_manager.py +++ b/source/isaaclab/test/managers/test_observation_manager.py @@ -192,7 +192,7 @@ class SampleGroupCfg(ObservationGroupCfg): print() print(obs_man_str) obs_man_str_split = obs_man_str.split("|") - term_1_str_index = obs_man_str_split.index(" term_1 ") + term_1_str_index = obs_man_str_split.index(" term_1 ") term_1_str_shape = obs_man_str_split[term_1_str_index + 1].strip() # Handle numpy 2.0 where shape may be represented as (np.int64(20),) instead of (20,) assert term_1_str_shape in ("(20,)", "(np.int64(20),)") diff --git a/source/isaaclab/test/sensors/test_camera.py b/source/isaaclab/test/sensors/test_camera.py index c9e60d05f308..f1effb9a70e7 100644 --- a/source/isaaclab/test/sensors/test_camera.py +++ b/source/isaaclab/test/sensors/test_camera.py @@ -16,7 +16,6 @@ """Rest everything follows.""" import copy -import os import random import numpy as np @@ -29,8 +28,6 @@ import isaaclab.sim as sim_utils from isaaclab.sensors.camera import Camera, CameraCfg -from isaaclab.utils import convert_dict_to_backend -from isaaclab.utils.timer import Timer # sample camera poses POSITION = (2.5, 2.5, 2.5) @@ -105,12 +102,6 @@ def test_camera_init(setup_sim_camera): assert camera._sensor_prims[0].GetPath().pathString == camera_cfg.prim_path assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exist and have correct shapes assert camera.data.pos_w.shape == (1, 3) assert camera.data.quat_w_ros.shape == (1, 4) @@ -199,12 +190,6 @@ def test_camera_init_offset(setup_sim_camera): rtol=1e-5, ) - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # check if transform correctly set in output np.testing.assert_allclose(camera_ros.data.pos_w[0].cpu().numpy(), cam_cfg_offset_ros.offset.pos, rtol=1e-5) np.testing.assert_allclose(camera_ros.data.quat_w_ros[0].cpu().numpy(), QUAT_ROS, rtol=1e-5) @@ -228,11 +213,6 @@ def test_multi_camera_init(setup_sim_camera): # play sim sim.reset() - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() # Simulate physics for _ in range(10): # perform rendering @@ -264,11 +244,6 @@ def test_multi_camera_with_different_resolution(setup_sim_camera): # play sim sim.reset() - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() # perform rendering sim.step() # update camera @@ -348,12 +323,6 @@ def test_camera_set_world_poses(setup_sim_camera): # set new pose camera.set_world_poses(position.clone(), orientation.clone(), convention="world") - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # check if transform correctly set in output torch.testing.assert_close(camera.data.pos_w, position) torch.testing.assert_close(camera.data.quat_w_world, orientation) @@ -376,12 +345,6 @@ def test_camera_set_world_poses_from_view(setup_sim_camera): # set new pose camera.set_world_poses_from_view(eyes.clone(), targets.clone()) - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # check if transform correctly set in output torch.testing.assert_close(camera.data.pos_w, eyes) torch.testing.assert_close(camera.data.quat_w_ros, quat_ros_gt) @@ -402,12 +365,6 @@ def test_intrinsic_matrix(setup_sim_camera): # Set matrix into simulator camera.set_intrinsic_matrices(rs_intrinsic_matrix.clone()) - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Simulate physics for _ in range(10): # perform rendering @@ -460,11 +417,6 @@ def test_depth_clipping(setup_sim_camera): # Play sim sim.reset() - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - camera_zero.update(dt) camera_none.update(dt) camera_max.update(dt) @@ -559,11 +511,6 @@ def test_camera_resolution_all_colorize(setup_sim_camera): # Play sim sim.reset() - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() camera.update(dt) # expected sizes @@ -625,11 +572,6 @@ def test_camera_resolution_no_colorize(setup_sim_camera): # Play sim sim.reset() - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(12): - sim.step() camera.update(dt) # expected sizes @@ -694,11 +636,6 @@ def test_camera_large_resolution_all_colorize(setup_sim_camera): # Play sim sim.reset() - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() camera.update(dt) # expected sizes @@ -746,11 +683,6 @@ def test_camera_resolution_rgb_only(setup_sim_camera): # Play sim sim.reset() - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() camera.update(dt) # expected sizes @@ -773,11 +705,6 @@ def test_camera_resolution_rgba_only(setup_sim_camera): # Play sim sim.reset() - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() camera.update(dt) # expected sizes @@ -800,11 +727,6 @@ def test_camera_resolution_albedo_only(setup_sim_camera): # Play sim sim.reset() - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() camera.update(dt) # expected sizes @@ -831,11 +753,6 @@ def test_camera_resolution_simple_shading_only(setup_sim_camera, data_type): # Play sim sim.reset() - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() camera.update(dt) # expected sizes @@ -858,11 +775,6 @@ def test_camera_resolution_depth_only(setup_sim_camera): # Play sim sim.reset() - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() camera.update(dt) # expected sizes @@ -874,59 +786,6 @@ def test_camera_resolution_depth_only(setup_sim_camera): assert output["depth"].dtype == torch.float -def test_throughput(setup_sim_camera): - """Checks that the single camera gets created properly with a rig.""" - # Create directory temp dir to dump the results - file_dir = os.path.dirname(os.path.realpath(__file__)) - temp_dir = os.path.join(file_dir, "output", "camera", "throughput") - os.makedirs(temp_dir, exist_ok=True) - # Create replicator writer - rep_writer = rep.BasicWriter(output_dir=temp_dir, frame_padding=3) - # create camera - sim, camera_cfg, dt = setup_sim_camera - camera_cfg.height = 480 - camera_cfg.width = 640 - camera = Camera(camera_cfg) - - # Play simulator - sim.reset() - - # Set camera pose - eyes = torch.tensor([[2.5, 2.5, 2.5]], dtype=torch.float32, device=camera.device) - targets = torch.tensor([[0.0, 0.0, 0.0]], dtype=torch.float32, device=camera.device) - camera.set_world_poses_from_view(eyes, targets) - - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Simulate physics - for _ in range(5): - # perform rendering - sim.step() - # update camera - with Timer(f"Time taken for updating camera with shape {camera.image_shape}"): - camera.update(dt) - # Save images - with Timer(f"Time taken for writing data with shape {camera.image_shape} "): - # Pack data back into replicator format to save them using its writer - rep_output = {"annotators": {}} - camera_data = convert_dict_to_backend({k: v[0] for k, v in camera.data.output.items()}, backend="numpy") - for key, data, info in zip(camera_data.keys(), camera_data.values(), camera.data.info[0].values()): - if info is not None: - rep_output["annotators"][key] = {"render_product": {"data": data, **info}} - else: - rep_output["annotators"][key] = {"render_product": {"data": data}} - # Save images - rep_output["trigger_outputs"] = {"on_time": camera.frame[0]} - rep_writer.write(rep_output) - print("----------------------------------------") - # Check image data - for im_data in camera.data.output.values(): - assert im_data.shape == (1, camera_cfg.height, camera_cfg.width, 1) - - def test_sensor_print(setup_sim_camera): """Test sensor print is working correctly.""" # Create sensor diff --git a/source/isaaclab/test/sensors/test_first_frame_textured_rendering.py b/source/isaaclab/test/sensors/test_first_frame_textured_rendering.py new file mode 100644 index 000000000000..9fef377fc13d --- /dev/null +++ b/source/isaaclab/test/sensors/test_first_frame_textured_rendering.py @@ -0,0 +1,215 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# TODO: These tests appear to be flaky because 3 warmup steps may not be enough for textures to stream in. +# A polling-based fix was prototyped in https://github.com/isaac-sim/IsaacLab/pull/5097 — see commits: +# 69e73530c84 Fix test_first_frame_textured_rendering (core 1/3): poll for texture load instead of fixed warmup +# 1a7c4036da1 Fix test_first_frame_textured_rendering.py (core 1/3) - increase warmup time +# 1632d3ae859 test_first_frame_textured_rendering.py: increase # of warmup steps + +"""Launch Isaac Sim Simulator first.""" + +from isaaclab.app import AppLauncher + +# launch omniverse app +simulation_app = AppLauncher(headless=True, enable_cameras=True).app + +"""Rest everything follows.""" + +import pytest +import torch + +import omni.replicator.core as rep + +import isaaclab.sim as sim_utils +from isaaclab.sensors.camera import Camera, CameraCfg, TiledCamera, TiledCameraCfg +from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR + +# resolution +HEIGHT = 256 +WIDTH = 256 + +# grey default-material detection: channels within this tolerance and mean below threshold +GREY_CHANNEL_TOLERANCE = 3.0 +GREY_MEAN_THRESHOLD = 85.0 + +# number of sim steps to warm up before capturing the first frame +WARMUP_STEPS = 3 + +# number of extra sim steps before capturing the stabilised reference frame +STABILISATION_STEPS = 5 + +# max allowed per-channel mean difference between first and stabilised frames +FRAME_CONSISTENCY_THRESHOLD = 15.0 + +# scene: dome light +DOME_LIGHT_INTENSITY = 3000.0 + +# scene: textured cube pose +CUBE_TRANSLATION = (0.0, 0.0, 0.6) +CUBE_ORIENTATION = (0.7071, 0.0, 0.7071, 0.0) # rotate DexCube with its yellow "E" face texture up +CUBE_SCALE = (0.9, 0.9, 0.9) + + +@pytest.fixture(scope="function") +def setup_sim(device): + """Fixture to set up and tear down the textured rendering test environment.""" + # Create a new stage + sim_utils.create_new_stage() + # Simulation time-step + dt = 0.01 + # Load kit helper + sim_cfg = sim_utils.SimulationCfg(dt=dt, device=device) + sim = sim_utils.SimulationContext(sim_cfg) + # populate scene + _populate_scene() + # load stage + sim_utils.update_stage() + yield sim, dt + # Teardown + rep.vp_manager.destroy_hydra_textures("Replicator") + sim.stop() + sim.clear_instance() + + +def _assert_first_frame_textured(first_frame: torch.Tensor, stable_frame: torch.Tensor): + """Verify that first_frame shows loaded textures and is consistent with stable_frame.""" + mean_first = first_frame.mean(dim=(0, 1)) + mean_stable = stable_frame.mean(dim=(0, 1)) + + # Guard 1: not the grey default material + channels_equal = (mean_first[1] - mean_first[0]).abs() < GREY_CHANNEL_TOLERANCE and ( + mean_first[2] - mean_first[0] + ).abs() < GREY_CHANNEL_TOLERANCE + all_low = mean_first.mean() < GREY_MEAN_THRESHOLD + assert not (channels_equal and all_low), ( + f"First frame looks like the grey default material " + f"(mean RGB: {mean_first[0]:.1f}, {mean_first[1]:.1f}, {mean_first[2]:.1f}). " + "Texture streaming may not have completed before the first capture." + ) + + # Guard 2: first frame and stabilised frame are broadly consistent + per_channel_diff = (mean_first - mean_stable).abs() + assert per_channel_diff.max().item() < FRAME_CONSISTENCY_THRESHOLD, ( + f"First and stabilised frames differ too much per-channel " + f"(max delta {per_channel_diff.max():.1f}, means: " + f"first=({mean_first[0]:.1f}, {mean_first[1]:.1f}, {mean_first[2]:.1f}), " + f"stable=({mean_stable[0]:.1f}, {mean_stable[1]:.1f}, {mean_stable[2]:.1f})). " + "The first frame may not be fully textured." + ) + + +@pytest.mark.parametrize("device", ["cuda:0"]) +@pytest.mark.isaacsim_ci +def test_first_frame_is_textured_camera(setup_sim, device): + """First RTX frame from a USD Camera must show loaded textures, not a grey placeholder.""" + sim, dt = setup_sim + camera_cfg = CameraCfg( + height=HEIGHT, + width=WIDTH, + offset=CameraCfg.OffsetCfg(pos=(0.0, 0.0, 0.75), rot=(0.0, 1.0, 0.0, 0.0), convention="ros"), + prim_path="/World/Camera", + update_period=0, + data_types=["rgb"], + spawn=sim_utils.PinholeCameraCfg( + focal_length=24.0, + focus_distance=400.0, + horizontal_aperture=20.955, + clipping_range=(0.1, 1.0e5), + ), + ) + # Create camera + camera = Camera(camera_cfg) + + # Play sim + sim.reset() + + # Warm up the renderer so textures have time to stream in + for _ in range(WARMUP_STEPS): + sim.step() + + # Capture the first frame after warm-up + sim.step() + camera.update(dt) + first_frame = camera.data.output["rgb"][0].clone().to(dtype=torch.float32) + + # Let the renderer step, then capture the reference frame + for _ in range(STABILISATION_STEPS): + sim.step() + camera.update(dt) + stable_frame = camera.data.output["rgb"][0].clone().to(dtype=torch.float32) + + del camera + + _assert_first_frame_textured(first_frame, stable_frame) + + +@pytest.mark.parametrize("device", ["cuda:0"]) +@pytest.mark.isaacsim_ci +def test_first_frame_is_textured_tiled_camera(setup_sim, device): + """First RTX frame from a TiledCamera must show loaded textures, not a grey placeholder.""" + sim, dt = setup_sim + camera_cfg = TiledCameraCfg( + height=HEIGHT, + width=WIDTH, + offset=TiledCameraCfg.OffsetCfg(pos=(0.0, 0.0, 0.75), rot=(0.0, 1.0, 0.0, 0.0), convention="ros"), + prim_path="/World/Camera", + update_period=0, + data_types=["rgb"], + spawn=sim_utils.PinholeCameraCfg( + focal_length=24.0, + focus_distance=400.0, + horizontal_aperture=20.955, + clipping_range=(0.1, 1.0e5), + ), + ) + # Create camera + camera = TiledCamera(camera_cfg) + + # Play sim + sim.reset() + + # Warm up the renderer so textures have time to stream in + for _ in range(WARMUP_STEPS): + sim.step() + + # Capture the first frame after warm-up + sim.step() + camera.update(dt) + first_frame = camera.data.output["rgb"][0].clone().to(dtype=torch.float32) + + # Let the renderer step, then capture the reference frame + for _ in range(STABILISATION_STEPS): + sim.step() + camera.update(dt) + stable_frame = camera.data.output["rgb"][0].clone().to(dtype=torch.float32) + + del camera + + _assert_first_frame_textured(first_frame, stable_frame) + + +""" +Helper functions. +""" + + +def _populate_scene(): + """Add prims to the scene.""" + # Ground-plane + cfg = sim_utils.GroundPlaneCfg() + cfg.func("/World/defaultGroundPlane", cfg) + # Lights + cfg = sim_utils.DomeLightCfg(intensity=DOME_LIGHT_INTENSITY, color=(1.0, 1.0, 1.0)) + cfg.func("/World/Light/Dome", cfg) + # Textured cube rotated so yellow "E" face is visible + sim_utils.create_prim( + "/World/Objects/ReferenceCube", + "Xform", + usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/DexCube/dex_cube_instanceable.usd", + translation=CUBE_TRANSLATION, + orientation=CUBE_ORIENTATION, + scale=CUBE_SCALE, + ) diff --git a/source/isaaclab/test/sensors/test_multi_mesh_ray_caster_camera.py b/source/isaaclab/test/sensors/test_multi_mesh_ray_caster_camera.py index 688e20086ff9..20aa300c7a4a 100644 --- a/source/isaaclab/test/sensors/test_multi_mesh_ray_caster_camera.py +++ b/source/isaaclab/test/sensors/test_multi_mesh_ray_caster_camera.py @@ -16,7 +16,6 @@ """Rest everything follows.""" import copy -import os import numpy as np import pytest @@ -31,8 +30,6 @@ from isaaclab.sim import PinholeCameraCfg from isaaclab.terrains.trimesh.utils import make_plane from isaaclab.terrains.utils import create_prim_from_mesh -from isaaclab.utils import convert_dict_to_backend -from isaaclab.utils.timer import Timer # sample camera poses (quaternions in xyzw format) POSITION = [2.5, 2.5, 2.5] @@ -134,11 +131,6 @@ def test_camera_init(setup_simulation): sim.reset() # Check if camera is initialized assert camera.is_initialized - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (1, 3) assert camera.data.quat_w_ros.shape == (1, 4) @@ -169,11 +161,6 @@ def test_camera_resolution(setup_simulation): camera = MultiMeshRayCasterCamera(cfg=camera_cfg) # Play sim sim.reset() - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() camera.update(dt) # access image data and compare shapes for im_data in camera.data.output.values(): @@ -254,11 +241,6 @@ def test_multi_camera_init(setup_simulation): # play sim sim.reset() - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() # Simulate physics for _ in range(10): # perform rendering @@ -336,11 +318,6 @@ def test_intrinsic_matrix(setup_simulation, height, width): rs_intrinsic_matrix = torch.tensor(rs_intrinsic_matrix, device=camera.device).reshape(3, 3).unsqueeze(0) # Set matrix into simulator camera.set_intrinsic_matrices(rs_intrinsic_matrix.clone()) - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() # Simulate physics for _ in range(10): # perform rendering @@ -353,64 +330,6 @@ def test_intrinsic_matrix(setup_simulation, height, width): del camera -@pytest.mark.isaacsim_ci -def test_throughput(setup_simulation): - """Test camera throughput for different image sizes.""" - sim, dt, camera_cfg = setup_simulation - - # Create directory temp dir to dump the results - file_dir = os.path.dirname(os.path.realpath(__file__)) - temp_dir = os.path.join(file_dir, "output", "camera", "throughput") - os.makedirs(temp_dir, exist_ok=True) - # Create replicator writer - rep_writer = rep.BasicWriter(output_dir=temp_dir, frame_padding=3) - # create camera - camera_cfg_copy = copy.deepcopy(camera_cfg) - camera_cfg_copy.pattern_cfg.height = 480 - camera_cfg_copy.pattern_cfg.width = 640 - camera = MultiMeshRayCasterCamera(camera_cfg_copy) - - # Play simulator - sim.reset() - - # Set camera pose - eyes = torch.tensor([[2.5, 2.5, 2.5]], dtype=torch.float32, device=camera.device) - targets = torch.tensor([[0.0, 0.0, 0.0]], dtype=torch.float32, device=camera.device) - camera.set_world_poses_from_view(eyes, targets) - - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Simulate physics - for _ in range(5): - # perform rendering - sim.step() - # update camera - with Timer(f"Time taken for updating camera with shape {camera.image_shape}"): - camera.update(dt) - # Save images - with Timer(f"Time taken for writing data with shape {camera.image_shape} "): - # Pack data back into replicator format to save them using its writer - rep_output = {"annotators": {}} - camera_data = convert_dict_to_backend(camera.data.output, backend="numpy") - for key, data, info in zip(camera_data.keys(), camera_data.values(), camera.data.info[0].values()): - if info is not None: - rep_output["annotators"][key] = {"render_product": {"data": data, **info}} - else: - rep_output["annotators"][key] = {"render_product": {"data": data}} - # Save images - rep_output["trigger_outputs"] = {"on_time": camera.frame[0]} - rep_writer.write(rep_output) - print("----------------------------------------") - # Check image data - for im_data in camera.data.output.values(): - assert im_data.shape == (1, camera_cfg_copy.pattern_cfg.height, camera_cfg_copy.pattern_cfg.width, 1) - - del camera - - @pytest.mark.parametrize( "data_types", [ diff --git a/source/isaaclab/test/sensors/test_multi_tiled_camera.py b/source/isaaclab/test/sensors/test_multi_tiled_camera.py index 9c922ca6d1de..6c90ce2696ca 100644 --- a/source/isaaclab/test/sensors/test_multi_tiled_camera.py +++ b/source/isaaclab/test/sensors/test_multi_tiled_camera.py @@ -95,12 +95,6 @@ def test_multi_tiled_camera_init(setup_camera): assert camera._sensor_prims[1].GetPath().pathString == f"/World/Origin_{i}_1/CameraSensor" assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - for camera in tiled_cameras: # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras_per_tiled_camera, 3) @@ -193,12 +187,6 @@ def test_all_annotators_multi_tiled_camera(setup_camera): assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert sorted(camera.data.output.keys()) == sorted(all_annotator_types) - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - for camera in tiled_cameras: # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras_per_tiled_camera, 3) @@ -295,12 +283,6 @@ def test_different_resolution_multi_tiled_camera(setup_camera): assert camera._sensor_prims[1].GetPath().pathString == f"/World/Origin_{i}_1/CameraSensor" assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - for camera in tiled_cameras: # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras_per_tiled_camera, 3) @@ -425,12 +407,6 @@ def test_frame_different_poses_multi_tiled_camera(setup_camera): # Play sim sim.reset() - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Simulate physics for _ in range(10): # Initialize data arrays diff --git a/source/isaaclab/test/sensors/test_ray_caster_camera.py b/source/isaaclab/test/sensors/test_ray_caster_camera.py index 80fa4d03a1ee..0ae64e0e17e3 100644 --- a/source/isaaclab/test/sensors/test_ray_caster_camera.py +++ b/source/isaaclab/test/sensors/test_ray_caster_camera.py @@ -31,8 +31,6 @@ from isaaclab.sim import PinholeCameraCfg from isaaclab.terrains.trimesh.utils import make_plane from isaaclab.terrains.utils import create_prim_from_mesh -from isaaclab.utils import convert_dict_to_backend -from isaaclab.utils.timer import Timer # sample camera poses POSITION = [2.5, 2.5, 2.5] @@ -452,58 +450,6 @@ def test_intrinsic_matrix(setup_sim): torch.testing.assert_close(rs_intrinsic_matrix, camera.data.intrinsic_matrices) -@pytest.mark.isaacsim_ci -def test_throughput(setup_sim): - """Checks that the single camera gets created properly with a rig.""" - sim, camera_cfg, dt = setup_sim - # Create directory temp dir to dump the results - file_dir = os.path.dirname(os.path.realpath(__file__)) - temp_dir = os.path.join(file_dir, "output", "camera", "throughput") - os.makedirs(temp_dir, exist_ok=True) - # Create replicator writer - rep_writer = rep.BasicWriter(output_dir=temp_dir, frame_padding=3) - # create camera - camera_cfg.pattern_cfg.height = 480 - camera_cfg.pattern_cfg.width = 640 - camera = RayCasterCamera(camera_cfg) - - # Play simulator - sim.reset() - - # Set camera pose - eyes = torch.tensor([[2.5, 2.5, 2.5]], dtype=torch.float32, device=camera.device) - targets = torch.tensor([[0.0, 0.0, 0.0]], dtype=torch.float32, device=camera.device) - camera.set_world_poses_from_view(eyes, targets) - - # Simulate for a few steps - for _ in range(5): - sim.step() - # Simulate physics - for _ in range(5): - # perform rendering - sim.step() - # update camera - with Timer(f"Time taken for updating camera with shape {camera.image_shape}"): - camera.update(dt) - # Save images - with Timer(f"Time taken for writing data with shape {camera.image_shape} "): - # Pack data back into replicator format to save them using its writer - rep_output = {"annotators": {}} - camera_data = convert_dict_to_backend({k: v[0] for k, v in camera.data.output.items()}, backend="numpy") - for key, data, info in zip(camera_data.keys(), camera_data.values(), camera.data.info[0].values()): - if info is not None: - rep_output["annotators"][key] = {"render_product": {"data": data, **info}} - else: - rep_output["annotators"][key] = {"render_product": {"data": data}} - # Save images - rep_output["trigger_outputs"] = {"on_time": camera.frame[0]} - rep_writer.write(rep_output) - print("----------------------------------------") - # Check image data - for im_data in camera.data.output.values(): - assert im_data.shape == (1, camera_cfg.pattern_cfg.height, camera_cfg.pattern_cfg.width, 1) - - @pytest.mark.isaacsim_ci def test_output_equal_to_usdcamera(setup_sim): sim, camera_cfg, dt = setup_sim diff --git a/source/isaaclab/test/sensors/test_tiled_camera.py b/source/isaaclab/test/sensors/test_tiled_camera.py index 019baf61217c..0fcf5f26c612 100644 --- a/source/isaaclab/test/sensors/test_tiled_camera.py +++ b/source/isaaclab/test/sensors/test_tiled_camera.py @@ -81,12 +81,6 @@ def test_single_camera_init(setup_camera, device): assert camera._sensor_prims[0].GetPath().pathString == camera_cfg.prim_path assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (1, 3) assert camera.data.quat_w_ros.shape == (1, 4) @@ -138,11 +132,6 @@ def test_depth_clipping_max(setup_camera, device): # Play sim sim.reset() - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - camera.update(dt) assert len(camera.data.output["depth"][torch.isinf(camera.data.output["depth"])]) == 0 @@ -178,11 +167,6 @@ def test_depth_clipping_none(setup_camera, device): # Play sim sim.reset() - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - camera.update(dt) assert len(camera.data.output["depth"][torch.isinf(camera.data.output["depth"])]) > 0 @@ -222,11 +206,6 @@ def test_depth_clipping_zero(setup_camera, device): # Play sim sim.reset() - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - camera.update(dt) assert len(camera.data.output["depth"][torch.isinf(camera.data.output["depth"])]) == 0 @@ -260,12 +239,6 @@ def test_multi_camera_init(setup_camera, device): assert camera._sensor_prims[1].GetPath().pathString == "/World/Origin_1/CameraSensor" assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -318,12 +291,6 @@ def test_rgb_only_camera(setup_camera, device): assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert list(camera.data.output.keys()) == ["rgba", "rgb"] - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -369,11 +336,6 @@ def test_data_types(setup_camera, device): # Play sim sim.reset() - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check if cameras are initialized assert camera_distance.is_initialized assert camera_depth.is_initialized @@ -420,12 +382,6 @@ def test_depth_only_camera(setup_camera, device): assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert list(camera.data.output.keys()) == ["distance_to_camera"] - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -474,12 +430,6 @@ def test_rgba_only_camera(setup_camera, device): assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert list(camera.data.output.keys()) == ["rgba"] - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -528,12 +478,6 @@ def test_albedo_only_camera(setup_camera, device): assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert list(camera.data.output.keys()) == ["albedo"] - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -586,12 +530,6 @@ def test_simple_shading_only_camera(setup_camera, device, data_type): assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert list(camera.data.output.keys()) == [data_type] - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -640,12 +578,6 @@ def test_distance_to_camera_only_camera(setup_camera, device): assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert list(camera.data.output.keys()) == ["distance_to_camera"] - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -694,12 +626,6 @@ def test_distance_to_image_plane_only_camera(setup_camera, device): assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert list(camera.data.output.keys()) == ["distance_to_image_plane"] - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -748,12 +674,6 @@ def test_normals_only_camera(setup_camera, device): assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert list(camera.data.output.keys()) == ["normals"] - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -805,12 +725,6 @@ def test_motion_vectors_only_camera(setup_camera, device): assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert list(camera.data.output.keys()) == ["motion_vectors"] - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -859,12 +773,6 @@ def test_semantic_segmentation_colorize_only_camera(setup_camera, device): assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert list(camera.data.output.keys()) == ["semantic_segmentation"] - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -914,12 +822,6 @@ def test_instance_segmentation_fast_colorize_only_camera(setup_camera, device): assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert list(camera.data.output.keys()) == ["instance_segmentation_fast"] - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -969,12 +871,6 @@ def test_instance_id_segmentation_fast_colorize_only_camera(setup_camera, device assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert list(camera.data.output.keys()) == ["instance_id_segmentation_fast"] - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -1025,12 +921,6 @@ def test_semantic_segmentation_non_colorize_only_camera(setup_camera, device): assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert list(camera.data.output.keys()) == ["semantic_segmentation"] - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -1082,12 +972,6 @@ def test_instance_segmentation_fast_non_colorize_only_camera(setup_camera, devic assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert list(camera.data.output.keys()) == ["instance_segmentation_fast"] - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -1137,12 +1021,6 @@ def test_instance_id_segmentation_fast_non_colorize_only_camera(setup_camera, de assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert list(camera.data.output.keys()) == ["instance_id_segmentation_fast"] - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -1206,12 +1084,6 @@ def test_all_annotators_camera(setup_camera, device): assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert sorted(camera.data.output.keys()) == sorted(all_annotator_types) - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -1311,12 +1183,6 @@ def test_all_annotators_low_resolution_camera(setup_camera, device): assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert sorted(camera.data.output.keys()) == sorted(all_annotator_types) - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -1414,12 +1280,6 @@ def test_all_annotators_non_perfect_square_number_camera(setup_camera, device): assert isinstance(camera._sensor_prims[0], UsdGeom.Camera) assert sorted(camera.data.output.keys()) == sorted(all_annotator_types) - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Check buffers that exists and have correct shapes assert camera.data.pos_w.shape == (num_cameras, 3) assert camera.data.quat_w_ros.shape == (num_cameras, 4) @@ -1554,9 +1414,6 @@ def test_all_annotators_instanceable(setup_camera, device): cube_view = physics_sim_view.create_rigid_body_view("/World/Cube_*") all_indices = torch.arange(num_cameras, dtype=torch.int32, device=device) - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. for frame in range(2): # Build transforms: [x, y, z, qx, qy, qz, qw] — move cubes down by 0.5 each frame transforms = torch.zeros(num_cameras, 7, device=device) @@ -1647,12 +1504,6 @@ def test_throughput(setup_camera, device): # Play simulator sim.reset() - # Simulate for a few steps - # note: This is a workaround to ensure that the textures are loaded. - # Check "Known Issues" section in the documentation for more details. - for _ in range(5): - sim.step() - # Simulate physics for _ in range(5): # perform rendering diff --git a/source/isaaclab_newton/docs/CHANGELOG.rst b/source/isaaclab_newton/docs/CHANGELOG.rst index 942b34a8a140..59a80364d19f 100644 --- a/source/isaaclab_newton/docs/CHANGELOG.rst +++ b/source/isaaclab_newton/docs/CHANGELOG.rst @@ -1,6 +1,17 @@ Changelog --------- +0.5.9 (2026-03-16) +~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed ``test_body_incoming_joint_wrench_b_single_joint`` computing the expected + wrench in the parent body's frame instead of the child body's frame. The expected + wrench is now expressed in the child body's own frame and body indices are resolved + by name to be robust across backends. + 0.5.9 (2026-03-13) ~~~~~~~~~~~~~~~~~~ diff --git a/source/isaaclab_newton/isaaclab_newton/physics/_cubric.py b/source/isaaclab_newton/isaaclab_newton/physics/_cubric.py new file mode 100644 index 000000000000..cc549d4b82be --- /dev/null +++ b/source/isaaclab_newton/isaaclab_newton/physics/_cubric.py @@ -0,0 +1,273 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Pure-Python ctypes bindings for the cubric GPU transform-hierarchy API. + +Acquires the ``omni::cubric::IAdapter`` carb interface directly from the +Carbonite framework and wraps its function-pointer methods so that Newton +can call cubric's GPU transform propagation without C++ pybind11 changes. + +The flow mirrors PhysX's ``DirectGpuHelper::updateXForms_GPU()``: + +1. ``IAdapter::create`` → allocate a cubric adapter ID +2. ``IAdapter::bindToStage`` → bind to the current Fabric stage +3. ``IAdapter::compute`` → GPU kernel: propagate world transforms +4. ``IAdapter::release`` → free the adapter + +When cubric is unavailable (e.g. CPU-only machine, plugin not loaded), the +caller falls back to the CPU ``update_world_xforms()`` path. +""" + +from __future__ import annotations + +import ctypes +import logging + +logger = logging.getLogger(__name__) + +# --------------------------------------------------------------------------- +# Carb Framework struct layout (CARB_ABI function-pointer offsets, x86_64) +# --------------------------------------------------------------------------- +# Counting only CARB_ABI fields from the top of ``struct Framework``: +# 0: loadPluginsEx +# 8: unloadAllPlugins +# 16: acquireInterfaceWithClient +# 24: tryAcquireInterfaceWithClient ← we use this one +_FW_OFF_TRY_ACQUIRE = 24 + +# --------------------------------------------------------------------------- +# IAdapter struct layout (from omni/cubric/IAdapter.h) +# --------------------------------------------------------------------------- +# 0: getAttribute +# 8: create(AdapterId*) +# 16: refcount +# 24: retain +# 32: release(AdapterId) +# 40: bindToStage(AdapterId, const FabricId&) +# 48: unbind +# 56: compute(AdapterId, options, dirtyMode, outFlags*) +_IA_OFF_CREATE = 8 +_IA_OFF_RELEASE = 32 +_IA_OFF_BIND = 40 +_IA_OFF_COMPUTE = 56 + +# AdapterId sentinel +_INVALID_ADAPTER_ID = ctypes.c_uint64(~0).value + +# AdapterComputeOptions flags (from IAdapter.h) +_OPT_FORCE_UPDATE = 1 << 0 # Force update, ignoring invalidation status +_OPT_FORCE_STATE_RECONSTRUCTION = 1 << 1 # Force full rebuild of internal accel structures +_OPT_SKIP_ISOLATED = 1 << 2 # Skip prims with connectivity degree 0 +_OPT_RIGID_BODY = 1 << 3 # Use PhysicsRigidBodyAPI tag for inverse propagation + +# Newton prims get tagged with PhysicsRigidBodyAPI at init time so +# cubric's eRigidBody mode can distinguish rigid-body buckets +# (Inverse: preserve world matrix written by Newton, derive local) +# from non-rigid-body buckets (Forward: propagate to children). +# eForceUpdate is ORed in to bypass the change-listener check. +_OPT_DEFAULT = _OPT_RIGID_BODY | _OPT_FORCE_UPDATE + +# AdapterDirtyMode +_DIRTY_ALL = 0 # eAll — dirty all prims in the stage +_DIRTY_COARSE = 1 # eCoarse — dirty all prims in visited buckets + + +# --------------------------------------------------------------------------- +# ctypes struct mirrors +# --------------------------------------------------------------------------- +class _Version(ctypes.Structure): + _fields_ = [("major", ctypes.c_uint32), ("minor", ctypes.c_uint32)] + + +class _InterfaceDesc(ctypes.Structure): + """``carb::InterfaceDesc`` — {const char* name, Version version}.""" + + _fields_ = [ + ("name", ctypes.c_char_p), + ("version", _Version), + ] + + +def _read_u64(addr: int) -> int: + return ctypes.c_uint64.from_address(addr).value + + +# --------------------------------------------------------------------------- +# Public API +# --------------------------------------------------------------------------- +class CubricBindings: + """Typed wrappers around the cubric ``IAdapter`` API. + + Call :meth:`initialize` once; if it returns ``True``, the four adapter + methods are available. + """ + + def __init__(self) -> None: + self._ia_ptr: int = 0 + self._create_fn = None + self._release_fn = None + self._bind_fn = None + self._compute_fn = None + + # -- lifecycle ----------------------------------------------------------- + + def initialize(self) -> bool: + """Acquire the cubric ``IAdapter`` from the carb framework.""" + # Ensure the omni.cubric extension (native carb plugin) is loaded. + try: + import omni.kit.app + + ext_mgr = omni.kit.app.get_app().get_extension_manager() + if not ext_mgr.is_extension_enabled("omni.cubric"): + ext_mgr.set_extension_enabled_immediate("omni.cubric", True) + if not ext_mgr.is_extension_enabled("omni.cubric"): + logger.warning("Failed to enable omni.cubric extension") + return False + except Exception as exc: + logger.warning("Cannot enable omni.cubric: %s", exc) + return False + + # Get Framework* via libcarb.so acquireFramework (singleton). + try: + libcarb = ctypes.CDLL("libcarb.so") + except OSError: + logger.warning("Could not load libcarb.so") + return False + + libcarb.acquireFramework.restype = ctypes.c_void_p + libcarb.acquireFramework.argtypes = [ctypes.c_char_p, _Version] + fw_ptr = libcarb.acquireFramework(b"isaaclab.cubric", _Version(0, 0)) + if not fw_ptr: + logger.warning("acquireFramework returned null") + return False + + # Read tryAcquireInterfaceWithClient fn-ptr from Framework vtable. + try_acquire_addr = _read_u64(fw_ptr + _FW_OFF_TRY_ACQUIRE) + if try_acquire_addr == 0: + logger.warning("tryAcquireInterfaceWithClient is null in Framework") + return False + + try_acquire_fn = ctypes.CFUNCTYPE( + ctypes.c_void_p, # return: void* (IAdapter*) + ctypes.c_char_p, # clientName + _InterfaceDesc, # desc (by value) + ctypes.c_char_p, # pluginName + )(try_acquire_addr) + + desc = _InterfaceDesc( + name=b"omni::cubric::IAdapter", + version=_Version(0, 1), + ) + + # Try several acquisition strategies — the required client name + # varies across Kit configurations. + ia_ptr = try_acquire_fn(b"carb.scripting-python.plugin", desc, None) + if not ia_ptr: + ia_ptr = try_acquire_fn(None, desc, None) + if not ia_ptr: + acquire_addr = _read_u64(fw_ptr + 16) # acquireInterfaceWithClient + if acquire_addr: + acquire_fn = ctypes.CFUNCTYPE( + ctypes.c_void_p, + ctypes.c_char_p, + _InterfaceDesc, + ctypes.c_char_p, + )(acquire_addr) + ia_ptr = acquire_fn(b"isaaclab.cubric", desc, None) + if not ia_ptr: + logger.warning( + "Could not acquire omni::cubric::IAdapter — " + "cubric plugin may not be registered or interface version mismatch" + ) + return False + self._ia_ptr = ia_ptr + + # Wrap the four IAdapter function pointers we need. + create_addr = _read_u64(ia_ptr + _IA_OFF_CREATE) + release_addr = _read_u64(ia_ptr + _IA_OFF_RELEASE) + bind_addr = _read_u64(ia_ptr + _IA_OFF_BIND) + compute_addr = _read_u64(ia_ptr + _IA_OFF_COMPUTE) + + if not all([create_addr, release_addr, bind_addr, compute_addr]): + logger.warning("One or more IAdapter function pointers are null") + return False + + self._create_fn = ctypes.CFUNCTYPE( + ctypes.c_bool, + ctypes.POINTER(ctypes.c_uint64), + )(create_addr) + + self._release_fn = ctypes.CFUNCTYPE( + ctypes.c_bool, + ctypes.c_uint64, + )(release_addr) + + # FabricId is uint64, passed by const-ref -> pointer on x86_64 + self._bind_fn = ctypes.CFUNCTYPE( + ctypes.c_bool, + ctypes.c_uint64, + ctypes.POINTER(ctypes.c_uint64), + )(bind_addr) + + self._compute_fn = ctypes.CFUNCTYPE( + ctypes.c_bool, + ctypes.c_uint64, # adapterId + ctypes.c_uint32, # options (AdapterComputeOptions) + ctypes.c_int32, # dirtyMode (AdapterDirtyMode) + ctypes.c_void_p, # outAccountFlags* (nullable) + )(compute_addr) + + logger.info("cubric IAdapter bindings ready") + return True + + @property + def available(self) -> bool: + return self._ia_ptr != 0 + + # -- cubric adapter methods ---------------------------------------------- + + def create_adapter(self) -> int | None: + """Create a cubric adapter. Returns an adapter ID or ``None``.""" + if not self._create_fn: + return None + adapter_id = ctypes.c_uint64(_INVALID_ADAPTER_ID) + ok = self._create_fn(ctypes.byref(adapter_id)) + if not ok or adapter_id.value == _INVALID_ADAPTER_ID: + logger.warning("IAdapter::create failed") + return None + return adapter_id.value + + def bind_to_stage(self, adapter_id: int, fabric_id: int) -> bool: + """Bind the adapter to a Fabric stage.""" + if not self._bind_fn: + return False + fid = ctypes.c_uint64(fabric_id) + ok = self._bind_fn(adapter_id, ctypes.byref(fid)) + if not ok: + logger.warning("IAdapter::bindToStage failed (adapter=%d, fabricId=%d)", adapter_id, fabric_id) + return ok + + def compute(self, adapter_id: int) -> bool: + """Run the GPU transform-hierarchy compute pass. + + Uses ``eRigidBody | eForceUpdate`` with ``eAll`` dirty mode. + ``eRigidBody`` makes cubric apply Inverse propagation on buckets + tagged with ``PhysicsRigidBodyAPI`` (keeps Newton's world transforms, + derives local) and Forward on everything else (propagates to children). + ``eForceUpdate`` bypasses the change-listener dirty check. + """ + if not self._compute_fn: + return False + flags = ctypes.c_uint32(0) + ok = self._compute_fn(adapter_id, _OPT_DEFAULT, _DIRTY_ALL, ctypes.byref(flags)) + if not ok: + logger.warning("IAdapter::compute returned false (flags=0x%x)", flags.value) + return ok + + def release_adapter(self, adapter_id: int) -> None: + """Release an adapter.""" + if not adapter_id or not self._release_fn: + return + self._release_fn(adapter_id) diff --git a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py index a8f7d1ba786c..a96749d7b3f3 100644 --- a/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py +++ b/source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py @@ -7,12 +7,25 @@ from __future__ import annotations +import contextlib +import ctypes import inspect import logging from typing import TYPE_CHECKING import numpy as np import warp as wp + +# Load CUDA runtime for relaxed-mode graph capture (RTX-compatible). +# cudaStreamCaptureModeRelaxed (2) allows the RTX compositor's background +# CUDA stream to keep running during capture without invalidating it. +try: + _cudart = ctypes.CDLL("libcudart.so.12") +except OSError: + try: + _cudart = ctypes.CDLL("libcudart.so") + except OSError: + _cudart = None from newton import Axis, CollisionPipeline, Contacts, Control, Model, ModelBuilder, State, eval_fk from newton._src.usd.schemas import SchemaResolverNewton, SchemaResolverPhysx from newton.sensors import SensorContact as NewtonContactSensor @@ -83,12 +96,19 @@ class NewtonManager(PhysicsManager): # CUDA graphing _graph = None + _graph_capture_pending: bool = False # USD/Fabric sync _newton_stage_path = None _usdrt_stage = None _newton_index_attr = "newton:index" _clone_physics_only = False + _transforms_dirty: bool = False + + # cubric GPU transform hierarchy (replaces CPU update_world_xforms) + _cubric = None + _cubric_adapter: int | None = None + _cubric_bound_fabric_id: int | None = None # Model changes (callbacks use unified system from PhysicsManager) _model_changes: set[int] = set() @@ -139,49 +159,117 @@ def forward(cls) -> None: """Update articulation kinematics without stepping physics.""" eval_fk(cls._model, cls._state_0.joint_q, cls._state_0.joint_qd, cls._state_0, None) + @classmethod + def pre_render(cls) -> None: + """Flush deferred Fabric writes before cameras/visualizers read the scene.""" + cls.sync_transforms_to_usd() + @classmethod def sync_transforms_to_usd(cls) -> None: """Write Newton body_q to USD Fabric world matrices for Kit viewport / RTX rendering. - No-op when ``_usdrt_stage`` is None (i.e. Kit visualizer is not active). - Called by :class:`~isaaclab.sim.scene_data_providers.NewtonSceneDataProvider` at render - cadence (Kit), and after each physics step when using Newton+RTX so the renderer sees - updated poses. + No-op when ``_usdrt_stage`` is None (i.e. Kit visualizer is not active) + or when transforms have not changed since the last sync. + + Called at render cadence by :meth:`pre_render` (via + :meth:`~isaaclab.sim.SimulationContext.render`). + Physics stepping marks transforms dirty via :meth:`_mark_transforms_dirty` + so that the expensive Fabric hierarchy update only runs once per render + frame rather than after every physics step. Uses ``wp.fabricarray`` directly (no ``isaacsim.physics.newton`` extension needed). The Warp kernel reads ``state_0.body_q[newton_index[i]]`` and writes the corresponding ``mat44d`` to ``omni:fabric:worldMatrix`` for each prim. + + When cubric is available the method mirrors PhysX's ``DirectGpuHelper`` + pattern: pause Fabric change tracking, write transforms, resume tracking, + then call ``IAdapter::compute`` on the GPU to propagate the hierarchy and + notify the Fabric Scene Delegate. Otherwise it falls back to the CPU + ``update_world_xforms()`` path. """ if cls._usdrt_stage is None or cls._model is None or cls._state_0 is None: return + if not cls._transforms_dirty: + return try: import usdrt - selection = cls._usdrt_stage.SelectPrims( - require_attrs=[ - (usdrt.Sdf.ValueTypeNames.Matrix4d, "omni:fabric:worldMatrix", usdrt.Usd.Access.ReadWrite), - (usdrt.Sdf.ValueTypeNames.UInt, cls._newton_index_attr, usdrt.Usd.Access.Read), - ], - device=str(PhysicsManager._device), - ) - if selection.GetCount() == 0: - return - fabric_transforms = wp.fabricarray(selection, "omni:fabric:worldMatrix") - newton_indices = wp.fabricarray(selection, cls._newton_index_attr) - wp.launch( - _set_fabric_transforms, - dim=newton_indices.shape[0], - inputs=[fabric_transforms, newton_indices, cls._state_0.body_q], - device=PhysicsManager._device, - ) - wp.synchronize_device(PhysicsManager._device) + # Lazy adapter creation: deferred from initialize_solver() to avoid + # startup-ordering issues with the cubric plugin. + if cls._cubric is not None and cls._cubric.available and cls._cubric_adapter is None: + cls._cubric_adapter = cls._cubric.create_adapter() + if cls._cubric_adapter is not None: + logger.info("cubric GPU transform hierarchy enabled") + else: + logger.warning("cubric adapter creation failed; falling back to update_world_xforms()") + cls._cubric = None + + use_cubric = cls._cubric is not None and cls._cubric_adapter is not None + + fabric_hierarchy = None if hasattr(usdrt, "hierarchy"): fabric_hierarchy = usdrt.hierarchy.IFabricHierarchy().get_fabric_hierarchy( cls._usdrt_stage.GetFabricId(), cls._usdrt_stage.GetStageIdAsStageId() ) - fabric_hierarchy.update_world_xforms() - except Exception as exc: - logger.debug("[NewtonManager] sync_transforms_to_usd: %s", exc) + + # Pause hierarchy change tracking BEFORE SelectPrims. + # SelectPrims with ReadWrite access calls getAttributeArrayGpu + # internally, which marks Fabric buffers dirty. If tracking is + # still active at that point the hierarchy records the change and + # Kit's updateWorldXforms will do an expensive connectivity + # rebuild every frame. PhysX avoids this via ScopedUSDRT which + # pauses tracking before any Fabric writes. + if use_cubric and fabric_hierarchy is not None: + fabric_hierarchy.track_world_xform_changes(False) + fabric_hierarchy.track_local_xform_changes(False) + + try: + selection = cls._usdrt_stage.SelectPrims( + require_attrs=[ + (usdrt.Sdf.ValueTypeNames.Matrix4d, "omni:fabric:worldMatrix", usdrt.Usd.Access.ReadWrite), + (usdrt.Sdf.ValueTypeNames.UInt, cls._newton_index_attr, usdrt.Usd.Access.Read), + ], + device=str(PhysicsManager._device), + ) + if selection.GetCount() == 0: + cls._transforms_dirty = False + return + + fabric_transforms = wp.fabricarray(selection, "omni:fabric:worldMatrix") + newton_indices = wp.fabricarray(selection, cls._newton_index_attr) + wp.launch( + _set_fabric_transforms, + dim=newton_indices.shape[0], + inputs=[fabric_transforms, newton_indices, cls._state_0.body_q], + device=PhysicsManager._device, + ) + wp.synchronize_device(PhysicsManager._device) + + cls._transforms_dirty = False + + if use_cubric and fabric_hierarchy is not None: + fabric_id = cls._usdrt_stage.GetFabricId().id + if fabric_id != cls._cubric_bound_fabric_id: + cls._cubric.bind_to_stage(cls._cubric_adapter, fabric_id) + cls._cubric_bound_fabric_id = fabric_id + cls._cubric.compute(cls._cubric_adapter) + elif fabric_hierarchy is not None: + fabric_hierarchy.update_world_xforms() + finally: + if use_cubric and fabric_hierarchy is not None: + fabric_hierarchy.track_world_xform_changes(True) + fabric_hierarchy.track_local_xform_changes(True) + except Exception: + logger.exception("[NewtonManager] sync_transforms_to_usd FAILED") + + @classmethod + def _mark_transforms_dirty(cls) -> None: + """Flag that physics state has changed and Fabric needs re-sync. + + Called by :meth:`_simulate` after stepping. The actual sync is deferred + to :meth:`sync_transforms_to_usd`, which runs at render cadence. + """ + cls._transforms_dirty = True @classmethod def step(cls) -> None: @@ -197,12 +285,26 @@ def step(cls) -> None: cls._solver.notify_model_changed(change) cls._model_changes = set() - # Step simulation (graphed or not; _graph is None when RTX/Fabric sync is active or on CPU) + # Lazy CUDA graph capture: deferred from initialize_solver() when RTX was active. + # By the time step() is first called, RTX has fully initialized (all cudaImportExternalMemory + # calls are done) and is idle between render frames — giving us a clean capture window. cfg = PhysicsManager._cfg - if cfg is not None and cfg.use_cuda_graph and cls._graph is not None and "cuda" in PhysicsManager._device: # type: ignore[union-attr] + device = PhysicsManager._device + if cls._graph_capture_pending and cfg is not None and cfg.use_cuda_graph and "cuda" in device: # type: ignore[union-attr] + cls._graph_capture_pending = False + cls._graph = cls._capture_relaxed_graph(device) + if cls._graph is not None: + logger.info("Newton CUDA graph captured (deferred relaxed mode, RTX-compatible)") + else: + logger.warning("Newton deferred CUDA graph capture failed; using eager execution") + + # Step simulation (graphed or not; _graph is None when capture is disabled or failed) + if cfg is not None and cfg.use_cuda_graph and cls._graph is not None and "cuda" in device: # type: ignore[union-attr] wp.capture_launch(cls._graph) + if cls._usdrt_stage is not None: + cls._mark_transforms_dirty() else: - with wp.ScopedDevice(PhysicsManager._device): + with wp.ScopedDevice(device): cls._simulate() # Debug convergence info @@ -239,6 +341,11 @@ def is_fabric_enabled(cls) -> bool: @classmethod def clear(cls): """Clear all Newton-specific state (callbacks cleared by super().close()).""" + if cls._cubric is not None and cls._cubric_adapter is not None: + cls._cubric.release_adapter(cls._cubric_adapter) + cls._cubric = None + cls._cubric_adapter = None + cls._cubric_bound_fabric_id = None cls._builder = None cls._model = None cls._solver = None @@ -252,8 +359,10 @@ def clear(cls): cls._newton_contact_sensors = {} cls._report_contacts = False cls._graph = None + cls._graph_capture_pending = False cls._newton_stage_path = None cls._usdrt_stage = None + cls._transforms_dirty = False cls._up_axis = "Z" cls._model_changes = set() cls._views = [] @@ -314,10 +423,15 @@ def start_simulation(cls) -> None: prim = cls._usdrt_stage.GetPrimAtPath(prim_path) prim.CreateAttribute(cls._newton_index_attr, usdrt.Sdf.ValueTypeNames.UInt, True) prim.GetAttribute(cls._newton_index_attr).Set(i) + # Tag with PhysicsRigidBodyAPI so cubric's eRigidBody mode + # applies Inverse propagation (preserves Newton's world + # transforms and derives local) instead of Forward. + prim.AddAppliedSchema("PhysicsRigidBodyAPI") xformable_prim = usdrt.Rt.Xformable(prim) if not xformable_prim.HasWorldXform(): xformable_prim.SetWorldXformFromUsd() + cls._mark_transforms_dirty() cls.sync_transforms_to_usd() @classmethod @@ -477,25 +591,174 @@ def initialize_solver(cls) -> None: # Initialize contacts and collision pipeline cls._initialize_contacts() + # Prepare cubric ctypes bindings (acquires IAdapter from carb framework). + # Adapter creation is deferred to the first sync_transforms_to_usd() call + # at render time to avoid any startup-ordering issues with the cubric + # plugin initialisation. + if cls._usdrt_stage is not None: + from isaaclab_newton.physics._cubric import CubricBindings + + cls._cubric = CubricBindings() + if cls._cubric.initialize(): + logger.info("cubric bindings ready (adapter deferred to first render)") + else: + logger.warning("cubric bindings init failed; falling back to update_world_xforms()") + cls._cubric = None + device = PhysicsManager._device - # Skip CUDA graph when syncing to USD/Fabric for RTX: capture conflicts with RTX/Replicator - # using the legacy stream (cudaErrorStreamCaptureImplicit). - use_cuda_graph = cfg.use_cuda_graph and (cls._usdrt_stage is None) # type: ignore[union-attr] + use_cuda_graph = cfg.use_cuda_graph and "cuda" in device # type: ignore[union-attr] with Timer(name="newton_cuda_graph", msg="CUDA graph took:"): - if use_cuda_graph and "cuda" in device: - with wp.ScopedCapture() as capture: - cls._simulate() - cls._graph = capture.graph + if use_cuda_graph: + if cls._usdrt_stage is None: + # No RTX active — use standard Warp capture (cudaStreamCaptureModeGlobal). + with wp.ScopedCapture() as capture: + cls._simulate() + cls._graph = capture.graph + logger.info("Newton CUDA graph captured (standard Warp mode)") + else: + # RTX is active during initialization — cudaImportExternalMemory and other + # non-capturable RTX ops run on background CUDA streams right now. + # Defer capture to the first step() call, after RTX is fully initialized + # and idle between render frames (clean capture window). + cls._graph = None + cls._graph_capture_pending = True + logger.info("Newton CUDA graph capture deferred until first step() (RTX active)") else: cls._graph = None @classmethod - def _simulate(cls) -> None: - """Run one simulation step with substeps.""" + def _capture_relaxed_graph(cls, device: str): + """Capture Newton physics (only) as a CUDA graph, RTX-compatible. + + Uses a hybrid approach to work around two conflicting requirements: + + 1. RTX background threads use CUDA's legacy stream (stream 0) for async operations + like ``cudaImportExternalMemory``. A standard ``wp.ScopedCapture()`` uses + ``cudaStreamCaptureModeThreadLocal`` on Warp's default stream (a blocking stream). + A blocking stream synchronises implicitly with legacy stream 0, so RTX ops inside + the capture window fail with error 906. + + 2. ``mujoco_warp`` calls ``wp.capture_while`` inside ``solver.solve()``. + ``wp.capture_while`` checks ``device.captures`` (populated by ``wp.capture_begin``) + to decide whether to insert a conditional graph node (graph-capture path) or to run + eagerly with ``wp.synchronize_stream`` (non-capture path). Without an entry in + ``device.captures``, it synchronises the capturing stream — which raises "Cannot + synchronize stream while graph capture is active". + + Solution: + + - Create a **non-blocking** stream (``cudaStreamNonBlocking = 0x01``): no implicit sync + with legacy stream 0, so RTX background threads are unaffected (avoids error 906). + - Start the capture externally via ``cudaStreamBeginCapture`` with + ``cudaStreamCaptureModeRelaxed`` so no other CUDA activity is disrupted. + - Call ``wp.capture_begin(external=True, stream=fresh_stream)``: + this registers the capture in Warp's ``device.captures`` *without* calling + ``cudaStreamBeginCapture`` (already done) and *without* changing device-wide memory + pool attributes (avoids error 900 in RTX's ``cudaMallocAsync``). + - Run ``_simulate_physics_only()`` inside ``ScopedStream(fresh_stream)``: + kernels dispatch to ``fresh_stream`` and are captured; ``wp.capture_while`` finds the + active capture and inserts a conditional graph node instead of synchronising. + - Call ``wp.capture_end(stream=fresh_stream)`` to finalise the Warp-level capture. + - Call ``cudaStreamEndCapture`` to close the CUDA stream capture and get the graph. + + Warmup run pre-allocates all MuJoCo-Warp scratch buffers so no ``cudaMalloc`` occurs during + capture. ``sync_transforms_to_usd`` (which calls ``wp.synchronize_device``) is + excluded from the capture and runs eagerly in ``step()`` after ``wp.capture_launch``. + + Returns a ``wp.Graph`` on success, or ``None`` on failure. + """ + if _cudart is None: + logger.warning("libcudart not available; cannot use relaxed graph capture") + return None + + # Warmup: pre-allocate all MuJoCo-Warp scratch buffers so the capture window has + # no new cudaMalloc calls (which are forbidden inside graph capture). + with wp.ScopedDevice(device): + cls._simulate_physics_only() + wp.synchronize_stream(wp.get_stream(device)) + + # Create a non-blocking stream (cudaStreamNonBlocking = 0x01). + raw_handle = ctypes.c_void_p() + ret = _cudart.cudaStreamCreateWithFlags(ctypes.byref(raw_handle), ctypes.c_uint(0x01)) + if ret != 0: + logger.warning("cudaStreamCreateWithFlags(NonBlocking) failed (code %d)", ret) + return None + fresh_handle = raw_handle.value + fresh_stream = wp.Stream(device, cuda_stream=fresh_handle, owner=False) + + # Start capture in relaxed mode BEFORE entering ScopedStream. + ret = _cudart.cudaStreamBeginCapture(ctypes.c_void_p(fresh_handle), ctypes.c_int(2)) + if ret != 0: + _cudart.cudaStreamDestroy(ctypes.c_void_p(fresh_handle)) + logger.warning("cudaStreamBeginCapture(relaxed) failed (code %d)", ret) + return None + + try: + wp.capture_begin(stream=fresh_stream, external=True) + except Exception as exc: + raw_graph = ctypes.c_void_p() + _cudart.cudaStreamEndCapture(ctypes.c_void_p(fresh_handle), ctypes.byref(raw_graph)) + if raw_graph.value: + _cudart.cudaGraphDestroy(raw_graph) + _cudart.cudaStreamDestroy(ctypes.c_void_p(fresh_handle)) + logger.warning("wp.capture_begin(external=True) failed: %s", exc) + return None + + err_during_capture = None + with wp.ScopedStream(fresh_stream, sync_enter=False): + try: + cls._simulate_physics_only() + except Exception as exc: + err_during_capture = exc - # MJWarp can use its internal collision pipeline. + if err_during_capture is None: + try: + graph = wp.capture_end(stream=fresh_stream) + except Exception as exc: + err_during_capture = exc + graph = None + else: + with contextlib.suppress(Exception): + wp.capture_end(stream=fresh_stream) + graph = None + + raw_graph = ctypes.c_void_p() + end_ret = _cudart.cudaStreamEndCapture(ctypes.c_void_p(fresh_handle), ctypes.byref(raw_graph)) + _cudart.cudaStreamDestroy(ctypes.c_void_p(fresh_handle)) + + if err_during_capture is not None: + if raw_graph.value: + _cudart.cudaGraphDestroy(raw_graph) + logger.warning("Newton graph capture aborted during simulate: %s", err_during_capture) + return None + + if end_ret != 0 or not raw_graph.value: + logger.warning("cudaStreamEndCapture failed (code %d)", end_ret) + return None + + # Patch the Warp Graph object with the raw CUDA graph handle obtained + # from our external cudaStreamEndCapture. wp.capture_end(external=True) + # returns a Graph with a stale handle; we overwrite it so that + # wp.capture_launch() replays the correct graph. + # NOTE: This relies on Warp internals (Graph.graph / Graph.graph_exec). + # Setting graph_exec = None triggers lazy cudaGraphInstantiate on + # the next capture_launch. Replace with public API when available. + graph.graph = raw_graph + graph.graph_exec = None + return graph + + @classmethod + def _simulate_physics_only(cls) -> None: + """Run one physics step without Fabric/USD sync — safe for CUDA graph capture. + + Used by :meth:`_capture_relaxed_graph` to capture only the pure physics kernels. + ``sync_transforms_to_usd`` is excluded because it calls ``wp.synchronize_device`` + (forbidden inside graph capture) and ``wp.fabricarray`` (device-wide allocation). + The caller (``step()``) is responsible for calling ``sync_transforms_to_usd()`` + eagerly after ``wp.capture_launch``. + """ if cls._needs_collision_pipeline: cls._collision_pipeline.collide(cls._state_0, cls._contacts) contacts = cls._contacts @@ -512,7 +775,6 @@ def step_fn(state_0, state_1): else: cfg = PhysicsManager._cfg need_copy_on_last_substep = (cfg is not None and cfg.use_cuda_graph) and cls._num_substeps % 2 == 1 # type: ignore[union-attr] - for i in range(cls._num_substeps): step_fn(cls._state_0, cls._state_1) if need_copy_on_last_substep and i == cls._num_substeps - 1: @@ -521,18 +783,23 @@ def step_fn(state_0, state_1): cls._state_0, cls._state_1 = cls._state_1, cls._state_0 cls._state_0.clear_forces() - # Populate contacts for contact sensors if cls._report_contacts: - # For newton_contacts (unified pipeline): use locally computed contacts - # For mujoco_contacts: use class-level _contacts, solver populates it from MuJoCo data eval_contacts = contacts if contacts is not None else cls._contacts cls._solver.update_contacts(eval_contacts, cls._state_0) for sensor in cls._newton_contact_sensors.values(): sensor.update(cls._state_0, eval_contacts) - # Sync Newton state to USD/Fabric for RTX rendering (e.g., Newton Physics + RTX Renderer preset) + @classmethod + def _simulate(cls) -> None: + """Run one simulation step with substeps and USD sync. + + Delegates physics work to :meth:`_simulate_physics_only` and then + marks transforms dirty for the next render-cadence sync. + """ + cls._simulate_physics_only() + if cls._usdrt_stage is not None: - cls.sync_transforms_to_usd() + cls._mark_transforms_dirty() @classmethod def get_solver_convergence_steps(cls) -> dict[str, float | int]: diff --git a/source/isaaclab_newton/isaaclab_newton/renderers/newton_warp_renderer.py b/source/isaaclab_newton/isaaclab_newton/renderers/newton_warp_renderer.py index 6a616d3b8c4a..461fee5508da 100644 --- a/source/isaaclab_newton/isaaclab_newton/renderers/newton_warp_renderer.py +++ b/source/isaaclab_newton/isaaclab_newton/renderers/newton_warp_renderer.py @@ -46,8 +46,8 @@ class CameraOutputs: normals_image: wp.array(dtype=wp.vec3f, ndim=4) = None instance_segmentation_image: wp.array(dtype=wp.uint32, ndim=4) = None - def __init__(self, render_context: newton.sensors.SensorTiledCamera.RenderContext, sensor: SensorBase): - self.render_context = render_context + def __init__(self, newton_sensor: newton.sensors.SensorTiledCamera, sensor: SensorBase): + self.newton_sensor = newton_sensor # Currently camera owns the renderer and render data. By holding full # reference of the sensor, we create a circular reference between the @@ -98,20 +98,20 @@ def update(self, positions: torch.Tensor, orientations: torch.Tensor, intrinsics ) self.camera_transforms = wp.empty( - (1, self.render_context.world_count), dtype=wp.transformf, device=self.render_context.device + (1, self.newton_sensor.model.world_count), dtype=wp.transformf, device=self.newton_sensor.model.device ) wp.launch( RenderData._update_transforms, - self.render_context.world_count, + self.newton_sensor.model.world_count, [positions, converted_orientations, self.camera_transforms], - device=self.render_context.device, + device=self.newton_sensor.model.device, ) - if self.render_context is not None: + if self.camera_rays is None: first_focal_length = intrinsics[:, 1, 1][0:1] fov_radians_all = 2.0 * torch.atan(self.height / (2.0 * first_focal_length)) - self.camera_rays = self.render_context.utils.compute_pinhole_camera_rays( + self.camera_rays = self.newton_sensor.utils.compute_pinhole_camera_rays( self.width, self.height, wp.from_torch(fov_radians_all, dtype=wp.float32) ) @@ -121,14 +121,14 @@ def _from_torch(self, tensor: torch.Tensor, dtype) -> wp.array: return wp.array( ptr=torch_array.ptr, dtype=dtype, - shape=(self.render_context.world_count, self.num_cameras, self.height, self.width), + shape=(self.newton_sensor.model.world_count, self.num_cameras, self.height, self.width), device=torch_array.device, copy=False, ) logger.warning("NewtonWarpRenderer - torch output array is non-contiguous") return wp.zeros( - (self.render_context.world_count, self.num_cameras, self.height, self.width), + (self.newton_sensor.model.world_count, self.num_cameras, self.height, self.width), dtype=dtype, device=torch_array.device, ) @@ -169,6 +169,7 @@ def __init__(self, cfg: NewtonWarpRendererCfg): "(e.g., unsupported PhysX schemas such as tendons). " "Check the log for earlier Newton model build errors." ) + self.newton_sensor = newton.sensors.SensorTiledCamera(newton_model) def prepare_stage(self, stage: Any, num_envs: int) -> None: @@ -179,7 +180,7 @@ def prepare_stage(self, stage: Any, num_envs: int) -> None: def create_render_data(self, sensor: SensorBase) -> RenderData: """Create render data for the Newton tiled camera. See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.create_render_data`.""" - return RenderData(self.newton_sensor.render_context, sensor) + return RenderData(self.newton_sensor, sensor) def set_outputs(self, render_data: RenderData, output_data: dict[str, torch.Tensor]): """Store output buffers. See :meth:`~isaaclab.renderers.base_renderer.BaseRenderer.set_outputs`.""" diff --git a/source/isaaclab_newton/setup.py b/source/isaaclab_newton/setup.py index a2d0305ba84a..c15812f8282a 100644 --- a/source/isaaclab_newton/setup.py +++ b/source/isaaclab_newton/setup.py @@ -45,7 +45,7 @@ def run(self): "mujoco==3.5.0", "mujoco-warp==3.5.0.2", "PyOpenGL-accelerate==3.1.10", - "newton==1.0.0", + "newton @ git+https://github.com/newton-physics/newton.git@2684d75bfa4bb8b058a93b81c458a74b7701c997", ], } diff --git a/source/isaaclab_newton/test/assets/test_articulation.py b/source/isaaclab_newton/test/assets/test_articulation.py index b872dd9fb63f..3a90bf203b37 100644 --- a/source/isaaclab_newton/test/assets/test_articulation.py +++ b/source/isaaclab_newton/test/assets/test_articulation.py @@ -2058,11 +2058,15 @@ def test_body_incoming_joint_wrench_b_single_joint(sim, num_articulations, devic # Play the simulator sim.reset() + + # Resolve body indices by name (ordering may differ across physics backends) + arm_idx = articulation.body_names.index("Arm") + root_idx = articulation.body_names.index("CenterPivot") # apply external force external_force_vector_b = torch.zeros((num_articulations, articulation.num_bodies, 3), device=device) - external_force_vector_b[:, 1, 1] = 10.0 # 10 N in Y direction + external_force_vector_b[:, arm_idx, 1] = 10.0 # 10 N in Y direction external_torque_vector_b = torch.zeros((num_articulations, articulation.num_bodies, 3), device=device) - external_torque_vector_b[:, 1, 2] = 10.0 # 10 Nm in z direction + external_torque_vector_b[:, arm_idx, 2] = 10.0 # 10 Nm in z direction # apply action to the articulation joint_pos = torch.ones_like(wp.to_torch(articulation.data.joint_pos)) * 1.5708 / 2.0 @@ -2096,34 +2100,36 @@ def test_body_incoming_joint_wrench_b_single_joint(sim, num_articulations, devic pos_w = wp.to_torch(articulation.data.body_pos_w) quat_w = wp.to_torch(articulation.data.body_quat_w) - mass_link2 = mass[:, 1].view(num_articulations, -1) + mass_link2 = mass[:, arm_idx].view(num_articulations, -1) gravity = torch.tensor(sim.cfg.gravity, device="cpu").repeat(num_articulations, 1).view((num_articulations, 3)) # NOTE: the com and link pose for single joint are colocated weight_vector_w = mass_link2 * gravity # expected wrench from link mass and external wrench - arm_idx = articulation.body_names.index("Arm") - root_idx = articulation.body_names.index("CenterPivot") + # The incoming joint wrench is the constraint/support force from parent onto child (body1=Arm), + # expressed in Arm's frame. In static equilibrium this equals -(gravity + external forces on Arm). + total_force_w = weight_vector_w.to(device) + math_utils.quat_apply( + quat_w[:, arm_idx, :], external_force_vector_b[:, arm_idx, :] + ) + total_torque_w = torch.cross( + pos_w[:, arm_idx, :].to(device) - pos_w[:, root_idx, :].to(device), + total_force_w, + dim=-1, + ) + math_utils.quat_apply(quat_w[:, arm_idx, :], external_torque_vector_b[:, arm_idx, :]) expected_wrench = torch.zeros((num_articulations, 6), device=device) expected_wrench[:, :3] = math_utils.quat_apply( - math_utils.quat_conjugate(quat_w[:, root_idx, :]), - weight_vector_w.to(device) + math_utils.quat_apply(quat_w[:, arm_idx, :], external_force_vector_b[:, 1, :]), + math_utils.quat_conjugate(quat_w[:, arm_idx, :]), + -total_force_w, ) expected_wrench[:, 3:] = math_utils.quat_apply( - math_utils.quat_conjugate(quat_w[:, root_idx, :]), - torch.cross( - pos_w[:, arm_idx, :].to(device) - pos_w[:, root_idx, :].to(device), - weight_vector_w.to(device) + math_utils.quat_apply(quat_w[:, arm_idx, :], external_force_vector_b[:, 1, :]), - dim=-1, - ) - + math_utils.quat_apply(quat_w[:, arm_idx, :], external_torque_vector_b[:, 1, :]), + math_utils.quat_conjugate(quat_w[:, arm_idx, :]), + -total_torque_w, ) # check value of last joint wrench - actual_wrench = wp.to_torch(articulation.data.body_incoming_joint_wrench_b)[:, arm_idx, :].squeeze(1) torch.testing.assert_close( expected_wrench, - actual_wrench, + wp.to_torch(articulation.data.body_incoming_joint_wrench_b)[:, arm_idx, :].squeeze(1), atol=1e-2, rtol=1e-3, ) diff --git a/source/isaaclab_newton/test/sensors/test_contact_sensor.py b/source/isaaclab_newton/test/sensors/test_contact_sensor.py index a5f35315f803..5b5775df4650 100644 --- a/source/isaaclab_newton/test/sensors/test_contact_sensor.py +++ b/source/isaaclab_newton/test/sensors/test_contact_sensor.py @@ -470,6 +470,9 @@ def test_higher_drop_produces_larger_impact_force(device: str, use_mujoco_contac @pytest.mark.parametrize("device", ["cuda:0", "cpu"]) +# TODO: Newton's force_matrix_w on CUDA produces inconsistent magnitude values (e.g. 4.5, 9.8, 41.7 N +# across runs), causing the magnitude assertion to fail. A possible fix is to make the magnitude check +# mujoco-only — see https://github.com/isaac-sim/IsaacLab/pull/5097 commit c2425f04cb4. @pytest.mark.parametrize( "use_mujoco_contacts", [ diff --git a/source/isaaclab_ov/config/extension.toml b/source/isaaclab_ov/config/extension.toml index f32bb96fc7b9..67f5582202d9 100644 --- a/source/isaaclab_ov/config/extension.toml +++ b/source/isaaclab_ov/config/extension.toml @@ -1,5 +1,5 @@ [package] -version = "0.1.1" +version = "0.1.2" title = "Omniverse renderers for IsaacLab" description = "Extension providing Omniverse renderers (OVRTX, ovphysx, etc.) for tiled camera rendering." readme = "docs/README.md" diff --git a/source/isaaclab_ov/docs/CHANGELOG.rst b/source/isaaclab_ov/docs/CHANGELOG.rst index ed93de19af99..2babcbdabd9a 100644 --- a/source/isaaclab_ov/docs/CHANGELOG.rst +++ b/source/isaaclab_ov/docs/CHANGELOG.rst @@ -1,6 +1,17 @@ Changelog --------- +0.1.2 (2026-03-23) +~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Semantic segmentation in :class:`~isaaclab_ov.renderers.OVRTXRenderer` maps + semantic instance IDs to RGBA using the same pseudo-random per-ID HSV scheme as the + Isaac Sim RTX render backend, so OVRTX and Isaac RTX produce matching colors for the + same IDs. Numeric IDs ``0`` (BACKGROUND) and ``1`` (UNLABELLED) use fixed RGBA. + 0.1.1 (2026-03-07) ~~~~~~~~~~~~~~~~~~ diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py index 8b9d8239cd90..a4e3551f9be2 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer.py @@ -48,6 +48,7 @@ create_camera_transforms_kernel, extract_depth_tile_from_tiled_buffer_kernel, extract_tile_from_tiled_buffer_kernel, + generate_random_colors_from_ids_kernel, sync_newton_transforms_kernel, ) from .ovrtx_usd import ( @@ -121,6 +122,7 @@ def __init__(self, cfg: OVRTXRendererCfg): self._sensor_ref: weakref.ref[object] | None = None self._exported_usd_path: str | None = None self._camera_rel_path: str | None = None + self._output_semantic_color_buffer: wp.array | None = None def prepare_stage(self, stage: Any, num_envs: int) -> None: """Export the USD stage for OVRTX before create_render_data. @@ -398,6 +400,22 @@ def write_output( if src.ptr != output_data.data_ptr(): wp.copy(dest=wp.from_torch(output_data), src=src) + def _generate_random_colors_from_ids(self, input_ids: wp.array) -> wp.array: + """Generate pseudo-random colors from semantic IDs.""" + if self._output_semantic_color_buffer is None or self._output_semantic_color_buffer.shape != input_ids.shape: + self._output_semantic_color_buffer = wp.zeros(shape=input_ids.shape, dtype=wp.uint32, device=DEVICE) + + output_colors = self._output_semantic_color_buffer + + wp.launch( + kernel=generate_random_colors_from_ids_kernel, + dim=input_ids.shape, + inputs=[input_ids, output_colors], + device=DEVICE, + ) + + return output_colors + def _extract_rgba_tiles( self, render_data: OVRTXRenderData, @@ -478,16 +496,22 @@ def _process_render_frame(self, render_data: OVRTXRenderData, frame, output_buff tiled_albedo_data = wp.from_dlpack(mapping.tensor) self._extract_rgba_tiles(render_data, tiled_albedo_data, output_buffers, "albedo", suffix="albedo") - if "SemanticSegmentationSD" in frame.render_vars and "semantic_segmentation" in output_buffers: - with frame.render_vars["SemanticSegmentationSD"].map(device=Device.CUDA) as mapping: + if "SemanticSegmentation" in frame.render_vars and "semantic_segmentation" in output_buffers: + with frame.render_vars["SemanticSegmentation"].map(device=Device.CUDA) as mapping: tiled_semantic_data = wp.from_dlpack(mapping.tensor) + if tiled_semantic_data.dtype == wp.uint32: - semantic_torch = wp.to_torch(tiled_semantic_data) + semantic_colors = self._generate_random_colors_from_ids(tiled_semantic_data) + + semantic_torch = wp.to_torch(semantic_colors) semantic_uint8 = semantic_torch.view(torch.uint8) + if semantic_torch.dim() == 2: h, w = semantic_torch.shape semantic_uint8 = semantic_uint8.reshape(h, w, 4) + tiled_semantic_data = wp.from_torch(semantic_uint8, dtype=wp.uint8) + self._extract_rgba_tiles( render_data, tiled_semantic_data, @@ -549,4 +573,5 @@ def _safe_unbind(binding, name: str) -> None: self._renderer = None self._render_product_paths.clear() + self._output_semantic_color_buffer = None self._initialized_scene = False diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_kernels.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_kernels.py index eb9e69873960..7bf587ee4aaa 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_kernels.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_renderer_kernels.py @@ -89,6 +89,134 @@ def extract_depth_tile_from_tiled_buffer_kernel( tile_buffer[y, x, 0] = tiled_buffer[src_y, src_x] +@wp.func +def color_hash(seed: wp.uint32) -> wp.uint32: + """Simple hash function for better distribution. Used for colorization.""" + # uint32 integers are promoted to uint64 to avoid overflow during multiplication. + h = wp.uint64(seed) + h = h ^ (h >> wp.uint64(16)) + h = h * wp.uint64(wp.uint32(0x85EBCA6B)) + h = h ^ (h >> wp.uint64(13)) + h = h * wp.uint64(wp.uint32(0xC2B2AE35)) + h = h ^ (h >> wp.uint64(16)) + return wp.uint32(h) + + +@wp.func +def random_color_from_id(input_id: wp.uint32) -> wp.uint32: + """Generate random color from a single ID. + + Generate visually distinct colours by linearly spacing the hue channel in HSV space and then convert to RGB space. + + Args: + input_id: uint32 semantic ID + + Returns: + uint32 color: ``r | (g<<8) | (b<<16) | (a<<24)`` + """ + hash_val = color_hash(input_id) + + # Golden ratio inverse = 1.0 / 1.618033988749895 (Replicator constant) + GOLDEN_RATIO_INV = wp.float64(1.0) / wp.float64(1.618033988749895) + + # Use golden ratio spacing for maximum hue spread + hue_tmp = wp.float64(input_id) * GOLDEN_RATIO_INV + hue = hue_tmp - wp.floor(hue_tmp) + + # Add hash-based perturbation for better distribution + hue_perturbation = wp.float64(hash_val & wp.uint32(0xFFFF)) / wp.float64(65536.0) + hue_tmp = hue + hue_perturbation * wp.float64(0.1) + hue = hue_tmp - wp.floor(hue_tmp) + + # Use hash to determine saturation and value for maximum spread + sat_part = wp.uint32((hash_val >> wp.uint32(16)) & wp.uint32(0xFF)) + val_part = wp.uint32((hash_val >> wp.uint32(8)) & wp.uint32(0xFF)) + + # Saturation: 0.7 to 1.0 for vibrant colors + saturation = wp.float64(0.7) + wp.float64(0.3) * (wp.float64(sat_part) / wp.float64(255.0)) + + # Value: 0.8 to 1.0 for bright colors + value = wp.float64(0.8) + wp.float64(0.2) * (wp.float64(val_part) / wp.float64(255.0)) + + # HSV to RGB conversion (match Replicator: ``f`` uses pre-modulo ``int(hue*6)``, then ``i %= 6``). + hue_i = wp.int32(hue * wp.float64(6.0)) + hue_f = hue * wp.float64(6.0) - wp.float64(hue_i) + p = value * (wp.float64(1.0) - saturation) + q = value * (wp.float64(1.0) - saturation * hue_f) + t = value * (wp.float64(1.0) - saturation * (wp.float64(1.0) - hue_f)) + + r = wp.float64(0.0) + g = wp.float64(0.0) + b = wp.float64(0.0) + + hue_i = hue_i % 6 + + if hue_i == 0: + r = value + g = t + b = p + elif hue_i == 1: + r = q + g = value + b = p + elif hue_i == 2: + r = p + g = value + b = t + elif hue_i == 3: + r = p + g = q + b = value + elif hue_i == 4: + r = t + g = p + b = value + else: + r = value + g = p + b = q + + ri = wp.min(255, wp.max(0, wp.int32(r * wp.float64(255.0)))) + gi = wp.min(255, wp.max(0, wp.int32(g * wp.float64(255.0)))) + bi = wp.min(255, wp.max(0, wp.int32(b * wp.float64(255.0)))) + ai = wp.int32(255) + + color = ( + wp.uint32(ri) + | (wp.uint32(gi) << wp.uint32(8)) + | (wp.uint32(bi) << wp.uint32(16)) + | (wp.uint32(ai) << wp.uint32(24)) + ) + return color + + +@wp.kernel +def generate_random_colors_from_ids_kernel( + input_ids: wp.array(dtype=wp.uint32, ndim=2), # type: ignore + output_colors: wp.array(dtype=wp.uint32, ndim=2), # type: ignore +): + """Generate random colors given IDs (e.g. semantic IDs). + + Args: + input_ids: 2D uint32 array of semantic IDs per pixel + output_data: 2D uint32 array; each word is `r | (g<<8) | (b<<16) | (a<<24)` + """ + i, j = wp.tid() + + input_id = input_ids[i, j] + + if input_id == wp.uint32(0): + # BACKGROUND special case + output_color = wp.uint32(0) + elif input_id == wp.uint32(1): + # UNLABELLED special case + output_color = wp.uint32(0xFF000000) + else: + output_color = random_color_from_id(input_id) + + output_colors[i, j] = output_color + + @wp.kernel def sync_newton_transforms_kernel( ovrtx_transforms: wp.array(dtype=wp.mat44d), # type: ignore diff --git a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_usd.py b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_usd.py index 28cdfbc6646c..48ed2f8a968f 100644 --- a/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_usd.py +++ b/source/isaaclab_ov/isaaclab_ov/renderers/ovrtx_usd.py @@ -31,7 +31,7 @@ def get_render_var_config(data_types: list[str], simple_shading_mode: bool) -> t if use_albedo and not (use_rgb or use_semantic): return "/Render/Vars/albedo", "albedo", "DiffuseAlbedoSD" if use_semantic and not (use_rgb or use_albedo): - return "/Render/Vars/semantic", "semantic", "SemanticSegmentationSD" + return "/Render/Vars/semantic", "semantic", "SemanticSegmentation" if simple_shading_mode: return "/Render/Vars/SimpleShading", "SimpleShading", "SimpleShadingSD" return "/Render/Vars/LdrColor", "LdrColor", "LdrColor" diff --git a/source/isaaclab_ov/test/test_ovrtx_renderer_kernels.py b/source/isaaclab_ov/test/test_ovrtx_renderer_kernels.py new file mode 100644 index 000000000000..5bbbb6139e2b --- /dev/null +++ b/source/isaaclab_ov/test/test_ovrtx_renderer_kernels.py @@ -0,0 +1,153 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unit tests for OVRTX renderer kernels.""" + +import math + +import numpy as np +import pytest +import warp as wp +from isaaclab_ov.renderers.ovrtx_renderer_kernels import ( + DEVICE, + generate_random_colors_from_ids_kernel, +) + + +def _color_hash(seed: int) -> int: + h = seed + h ^= h >> 16 + h *= 0x85EBCA6B + h ^= h >> 13 + h *= 0xC2B2AE35 + h ^= h >> 16 + return h + + +def _random_colours_id(input_id: int) -> tuple[int, int, int, int]: + GOLDEN_RATIO_INV = 1.0 / 1.618033988749895 + + hash_val = _color_hash(input_id) + hue = math.fmod(input_id * GOLDEN_RATIO_INV, 1.0) + hue_perturbation = (hash_val & 0xFFFF) / 65536.0 + hue = math.fmod(hue + hue_perturbation * 0.1, 1.0) + sat_hash = hash_val >> 16 + val_hash = hash_val >> 8 + saturation = 0.7 + 0.3 * ((sat_hash & 0xFF) / 255.0) + value = 0.8 + 0.2 * ((val_hash & 0xFF) / 255.0) + i = int(hue * 6.0) + f = (hue * 6.0) - i + p = value * (1.0 - saturation) + q = value * (1.0 - saturation * f) + t = value * (1.0 - saturation * (1.0 - f)) + i = i % 6 + if i == 0: + r, g, b = value, t, p + elif i == 1: + r, g, b = q, value, p + elif i == 2: + r, g, b = p, value, t + elif i == 3: + r, g, b = p, q, value + elif i == 4: + r, g, b = t, p, value + else: + r, g, b = value, p, q + return (int(r * 255), int(g * 255), int(b * 255), 255) + + +def _reference_color(input_id: int) -> int: + if input_id == 0: + return 0 + if input_id == 1: + return 0xFF000000 + + r, g, b, a = _random_colours_id(input_id) + return r | (g << 8) | (b << 16) | (a << 24) + + +@pytest.mark.skip(reason="OVRTX is optional and experimental feature and temporarily is excluded from testing.") +class TestRandomColorsFromIdsKernel: + """Tests for generate_random_colors_from_ids_kernel.""" + + def test_random_colors(self): + inputs_np = np.array([[0, 1], [2, 3]], dtype=np.uint32) + input_ids = wp.array(inputs_np, dtype=wp.uint32, ndim=2, device=DEVICE) + h, w = inputs_np.shape + output_colors = wp.zeros(shape=(h, w), dtype=wp.uint32, device=DEVICE) + + wp.launch( + kernel=generate_random_colors_from_ids_kernel, + dim=(h, w), + inputs=[input_ids, output_colors], + device=DEVICE, + ) + wp.synchronize() + + out_np = output_colors.numpy() + for i in range(h): + for j in range(w): + input_id = int(inputs_np[i, j]) + ref_color = _reference_color(input_id) + out_color = int(out_np[i, j]) + assert out_color == ref_color, ( + f"At ({i},{j}) id={input_id}: expected 0x{ref_color:08x}, got 0x{out_color:08x}" + ) + + def test_deterministic_across_launches(self): + h, w = 4, 4 + rng = np.random.default_rng(42) + inputs_np = rng.integers(0, 2**31, size=(h, w), dtype=np.uint32) + input_ids = wp.array(inputs_np, dtype=wp.uint32, ndim=2, device=DEVICE) + output_colors = wp.zeros(shape=(h, w), dtype=wp.uint32, device=DEVICE) + + wp.launch( + kernel=generate_random_colors_from_ids_kernel, + dim=(h, w), + inputs=[input_ids, output_colors], + device=DEVICE, + ) + wp.synchronize() + first_run = output_colors.numpy().copy() + + wp.launch( + kernel=generate_random_colors_from_ids_kernel, + dim=(h, w), + inputs=[input_ids, output_colors], + device=DEVICE, + ) + wp.synchronize() + second_run = output_colors.numpy() + + np.testing.assert_array_equal(first_run, second_run) + + @pytest.mark.parametrize( + "input_value", + [ + 0, + 1, + 2, + 3, + 100, + ], + ) + def test_single_value(self, input_value): + inputs_np = np.array([[input_value]], dtype=np.uint32) + input_ids = wp.array(inputs_np, dtype=wp.uint32, ndim=2, device=DEVICE) + output_colors = wp.zeros(shape=(1, 1), dtype=wp.uint32, device=DEVICE) + + wp.launch( + kernel=generate_random_colors_from_ids_kernel, + dim=(1, 1), + inputs=[input_ids, output_colors], + device=DEVICE, + ) + wp.synchronize() + + ref_color = _reference_color(int(np.uint32(input_value))) + out_color = int(output_colors.numpy()[0, 0]) + assert out_color == ref_color, ( + f"id=0x{int(np.uint32(input_value)):08x}: expected 0x{ref_color:08x}, got 0x{out_color:08x}" + ) diff --git a/source/isaaclab_physx/config/extension.toml b/source/isaaclab_physx/config/extension.toml index ac788a3e9df9..996af61314e5 100644 --- a/source/isaaclab_physx/config/extension.toml +++ b/source/isaaclab_physx/config/extension.toml @@ -1,7 +1,7 @@ [package] # Note: Semantic Versioning is used: https://semver.org/ -version = "0.5.11" +version = "0.5.13" # Description title = "PhysX simulation interfaces for IsaacLab core package" diff --git a/source/isaaclab_physx/docs/CHANGELOG.rst b/source/isaaclab_physx/docs/CHANGELOG.rst index 3512b61e384f..6ea71fa755c2 100644 --- a/source/isaaclab_physx/docs/CHANGELOG.rst +++ b/source/isaaclab_physx/docs/CHANGELOG.rst @@ -1,6 +1,35 @@ Changelog --------- +0.5.13 (2026-03-25) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed device mismatch in :meth:`~isaaclab_physx.assets.RigidObjectCollection.reshape_view_to_data_2d` + and :meth:`~isaaclab_physx.assets.RigidObjectCollection.reshape_view_to_data_3d` that caused + ``wp.clone`` to fail with CUDA errors when PhysX returns data on CPU (e.g., masses, COMs, inertias) + while the simulation runs on GPU. The strided view now correctly uses ``data.device`` instead of + ``self.device``, matching the fix already present in :class:`~isaaclab_physx.assets.RigidObjectCollectionData`. + + +0.5.12 (2026-03-16) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed ``test_body_incoming_joint_wrench_b_single_joint`` computing the expected + wrench in the parent body's frame instead of the child body's frame. The expected + wrench is now expressed in + :attr:`~isaaclab_physx.assets.ArticulationData.body_incoming_joint_wrench_b`'s + actual convention (child body frame) and body indices are resolved by name to be + robust across backends. Also corrected the docstring for + :attr:`~isaaclab_physx.assets.ArticulationData.body_incoming_joint_wrench_b` to + accurately describe the frame convention. + + 0.5.11 (2026-03-13) ~~~~~~~~~~~~~~~~~~~ diff --git a/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py b/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py index 4972015fb35a..42190a28f473 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py @@ -750,11 +750,15 @@ def body_com_pose_b(self) -> wp.array: @property def body_incoming_joint_wrench_b(self) -> wp.array: - """Joint reaction wrench applied from body parent to child body in parent body frame. + """Joint reaction wrench applied to each body through its incoming joint, expressed in that body's frame. Shape is (num_instances, num_bodies, 6). All body reaction wrenches are provided including the root body to the world of an articulation. + .. note:: + PhysX expresses this wrench in the frame of ``body1`` as defined in the USD joint, which corresponds to + the child body's own frame when the USD convention is ``body0`` = parent, ``body1`` = child. + For more information on joint wrenches, please check the `PhysX documentation`_ and the underlying `PhysX Tensor API`_. diff --git a/source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection.py b/source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection.py index 2936ead353b9..877a44261293 100644 --- a/source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection.py +++ b/source/isaaclab_physx/isaaclab_physx/assets/rigid_object_collection/rigid_object_collection.py @@ -1081,7 +1081,8 @@ def reshape_view_to_data_2d(self, data: wp.array, device: str = "cpu") -> wp.arr shape=(self.num_instances, self.num_bodies), dtype=data.dtype, strides=(element_size, self.num_instances * element_size), - device=self.device, + # PhysX returns some data on CPU, use self.device may cause a device mismatch error + device=data.device, ) # Clone to make contiguous return wp.clone(strided_view, device=device) @@ -1115,7 +1116,8 @@ def reshape_view_to_data_3d(self, data: wp.array, data_dim: int, device: str = " shape=(self.num_instances, self.num_bodies, data_dim), dtype=data.dtype, strides=(row_size, self.num_instances * row_size, element_size), - device=self.device, + # PhysX returns some data on CPU, use self.device may cause a device mismatch error + device=data.device, ) return wp.clone(strided_view, device=device) diff --git a/source/isaaclab_physx/isaaclab_physx/renderers/isaac_rtx_renderer_utils.py b/source/isaaclab_physx/isaaclab_physx/renderers/isaac_rtx_renderer_utils.py index 011451a0d5cc..8e5b9abc8549 100644 --- a/source/isaaclab_physx/isaaclab_physx/renderers/isaac_rtx_renderer_utils.py +++ b/source/isaaclab_physx/isaaclab_physx/renderers/isaac_rtx_renderer_utils.py @@ -7,14 +7,88 @@ from __future__ import annotations +import logging +import time + import isaaclab.sim as sim_utils +logger = logging.getLogger(__name__) + # Module-level dedup stamp: tracks the last (sim instance, physics step) at # which Kit's ``app.update()`` was pumped. Keyed on ``id(sim)`` so that a # new ``SimulationContext`` (e.g. in a new test) automatically invalidates # any stale stamp from a previous instance. _last_render_update_key: tuple[int, int] = (0, -1) +# --------------------------------------------------------------------------- +# RTX streaming status tracking +# --------------------------------------------------------------------------- +_RTX_STREAMING_STATUS_EVENT: str = "omni.streamingstatus:streaming_status" + +_streaming_is_busy: bool = False +_streaming_subscription = None +_streaming_subscribed: bool = False + +_STREAMING_WAIT_TIMEOUT_S: float = 30.0 + + +def _on_streaming_status_event(event) -> None: + """Callback fired by the RTX renderer whenever streaming status changes.""" + global _streaming_is_busy + try: + is_busy = event["isBusy"] + if is_busy is not None: + _streaming_is_busy = bool(is_busy) + except (KeyError, TypeError): + pass + + +def _ensure_streaming_subscription() -> None: + """Subscribe to RTX streaming status events (idempotent).""" + global _streaming_subscription, _streaming_subscribed + if _streaming_subscribed: + return + + # Mark initialization as attempted even if dispatcher lookup fails. + # This flag enforces no-retry behavior after the first attempt. + _streaming_subscribed = True + + from carb.eventdispatcher import get_eventdispatcher + + dispatcher = get_eventdispatcher() + if dispatcher is None: + logger.warning("carb event dispatcher unavailable – RTX streaming wait will be inactive.") + else: + _streaming_subscription = dispatcher.observe_event( + observer_name="isaaclab_rtx_streaming_wait", + event_name=_RTX_STREAMING_STATUS_EVENT, + on_event=_on_streaming_status_event, + ) + + +def _wait_for_streaming_complete() -> None: + """Pump ``app.update()`` until RTX streaming reports idle or timeout. + + After streaming finishes a final ``app.update()`` is issued so that the + frame captured by downstream annotators reflects the newly loaded textures. + """ + import omni.kit.app + + start = time.monotonic() + while _streaming_is_busy and (time.monotonic() - start) < _STREAMING_WAIT_TIMEOUT_S: + omni.kit.app.get_app().update() + + elapsed = time.monotonic() - start + if _streaming_is_busy: + logger.warning( + "RTX streaming did not complete within %.1f s – proceeding anyway.", + _STREAMING_WAIT_TIMEOUT_S, + ) + elif elapsed > 0.01: + logger.info("RTX streaming completed in %.2f s.", elapsed) + + omni.kit.app.get_app().update() + def ensure_isaac_rtx_render_update() -> None: """Ensure the Isaac RTX renderer has been pumped for the current physics step. @@ -31,12 +105,16 @@ def ensure_isaac_rtx_render_update() -> None: ``SimulationContext`` (e.g. in a subsequent test) automatically invalidates any stale stamp left over from a previous instance. + If RTX texture/geometry streaming is in progress, additional + ``app.update()`` calls are pumped until the streaming subsystem reports + idle (or a timeout is reached). + No-op conditions: * Already called this step (dedup across camera instances). * A visualizer already pumps ``app.update()`` (e.g. KitVisualizer). * Rendering is not active. """ - global _last_render_update_key + global _last_render_update_key, _streaming_is_busy, _streaming_subscribed, _streaming_subscription sim = sim_utils.SimulationContext.instance() if sim is None: @@ -46,6 +124,12 @@ def ensure_isaac_rtx_render_update() -> None: if _last_render_update_key == key: return # Already pumped this step (by another camera or a visualizer) + # Reset stale streaming state when a new SimulationContext is detected. + if key[0] != _last_render_update_key[0]: + _streaming_is_busy = False + _streaming_subscribed = False + _streaming_subscription = None + # If a visualizer already pumps the Kit app loop, mark as done and skip. if any(viz.pumps_app_update() for viz in sim.visualizers): _last_render_update_key = key @@ -54,6 +138,8 @@ def ensure_isaac_rtx_render_update() -> None: if not sim.is_rendering: return + _ensure_streaming_subscription() + # Sync physics results → Fabric so RTX sees updated positions. # physics_manager.step() only runs simulate()/fetch_results() and does NOT # call _update_fabric(), so without this the render would lag one frame behind. @@ -63,6 +149,10 @@ def ensure_isaac_rtx_render_update() -> None: sim.set_setting("/app/player/playSimulations", False) omni.kit.app.get_app().update() + + if _streaming_is_busy: + _wait_for_streaming_complete() + sim.set_setting("/app/player/playSimulations", True) _last_render_update_key = key diff --git a/source/isaaclab_physx/test/assets/test_articulation.py b/source/isaaclab_physx/test/assets/test_articulation.py index 083c61092c09..f1e31795c130 100644 --- a/source/isaaclab_physx/test/assets/test_articulation.py +++ b/source/isaaclab_physx/test/assets/test_articulation.py @@ -1879,11 +1879,15 @@ def test_body_incoming_joint_wrench_b_single_joint(sim, num_articulations, devic # Play the simulator sim.reset() + + # Resolve body indices by name (ordering may differ across physics backends) + arm_idx = articulation.body_names.index("Arm") + root_idx = articulation.body_names.index("CenterPivot") # apply external force external_force_vector_b = torch.zeros((num_articulations, articulation.num_bodies, 3), device=device) - external_force_vector_b[:, 1, 1] = 10.0 # 10 N in Y direction + external_force_vector_b[:, arm_idx, 1] = 10.0 # 10 N in Y direction external_torque_vector_b = torch.zeros((num_articulations, articulation.num_bodies, 3), device=device) - external_torque_vector_b[:, 1, 2] = 10.0 # 10 Nm in z direction + external_torque_vector_b[:, arm_idx, 2] = 10.0 # 10 Nm in z direction # apply action to the articulation joint_pos = torch.ones_like(wp.to_torch(articulation.data.joint_pos)) * 1.5708 / 2.0 @@ -1917,31 +1921,38 @@ def test_body_incoming_joint_wrench_b_single_joint(sim, num_articulations, devic pos_w = wp.to_torch(articulation.data.body_pos_w) quat_w = wp.to_torch(articulation.data.body_quat_w) - mass_link2 = mass[:, 1].view(num_articulations, -1) + mass_link2 = mass[:, arm_idx].view(num_articulations, -1) gravity = torch.tensor(sim.cfg.gravity, device="cpu").repeat(num_articulations, 1).view((num_articulations, 3)) # NOTE: the com and link pose for single joint are colocated weight_vector_w = mass_link2 * gravity # expected wrench from link mass and external wrench + # PhysX reports the incoming joint wrench as the force FROM body0 ONTO body1 (body1's frame). + # The USD asset defines body0=CenterPivot, body1=Arm, so the wrench is the constraint/support + # force from CenterPivot onto Arm, expressed in Arm's frame. + # In static equilibrium this equals -(gravity + external forces on Arm). + total_force_w = weight_vector_w.to(device) + math_utils.quat_apply( + quat_w[:, arm_idx, :], external_force_vector_b[:, arm_idx, :] + ) + total_torque_w = torch.cross( + pos_w[:, arm_idx, :].to(device) - pos_w[:, root_idx, :].to(device), + total_force_w, + dim=-1, + ) + math_utils.quat_apply(quat_w[:, arm_idx, :], external_torque_vector_b[:, arm_idx, :]) expected_wrench = torch.zeros((num_articulations, 6), device=device) expected_wrench[:, :3] = math_utils.quat_apply( - math_utils.quat_conjugate(quat_w[:, 0, :]), - weight_vector_w.to(device) + math_utils.quat_apply(quat_w[:, 1, :], external_force_vector_b[:, 1, :]), + math_utils.quat_conjugate(quat_w[:, arm_idx, :]), + -total_force_w, ) expected_wrench[:, 3:] = math_utils.quat_apply( - math_utils.quat_conjugate(quat_w[:, 0, :]), - torch.cross( - pos_w[:, 1, :].to(device) - pos_w[:, 0, :].to(device), - weight_vector_w.to(device) + math_utils.quat_apply(quat_w[:, 1, :], external_force_vector_b[:, 1, :]), - dim=-1, - ) - + math_utils.quat_apply(quat_w[:, 1, :], external_torque_vector_b[:, 1, :]), + math_utils.quat_conjugate(quat_w[:, arm_idx, :]), + -total_torque_w, ) # check value of last joint wrench torch.testing.assert_close( expected_wrench, - wp.to_torch(articulation.data.body_incoming_joint_wrench_b)[:, 1, :].squeeze(1), + wp.to_torch(articulation.data.body_incoming_joint_wrench_b)[:, arm_idx, :].squeeze(1), atol=1e-2, rtol=1e-3, ) diff --git a/source/isaaclab_physx/test/renderers/test_isaac_rtx_renderer_utils.py b/source/isaaclab_physx/test/renderers/test_isaac_rtx_renderer_utils.py new file mode 100644 index 000000000000..d3fce4d95b5e --- /dev/null +++ b/source/isaaclab_physx/test/renderers/test_isaac_rtx_renderer_utils.py @@ -0,0 +1,203 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Unit tests for RTX streaming wait helpers. + +Covers callback state updates, subscription behavior, and timeout-aware wait +logic in :mod:`isaaclab_physx.renderers.isaac_rtx_renderer_utils`. +""" + +from __future__ import annotations + +import time +from unittest.mock import MagicMock, patch + +import isaaclab_physx.renderers.isaac_rtx_renderer_utils as rtx_utils +import pytest + +# test-specific timeout overrides for _STREAMING_WAIT_TIMEOUT_S +STREAMING_TIMEOUT_S = 0.1 +STREAMING_TIMEOUT_SHORT_S = 0.01 + +# simulated per-update sleep to advance wall-clock time inside the wait loop +MOCK_UPDATE_SLEEP_S = 0.02 + +# how many app.update() iterations before the mock becomes idle +MOCK_ITERATIONS_BEFORE_IDLE = 3 + + +@pytest.fixture(autouse=True) +def _reset_streaming_globals(monkeypatch): + """Restore module-level streaming state so tests are isolated.""" + monkeypatch.setattr(rtx_utils, "_streaming_is_busy", False) + monkeypatch.setattr(rtx_utils, "_streaming_subscription", None) + monkeypatch.setattr(rtx_utils, "_streaming_subscribed", False) + + +# --------------------------------------------------------------------------- +# _on_streaming_status_event +# --------------------------------------------------------------------------- + + +class TestOnStreamingStatusEvent: + """Callback correctly translates RTX streaming events into the busy flag.""" + + def test_sets_busy_true(self): + """Sets busy flag to true when event reports busy.""" + rtx_utils._on_streaming_status_event({"isBusy": True}) + assert rtx_utils._streaming_is_busy is True + + def test_sets_busy_false(self): + """Sets busy flag to false when event reports idle.""" + rtx_utils._streaming_is_busy = True + rtx_utils._on_streaming_status_event({"isBusy": False}) + assert rtx_utils._streaming_is_busy is False + + def test_ignores_missing_key(self): + """Leaves busy state unchanged when key is absent.""" + rtx_utils._streaming_is_busy = True + rtx_utils._on_streaming_status_event({"otherField": 42}) + assert rtx_utils._streaming_is_busy is True + + def test_ignores_none_value(self): + """Leaves busy state unchanged when value is None.""" + rtx_utils._streaming_is_busy = True + rtx_utils._on_streaming_status_event({"isBusy": None}) + assert rtx_utils._streaming_is_busy is True + + def test_handles_non_subscriptable_event(self): + """Ignores malformed events that are not subscriptable.""" + rtx_utils._on_streaming_status_event(None) + assert rtx_utils._streaming_is_busy is False + + +# --------------------------------------------------------------------------- +# _ensure_streaming_subscription +# --------------------------------------------------------------------------- + + +class TestEnsureStreamingSubscription: + """Subscription helper registers once and does not retry on first failure.""" + + def test_subscribes_to_correct_event(self): + """Subscribes to the expected event and stores its handle.""" + mock_dispatcher = MagicMock() + mock_dispatcher.observe_event.return_value = "sub_handle" + + with patch("carb.eventdispatcher.get_eventdispatcher", return_value=mock_dispatcher): + rtx_utils._ensure_streaming_subscription() + + mock_dispatcher.observe_event.assert_called_once_with( + observer_name="isaaclab_rtx_streaming_wait", + event_name=rtx_utils._RTX_STREAMING_STATUS_EVENT, + on_event=rtx_utils._on_streaming_status_event, + ) + assert rtx_utils._streaming_subscribed is True + assert rtx_utils._streaming_subscription == "sub_handle" + + def test_idempotent_after_first_call(self): + """Performs subscription at most once across repeated calls.""" + mock_dispatcher = MagicMock() + with patch("carb.eventdispatcher.get_eventdispatcher", return_value=mock_dispatcher): + rtx_utils._ensure_streaming_subscription() + rtx_utils._ensure_streaming_subscription() + + assert mock_dispatcher.observe_event.call_count == 1 + + def test_handles_missing_dispatcher(self): + """Marks subscription as attempted even when dispatcher is unavailable.""" + with patch("carb.eventdispatcher.get_eventdispatcher", return_value=None): + rtx_utils._ensure_streaming_subscription() + + assert rtx_utils._streaming_subscribed is True + assert rtx_utils._streaming_subscription is None + + +# --------------------------------------------------------------------------- +# _wait_for_streaming_complete +# --------------------------------------------------------------------------- + + +class TestWaitForStreamingComplete: + """Blocking wait pumps app.update() while busy and respects timeout.""" + + def test_returns_immediately_when_not_busy(self): + """Skips loop and issues only the final update when idle.""" + mock_app = MagicMock() + with patch("omni.kit.app.get_app", return_value=mock_app): + rtx_utils._wait_for_streaming_complete() + + # Only the final update call, no streaming loop iterations. + mock_app.update.assert_called_once() + + def test_pumps_updates_until_idle(self): + """Pumps updates until busy flips to false.""" + rtx_utils._streaming_is_busy = True + mock_app = MagicMock() + loop_calls = 0 + + def _simulate_streaming_done(): + nonlocal loop_calls + loop_calls += 1 + if loop_calls >= MOCK_ITERATIONS_BEFORE_IDLE: + rtx_utils._streaming_is_busy = False + + mock_app.update.side_effect = _simulate_streaming_done + + with patch("omni.kit.app.get_app", return_value=mock_app): + rtx_utils._wait_for_streaming_complete() + + assert mock_app.update.call_count == MOCK_ITERATIONS_BEFORE_IDLE + 1 + assert rtx_utils._streaming_is_busy is False + + def test_respects_timeout(self, monkeypatch): + """Exits wait loop on timeout if busy never clears.""" + monkeypatch.setattr(rtx_utils, "_STREAMING_WAIT_TIMEOUT_S", STREAMING_TIMEOUT_S) + rtx_utils._streaming_is_busy = True + mock_app = MagicMock() + mock_app.update.side_effect = lambda: time.sleep(MOCK_UPDATE_SLEEP_S) + + with patch("omni.kit.app.get_app", return_value=mock_app): + rtx_utils._wait_for_streaming_complete() + + assert rtx_utils._streaming_is_busy is True + assert mock_app.update.call_count > 0 + + def test_timeout_logs_warning(self, monkeypatch): + """Logs warning when timeout is reached while still busy.""" + monkeypatch.setattr(rtx_utils, "_STREAMING_WAIT_TIMEOUT_S", STREAMING_TIMEOUT_SHORT_S) + rtx_utils._streaming_is_busy = True + mock_app = MagicMock() + mock_logger = MagicMock() + + with ( + patch("omni.kit.app.get_app", return_value=mock_app), + patch.object(rtx_utils, "logger", mock_logger), + ): + rtx_utils._wait_for_streaming_complete() + + mock_logger.warning.assert_called_once() + assert "RTX streaming did not complete within" in mock_logger.warning.call_args[0][0] + + def test_logs_info_on_non_trivial_completion(self): + """Logs completion info when streaming finishes after delay.""" + rtx_utils._streaming_is_busy = True + mock_app = MagicMock() + mock_logger = MagicMock() + + def _become_idle_after_delay(): + time.sleep(MOCK_UPDATE_SLEEP_S) + rtx_utils._streaming_is_busy = False + + mock_app.update.side_effect = _become_idle_after_delay + + with ( + patch("omni.kit.app.get_app", return_value=mock_app), + patch.object(rtx_utils, "logger", mock_logger), + ): + rtx_utils._wait_for_streaming_complete() + + mock_logger.info.assert_called_once() + assert "RTX streaming completed in" in mock_logger.info.call_args[0][0] diff --git a/source/isaaclab_tasks/config/extension.toml b/source/isaaclab_tasks/config/extension.toml index 023c7cb0558e..8cda63ff36ab 100644 --- a/source/isaaclab_tasks/config/extension.toml +++ b/source/isaaclab_tasks/config/extension.toml @@ -1,7 +1,7 @@ [package] # Note: Semantic Versioning is used: https://semver.org/ -version = "1.5.11" +version = "1.5.17" # Description title = "Isaac Lab Environments" diff --git a/source/isaaclab_tasks/docs/CHANGELOG.rst b/source/isaaclab_tasks/docs/CHANGELOG.rst index d6b3ee9675ab..7d449e605845 100644 --- a/source/isaaclab_tasks/docs/CHANGELOG.rst +++ b/source/isaaclab_tasks/docs/CHANGELOG.rst @@ -1,6 +1,56 @@ Changelog --------- +1.5.17 (2026-03-30) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :func:`~isaaclab_tasks.utils.hydra.apply_overrides` raising a false + conflict error when two global presets resolve to the same value for a path + (e.g. ``newton`` aliased to ``cube``). + + +1.5.16 (2026-03-24) +~~~~~~~~~~~~~~~~~~~ + +Fixed +^^^^^ + +* Fixed :func:`~isaaclab_tasks.utils.hydra.collect_presets` not discovering + presets inside nested dicts (e.g. ``EventTerm.params.terms.*.params``). + + +1.5.15 (2026-03-25) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added semantic segmentation to preset data types for the Cartpole Camera environment. +* Added semantic segmentation to preset data types for the Shadow Hand environment. +* Added semantic_segmentation64 to preset data types for for the Dexsuite Kuka-Allegro environment. + +1.5.13 (2026-03-18) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added consistency validation to the camera outputs in ``test_rendering_correctness.py``. + + +1.5.12 (2026-03-16) +~~~~~~~~~~~~~~~~~~~ + +Changed +^^^^^^^ + +* Increased ``max_iterations`` from 200 to 300 for ``Isaac-Dexsuite-Kuka-Allegro-Lift-v0`` + in the benchmarking configuration to allow sufficient training time for convergence. + + 1.5.11 (2026-03-13) ~~~~~~~~~~~~~~~~~~~ @@ -21,6 +71,7 @@ Added * Added ``test_rendering_correctness.py`` to validate rendering correctness of the environments. + 1.5.9 (2026-03-10) ~~~~~~~~~~~~~~~~~~ @@ -156,7 +207,6 @@ Changed Material and fixed-tendon randomization remain exclusively in :class:`~isaaclab_tasks.direct.shadow_hand.shadow_hand_env_cfg.PhysxEventCfg`. - 1.5.2 (2026-03-05) ~~~~~~~~~~~~~~~~~~ diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_env.py b/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_env.py index 409e9cb244ed..3c2a896766ea 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_env.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_env.py @@ -115,6 +115,9 @@ def _get_observations(self) -> dict: elif "depth" in self.cfg.tiled_camera.data_types: camera_data = self._tiled_camera.data.output[data_type] camera_data[camera_data == float("inf")] = 0 + elif "semantic_segmentation" in self.cfg.tiled_camera.data_types: + camera_data = self._tiled_camera.data.output[data_type] + observations = {"policy": camera_data.clone()} if self.cfg.write_image_to_file: diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_presets_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_presets_env_cfg.py index d2b2abfa560e..33433153f386 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_presets_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/cartpole/cartpole_camera_presets_env_cfg.py @@ -48,6 +48,7 @@ class CartpoleTiledCameraCfg(TiledCameraCfg): default = CartpoleTiledCameraCfg(data_types=["rgb"]) depth = CartpoleTiledCameraCfg(data_types=["depth"]) albedo = CartpoleTiledCameraCfg(data_types=["albedo"]) + semantic_segmentation = CartpoleTiledCameraCfg(data_types=["semantic_segmentation"]) simple_shading_constant_diffuse = CartpoleTiledCameraCfg(data_types=["simple_shading_constant_diffuse"]) simple_shading_diffuse_mdl = CartpoleTiledCameraCfg(data_types=["simple_shading_diffuse_mdl"]) simple_shading_full_mdl = CartpoleTiledCameraCfg(data_types=["simple_shading_full_mdl"]) @@ -100,6 +101,7 @@ class BaseCartpoleCameraEnvCfg(DirectRLEnvCfg): default = BaseCartpoleCameraEnvCfg() depth = BaseCartpoleCameraEnvCfg(observation_space=[100, 100, 1]) albedo = BaseCartpoleCameraEnvCfg(observation_space=[100, 100, 3]) + semantic_segmentation = BaseCartpoleCameraEnvCfg(observation_space=[100, 100, 4]) simple_shading_constant_diffuse = BaseCartpoleCameraEnvCfg(observation_space=[100, 100, 3]) simple_shading_diffuse_mdl = BaseCartpoleCameraEnvCfg(observation_space=[100, 100, 3]) simple_shading_full_mdl = BaseCartpoleCameraEnvCfg(observation_space=[100, 100, 3]) diff --git a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_vision_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_vision_env_cfg.py index 6a6d0b11152f..4f57500f5f8e 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_vision_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/direct/shadow_hand/shadow_hand_vision_env_cfg.py @@ -103,6 +103,11 @@ class ShadowHandVisionTiledCameraCfg(PresetCfg): presets=depth,ovrtx_renderer # depth rendering with OVRTX renderer """ + semantic_segmentation: _ShadowHandBaseTiledCameraCfg = _ShadowHandBaseTiledCameraCfg( + data_types=["semantic_segmentation"] + ) + """Semantic segmentation (3 CNN input channels).""" + @configclass class ShadowHandVisionEnvCfg(ShadowHandEnvCfg): diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/camera_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/camera_cfg.py index f79ac404ba11..2e35f20ba81e 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/camera_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/config/kuka_allegro/camera_cfg.py @@ -85,6 +85,9 @@ class BaseTiledCameraCfg(PresetCfg): simple_shading_full_mdl64 = BASE_CAMERA_CFG.replace(data_types=["simple_shading_full_mdl"], width=64, height=64) simple_shading_full_mdl128 = BASE_CAMERA_CFG.replace(data_types=["simple_shading_full_mdl"], width=128, height=128) simple_shading_full_mdl256 = BASE_CAMERA_CFG.replace(data_types=["simple_shading_full_mdl"], width=256, height=256) + semantic_segmentation64 = BASE_CAMERA_CFG.replace(data_types=["semantic_segmentation"], width=64, height=64) + semantic_segmentation128 = BASE_CAMERA_CFG.replace(data_types=["semantic_segmentation"], width=128, height=128) + semantic_segmentation256 = BASE_CAMERA_CFG.replace(data_types=["semantic_segmentation"], width=256, height=256) default = rgb64 @@ -101,27 +104,30 @@ class WristTiledCameraCfg(PresetCfg): albedo64 = WRIST_CAMERA_CFG.replace(data_types=["albedo"], width=64, height=64) albedo128 = WRIST_CAMERA_CFG.replace(data_types=["albedo"], width=128, height=128) albedo256 = WRIST_CAMERA_CFG.replace(data_types=["albedo"], width=256, height=256) - simple_shading_constant_diffuse64 = BASE_CAMERA_CFG.replace( + simple_shading_constant_diffuse64 = WRIST_CAMERA_CFG.replace( data_types=["simple_shading_constant_diffuse"], width=64, height=64 ) - simple_shading_constant_diffuse128 = BASE_CAMERA_CFG.replace( + simple_shading_constant_diffuse128 = WRIST_CAMERA_CFG.replace( data_types=["simple_shading_constant_diffuse"], width=128, height=128 ) - simple_shading_constant_diffuse256 = BASE_CAMERA_CFG.replace( + simple_shading_constant_diffuse256 = WRIST_CAMERA_CFG.replace( data_types=["simple_shading_constant_diffuse"], width=256, height=256 ) - simple_shading_diffuse_mdl64 = BASE_CAMERA_CFG.replace( + simple_shading_diffuse_mdl64 = WRIST_CAMERA_CFG.replace( data_types=["simple_shading_diffuse_mdl"], width=64, height=64 ) - simple_shading_diffuse_mdl128 = BASE_CAMERA_CFG.replace( + simple_shading_diffuse_mdl128 = WRIST_CAMERA_CFG.replace( data_types=["simple_shading_diffuse_mdl"], width=128, height=128 ) - simple_shading_diffuse_mdl256 = BASE_CAMERA_CFG.replace( + simple_shading_diffuse_mdl256 = WRIST_CAMERA_CFG.replace( data_types=["simple_shading_diffuse_mdl"], width=256, height=256 ) - simple_shading_full_mdl64 = BASE_CAMERA_CFG.replace(data_types=["simple_shading_full_mdl"], width=64, height=64) - simple_shading_full_mdl128 = BASE_CAMERA_CFG.replace(data_types=["simple_shading_full_mdl"], width=128, height=128) - simple_shading_full_mdl256 = BASE_CAMERA_CFG.replace(data_types=["simple_shading_full_mdl"], width=256, height=256) + simple_shading_full_mdl64 = WRIST_CAMERA_CFG.replace(data_types=["simple_shading_full_mdl"], width=64, height=64) + simple_shading_full_mdl128 = WRIST_CAMERA_CFG.replace(data_types=["simple_shading_full_mdl"], width=128, height=128) + simple_shading_full_mdl256 = WRIST_CAMERA_CFG.replace(data_types=["simple_shading_full_mdl"], width=256, height=256) + semantic_segmentation64 = WRIST_CAMERA_CFG.replace(data_types=["semantic_segmentation"], width=64, height=64) + semantic_segmentation128 = WRIST_CAMERA_CFG.replace(data_types=["semantic_segmentation"], width=128, height=128) + semantic_segmentation256 = WRIST_CAMERA_CFG.replace(data_types=["semantic_segmentation"], width=256, height=256) default = rgb64 diff --git a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/dexsuite_env_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/dexsuite_env_cfg.py index 96e2107427ad..f1e43a51d42b 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/dexsuite_env_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/manager_based/manipulation/dexsuite/dexsuite_env_cfg.py @@ -77,6 +77,7 @@ class ObjectCfg(PresetCfg): collision_props=sim_utils.CollisionPropertiesCfg(), mass_props=sim_utils.MassPropertiesCfg(mass=0.2), ) + newton = cube # newton does not support multi-asset spawning yet default = shapes diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/hydra.py b/source/isaaclab_tasks/isaaclab_tasks/utils/hydra.py index e616ee8e7782..c5feca37d40c 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/hydra.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/hydra.py @@ -95,13 +95,46 @@ def preset(**options) -> PresetCfg: return cls() +def _preset_fields(preset_obj) -> dict: + """Extract all alternatives from a :class:`PresetCfg`, class attrs over instance. + + Class-level values take priority because robot-specific modules + (e.g. ``joint_pos_env_cfg.py``) reassign fields on the class after + instances are already created. + """ + cls = type(preset_obj) + d = {} + for fn in preset_obj.__dataclass_fields__: + cls_val = getattr(cls, fn, None) + d[fn] = cls_val if cls_val is not None else getattr(preset_obj, fn) + for attr in vars(cls): + if attr.startswith("_") or attr in d or callable(getattr(cls, attr)): + continue + d[attr] = getattr(cls, attr) + return d + + +def _walk_cfg(cfg, path: str, on_preset: Callable) -> None: + """Depth-first walk of a config tree, calling *on_preset(parent, key, obj, path)* + for every :class:`PresetCfg` node. Recurses through dataclass attrs, dicts, and + nested dicts transparently.""" + items = ( + cfg.items() + if isinstance(cfg, dict) + else ((n, v) for n in dir(cfg) if not n.startswith("_") for v in [getattr(cfg, n, None)] if v is not None) + ) + for key, val in items: + child_path = f"{path}.{key}" if path else key + if isinstance(val, PresetCfg): + on_preset(cfg, key, val, child_path) + elif hasattr(val, "__dataclass_fields__") or isinstance(val, dict): + _walk_cfg(val, child_path, on_preset) + + def collect_presets(cfg, path: str = "") -> dict: - """Recursively walk config tree and collect :class:`PresetCfg` fields. + """Recursively discover :class:`PresetCfg` nodes in the config tree. - Presets are defined by subclassing :class:`PresetCfg` with typed fields for - each alternative, or by using the :func:`preset` factory for scalar values. - This function discovers them at every level of the config tree, including - inside dict-valued fields (e.g. ``actuators``). + Walks dataclass fields and dict values at any nesting depth. Args: cfg: A configclass instance to walk. @@ -113,70 +146,26 @@ def collect_presets(cfg, path: str = "") -> dict: """ result = {} - # Root-level PresetCfg: the cfg itself is a PresetCfg subclass - if isinstance(cfg, PresetCfg) and hasattr(cfg, "__dataclass_fields__"): - preset_dict = {} - for field_name in cfg.__dataclass_fields__: - preset_dict[field_name] = getattr(cfg, field_name) - result[path] = preset_dict - for alt in preset_dict.values(): + def _record(preset_obj, preset_path): + fields = _preset_fields(preset_obj) + result[preset_path] = fields + for alt in fields.values(): if hasattr(alt, "__dataclass_fields__"): - result.update(collect_presets(alt, path)) - return result + result.update(collect_presets(alt, preset_path)) - # Recurse into nested configclass attributes - for name in dir(cfg): - if name.startswith("_"): - continue - try: - value = getattr(cfg, name) - except Exception: - continue - - child_path = f"{path}.{name}" if path else name - - if hasattr(value, "__dataclass_fields__"): - if isinstance(value, PresetCfg): - preset_dict = {} - for field_name in value.__dataclass_fields__: - preset_dict[field_name] = getattr(value, field_name) - result[child_path] = preset_dict - for alt in preset_dict.values(): - if hasattr(alt, "__dataclass_fields__"): - result.update(collect_presets(alt, child_path)) - else: - result.update(collect_presets(value, child_path)) - elif isinstance(value, dict): - for dict_key, dict_val in value.items(): - if hasattr(dict_val, "__dataclass_fields__"): - result.update(collect_presets(dict_val, f"{child_path}.{dict_key}")) + if isinstance(cfg, PresetCfg): + _record(cfg, path) + return result + _walk_cfg(cfg, path, lambda _p, _k, obj, cp: _record(obj, cp)) return result -def resolve_task_config(task_name: str, agent_cfg_entry_point: str): - """Resolve env and agent configs with Hydra overrides, presets, and scalars fully applied. - - Safe to call before Kit is launched — callable config values are stored as - :class:`~isaaclab.utils.string.ResolvableString` and resolved lazily on - first use, so no implementation modules are imported eagerly. - - Args: - task_name: Task name (e.g., "Isaac-Velocity-Flat-Anymal-C-v0"). - agent_cfg_entry_point: Agent config entry point key (e.g., "rsl_rl_cfg_entry_point"). - - Returns: - Tuple of (env_cfg, agent_cfg) fully resolved. - """ - task = task_name.split(":")[-1] - env_cfg, agent_cfg, presets = register_task(task, agent_cfg_entry_point) - +def _run_hydra(task, env_cfg, agent_cfg, presets, callback): + """Shared Hydra entry point for :func:`resolve_task_config` and :func:`hydra_task_config`.""" global_presets, preset_sel, preset_scalar, global_scalar = parse_overrides(sys.argv[1:], presets) - original_argv, sys.argv = sys.argv, [sys.argv[0]] + global_scalar - resolved = {} - @hydra.main(config_path=None, config_name=task, version_base="1.3") def hydra_main(hydra_cfg, env_cfg=env_cfg, agent_cfg=agent_cfg): hydra_cfg = replace_strings_with_slices(OmegaConf.to_container(hydra_cfg, resolve=True)) @@ -189,14 +178,32 @@ def hydra_main(hydra_cfg, env_cfg=env_cfg, agent_cfg=agent_cfg): agent_cfg = hydra_cfg["agent"] else: agent_cfg.from_dict(hydra_cfg["agent"]) - resolved["env_cfg"] = env_cfg - resolved["agent_cfg"] = agent_cfg + callback(env_cfg, agent_cfg) try: hydra_main() finally: sys.argv = original_argv + +def resolve_task_config(task_name: str, agent_cfg_entry_point: str): + """Resolve env and agent configs with Hydra overrides, presets, and scalars fully applied. + + Safe to call before Kit is launched — callable config values are stored as + :class:`~isaaclab.utils.string.ResolvableString` and resolved lazily on + first use, so no implementation modules are imported eagerly. + + Args: + task_name: Task name (e.g., "Isaac-Velocity-Flat-Anymal-C-v0"). + agent_cfg_entry_point: Agent config entry point key (e.g., "rsl_rl_cfg_entry_point"). + + Returns: + Tuple of (env_cfg, agent_cfg) fully resolved. + """ + task = task_name.split(":")[-1] + env_cfg, agent_cfg, presets = register_task(task, agent_cfg_entry_point) + resolved = {} + _run_hydra(task, env_cfg, agent_cfg, presets, lambda e, a: resolved.update(env_cfg=e, agent_cfg=a)) return resolved["env_cfg"], resolved["agent_cfg"] @@ -216,31 +223,7 @@ def decorator(func): def wrapper(*args, **kwargs): task = task_name.split(":")[-1] env_cfg, agent_cfg, presets = register_task(task, agent_cfg_entry_point) - - # Split args: global presets, path presets, scalars - global_presets, preset_sel, preset_scalar, global_scalar = parse_overrides(sys.argv[1:], presets) - - # Only pass global scalars to Hydra - original_argv, sys.argv = sys.argv, [sys.argv[0]] + global_scalar - - @hydra.main(config_path=None, config_name=task, version_base="1.3") - def hydra_main(hydra_cfg, env_cfg=env_cfg, agent_cfg=agent_cfg): - hydra_cfg = replace_strings_with_slices(OmegaConf.to_container(hydra_cfg, resolve=True)) - env_cfg, agent_cfg = apply_overrides( - env_cfg, agent_cfg, hydra_cfg, global_presets, preset_sel, preset_scalar, presets - ) - env_cfg.from_dict(hydra_cfg["env"]) - env_cfg = replace_strings_with_env_cfg_spaces(env_cfg) - if isinstance(agent_cfg, dict) or agent_cfg is None: - agent_cfg = hydra_cfg["agent"] - else: - agent_cfg.from_dict(hydra_cfg["agent"]) - func(env_cfg, agent_cfg, *args, **kwargs) - - try: - hydra_main() - finally: - sys.argv = original_argv + _run_hydra(task, env_cfg, agent_cfg, presets, lambda e, a: func(e, a, *args, **kwargs)) return wrapper @@ -248,35 +231,28 @@ def hydra_main(hydra_cfg, env_cfg=env_cfg, agent_cfg=agent_cfg): def resolve_preset_defaults(cfg): - """Replace PresetCfg fields with their 'default' value before serialization. + """Replace PresetCfg fields with their ``default`` value, recursively. - This must be called before to_dict() so the hydra dict contains only the + Must be called before ``to_dict()`` so the Hydra dict contains only the resolved config rather than the raw PresetCfg with all alternatives. Returns the (possibly replaced) cfg if the root itself is a PresetCfg. """ - if isinstance(cfg, PresetCfg) and hasattr(cfg, "__dataclass_fields__"): + if isinstance(cfg, PresetCfg): default = getattr(cfg, "default", None) - if default is not None: - return resolve_preset_defaults(default) - return cfg - - for name in list(getattr(cfg, "__dataclass_fields__", {}).keys()): - try: - value = getattr(cfg, name) - except Exception: - continue - if isinstance(value, PresetCfg) and hasattr(value, "__dataclass_fields__"): - default = getattr(value, "default", None) - if default is not None: - setattr(cfg, name, default) - if hasattr(default, "__dataclass_fields__"): - resolve_preset_defaults(default) - elif hasattr(value, "__dataclass_fields__"): - resolve_preset_defaults(value) - elif isinstance(value, dict): - for dict_val in value.values(): - if hasattr(dict_val, "__dataclass_fields__"): - resolve_preset_defaults(dict_val) + return resolve_preset_defaults(default) if default is not None else cfg + + def _on_preset(parent, key, preset_obj, _path): + default = getattr(preset_obj, "default", None) + if default is None: + return + if isinstance(parent, dict): + parent[key] = default + else: + setattr(parent, key, default) + if hasattr(default, "__dataclass_fields__"): + resolve_preset_defaults(default) + + _walk_cfg(cfg, "", _on_preset) return cfg @@ -335,8 +311,8 @@ def parse_overrides(args: list[str], presets: dict) -> tuple: - preset_scalar: [(full_path, value), ...] - scalars in preset paths - global_scalar: [arg, ...] - pass to Hydra """ - # Build lookup of preset group paths (e.g., "env.actions") - # Root-level PresetCfg has path="" -> bare "env" or "agent" key + # Build lookup of preset group paths (e.g., "env.actions"). + # Root-level PresetCfg has path="" -> bare "env" or "agent" key. preset_paths = {f"{s}.{p}" if p else s for s, v in presets.items() for p in v} global_presets, preset_sel, preset_scalar, global_scalar = [], [], [], [] @@ -344,26 +320,17 @@ def parse_overrides(args: list[str], presets: dict) -> tuple: if "=" not in arg: global_scalar.append(arg) continue - key, val = arg.split("=", 1) if key == "presets": - # Global presets: presets=name1,name2 -> apply everywhere global_presets.extend(v.strip() for v in val.split(",") if v.strip()) elif key in preset_paths: - # Exact match -> preset selection - if "." in key: - sec, path = key.split(".", 1) - else: - sec, path = key, "" + sec, path = key.split(".", 1) if "." in key else (key, "") preset_sel.append((sec, path, val)) elif any(key.startswith(pp + ".") for pp in preset_paths): - # Prefix match -> scalar within preset path preset_scalar.append((key, val)) else: - # No match -> global scalar, let Hydra handle it global_scalar.append(arg) - # Sort preset selections: parents before children preset_sel.sort(key=lambda x: x[1].count(".")) return global_presets, preset_sel, preset_scalar, global_scalar @@ -379,11 +346,10 @@ def apply_overrides( ): """Apply preset selections and scalar overrides with REPLACE semantics. - This is the core function that implements REPLACE (not merge) behavior: - 0. Auto-apply "default" presets for paths not explicitly selected - 1. Global presets (presets=name) apply to ALL configs that have matching preset - 2. Path-specific presets (env.actions=name) replace specific sections - 3. Scalar overrides are applied on top + Phase 1: Determine the selected preset name for every path (explicit + selections, then global broadcasts, then ``default`` fallback). + Phase 2: Apply in depth order, pruning children whose parent is None. + Phase 3: Apply scalar overrides on top. Returns: (env_cfg, agent_cfg) — possibly replaced if root-level PresetCfg was resolved. @@ -394,21 +360,12 @@ def apply_overrides( cfgs = {"env": env_cfg, "agent": agent_cfg} def _path_reachable(sec: str, path: str) -> bool: - """Check that every ancestor along *path* is non-None on the live config. - - For "scene.camera" we walk to ``cfg.scene`` and verify it is not None, - then check ``cfg.scene.camera`` is not None. If any segment is missing - or None the child preset cannot be applied. - """ if not path: return cfgs[sec] is not None obj = cfgs[sec] for part in path.split("."): try: - if isinstance(obj, dict): - obj = obj[part] - else: - obj = getattr(obj, part) + obj = obj[part] if isinstance(obj, dict) else getattr(obj, part) except (AttributeError, TypeError, KeyError): return False if obj is None: @@ -416,15 +373,7 @@ def _path_reachable(sec: str, path: str) -> bool: return True def _apply_node(sec: str, path: str, node): - """Replace a config node at the given section/path, handling root (path='').""" - if node is None: - node_dict = None - elif hasattr(node, "to_dict"): - node_dict = node.to_dict() - elif isinstance(node, Mapping): - node_dict = dict(node) - else: - node_dict = node + node_dict = node.to_dict() if hasattr(node, "to_dict") else dict(node) if isinstance(node, Mapping) else node if path == "": cfgs[sec] = node hydra_cfg[sec] = node_dict @@ -433,8 +382,7 @@ def _apply_node(sec: str, path: str, node): _setattr(hydra_cfg, f"{sec}.{path}", node_dict) # --- Phase 1: Determine selected preset name for every path --------------- - # Start with explicit path selections - resolved: dict[str, tuple[str, str, str]] = {} # full_path -> (sec, path, name) + resolved: dict[str, tuple[str, str, str]] = {} for sec, path, name in preset_sel: if path not in presets.get(sec, {}): raise ValueError(f"Unknown preset group: {sec}.{path}") @@ -444,7 +392,7 @@ def _apply_node(sec: str, path: str, node): full_path = f"{sec}.{path}" if path else sec resolved[full_path] = (sec, path, name) - # Apply global presets (error on conflict) + # Apply global presets (error on real conflict — same path, different value) applied_by: dict[str, str] = {} for name in global_presets: for sec in ("env", "agent"): @@ -452,11 +400,16 @@ def _apply_node(sec: str, path: str, node): if name in path_presets: full_path = f"{sec}.{path}" if path else sec if full_path in applied_by: - raise ValueError( - f"Conflicting global presets: '{applied_by[full_path]}' and '{name}' " - f"both define preset for '{full_path}'" - ) - applied_by[full_path] = name + prev_name = applied_by[full_path] + prev_val = path_presets[prev_name] + cur_val = path_presets[name] + if prev_val is not cur_val and prev_val != cur_val: + raise ValueError( + f"Conflicting global presets: '{prev_name}' and '{name}' " + f"both define preset for '{full_path}'" + ) + else: + applied_by[full_path] = name if full_path not in resolved: resolved[full_path] = (sec, path, name) diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/parse_cfg.py b/source/isaaclab_tasks/isaaclab_tasks/utils/parse_cfg.py index 010cfaa55d35..2c7b39fe90b9 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/parse_cfg.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/parse_cfg.py @@ -21,103 +21,6 @@ from isaaclab.envs import DirectRLEnvCfg, ManagerBasedRLEnvCfg -def _is_preset_cfg(obj: object) -> bool: - """Return True if *obj* is an instance of a PresetCfg subclass (new typed-field style). - - Uses MRO class-name matching so that this module has no dependency on the - hydra-gated ``isaaclab_tasks.utils.hydra`` import path. - """ - return any(cls.__name__ == "PresetCfg" for cls in type(obj).__mro__) - - -def _is_old_style_preset(obj: object) -> bool: - """Return True if *obj* is an old-style preset wrapper (has ``presets`` dict with a ``'default'`` key).""" - presets = getattr(obj, "presets", None) - return hasattr(obj, "__dataclass_fields__") and isinstance(presets, dict) and "default" in presets - - -def _resolve_presets_to_default(cfg: object) -> object: - """Recursively replace preset wrapper fields with their *default* preset. - - Handles two preset patterns used in IsaacLab task configs: - - * **New style** (``PresetCfg`` subclass): typed fields where ``default`` is a class attribute. - * **Old style** (``presets`` dict): configclass with ``presets: dict[str, Cfg]`` and a ``'default'`` key. - - Both are resolved in-place so the config can be used without a Hydra CLI override (e.g. in tests). - """ - if not hasattr(cfg, "__dataclass_fields__"): - return cfg - for field_name in list(cfg.__dataclass_fields__): - value = getattr(cfg, field_name, None) - if value is None: - continue - if hasattr(value, "__dataclass_fields__"): - if _is_preset_cfg(value): - resolved = value.default - setattr(cfg, field_name, resolved) - _resolve_presets_to_default(resolved) - elif _is_old_style_preset(value): - resolved = value.presets["default"] - setattr(cfg, field_name, resolved) - _resolve_presets_to_default(resolved) - else: - _resolve_presets_to_default(value) - elif isinstance(value, dict): - for dict_val in value.values(): - if hasattr(dict_val, "__dataclass_fields__"): - _resolve_presets_to_default(dict_val) - return cfg - - -def apply_named_preset(env_cfg: object, raw_cfg: object, preset_name: str) -> None: - """Apply a named preset to all preset-wrapper fields in *env_cfg*, guided by *raw_cfg*. - - Walks *raw_cfg* to find preset wrappers (both :class:`PresetCfg` subclasses and - old-style wrappers with a ``presets`` dict). For each wrapper that contains - *preset_name*, overrides the corresponding already-resolved field in *env_cfg*. - - This is used in tests to apply a non-default physics preset (e.g. ``'newton'``) - after :func:`parse_env_cfg` has already resolved all wrappers to ``'default'``. - - Args: - env_cfg: Resolved env config (from :func:`parse_env_cfg`) to update in-place. - raw_cfg: Raw env config (from :func:`load_cfg_from_registry`) with preset - wrappers still intact. - preset_name: Name of the preset to apply (e.g., ``'newton'``). - """ - if not hasattr(raw_cfg, "__dataclass_fields__"): - return - for field_name in raw_cfg.__dataclass_fields__: - raw_value = getattr(raw_cfg, field_name, None) - if raw_value is None: - continue - if hasattr(raw_value, "__dataclass_fields__"): - if _is_preset_cfg(raw_value): - if hasattr(raw_value, preset_name): - resolved = getattr(raw_value, preset_name) - setattr(env_cfg, field_name, resolved) - apply_named_preset(resolved, resolved, preset_name) - elif _is_old_style_preset(raw_value): - if preset_name in raw_value.presets: - resolved = raw_value.presets[preset_name] - setattr(env_cfg, field_name, resolved) - apply_named_preset(resolved, resolved, preset_name) - else: - env_value = getattr(env_cfg, field_name, None) - if env_value is not None and hasattr(env_value, "__dataclass_fields__"): - apply_named_preset(env_value, raw_value, preset_name) - elif isinstance(raw_value, dict): - env_dict = getattr(env_cfg, field_name, None) - if not isinstance(env_dict, dict): - continue - for key, raw_dict_val in raw_value.items(): - if hasattr(raw_dict_val, "__dataclass_fields__") and key in env_dict: - env_dict_val = env_dict[key] - if hasattr(env_dict_val, "__dataclass_fields__"): - apply_named_preset(env_dict_val, raw_dict_val, preset_name) - - def load_cfg_from_registry(task_name: str, entry_point_key: str) -> dict | object: """Load default configuration given its entry point from the gym registry. @@ -238,6 +141,8 @@ def parse_env_cfg( RuntimeError: If the configuration for the task is not a class. We assume users always use a class for the environment configuration. """ + from isaaclab_tasks.utils.hydra import resolve_preset_defaults + # load the default configuration cfg = load_cfg_from_registry(task_name.split(":")[-1], "env_cfg_entry_point") @@ -246,17 +151,12 @@ def parse_env_cfg( if isinstance(cfg, dict): raise RuntimeError(f"Configuration for the task: '{task_name}' is not a class. Please provide a class.") - # If the top-level cfg is itself a PresetCfg wrapper, resolve to the default preset before - # attempting any attribute access (e.g. cfg.sim, cfg.scene). - if _is_preset_cfg(cfg): - cfg = cfg.default - # Resolve any PresetCfg wrappers to their default preset so the config # is usable without a Hydra CLI override (e.g. in tests). # Must happen BEFORE attribute overrides, otherwise overrides on PresetCfg wrapper # fields (e.g. cfg.scene when scene is a PresetCfg) get discarded when the wrapper # is replaced by its .default. - _resolve_presets_to_default(cfg) + cfg = resolve_preset_defaults(cfg) # simulation device cfg.sim.device = device diff --git a/source/isaaclab_tasks/isaaclab_tasks/utils/sim_launcher.py b/source/isaaclab_tasks/isaaclab_tasks/utils/sim_launcher.py index cfb361ed877e..1296873b1537 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/utils/sim_launcher.py +++ b/source/isaaclab_tasks/isaaclab_tasks/utils/sim_launcher.py @@ -201,10 +201,15 @@ def launch_simulation( " See https://isaac-sim.github.io/IsaacLab/main/source/setup/installation for details.\n" ) raise SystemExit(1) - from isaaclab.app import AppLauncher - app_launcher = AppLauncher(launcher_args) - close_fn = app_launcher.app.close + # If the simulation app is not launched, we launch it. + from isaaclab.utils import has_kit + + if not has_kit(): + from isaaclab.app import AppLauncher + + app_launcher = AppLauncher(launcher_args) + close_fn = app_launcher.app.close elif visualizer_types: # Newton path without Kit: AppLauncher is skipped, so manually store the visualizer # selection in SettingsManager (works in standalone mode via plain dict) so that diff --git a/source/isaaclab_tasks/test/benchmarking/configs.yaml b/source/isaaclab_tasks/test/benchmarking/configs.yaml index 6dd6c7b66f14..7a7a0aa49945 100644 --- a/source/isaaclab_tasks/test/benchmarking/configs.yaml +++ b/source/isaaclab_tasks/test/benchmarking/configs.yaml @@ -32,7 +32,7 @@ fast: reward: 45 episode_length: 900 upper_thresholds: - duration: 1000 #750 + duration: 1200 #750 skrl:Isaac-Cartpole-RGB-Camera-Direct-v0: max_iterations: 50 lower_thresholds: @@ -76,12 +76,12 @@ fast: upper_thresholds: duration: 2000 rsl_rl:Isaac-Dexsuite-Kuka-Allegro-Lift-v0: - max_iterations: 200 + max_iterations: 300 # 200 lower_thresholds: - reward: 0.7 + reward: 0.4 # 0.7 episode_length: 150 upper_thresholds: - duration: 1200 + duration: 1400 #1200 rsl_rl:Isaac-Reach-OpenArm-v0: max_iterations: 200 lower_thresholds: diff --git a/source/isaaclab_tasks/test/benchmarking/conftest.py b/source/isaaclab_tasks/test/benchmarking/conftest.py index a9ba2c1727ba..51096c6de144 100644 --- a/source/isaaclab_tasks/test/benchmarking/conftest.py +++ b/source/isaaclab_tasks/test/benchmarking/conftest.py @@ -4,6 +4,7 @@ # SPDX-License-Identifier: BSD-3-Clause import json +import os from datetime import datetime import pytest @@ -87,6 +88,21 @@ def kpi_store(): return GLOBAL_KPI_STORE # Using global variable for storing KPI data +# Shard parametrized test items across parallel CI jobs. +# Reads the same TEST_SHARD_INDEX / TEST_SHARD_COUNT env vars used by tools/conftest.py +# for file-level sharding, but applies them at the test-item level so a single +# parametrized file can be split across multiple runners. +# This is a pytest hook — pytest calls it automatically during test collection. +def pytest_collection_modifyitems(config, items): + shard_index = os.environ.get("TEST_SHARD_INDEX", "") + shard_count = os.environ.get("TEST_SHARD_COUNT", "") + if shard_index and shard_count: + shard_index = int(shard_index) + shard_count = int(shard_count) + items[:] = [item for i, item in enumerate(items) if i % shard_count == shard_index] + print(f"Shard {shard_index}/{shard_count}: selected {len(items)} test items") + + # This hook dynamically generates test cases based on the --workflows option. # For any test that includes a 'workflow' fixture, this will parametrize it # with all values passed via the command line option --workflows. diff --git a/source/isaaclab_tasks/test/env_test_utils.py b/source/isaaclab_tasks/test/env_test_utils.py index 8a3ee68b1730..302051aaa538 100644 --- a/source/isaaclab_tasks/test/env_test_utils.py +++ b/source/isaaclab_tasks/test/env_test_utils.py @@ -20,7 +20,8 @@ from isaaclab.sim import SimulationContext from isaaclab.utils.version import get_isaac_sim_version -from isaaclab_tasks.utils.parse_cfg import apply_named_preset, load_cfg_from_registry, parse_env_cfg +from isaaclab_tasks.utils.hydra import apply_overrides, collect_presets +from isaaclab_tasks.utils.parse_cfg import load_cfg_from_registry, parse_env_cfg def _is_teleop_env(task_spec) -> bool: @@ -326,21 +327,12 @@ def _check_random_actions( # apply physics preset override before creating the environment if physics_preset_name is not None: # parse_env_cfg already resolved PresetCfg wrappers to their default, - # so we load the raw config to retrieve the named preset. + # so we load the raw config to retrieve preset alternatives. raw_cfg = load_cfg_from_registry(task_name, "env_cfg_entry_point") - # Unwrap if the top-level cfg is itself a PresetCfg wrapper. - raw_env_cfg = raw_cfg - if ( - not isinstance(raw_cfg, dict) - and hasattr(raw_cfg, "__dataclass_fields__") - and hasattr(raw_cfg, "default") - and not hasattr(type(raw_cfg), "class_type") - ): - raw_env_cfg = raw_cfg.default - # Apply the named preset to all preset wrappers in the config tree - # (e.g. sim.physics, scene.contact_forces, ...), not just sim.physics. - apply_named_preset(env_cfg, raw_env_cfg, physics_preset_name) - # Re-apply num_envs since apply_named_preset may have replaced + presets = {"env": collect_presets(raw_cfg), "agent": {}} + hydra_cfg = {"env": env_cfg.to_dict(), "agent": None} + apply_overrides(env_cfg, None, hydra_cfg, [physics_preset_name], [], [], presets) + # Re-apply num_envs since apply_overrides may have replaced # the scene config with the preset's default num_envs. if num_envs is not None: env_cfg.scene.num_envs = num_envs @@ -354,12 +346,16 @@ def _check_random_actions( if not hasattr(env_cfg, "possible_agents"): print(f"[INFO]: Skipping {task_name} as it is not a multi-agent task") return - env = gym.make(task_name, cfg=env_cfg) else: if hasattr(env_cfg, "possible_agents"): print(f"[INFO]: Skipping {task_name} as it is a multi-agent task") return - env = gym.make(task_name, cfg=env_cfg) + + # TODO: Some Newton preset + multi-asset spawning combinations fail config validation + # here with a ValueError. Consider filtering invalid combinations in setup_environment() + # rather than forgiving them at runtime. See PR #5097 commit fb2c74a3862 for a workaround + # that caught the error and called pytest.skip(). + env = gym.make(task_name, cfg=env_cfg) # disable control on stop env.unwrapped.sim._app_control_on_stop_handle = None # type: ignore diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-albedo.png new file mode 100644 index 000000000000..3b9171317d27 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-albedo.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-depth.png new file mode 100644 index 000000000000..23ed0b8caf92 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-rgb.png new file mode 100644 index 000000000000..3903c0b188af Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-rgba.png new file mode 100644 index 000000000000..1967cc7c7377 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-semantic_segmentation.png new file mode 100644 index 000000000000..12469f4e2947 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-semantic_segmentation.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png new file mode 100644 index 000000000000..ab71635ef193 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png new file mode 100644 index 000000000000..c867ab76d958 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png new file mode 100644 index 000000000000..1a3070d49e74 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-depth.png new file mode 100644 index 000000000000..9c88304d807e Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-rgb.png new file mode 100644 index 000000000000..aa03d9a1f532 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-rgba.png new file mode 100644 index 000000000000..6f651277cdd3 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/newton-newton_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-albedo.png new file mode 100644 index 000000000000..3b9171317d27 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-albedo.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-depth.png new file mode 100644 index 000000000000..23ed0b8caf92 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-rgb.png new file mode 100644 index 000000000000..d4cf16ce0285 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-rgba.png new file mode 100644 index 000000000000..c23f9f7dba2b Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-semantic_segmentation.png new file mode 100644 index 000000000000..12469f4e2947 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-semantic_segmentation.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png new file mode 100644 index 000000000000..ab71635ef193 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png new file mode 100644 index 000000000000..c867ab76d958 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png new file mode 100644 index 000000000000..1a3070d49e74 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-depth.png new file mode 100644 index 000000000000..9c88304d807e Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-rgb.png new file mode 100644 index 000000000000..aa03d9a1f532 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-rgba.png new file mode 100644 index 000000000000..6f651277cdd3 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/cartpole/physx-newton_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-albedo.png new file mode 100644 index 000000000000..c4c74f54c032 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-albedo.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-depth.png new file mode 100644 index 000000000000..0d48cb12328b Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-rgb.png new file mode 100644 index 000000000000..b6c650a41aea Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-rgba.png new file mode 100644 index 000000000000..adc66ee5ca88 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-semantic_segmentation.png new file mode 100644 index 000000000000..7d3533042777 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-semantic_segmentation.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png new file mode 100644 index 000000000000..f89a822583b7 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png new file mode 100644 index 000000000000..ed90ba5fed41 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png new file mode 100644 index 000000000000..1e6ac83d94d3 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-depth.png new file mode 100644 index 000000000000..2e8934284fcf Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-rgb.png new file mode 100644 index 000000000000..067d3c3277a9 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-rgba.png new file mode 100644 index 000000000000..6714615485fe Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/newton-newton_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-albedo.png new file mode 100644 index 000000000000..33718481e958 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-albedo.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-depth.png new file mode 100644 index 000000000000..6ff279f3d019 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-rgb.png new file mode 100644 index 000000000000..02033af50aa7 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-rgba.png new file mode 100644 index 000000000000..962b0bd5c66a Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-semantic_segmentation.png new file mode 100644 index 000000000000..2d375d0fa8a5 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-semantic_segmentation.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png new file mode 100644 index 000000000000..d4d0bb1d03bc Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png new file mode 100644 index 000000000000..82139997de76 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png new file mode 100644 index 000000000000..49454e82c0f0 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-depth.png new file mode 100644 index 000000000000..795098c6f2ea Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-rgb.png new file mode 100644 index 000000000000..16fd16743757 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-rgba.png new file mode 100644 index 000000000000..f153f224f119 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/dexsuite_kuka/physx-newton_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Albedo-Camera-Direct-v0/default_physics-default_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Albedo-Camera-Direct-v0/default_physics-default_renderer-albedo.png new file mode 100644 index 000000000000..6c0fba167232 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Albedo-Camera-Direct-v0/default_physics-default_renderer-albedo.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Presets-Direct-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Presets-Direct-v0/default_physics-default_renderer-rgb.png new file mode 100644 index 000000000000..d4cf16ce0285 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Presets-Direct-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Presets-Direct-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Presets-Direct-v0/default_physics-default_renderer-rgba.png new file mode 100644 index 000000000000..c23f9f7dba2b Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Presets-Direct-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-Box-Direct-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-Box-Direct-v0/default_physics-default_renderer-rgb.png new file mode 100644 index 000000000000..d4cf16ce0285 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-Box-Direct-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-Box-Direct-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-Box-Direct-v0/default_physics-default_renderer-rgba.png new file mode 100644 index 000000000000..c23f9f7dba2b Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-Box-Direct-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-Discrete-Direct-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-Discrete-Direct-v0/default_physics-default_renderer-rgb.png new file mode 100644 index 000000000000..58277556c375 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-Discrete-Direct-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-Discrete-Direct-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-Discrete-Direct-v0/default_physics-default_renderer-rgba.png new file mode 100644 index 000000000000..236500f98337 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-Discrete-Direct-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgb.png new file mode 100644 index 000000000000..3d3ee5e862c2 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgba.png new file mode 100644 index 000000000000..cd506a629d26 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Box-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-Box-Direct-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-Box-Direct-v0/default_physics-default_renderer-rgb.png new file mode 100644 index 000000000000..d4cf16ce0285 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-Box-Direct-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-Box-Direct-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-Box-Direct-v0/default_physics-default_renderer-rgba.png new file mode 100644 index 000000000000..c23f9f7dba2b Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-Box-Direct-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-Discrete-Direct-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-Discrete-Direct-v0/default_physics-default_renderer-rgb.png new file mode 100644 index 000000000000..d4cf16ce0285 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-Discrete-Direct-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-Discrete-Direct-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-Discrete-Direct-v0/default_physics-default_renderer-rgba.png new file mode 100644 index 000000000000..c23f9f7dba2b Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-Discrete-Direct-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgb.png new file mode 100644 index 000000000000..58277556c375 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgba.png new file mode 100644 index 000000000000..236500f98337 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Dict-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-Box-Direct-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-Box-Direct-v0/default_physics-default_renderer-rgb.png new file mode 100644 index 000000000000..58277556c375 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-Box-Direct-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-Box-Direct-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-Box-Direct-v0/default_physics-default_renderer-rgba.png new file mode 100644 index 000000000000..236500f98337 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-Box-Direct-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-Discrete-Direct-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-Discrete-Direct-v0/default_physics-default_renderer-rgb.png new file mode 100644 index 000000000000..39082290e49a Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-Discrete-Direct-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-Discrete-Direct-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-Discrete-Direct-v0/default_physics-default_renderer-rgba.png new file mode 100644 index 000000000000..962625b9aaff Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-Discrete-Direct-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgb.png new file mode 100644 index 000000000000..d4cf16ce0285 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgba.png new file mode 100644 index 000000000000..c23f9f7dba2b Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Camera-Showcase-Tuple-MultiDiscrete-Direct-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Depth-Camera-Direct-v0/default_physics-default_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Depth-Camera-Direct-v0/default_physics-default_renderer-depth.png new file mode 100644 index 000000000000..23ed0b8caf92 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Depth-Camera-Direct-v0/default_physics-default_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Depth-v0/default_physics-default_renderer-distance_to_camera.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Depth-v0/default_physics-default_renderer-distance_to_camera.png new file mode 100644 index 000000000000..742eedd33c55 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-Depth-v0/default_physics-default_renderer-distance_to_camera.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-Camera-Direct-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-Camera-Direct-v0/default_physics-default_renderer-rgb.png new file mode 100644 index 000000000000..58277556c375 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-Camera-Direct-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-Camera-Direct-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-Camera-Direct-v0/default_physics-default_renderer-rgba.png new file mode 100644 index 000000000000..236500f98337 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-Camera-Direct-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-ResNet18-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-ResNet18-v0/default_physics-default_renderer-rgb.png new file mode 100644 index 000000000000..f81e83eed6c1 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-ResNet18-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-ResNet18-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-ResNet18-v0/default_physics-default_renderer-rgba.png new file mode 100644 index 000000000000..3be5c0c83574 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-ResNet18-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-v0/default_physics-default_renderer-rgb.png new file mode 100644 index 000000000000..46adb81bb32e Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-v0/default_physics-default_renderer-rgba.png new file mode 100644 index 000000000000..2bcc5c7dceb8 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-RGB-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Constant-Camera-Direct-v0/default_physics-default_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Constant-Camera-Direct-v0/default_physics-default_renderer-simple_shading_constant_diffuse.png new file mode 100644 index 000000000000..d09fea61de88 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Constant-Camera-Direct-v0/default_physics-default_renderer-simple_shading_constant_diffuse.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Diffuse-Camera-Direct-v0/default_physics-default_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Diffuse-Camera-Direct-v0/default_physics-default_renderer-simple_shading_diffuse_mdl.png new file mode 100644 index 000000000000..35a1c6eac380 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Diffuse-Camera-Direct-v0/default_physics-default_renderer-simple_shading_diffuse_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Full-Camera-Direct-v0/default_physics-default_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Full-Camera-Direct-v0/default_physics-default_renderer-simple_shading_full_mdl.png new file mode 100644 index 000000000000..bb4eaefdcc89 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Cartpole-SimpleShading-Full-Camera-Direct-v0/default_physics-default_renderer-simple_shading_full_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-depth.png new file mode 100644 index 000000000000..d135266690c2 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-rgb.png new file mode 100644 index 000000000000..c1c531c39b7c Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-rgba.png new file mode 100644 index 000000000000..f83f024517e8 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-semantic_segmentation.png new file mode 100644 index 000000000000..185cbe5190ec Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/registered_tasks/Isaac-Repose-Cube-Shadow-Vision-Direct-v0/default_physics-default_renderer-semantic_segmentation.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-albedo.png new file mode 100644 index 000000000000..efa37a53e49b Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-albedo.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-depth.png new file mode 100644 index 000000000000..eb7a6d5e55d4 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-rgb.png new file mode 100644 index 000000000000..d79c4affd992 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-rgba.png new file mode 100644 index 000000000000..6b701861908c Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-semantic_segmentation.png new file mode 100644 index 000000000000..0e60f14b01b4 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-semantic_segmentation.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png new file mode 100644 index 000000000000..5e3fc754b799 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png new file mode 100644 index 000000000000..124b5e47b16a Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png new file mode 100644 index 000000000000..c47289017e5f Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-isaacsim_rtx_renderer-simple_shading_full_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-depth.png new file mode 100644 index 000000000000..810289bdd6ea Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-rgb.png new file mode 100644 index 000000000000..3e340a63c413 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-rgba.png new file mode 100644 index 000000000000..39fc8d068c1e Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/newton-newton_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-albedo.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-albedo.png new file mode 100644 index 000000000000..5c1d2531e2a8 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-albedo.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-depth.png new file mode 100644 index 000000000000..33f852e09960 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-rgb.png new file mode 100644 index 000000000000..2194bdd57ce8 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-rgba.png new file mode 100644 index 000000000000..31175c261484 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-semantic_segmentation.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-semantic_segmentation.png new file mode 100644 index 000000000000..185cbe5190ec Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-semantic_segmentation.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png new file mode 100644 index 000000000000..06843af19e24 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_constant_diffuse.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png new file mode 100644 index 000000000000..93892b00b34b Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_diffuse_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png new file mode 100644 index 000000000000..5f72997b5bf1 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-isaacsim_rtx_renderer-simple_shading_full_mdl.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-depth.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-depth.png new file mode 100644 index 000000000000..716b813f740a Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-depth.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-rgb.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-rgb.png new file mode 100644 index 000000000000..d71efd556cfb Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-rgb.png differ diff --git a/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-rgba.png b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-rgba.png new file mode 100644 index 000000000000..9a7b23dcabf8 Binary files /dev/null and b/source/isaaclab_tasks/test/golden_images/shadow_hand/physx-newton_renderer-rgba.png differ diff --git a/source/isaaclab_tasks/test/test_environments_newton.py b/source/isaaclab_tasks/test/test_environments_newton.py index 909f836ce716..8f0ae09e3496 100644 --- a/source/isaaclab_tasks/test/test_environments_newton.py +++ b/source/isaaclab_tasks/test/test_environments_newton.py @@ -36,6 +36,14 @@ ), ) @pytest.mark.newton_ci +@pytest.mark.xfail( + reason=( + "TODO: Nested PresetCfg resolution for named presets (e.g. 'newton') is not yet supported. " + "The logic in parse_cfg.apply_named_preset should be unified with the deep-nesting " + "fixes in https://github.com/isaac-sim/IsaacLab/pull/5029 (isaaclab_tasks.utils.hydra)." + ), + strict=False, +) def test_environments_newton(task_name, num_envs, device): # run environments with newton physics preset _run_environments(task_name, device, num_envs, physics_preset_name="newton", create_stage_in_memory=False) diff --git a/source/isaaclab_tasks/test/test_hydra.py b/source/isaaclab_tasks/test/test_hydra.py index 64930b00bdad..20e79bac54a8 100644 --- a/source/isaaclab_tasks/test/test_hydra.py +++ b/source/isaaclab_tasks/test/test_hydra.py @@ -700,3 +700,416 @@ class EnvCfgFactory: assert presets["robot.actuators.legs.armature"]["default"] == 0.0 assert presets["robot.actuators.legs.armature"]["newton"] == 0.01 assert presets["robot.actuators.legs.armature"]["physx"] == 0.0 + + +# ============================================================================= +# Tests: PresetCfg inside deeply nested dicts (e.g., event term params) +# ============================================================================= + + +@configclass +class OffsetCfg(PresetCfg): + """Mimics task-specific offset presets (e.g., AssembledOffsetCfg).""" + + task_a: tuple = (0.0, 0.0, 0.01) + task_b: tuple = (0.02, 0.0, 0.005) + default: tuple = task_a + + +@configclass +class FractionCfg(PresetCfg): + task_a: tuple = (0.05, 0.5) + task_b: tuple = (0.3, 1.0) + default: tuple = task_a + + +@configclass +class InnerTermCfg: + """Mimics an EventTermCfg with params containing presets.""" + + func: str = "reset_fn" + params: dict = None + + def __post_init__(self): + if self.params is None: + self.params = { + "offset": OffsetCfg(), + "fraction": FractionCfg(), + } + + +@configclass +class OuterTermCfg: + """Mimics a chained reset term with nested terms dict.""" + + func: str = "chain_fn" + params: dict = None + + def __post_init__(self): + if self.params is None: + self.params = { + "terms": { + "step_one": InnerTermCfg(), + } + } + + +@configclass +class DeepDictEnvCfg: + decimation: int = 4 + events: OuterTermCfg = OuterTermCfg() + + +def test_collect_presets_deep_nested_dicts(): + """collect_presets discovers PresetCfg inside dict→dict→configclass→dict chains.""" + cfg = DeepDictEnvCfg() + presets = collect_presets(cfg) + offset_path = "events.params.terms.step_one.params.offset" + fraction_path = "events.params.terms.step_one.params.fraction" + assert offset_path in presets, f"Expected '{offset_path}' in {list(presets.keys())}" + assert fraction_path in presets, f"Expected '{fraction_path}' in {list(presets.keys())}" + assert presets[offset_path]["task_a"] == (0.0, 0.0, 0.01) + assert presets[offset_path]["task_b"] == (0.02, 0.0, 0.005) + assert presets[fraction_path]["task_a"] == (0.05, 0.5) + assert presets[fraction_path]["task_b"] == (0.3, 1.0) + + +def test_resolve_preset_defaults_deep_nested_dicts(): + """resolve_preset_defaults resolves presets inside deeply nested dicts.""" + cfg = DeepDictEnvCfg() + resolved = resolve_preset_defaults(cfg) + inner = resolved.events.params["terms"]["step_one"] + assert inner.params["offset"] == (0.0, 0.0, 0.01) + assert inner.params["fraction"] == (0.05, 0.5) + assert not isinstance(inner.params["offset"], PresetCfg) + assert not isinstance(inner.params["fraction"], PresetCfg) + + +def test_deep_nested_dict_auto_default(): + """Deeply nested dict presets auto-apply default when no CLI override.""" + env_cfg = DeepDictEnvCfg() + agent_cfg = PresetCfgAgentCfg() + presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} + env_cfg = resolve_preset_defaults(env_cfg) + agent_cfg = resolve_preset_defaults(agent_cfg) + hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} + apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], [], [], presets) + inner = env_cfg.events.params["terms"]["step_one"] + assert inner.params["offset"] == (0.0, 0.0, 0.01) + assert inner.params["fraction"] == (0.05, 0.5) + + +def test_deep_nested_dict_global_preset(): + """Global preset=task_b replaces deeply nested dict presets.""" + env_cfg = DeepDictEnvCfg() + agent_cfg = PresetCfgAgentCfg() + presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} + env_cfg = resolve_preset_defaults(env_cfg) + agent_cfg = resolve_preset_defaults(agent_cfg) + hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} + apply_overrides(env_cfg, agent_cfg, hydra_cfg, ["task_b"], [], [], presets) + inner = env_cfg.events.params["terms"]["step_one"] + assert inner.params["offset"] == (0.02, 0.0, 0.005), f"offset should be task_b value, got {inner.params['offset']}" + assert inner.params["fraction"] == (0.3, 1.0), f"fraction should be task_b value, got {inner.params['fraction']}" + + +def test_deep_nested_dict_path_selection(): + """Path selection replaces a specific deeply nested dict preset.""" + env_cfg = DeepDictEnvCfg() + agent_cfg = PresetCfgAgentCfg() + presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} + env_cfg = resolve_preset_defaults(env_cfg) + agent_cfg = resolve_preset_defaults(agent_cfg) + hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} + sel = [("env", "events.params.terms.step_one.params.offset", "task_b")] + apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], sel, [], presets) + inner = env_cfg.events.params["terms"]["step_one"] + assert inner.params["offset"] == (0.02, 0.0, 0.005) + assert inner.params["fraction"] == (0.05, 0.5) # untouched + + +def test_deep_nested_dict_mixed_global_and_path(): + """Global preset applies to nested dicts, path selection overrides one.""" + env_cfg = DeepDictEnvCfg() + agent_cfg = PresetCfgAgentCfg() + presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} + env_cfg = resolve_preset_defaults(env_cfg) + agent_cfg = resolve_preset_defaults(agent_cfg) + hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} + sel = [("env", "events.params.terms.step_one.params.fraction", "task_a")] + apply_overrides(env_cfg, agent_cfg, hydra_cfg, ["task_b"], sel, [], presets) + inner = env_cfg.events.params["terms"]["step_one"] + assert inner.params["offset"] == (0.02, 0.0, 0.005) # from global task_b + assert inner.params["fraction"] == (0.05, 0.5) # path override keeps task_a + + +# ============================================================================= +# Tests: preset() factory function +# ============================================================================= + + +def test_preset_factory_creates_presetcfg(): + """preset() returns a PresetCfg subclass instance with correct fields.""" + p = preset(default=0.0, high=1.0, low=-1.0) + assert isinstance(p, PresetCfg) + assert p.default == 0.0 + assert p.high == 1.0 + assert p.low == -1.0 + + +def test_preset_factory_collectable(): + """preset()-created instances are discovered by collect_presets.""" + + @configclass + class FactoryEnvCfg: + damping: object = None + + def __post_init__(self): + if self.damping is None: + self.damping = preset(default=5.0, high=20.0) + + cfg = FactoryEnvCfg() + presets = collect_presets(cfg) + assert "damping" in presets + assert presets["damping"]["default"] == 5.0 + assert presets["damping"]["high"] == 20.0 + + +def test_preset_factory_requires_default(): + """preset() raises ValueError when 'default' is not provided.""" + with pytest.raises(ValueError, match="default"): + preset(high=1.0, low=-1.0) + + +def test_preset_factory_string_values(): + """preset() works with string values.""" + p = preset(default="cpu", gpu="cuda:0") + assert isinstance(p, PresetCfg) + assert p.default == "cpu" + assert p.gpu == "cuda:0" + + +# ============================================================================= +# Tests: _collect_fields class-vs-instance priority +# ============================================================================= + + +def test_collect_fields_prefers_class_attr_over_instance(): + """Class-level attr mutations take priority over instance attrs in collection. + + This mirrors the pattern where robot-specific modules (e.g., joint_pos_env_cfg.py) + mutate PresetCfg class attributes after instances are already created. + """ + + @configclass + class MutablePresetCfg(PresetCfg): + default: str = "original_default" + alt: str = "alternative" + + instance = MutablePresetCfg() + assert instance.default == "original_default" + + MutablePresetCfg.default = "robot_specific_default" + + presets = collect_presets(instance) + assert "" in presets + assert presets[""]["default"] == "robot_specific_default" + + MutablePresetCfg.default = "original_default" + + +def test_collect_fields_includes_dynamic_class_attrs(): + """Fields added to PresetCfg class at runtime are discovered.""" + + @configclass + class ExtensiblePresetCfg(PresetCfg): + default: str = "base" + alt_a: str = "a" + + ExtensiblePresetCfg.alt_b = "b" + + instance = ExtensiblePresetCfg() + presets = collect_presets(instance) + assert "" in presets + assert "alt_b" in presets[""] + assert presets[""]["alt_b"] == "b" + + delattr(ExtensiblePresetCfg, "alt_b") + + +# ============================================================================= +# Tests: apply_overrides error handling +# ============================================================================= + + +def test_apply_overrides_unknown_preset_group_raises(): + """apply_overrides raises ValueError for unknown preset group paths.""" + env_cfg = PresetCfgEnvCfg() + agent_cfg = PresetCfgAgentCfg() + presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} + hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} + with pytest.raises(ValueError, match="Unknown preset group"): + apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], [("env", "nonexistent", "val")], [], presets) + + +def test_apply_overrides_unknown_preset_name_raises(): + """apply_overrides raises ValueError for unknown preset name.""" + env_cfg = PresetCfgEnvCfg() + agent_cfg = PresetCfgAgentCfg() + presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} + hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} + with pytest.raises(ValueError, match="Unknown preset 'nonexistent'"): + apply_overrides(env_cfg, agent_cfg, hydra_cfg, [], [("env", "backend", "nonexistent")], [], presets) + + +def test_apply_overrides_conflicting_globals_raises(): + """Two global presets matching the same path cause ValueError.""" + + @configclass + class TwoAltsPresetCfg(PresetCfg): + default: str = "d" + opt_a: str = "a" + opt_b: str = "b" + + @configclass + class ConflictEnvCfg: + mode: TwoAltsPresetCfg = TwoAltsPresetCfg() + + env_cfg = ConflictEnvCfg() + agent_cfg = PresetCfgAgentCfg() + presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} + hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} + with pytest.raises(ValueError, match="Conflicting global presets"): + apply_overrides(env_cfg, agent_cfg, hydra_cfg, ["opt_a", "opt_b"], [], [], presets) + + +def test_apply_overrides_aliased_globals_no_conflict(): + """Two global presets resolving to equal values do not raise. + + Mirrors the dexsuite ObjectCfg pattern where ``newton = cube`` creates + separate but equal dataclass instances after @configclass processing. + """ + + @configclass + class SharedCfg: + value: int = 42 + + cube_val = SharedCfg() + newton_val = SharedCfg() + + @configclass + class AliasedPresetCfg(PresetCfg): + default: str = "d" + cube: SharedCfg = cube_val + newton: SharedCfg = newton_val + + @configclass + class AliasedEnvCfg: + mode: AliasedPresetCfg = AliasedPresetCfg() + + env_cfg = AliasedEnvCfg() + agent_cfg = PresetCfgAgentCfg() + presets = {"env": collect_presets(env_cfg), "agent": collect_presets(agent_cfg)} + assert presets["env"]["mode"]["cube"] is not presets["env"]["mode"]["newton"] + assert presets["env"]["mode"]["cube"] == presets["env"]["mode"]["newton"] + hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} + apply_overrides(env_cfg, agent_cfg, hydra_cfg, ["cube", "newton"], [], [], presets) + assert env_cfg.mode == SharedCfg() + + +# ============================================================================= +# Tests: parse_overrides edge cases +# ============================================================================= + + +def test_parse_overrides_multiple_global_presets(): + """Multiple comma-separated global presets are split correctly.""" + presets = {"env": {"backend": {"default": None, "newton": None}}, "agent": {}} + global_p, _, _, _ = parse_overrides(["presets=fast,newton,debug"], presets) + assert global_p == ["fast", "newton", "debug"] + + +def test_parse_overrides_no_equals_treated_as_global_scalar(): + """Arguments without '=' are passed through as global scalars.""" + presets = {"env": {}, "agent": {}} + _, _, _, global_scalar = parse_overrides(["--flag", "positional"], presets) + assert "--flag" in global_scalar + assert "positional" in global_scalar + + +def test_parse_overrides_preset_scalar_detection(): + """Scalar within a preset path is detected as preset_scalar.""" + presets = {"env": {"backend": {"default": None}}, "agent": {}} + _, _, preset_scalar, _ = parse_overrides(["env.backend.dt=0.001", "env.backend.substeps=4"], presets) + assert ("env.backend.dt", "0.001") in preset_scalar + assert ("env.backend.substeps", "4") in preset_scalar + + +def test_parse_overrides_root_level_env_preset(): + """Root-level PresetCfg (path='') makes env= a valid preset selection.""" + presets = {"env": {"": {"default": None, "fast": None}}, "agent": {}} + _, sel, _, _ = parse_overrides(["env=fast"], presets) + assert sel == [("env", "", "fast")] + + +# ============================================================================= +# Tests: _parse_val +# ============================================================================= + + +def test_parse_val_types(): + """_parse_val converts strings to correct Python types.""" + from isaaclab_tasks.utils.hydra import _parse_val + + assert _parse_val("true") is True + assert _parse_val("True") is True + assert _parse_val("false") is False + assert _parse_val("none") is None + assert _parse_val("null") is None + assert _parse_val("42") == 42 + assert isinstance(_parse_val("42"), int) + assert _parse_val("3.14") == 3.14 + assert isinstance(_parse_val("3.14"), float) + assert _parse_val("hello") == "hello" + assert _parse_val('"quoted"') == "quoted" + assert _parse_val("'single'") == "single" + + +# ============================================================================= +# Tests: scalar override within preset path +# ============================================================================= + + +def test_scalar_override_within_preset_path(class_presets): + """Scalar overrides within preset paths are applied on top of the preset.""" + env_cfg, agent_cfg, presets = class_presets + env_cfg = resolve_preset_defaults(env_cfg) + agent_cfg = resolve_preset_defaults(agent_cfg) + hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()} + apply_overrides( + env_cfg, + agent_cfg, + hydra_cfg, + [], + [("env", "backend", "newton")], + [("env.backend.dt", "0.001")], + presets, + ) + assert isinstance(env_cfg.backend, NewtonCfg) + assert env_cfg.backend.dt == 0.001 # overridden from 0.002 + assert env_cfg.backend.substeps == 4 # untouched + + +# ============================================================================= +# Tests: resolve_preset_defaults idempotency +# ============================================================================= + + +def test_resolve_preset_defaults_idempotent(): + """Calling resolve_preset_defaults twice yields the same result.""" + cfg = PresetCfgEnvCfg() + first = resolve_preset_defaults(cfg) + second = resolve_preset_defaults(first) + assert isinstance(second.backend, PhysxCfg) + assert isinstance(second.observations, NoiselessObservationsCfg) + assert second.backend.dt == first.backend.dt diff --git a/source/isaaclab_tasks/test/test_lazy_export_stubs.py b/source/isaaclab_tasks/test/test_lazy_export_stubs.py index 7a13dba6c6b0..b7e9a824d727 100644 --- a/source/isaaclab_tasks/test/test_lazy_export_stubs.py +++ b/source/isaaclab_tasks/test/test_lazy_export_stubs.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Verify that lazy_export() call sites use no arguments. +"""Verify lazy_export() call-site conventions and _parse_stub behaviour. Every ``__init__.py`` that calls ``lazy_export()`` should pass no arguments. Fallback packages and wildcard re-exports are inferred from the ``.pyi`` @@ -15,10 +15,13 @@ import ast import os +import tempfile from pathlib import Path import pytest +from isaaclab.utils.module import _parse_stub + _SOURCE_ROOT = Path(__file__).resolve().parent.parent.parent @@ -80,3 +83,126 @@ def test_no_lazy_export_violations_found(): if f == "__init__.py" and "lazy_export" in (Path(root) / f).read_text(errors="ignore") ) assert init_count > 0, "No __init__.py files with lazy_export() found — discovery may be broken" + + +# --------------------------------------------------------------------------- +# _parse_stub unit tests +# --------------------------------------------------------------------------- + + +def _write_stub(content: str) -> str: + """Write *content* to a temporary ``.pyi`` file and return its path.""" + fd, path = tempfile.mkstemp(suffix=".pyi") + with os.fdopen(fd, "w") as f: + f.write(content) + return path + + +def test_parse_stub_single_absolute_named_import(): + """Test single absolute named import extraction.""" + stub = _write_stub("from some.package import alpha, beta\n") + try: + _, _, _, absolute_named = _parse_stub(stub) + finally: + os.unlink(stub) + + assert "some.package" in absolute_named + assert absolute_named["some.package"] == ["alpha", "beta"] + + +def test_parse_stub_multiple_absolute_named_imports(): + """Test multiple absolute named imports from different packages.""" + stub = _write_stub("from pkg_a import foo\nfrom pkg_b import bar, baz\n") + try: + _, _, _, absolute_named = _parse_stub(stub) + finally: + os.unlink(stub) + + assert absolute_named["pkg_a"] == ["foo"] + assert absolute_named["pkg_b"] == ["bar", "baz"] + + +def test_parse_stub_same_package_multiple_lines_accumulates(): + """Test that imports from the same package on multiple lines accumulate.""" + stub = _write_stub("from pkg import a\nfrom pkg import b, c\n") + try: + _, _, _, absolute_named = _parse_stub(stub) + finally: + os.unlink(stub) + + assert absolute_named["pkg"] == ["a", "b", "c"] + + +def test_parse_stub_absolute_wildcard_not_in_absolute_named(): + """Test that absolute wildcard imports go to fallbacks, not absolute_named.""" + stub = _write_stub("from some.package import *\n") + try: + _, fallbacks, _, absolute_named = _parse_stub(stub) + finally: + os.unlink(stub) + + assert "some.package" in fallbacks + assert absolute_named == {} + + +def test_parse_stub_relative_import_not_in_absolute_named(): + """Test that relative imports are not included in absolute_named.""" + stub = _write_stub("from .sub import foo, bar\n") + try: + _, _, _, absolute_named = _parse_stub(stub) + finally: + os.unlink(stub) + + assert absolute_named == {} + + +def test_parse_stub_mixed_import_kinds(): + """All four import kinds in one stub are routed correctly.""" + stub = _write_stub( + "from .local import thing\nfrom .wildmod import *\nfrom abs.pkg import *\nfrom abs.other import x, y\n" + ) + try: + filtered_path, fallbacks, rel_wildcards, absolute_named = _parse_stub(stub) + finally: + if filtered_path is not None: + os.unlink(filtered_path) + os.unlink(stub) + + assert fallbacks == ["abs.pkg"] + assert rel_wildcards == ["wildmod"] + assert absolute_named == {"abs.other": ["x", "y"]} + assert filtered_path is not None + + +def test_parse_stub_no_imports_returns_empty(): + """Test that a stub with no imports returns empty collections.""" + stub = _write_stub("X: int\n") + try: + filtered_path, fallbacks, rel_wildcards, absolute_named = _parse_stub(stub) + finally: + os.unlink(stub) + + assert filtered_path is None + assert fallbacks == [] + assert rel_wildcards == [] + assert absolute_named == {} + + +def test_parse_stub_filtered_stub_excludes_absolute_named(): + """Absolute named imports must not leak into the filtered stub. + + The filtered stub is passed to lazy_loader which only handles relative named imports. + """ + stub = _write_stub("from .local import thing\nfrom abs.pkg import alpha\n") + try: + filtered_path, _, _, _ = _parse_stub(stub) + assert filtered_path is not None + with open(filtered_path) as f: + content = f.read() + assert "alpha" not in content + assert "abs" not in content + assert "thing" in content + finally: + if filtered_path is not None: + os.unlink(filtered_path) + os.unlink(stub) diff --git a/source/isaaclab_tasks/test/test_rendering_correctness.py b/source/isaaclab_tasks/test/test_rendering_correctness.py index 6f196ce38083..695f7dbfc2a6 100644 --- a/source/isaaclab_tasks/test/test_rendering_correctness.py +++ b/source/isaaclab_tasks/test/test_rendering_correctness.py @@ -6,9 +6,10 @@ """Tests for rendering correctness. Each test builds an environment with a given (physics_backend, renderer, data_type), -steps once, then asserts that camera outputs are not blank (at least one non-zero -pixel). Env-specific fixtures use parametrized combinations; a separate test -covers a list of registered task IDs that use camera-based observations. +steps once, then checks if camera outputs are not blank (at least one non-zero +pixel) and consistent with golden images. Env-specific fixtures use parametrized +combinations; a separate test covers a list of registered task IDs that use +camera-based observations. """ # Launch Isaac Sim Simulator first. @@ -17,11 +18,15 @@ app_launcher = AppLauncher(headless=True, enable_cameras=True) simulation_app = app_launcher.app -from typing import Any +import os # noqa: E402 +from datetime import datetime # noqa: E402 +from typing import Any # noqa: E402 import gymnasium as gym # noqa: E402 +import numpy as np # noqa: E402 import pytest # noqa: E402 import torch # noqa: E402 +from PIL import Image, ImageChops # noqa: E402 from isaaclab.envs.utils.spaces import sample_space # noqa: E402 from isaaclab.sim import SimulationContext # noqa: E402 @@ -33,6 +38,36 @@ ) from isaaclab_tasks.utils.parse_cfg import parse_env_cfg # noqa: E402 +# --------------------------------------------------------------------------- +# Constants +# --------------------------------------------------------------------------- + +# Directory containing golden images. +_GOLDEN_IMAGES_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), "golden_images") + +# Pixel L2 norm difference threshold. L2 norm difference is the Euclidean distance between two pixels: +# +# d = sqrt((R1 - R2)^2 + (G1 - G2)^2 + (B1 - B2)^2) +# +# If the difference between two pixels is less than this threshold, consider them "equal" (i.e. within the tolerance). +# +_PIXEL_L2_NORM_DIFFERENCE_THRESHOLD = 10.0 + +_OVRTX_DISABLED = pytest.mark.skip( + reason="OVRTX is optional and experimental feature and temporarily is excluded from testing." +) + +# Directory for comparison images saved during the test session. +# Located under the pytest output root so it gets copied alongside test reports. +_COMPARISON_IMAGES_DIR = os.path.join(os.getcwd(), "tests", "comparison-images") + +# Collects comparison scores from all golden-image comparisons during the session. +# Each entry: {"test": str, "backend": str, "renderer": str, "aov": str, +# "ssim": float, "diff_pct": float, "passed": bool, +# "img_result_path": str | None, "img_golden_path": str | None} +_COMPARISON_SCORES: list[dict] = [] + + # --------------------------------------------------------------------------- # Fixtures # --------------------------------------------------------------------------- @@ -52,19 +87,51 @@ def cleanup_simulation_context(): SimulationContext.clear_instance() +@pytest.fixture(scope="session", autouse=True) +def _generate_comparison_html_report(): + """Generate an HTML comparison report after all tests in the session complete.""" + yield + try: + _generate_html_report() + except Exception as exc: # noqa: BLE001 + import warnings + + warnings.warn(f"Failed to generate HTML comparison report: {exc}", stacklevel=1) + + +@pytest.fixture(autouse=True) +def _attach_comparison_properties(request): + """Attach pixel-diff, SSIM scores, and failure images as JUnit XML properties.""" + initial_count = len(_COMPARISON_SCORES) + yield + for entry in _COMPARISON_SCORES[initial_count:]: + label = f"{entry['backend']}-{entry['renderer']}-{entry['aov']}" + request.node.user_properties.append((f"diff_pct:{label}", f"{entry['diff_pct']:.2f}")) + request.node.user_properties.append((f"ssim:{label}", f"{entry['ssim']:.4f}")) + request.node.user_properties.append((f"threshold:{label}", f"{entry['threshold']:.1f}")) + if entry.get("img_result_path"): + request.node.user_properties.append((f"img_result:{label}", entry["img_result_path"])) + request.node.user_properties.append((f"img_golden:{label}", entry["img_golden_path"])) + + # --------------------------------------------------------------------------- # Parametrization: (physics_backend, renderer, data_type) # --------------------------------------------------------------------------- -_OVRTX_DISABLED = pytest.mark.skip( - reason="OVRTX is optional and experimental feature and temporarily is excluded from testing." -) - _PHYSICS_RENDERER_AOV_COMBINATIONS = [ # physx + isaacsim_rtx_renderer - pytest.param(("physx", "isaacsim_rtx_renderer", "rgb"), id="physx-isaacsim_rtx-rgb"), - pytest.param(("physx", "isaacsim_rtx_renderer", "albedo"), id="physx-isaacsim_rtx-albedo"), - pytest.param(("physx", "isaacsim_rtx_renderer", "depth"), id="physx-isaacsim_rtx-depth"), + pytest.param( + ("physx", "isaacsim_rtx_renderer", "rgb"), + id="physx-isaacsim_rtx-rgb", + ), + pytest.param( + ("physx", "isaacsim_rtx_renderer", "albedo"), + id="physx-isaacsim_rtx-albedo", + ), + pytest.param( + ("physx", "isaacsim_rtx_renderer", "depth"), + id="physx-isaacsim_rtx-depth", + ), pytest.param( ("physx", "isaacsim_rtx_renderer", "simple_shading_constant_diffuse"), id="physx-isaacsim_rtx-simple_shading_constant_diffuse", @@ -77,12 +144,28 @@ def cleanup_simulation_context(): ("physx", "isaacsim_rtx_renderer", "simple_shading_full_mdl"), id="physx-isaacsim_rtx-simple_shading_full_mdl", ), + pytest.param( + ("physx", "isaacsim_rtx_renderer", "semantic_segmentation"), + id="physx-isaacsim_rtx-semantic_segmentation", + ), # physx + newton_renderer (warp) - pytest.param(("physx", "newton_renderer", "rgb"), id="physx-newton_warp-rgb"), - pytest.param(("physx", "newton_renderer", "depth"), id="physx-newton_warp-depth"), + pytest.param( + ("physx", "newton_renderer", "rgb"), + id="physx-newton_warp-rgb", + ), + pytest.param( + ("physx", "newton_renderer", "depth"), + id="physx-newton_warp-depth", + ), # newton + isaacsim_rtx_renderer - pytest.param(("newton", "isaacsim_rtx_renderer", "rgb"), id="newton-isaacsim_rtx-rgb"), - pytest.param(("newton", "isaacsim_rtx_renderer", "albedo"), id="newton-isaacsim_rtx-albedo"), + pytest.param( + ("newton", "isaacsim_rtx_renderer", "rgb"), + id="newton-isaacsim_rtx-rgb", + ), + pytest.param( + ("newton", "isaacsim_rtx_renderer", "albedo"), + id="newton-isaacsim_rtx-albedo", + ), pytest.param( ("newton", "isaacsim_rtx_renderer", "depth"), id="newton-isaacsim_rtx-depth", @@ -99,8 +182,15 @@ def cleanup_simulation_context(): ("newton", "isaacsim_rtx_renderer", "simple_shading_full_mdl"), id="newton-isaacsim_rtx-simple_shading_full_mdl", ), + pytest.param( + ("newton", "isaacsim_rtx_renderer", "semantic_segmentation"), + id="newton-isaacsim_rtx-semantic_segmentation", + ), # newton + newton_renderer (warp) - pytest.param(("newton", "newton_renderer", "rgb"), id="newton-newton_warp-rgb"), + pytest.param( + ("newton", "newton_renderer", "rgb"), + id="newton-newton_warp-rgb", + ), pytest.param( ("newton", "newton_renderer", "depth"), id="newton-newton_warp-depth", @@ -136,6 +226,11 @@ def cleanup_simulation_context(): id="newton-ovrtx-simple_shading_full_mdl", marks=_OVRTX_DISABLED, ), + pytest.param( + ("newton", "ovrtx_renderer", "semantic_segmentation"), + id="newton-ovrtx-semantic_segmentation", + marks=_OVRTX_DISABLED, + ), ] @@ -161,21 +256,335 @@ def _apply_overrides_to_env_cfg(env_cfg: Any, override_args: list[str]) -> Any: return env_cfg -def _assert_camera_outputs_are_not_blank(label: str, camera_outputs: dict[str, dict[str, torch.Tensor]]) -> None: - """Assert each camera output has at least one non-zero pixel. +def _normalize_tensor(tensor: torch.Tensor, data_type: str) -> torch.Tensor: + """Convert camera output tensor to [0, 1] float32 for conversion to image. + + Args: + tensor: Camera output tensor. + data_type: Data type of the camera output. + + Returns: + Normalized tensor. + """ + normalized = tensor.float() + + if data_type in ["depth", "distance_to_camera", "distance_to_image_plane"]: + max_val = normalized.max() + if max_val > 0: + normalized = normalized / max_val + elif data_type in {"albedo"}: + normalized = normalized[..., :3] / 255.0 + else: + normalized = normalized / 255.0 + + return normalized + + +def _save_comparison_image(img: Image.Image, filename: str) -> str: + """Save a PIL image to the comparison-images/images directory. Args: - label: Label for error messages. - camera_outputs: Nested dict: sensor name -> {data_type -> tensor}. + img: PIL Image to save. + filename: File name (e.g. ``"test-backend-renderer-aov-result.png"``). + + Returns: + Absolute path to the saved file. + """ + path = os.path.join(_COMPARISON_IMAGES_DIR, "images", filename) + os.makedirs(os.path.dirname(path), exist_ok=True) + img.save(path, format="PNG") + return path + + +def _generate_html_report() -> None: + """Generate an HTML report of all comparison scores and save it alongside the comparison images. + + The report is written to ``<_COMPARISON_IMAGES_DIR>/_report_.html`` and includes a table of + all image comparison results sorted by PixelDiff % descending, with thumbnail links to actual + and golden images where available. """ - assert len(camera_outputs) > 0, f"[{label}] No camera outputs; env may have no cameras or wrong structure." - for sensor_name, output in camera_outputs.items(): - for data_type, tensor in output.items(): - invalid = torch.logical_or(torch.isinf(tensor), torch.isnan(tensor)) - corrected = torch.where(invalid, torch.zeros_like(tensor), tensor) - assert corrected.max() > 0, ( - f"[{label}] Sensor '{sensor_name}' output '{data_type}' has no non-zero pixels. " - f"Shape: {corrected.shape}, dtype: {corrected.dtype}." + if not _COMPARISON_SCORES: + return + + os.makedirs(_COMPARISON_IMAGES_DIR, exist_ok=True) + report_path = os.path.join(_COMPARISON_IMAGES_DIR, "_report_.html") + + sorted_scores = sorted(_COMPARISON_SCORES, key=lambda e: -e["diff_pct"]) + + rows = [] + for entry in sorted_scores: + status_class = "pass" if entry["passed"] else "fail" + status_text = status_class.upper() + + actual_img_html = "" + golden_img_html = "" + if entry.get("img_result_path"): + actual_fname = os.path.relpath(entry["img_result_path"], _COMPARISON_IMAGES_DIR) + golden_fname = os.path.relpath(entry["img_golden_path"], _COMPARISON_IMAGES_DIR) + actual_img_html = f'' + golden_img_html = f'' + + rows.append( + f'' + f"{entry['test']}" + f"{entry['backend']}" + f"{entry['renderer']}" + f"{entry['aov']}" + f"{entry['diff_pct']:.2f}" + f"{entry['threshold']:.1f}" + f"{entry['ssim']:.4f}" + f'{status_text}' + f"{actual_img_html}" + f"{golden_img_html}" + "" + ) + + html = ( + "\n" + "\n" + "\n" + '\n' + "Rendering Correctness — Image Comparison Report\n" + "\n" + "\n" + "\n" + "

Rendering Correctness — Image Comparison Report

\n" + f"

Sorted by PixelDiff % (desc) — {len(sorted_scores)}  total.

\n" + "\n" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "\n" + "\n" + "\n".join(rows) + "\n\n
TestBackendRendererAOVPixelDiff %Threshold %SSIMStatusACTUALGOLDEN
\n\n\n" + ) + + with open(report_path, "w", encoding="utf-8") as f: + f.write(html) + + +def _make_grid(images: torch.Tensor) -> torch.Tensor: + """Make a grid of images from a tensor of shape (B, H, W, C). + + Args: + images: A tensor of shape (B, H, W, C) containing the images. + + Returns: + A tensor of shape (H, W, C) containing the grid of images. + """ + from torchvision.utils import make_grid + + return make_grid(torch.swapaxes(images.unsqueeze(1), 1, -1).squeeze(-1), nrow=round(images.shape[0] ** 0.5)) + + +def _ssim(img1: torch.Tensor, img2: torch.Tensor, window_size: int = 11) -> float: + """Compute mean SSIM between two (1, C, H, W) float tensors in [0, 1]. + + https://en.wikipedia.org/wiki/Structural_similarity_index_measure + + Uses a uniform averaging window and the standard SSIM constants (K1=0.01, K2=0.03, + data_range=1.0). + + Args: + img1: First image tensor of shape (1, C, H, W) in [0, 1]. + img2: Second image tensor of shape (1, C, H, W) in [0, 1]. + window_size: Side length of the square averaging window. + + Returns: + Mean SSIM score (1.0 = identical). + """ + c1 = 0.01**2 + c2 = 0.03**2 + channels = img1.shape[1] + pad = window_size // 2 + + kernel = torch.ones(channels, 1, window_size, window_size, device=img1.device, dtype=img1.dtype) / ( + window_size * window_size + ) + + mu1 = torch.nn.functional.conv2d(img1, kernel, padding=pad, groups=channels) + mu2 = torch.nn.functional.conv2d(img2, kernel, padding=pad, groups=channels) + + mu1_sq = mu1 * mu1 + mu2_sq = mu2 * mu2 + mu1_mu2 = mu1 * mu2 + + sigma1_sq = torch.nn.functional.conv2d(img1 * img1, kernel, padding=pad, groups=channels) - mu1_sq + sigma2_sq = torch.nn.functional.conv2d(img2 * img2, kernel, padding=pad, groups=channels) - mu2_sq + sigma12 = torch.nn.functional.conv2d(img1 * img2, kernel, padding=pad, groups=channels) - mu1_mu2 + + ssim_map = ((2 * mu1_mu2 + c1) * (2 * sigma12 + c2)) / ((mu1_sq + mu2_sq + c1) * (sigma1_sq + sigma2_sq + c2)) + return ssim_map.mean().item() + + +def _pixel_diff_percentage( + result_image: Image.Image, + golden_image: Image.Image, + pixel_diff_threshold: float = _PIXEL_L2_NORM_DIFFERENCE_THRESHOLD, +) -> float: + """Compute the percentage of pixels whose L2 norm difference exceeds a threshold. + + Args: + result_image: Result image as PIL Image. + golden_image: Golden image as PIL Image (must be same size/mode). + pixel_diff_threshold: Pixel L2 norm difference threshold. + + Returns: + Percentage of pixels that differ beyond the threshold. + """ + diff_array = np.array(ImageChops.difference(result_image, golden_image)) + l2_norm_array = np.linalg.norm(diff_array, axis=2) + num_different_pixels = np.sum(l2_norm_array > pixel_diff_threshold) + return 100.0 * num_different_pixels / l2_norm_array.size + + +def _compare_images( + result_image: Image.Image, + golden_image: Image.Image, + max_different_pixels_percentage: float, +) -> tuple[bool, str | None, float, float]: + """Compare result and golden images using pixel L2 norm (pass/fail) and SSIM (reference). + + Args: + result_image: Result image as PIL Image to compare with golden image. + golden_image: Golden image as PIL Image to compare with result image. + max_different_pixels_percentage: Maximum percentage of pixels allowed to exceed pixel_diff_threshold. + + Returns: + (passed, error_message_or_None, diff_percentage, ssim_score). + Scores are 0.0 / 0.0 when comparison cannot be performed (size/mode mismatch). + """ + if result_image.size != golden_image.size: + return False, f"Size mismatch: expected {golden_image.size}, got {result_image.size}.", 0.0, 0.0 + + if result_image.mode != golden_image.mode: + return False, f"Mode mismatch: expected {golden_image.mode}, got {result_image.mode}.", 0.0, 0.0 + + diff_pct = _pixel_diff_percentage(result_image, golden_image) + + # SSIM (reference only, not used for pass/fail). + result_tensor = torch.from_numpy(np.array(result_image, dtype=np.float32) / 255.0).permute(2, 0, 1).unsqueeze(0) + golden_tensor = torch.from_numpy(np.array(golden_image, dtype=np.float32) / 255.0).permute(2, 0, 1).unsqueeze(0) + ssim_score = _ssim(result_tensor, golden_tensor) + + if diff_pct > max_different_pixels_percentage: + return ( + False, + f"The percentage of different pixels ({diff_pct:.2f}%) exceeds the threshold of" + f" {max_different_pixels_percentage:.2f}%. SSIM={ssim_score:.4f} (reference).", + diff_pct, + ssim_score, + ) + + return True, None, diff_pct, ssim_score + + +def _validate_camera_outputs( + test_name: str, + physics_backend: str, + renderer: str, + camera_outputs: dict[str, torch.Tensor], + max_different_pixels_percentage: float, +) -> None: + """Validate correctness and consistency of camera outputs. + + Args: + test_name: Test name. + physics_backend: Physics backend. + renderer: Renderer. + camera_outputs: {data_type -> tensor}. + max_different_pixels_percentage: Maximum percentage of pixels allowed to exceed pixel_diff_threshold. + """ + assert len(camera_outputs) > 0, f"[{test_name}] No camera outputs produced by {physics_backend} + {renderer}." + + golden_image_dir = os.path.join(_GOLDEN_IMAGES_DIRECTORY, test_name) + os.makedirs(golden_image_dir, exist_ok=True) + + for data_type, tensor in camera_outputs.items(): + # Replace inf/nan with zero so they do not break comparison; ensure the tensor has at least one non-zero value. + condition = torch.logical_or(torch.isinf(tensor), torch.isnan(tensor)) + corrected = torch.where(condition, torch.zeros_like(tensor), tensor) + max_val = corrected.max() + assert max_val > 0, ( + f"[{test_name}] Camera output '{data_type}' has no non-zero pixels. " + f"Shape: {corrected.shape}, dtype: {corrected.dtype}." + ) + + # convert tensors to a tiled image. + normalized = _normalize_tensor(corrected, data_type) + grid = _make_grid(normalized) + + # permute(1, 2, 0) is there to change the tensor layout from channel-first to channel-last so it matches what + # PIL expects. + ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy() + result_image = Image.fromarray(ndarr) + + # first run creates baseline and fails; second run validates. + golden_path = os.path.join(golden_image_dir, f"{physics_backend}-{renderer}-{data_type}.png") + if not os.path.exists(golden_path): + result_image.save(golden_path) + pytest.fail( + f"[{test_name}] Golden image not found at {golden_path}. Saved result image to {golden_path}. " + "Please run the test again to validate the consistency of rendering outputs." + ) + + try: + golden_image = Image.open(golden_path) + except Exception as e: + pytest.fail(f"Error opening golden image: {e}") + + # validate the consistency of rendering outputs. + succeeded, error_message, diff_pct, ssim_score = _compare_images( + result_image, golden_image, max_different_pixels_percentage + ) + + entry = { + "test": test_name, + "backend": physics_backend, + "renderer": renderer, + "aov": data_type, + "diff_pct": diff_pct, + "ssim": ssim_score, + "threshold": max_different_pixels_percentage, + "passed": succeeded, + "img_result_path": None, + "img_golden_path": None, + } + + if diff_pct > 0: + prefix = f"{test_name}-{physics_backend}-{renderer}-{data_type}" + entry["img_result_path"] = _save_comparison_image(result_image, f"{prefix}-actual.png") + entry["img_golden_path"] = _save_comparison_image(golden_image, f"{prefix}-golden.png") + + _COMPARISON_SCORES.append(entry) + + if not succeeded: + timestamp = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") + result_path = os.path.join(golden_image_dir, f"{physics_backend}-{renderer}-{data_type}-{timestamp}.png") + result_image.save(result_path) + pytest.fail( + f"[{test_name}] Inconsistency detected for camera output '{data_type}': {error_message}. " + f"Saved result image to {result_path} for further investigation. " + f"If result image is correct, please replace the golden image at {golden_path} with the result image." ) @@ -228,6 +637,7 @@ def shadow_hand_env(request): env_cfg = _apply_overrides_to_env_cfg(env_cfg, override_args) env_cfg.scene.num_envs = 4 + env_cfg.seed = 42 if data_type == "depth": # Disable CNN forward pass as it cannot be meaningfully trained from depth alone and will raise a ValueError. @@ -245,11 +655,17 @@ def shadow_hand_env(request): env.close() -def test_camera_outputs_are_not_blank_for_shadow_hand(shadow_hand_env): +def test_shadow_hand(shadow_hand_env): """Camera output must contain at least one non-zero pixel (Shadow Hand vision env).""" - physics_backend, renderer, data_type, env = shadow_hand_env - label = f"shadow_hand-{physics_backend}-{renderer}+{data_type}" - _assert_camera_outputs_are_not_blank(label, {"tiled_camera": env._tiled_camera.data.output}) + physics_backend, renderer, _, env = shadow_hand_env + + _validate_camera_outputs( + "shadow_hand", + physics_backend, + renderer, + env._tiled_camera.data.output, + max_different_pixels_percentage=5.0, + ) # --------------------------------------------------------------------------- @@ -271,6 +687,7 @@ def cartpole_env(request): env_cfg = _apply_overrides_to_env_cfg(env_cfg, override_args) env_cfg.scene.num_envs = 4 + env_cfg.seed = 42 env = None try: @@ -284,11 +701,17 @@ def cartpole_env(request): env.close() -def test_camera_outputs_are_not_blank_for_cartpole(cartpole_env): +def test_cartpole(cartpole_env): """Camera output must contain at least one non-zero pixel (Cartpole camera env).""" - physics_backend, renderer, data_type, env = cartpole_env - label = f"cartpole-{physics_backend}-{renderer}+{data_type}" - _assert_camera_outputs_are_not_blank(label, {"tiled_camera": env._tiled_camera.data.output}) + physics_backend, renderer, _, env = cartpole_env + + _validate_camera_outputs( + "cartpole", + physics_backend, + renderer, + env._tiled_camera.data.output, + max_different_pixels_percentage=5.0, + ) # --------------------------------------------------------------------------- @@ -314,6 +737,7 @@ def dexsuite_kuka_allegro_lift_env(request): env_cfg = _apply_overrides_to_env_cfg(env_cfg, override_args) env_cfg.scene.num_envs = 4 + env_cfg.seed = 42 env = None try: @@ -327,11 +751,17 @@ def dexsuite_kuka_allegro_lift_env(request): env.close() -def test_camera_outputs_are_not_blank_for_dexsuite_kuka_allegro_lift(dexsuite_kuka_allegro_lift_env): +def test_dexsuite_kuka_allegro_lift(dexsuite_kuka_allegro_lift_env): """Camera output must contain at least one non-zero pixel (Dexsuite Kuka-Allegro Lift, single camera).""" - physics_backend, renderer, data_type, env = dexsuite_kuka_allegro_lift_env - label = f"dexsuite_kuka_allegro_lift-{physics_backend}-{renderer}+{data_type}" - _assert_camera_outputs_are_not_blank(label, {"base_camera": env.scene.sensors["base_camera"].data.output}) + physics_backend, renderer, _, env = dexsuite_kuka_allegro_lift_env + + _validate_camera_outputs( + "dexsuite_kuka", + physics_backend, + renderer, + env.scene.sensors["base_camera"].data.output, + max_different_pixels_percentage=10.0, + ) # --------------------------------------------------------------------------- @@ -340,12 +770,7 @@ def test_camera_outputs_are_not_blank_for_dexsuite_kuka_allegro_lift(dexsuite_ku # Task IDs that expose camera/tiled_camera image observations; each is validated for non-blank rendering. _RENDER_CORRECTNESS_TASK_IDS = [ - "Isaac-Cartpole-RGB-Camera-Direct-v0", "Isaac-Cartpole-Albedo-Camera-Direct-v0", - "Isaac-Cartpole-SimpleShading-Constant-Camera-Direct-v0", - "Isaac-Cartpole-SimpleShading-Diffuse-Camera-Direct-v0", - "Isaac-Cartpole-SimpleShading-Full-Camera-Direct-v0", - "Isaac-Cartpole-Depth-Camera-Direct-v0", "Isaac-Cartpole-Camera-Presets-Direct-v0", "Isaac-Cartpole-Camera-Showcase-Box-Box-Direct-v0", "Isaac-Cartpole-Camera-Showcase-Box-Discrete-Direct-v0", @@ -356,19 +781,26 @@ def test_camera_outputs_are_not_blank_for_dexsuite_kuka_allegro_lift(dexsuite_ku "Isaac-Cartpole-Camera-Showcase-Tuple-Box-Direct-v0", "Isaac-Cartpole-Camera-Showcase-Tuple-Discrete-Direct-v0", "Isaac-Cartpole-Camera-Showcase-Tuple-MultiDiscrete-Direct-v0", - "Isaac-Repose-Cube-Shadow-Vision-Direct-v0", - "Isaac-Cartpole-RGB-v0", + "Isaac-Cartpole-Depth-Camera-Direct-v0", "Isaac-Cartpole-Depth-v0", + "Isaac-Cartpole-RGB-Camera-Direct-v0", "Isaac-Cartpole-RGB-ResNet18-v0", + "Isaac-Cartpole-RGB-v0", + "Isaac-Cartpole-SimpleShading-Constant-Camera-Direct-v0", + "Isaac-Cartpole-SimpleShading-Diffuse-Camera-Direct-v0", + "Isaac-Cartpole-SimpleShading-Full-Camera-Direct-v0", + "Isaac-Repose-Cube-Shadow-Vision-Direct-v0", ] @pytest.mark.parametrize("task_id", _RENDER_CORRECTNESS_TASK_IDS) -def test_camera_outputs_are_not_blank_for_registered_task(task_id): +def test_registered_tasks(task_id): """Camera output must be non-empty for each registered task with camera-based observations.""" env = None try: env_cfg = parse_env_cfg(task_id, num_envs=4) + env_cfg.seed = 42 + env = gym.make(task_id, cfg=env_cfg) unwrapped: Any = env.unwrapped sim = getattr(unwrapped, "sim", None) @@ -401,8 +833,19 @@ def test_camera_outputs_are_not_blank_for_registered_task(task_id): env.step(actions) - camera_outputs = _collect_camera_outputs(env) - _assert_camera_outputs_are_not_blank(task_id, camera_outputs) + camera_outputs_nested_dict = _collect_camera_outputs(env) + num_camera_outputs = len(camera_outputs_nested_dict) + assert num_camera_outputs == 1, f"[{task_id}] Expected 1 camera output, got {num_camera_outputs}." + + camera_outputs = next(iter(camera_outputs_nested_dict.values())) + + _validate_camera_outputs( + f"registered_tasks/{task_id}", + "default_physics", + "default_renderer", + camera_outputs, + max_different_pixels_percentage=5.0, + ) finally: if env is not None: env.close() diff --git a/source/isaaclab_teleop/config/extension.toml b/source/isaaclab_teleop/config/extension.toml index 547c213e91cd..48e59c25e80e 100644 --- a/source/isaaclab_teleop/config/extension.toml +++ b/source/isaaclab_teleop/config/extension.toml @@ -1,6 +1,6 @@ [package] # Semantic Versioning is used: https://semver.org/ -version = "0.3.3" +version = "0.3.4" # Description title = "Isaac Lab Teleop" diff --git a/source/isaaclab_teleop/docs/CHANGELOG.rst b/source/isaaclab_teleop/docs/CHANGELOG.rst index 8c28d8c383f2..e9545bd4b894 100644 --- a/source/isaaclab_teleop/docs/CHANGELOG.rst +++ b/source/isaaclab_teleop/docs/CHANGELOG.rst @@ -1,6 +1,25 @@ Changelog --------- +0.3.4 (2026-03-17) +~~~~~~~~~~~~~~~~~~~ + +Added +^^^^^ + +* Added :attr:`~isaaclab_teleop.IsaacTeleopCfg.target_frame_prim_path` for + config-driven frame rebasing. When set to a USD prim path, the device + automatically reads the prim's world transform each frame and uses its + inverse as the ``target_T_world`` rebase matrix, so all output poses are + expressed in the target frame (e.g. robot base link for IK). + +* Added ``target_T_world`` parameter to + :meth:`~isaaclab_teleop.IsaacTeleopDevice.advance` for rebasing all output + poses into an arbitrary target coordinate frame (e.g. robot base link for + IK). Accepts :class:`numpy.ndarray`, :class:`torch.Tensor`, or + ``wp.array``. + + 0.3.3 (2026-03-13) ~~~~~~~~~~~~~~~~~~~ diff --git a/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_cfg.py b/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_cfg.py index b2c9f303cc97..36dfb55a737c 100644 --- a/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_cfg.py +++ b/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_cfg.py @@ -108,5 +108,26 @@ def build_pipeline(): If ``None``, the tuning UI will not be opened. """ + target_frame_prim_path: str | None = None + """Optional USD prim path whose world frame becomes the target coordinate + frame for all output poses. + + When set, the device automatically reads this prim's world transform each + frame and uses its inverse as the ``target_T_world`` rebase matrix in + :meth:`~isaaclab_teleop.IsaacTeleopDevice.advance`. An explicit + ``target_T_world`` argument to :meth:`~isaaclab_teleop.IsaacTeleopDevice.advance` + takes precedence over this config. + + Typical usage: set to the robot base link prim path so that an IK + controller receives end-effector poses in the robot's base frame. + + Example:: + + IsaacTeleopCfg( + target_frame_prim_path="/World/envs/env_0/Robot/base_link", + ... + ) + """ + app_name: str = "IsaacLabTeleop" """Application name for the IsaacTeleop session.""" diff --git a/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_device.py b/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_device.py index f7448fffd548..832f5536b28c 100644 --- a/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_device.py +++ b/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_device.py @@ -9,7 +9,9 @@ import logging from collections.abc import Callable +from typing import TYPE_CHECKING +import numpy as np import torch from .command_handler import CommandHandler @@ -17,6 +19,9 @@ from .session_lifecycle import TeleopSessionLifecycle from .xr_anchor_manager import XrAnchorManager +if TYPE_CHECKING: + from .session_lifecycle import SupportsDLPack + logger = logging.getLogger(__name__) @@ -42,6 +47,24 @@ class IsaacTeleopDevice: The device uses IsaacTeleop's TensorReorderer to flatten pipeline outputs into a single action tensor matching the environment's action space. + Frame rebasing: + By default, all output poses are expressed in the simulation world + frame. When an application needs poses in a different frame (e.g. + robot base link for IK), there are two options: + + * **Config-driven** (recommended): set + :attr:`~IsaacTeleopCfg.target_frame_prim_path` to the USD prim + whose frame the output should be expressed in. The device reads + the prim's world transform each frame and applies the rebase + automatically. + * **Explicit**: pass a ``target_T_world`` matrix directly to + :meth:`advance`. + + In both cases the device composes + ``target_T_world @ world_T_anchor`` before feeding the matrix into + the retargeting pipeline, so all resulting poses are expressed in the + target frame. + Teleop commands: The device supports callbacks for START, STOP, and RESET commands that can be triggered via XR controller buttons or the message bus. @@ -54,10 +77,25 @@ class IsaacTeleopDevice: sim_device="cuda:0", ) + # Poses in world frame (default) + with IsaacTeleopDevice(cfg) as device: + while running: + action = device.advance() + env.step(action.repeat(num_envs, 1)) + + # Config-driven rebase into robot base frame + cfg.target_frame_prim_path = "/World/Robot/base_link" with IsaacTeleopDevice(cfg) as device: while running: action = device.advance() env.step(action.repeat(num_envs, 1)) + + # Explicit rebase into robot base frame + with IsaacTeleopDevice(cfg) as device: + while running: + robot_T_world = get_robot_base_transform() + action = device.advance(target_T_world=robot_T_world) + env.step(action.repeat(num_envs, 1)) """ def __init__(self, cfg: IsaacTeleopCfg): @@ -147,7 +185,7 @@ def add_callback(self, key: str, func: Callable) -> None: """ self._command_handler.add_callback(key, func) - def advance(self) -> torch.Tensor | None: + def advance(self, target_T_world: np.ndarray | torch.Tensor | SupportsDLPack | None = None) -> torch.Tensor | None: """Process current device state and return control commands. If the IsaacTeleop session has not been started yet (because the OpenXR @@ -155,6 +193,27 @@ def advance(self) -> torch.Tensor | None: attempt to start it on each call. Once the user clicks "Start AR" and the handles become available, the session is created transparently. + Args: + target_T_world: Optional 4x4 transform matrix that rebases all + output poses into an arbitrary target coordinate frame. When + provided, the matrix sent to the retargeting pipeline becomes + ``target_T_world @ world_T_anchor`` instead of just + ``world_T_anchor``, so all resulting poses are expressed in + the target frame rather than the simulation world frame. + + Typical use case: pass ``robot_base_T_world`` so that an IK + controller receives end-effector poses in the robot's base + link frame. + + Accepts any object supporting the DLPack buffer protocol + (``__dlpack__``), including :class:`numpy.ndarray`, + :class:`torch.Tensor`, and ``wp.array``. + + When ``None`` and + :attr:`~IsaacTeleopCfg.target_frame_prim_path` is set, the + transform is computed automatically by reading the prim's + world matrix from Fabric and inverting it. + Returns: A flattened action :class:`torch.Tensor` ready for the Isaac Lab environment, or ``None`` if the session has not started yet @@ -163,9 +222,14 @@ def advance(self) -> torch.Tensor | None: Raises: RuntimeError: If called outside of a context manager. """ + # Auto-compute target_T_world from config if not explicitly provided + if target_T_world is None and self._cfg.target_frame_prim_path is not None: + target_T_world = self._get_target_frame_T_world() + # Step the session (handles lazy start and action extraction) action = self._session_lifecycle.step( anchor_world_matrix_fn=self._anchor_manager.get_world_matrix, + target_T_world=target_T_world, ) if action is not None: @@ -174,6 +238,75 @@ def advance(self) -> torch.Tensor | None: return action + # ------------------------------------------------------------------ + # Target frame transform (config-driven rebase) + # ------------------------------------------------------------------ + + def _get_target_frame_T_world(self) -> np.ndarray | None: + """Read the target-frame prim's world matrix from Fabric and return its inverse. + + Uses USDRT to read the prim's hierarchical world matrix, matching the + pattern used by :class:`XrAnchorSynchronizer` for anchor prim reads. + + Returns: + A (4, 4) float32 :class:`numpy.ndarray` representing the inverse + of the prim's world transform (i.e. ``target_T_world``), or + ``None`` if the prim cannot be read. + """ + try: + import omni.usd + import usdrt + from pxr import UsdUtils + from usdrt import Rt + + stage = omni.usd.get_context().get_stage() + stage_cache = UsdUtils.StageCache.Get() + stage_id = stage_cache.GetId(stage).ToLongInt() + if stage_id < 0: + stage_id = stage_cache.Insert(stage).ToLongInt() + rt_stage = usdrt.Usd.Stage.Attach(stage_id) + if rt_stage is None: + return None + + rt_prim = rt_stage.GetPrimAtPath(self._cfg.target_frame_prim_path) + if not rt_prim.IsValid(): + return None + + rt_xformable = Rt.Xformable(rt_prim) + if not rt_xformable.GetPrim().IsValid(): + return None + + world_matrix_attr = rt_xformable.GetFabricHierarchyWorldMatrixAttr() + if world_matrix_attr is None: + return None + + rt_matrix = world_matrix_attr.Get() + if rt_matrix is None: + return None + + pos = rt_matrix.ExtractTranslation() + rt_quat = rt_matrix.ExtractRotationQuat() + + from scipy.spatial.transform import Rotation + + quat_xyzw = [ + float(rt_quat.GetImaginary()[0]), + float(rt_quat.GetImaginary()[1]), + float(rt_quat.GetImaginary()[2]), + float(rt_quat.GetReal()), + ] + + R = Rotation.from_quat(quat_xyzw).as_matrix().astype(np.float32) + t = np.array([float(pos[0]), float(pos[1]), float(pos[2])], dtype=np.float32) + + inv_mat = np.eye(4, dtype=np.float32) + inv_mat[:3, :3] = R.T + inv_mat[:3, 3] = -(R.T @ t) + return inv_mat + except Exception as e: + logger.warning(f"Failed to read target frame prim '{self._cfg.target_frame_prim_path}': {e}") + return None + # ------------------------------------------------------------------ # Controller button polling (glue between session and anchor manager) # ------------------------------------------------------------------ diff --git a/source/isaaclab_teleop/isaaclab_teleop/session_lifecycle.py b/source/isaaclab_teleop/isaaclab_teleop/session_lifecycle.py index 06c02a0205c9..8620e9d85b87 100644 --- a/source/isaaclab_teleop/isaaclab_teleop/session_lifecycle.py +++ b/source/isaaclab_teleop/isaaclab_teleop/session_lifecycle.py @@ -9,7 +9,7 @@ import logging from collections.abc import Callable -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any, Protocol import numpy as np import torch @@ -21,8 +21,53 @@ from .isaac_teleop_cfg import IsaacTeleopCfg + +class SupportsDLPack(Protocol): + """Duck type for objects supporting the DLPack buffer protocol. + + Satisfied by :class:`torch.Tensor`, :class:`numpy.ndarray` (>= 1.22), + ``wp.array``, CuPy arrays, JAX arrays, and other frameworks. + """ + + def __dlpack__(self, *, stream: Any = ...) -> Any: ... + + def __dlpack_device__(self) -> tuple[int, int]: ... + + logger = logging.getLogger(__name__) +_DLDEVICE_CPU = 1 + + +def _to_numpy_4x4(mat: np.ndarray | torch.Tensor | SupportsDLPack) -> np.ndarray: + """Convert a (4, 4) transform to a float32 numpy array. + + Prefers the DLPack buffer protocol (``__dlpack__``) for zero-copy + interop with torch, warp, cupy, jax, and other frameworks. + + Args: + mat: A (4, 4) transform matrix. + + Returns: + A (4, 4) float32 :class:`numpy.ndarray`. + """ + if isinstance(mat, np.ndarray): + return np.asarray(mat, dtype=np.float32) + if isinstance(mat, torch.Tensor): + return np.asarray(np.from_dlpack(mat.detach().cpu()), dtype=np.float32) + if hasattr(mat, "__dlpack_device__"): + device_type, _ = mat.__dlpack_device__() + if device_type == _DLDEVICE_CPU: + return np.asarray(np.from_dlpack(mat), dtype=np.float32) + # Non-CPU DLPack source (e.g. CUDA wp.array): .numpy() typically + # handles the device-to-host transfer internally. + if hasattr(mat, "numpy"): + return np.asarray(mat.numpy(), dtype=np.float32) # type: ignore[union-attr] + raise TypeError(f"Cannot convert non-CPU DLPack array of type {type(mat).__name__} to numpy") + if hasattr(mat, "numpy"): + return np.asarray(mat.numpy(), dtype=np.float32) # type: ignore[union-attr] + return np.asarray(mat, dtype=np.float32) + class TeleopSessionLifecycle: """Manages the IsaacTeleop session lifecycle. @@ -306,7 +351,11 @@ def _try_start_session(self) -> bool: # Stepping # ------------------------------------------------------------------ - def step(self, anchor_world_matrix_fn: Callable[[], np.ndarray] | None = None) -> torch.Tensor | None: + def step( + self, + anchor_world_matrix_fn: Callable[[], np.ndarray] | None = None, + target_T_world: np.ndarray | torch.Tensor | SupportsDLPack | None = None, + ) -> torch.Tensor | None: """Execute one step of the teleop session and return the action tensor. If the session has not been started yet (because OpenXR handles were @@ -323,6 +372,14 @@ def step(self, anchor_world_matrix_fn: Callable[[], np.ndarray] | None = None) - anchor_world_matrix_fn: Optional callable returning the (4, 4) world-to-anchor transform. Used to build external inputs for ``ValueInput`` leaf nodes in the pipeline. + target_T_world: Optional (4, 4) transform matrix that rebases + pipeline poses into a target coordinate frame. When provided, + the anchor matrix is left-multiplied by this transform + (``target_T_world @ world_T_anchor``) so all output poses + are expressed in the target frame. Accepts any object + supporting the DLPack buffer protocol (``__dlpack__``), + including :class:`numpy.ndarray`, :class:`torch.Tensor`, + and ``wp.array``. Returns: A flattened action :class:`torch.Tensor` ready for the Isaac Lab @@ -342,7 +399,7 @@ def step(self, anchor_world_matrix_fn: Callable[[], np.ndarray] | None = None) - # Build external inputs (e.g. world-to-anchor transform) if the # pipeline contains ValueInput leaf nodes. - external_inputs = self._build_external_inputs(anchor_world_matrix_fn) + external_inputs = self._build_external_inputs(anchor_world_matrix_fn, target_T_world) # Execute one step of the teleop session. # If the underlying OpenXR session was destroyed externally (e.g. @@ -360,11 +417,12 @@ def step(self, anchor_world_matrix_fn: Callable[[], np.ndarray] | None = None) - # Store the right controller TensorGroup for button polling self._last_right_controller = result.get(self._CONTROLLER_RIGHT_KEY) - # Extract the flattened action array from TensorReorderer output - action_np = result["action"][0] - - # Convert to torch tensor and move to device - action = torch.from_numpy(np.asarray(action_np, dtype=np.float32)).to(self._device) + # Extract the flattened action array (DLPack-compatible) from + # TensorReorderer and move to the simulation device. + action_array = result["action"][0] + action = torch.from_dlpack(action_array).to( # type: ignore[attr-defined] + dtype=torch.float32, device=self._device + ) return action @@ -395,16 +453,27 @@ def _teardown_dead_session(self) -> None: # External input building # ------------------------------------------------------------------ - def _build_external_inputs(self, anchor_world_matrix_fn: Callable[[], np.ndarray] | None) -> dict | None: + def _build_external_inputs( + self, + anchor_world_matrix_fn: Callable[[], np.ndarray] | None, + target_T_world: np.ndarray | torch.Tensor | SupportsDLPack | None = None, + ) -> dict | None: """Build external inputs for non-DeviceIO leaf nodes in the pipeline. Checks whether the active ``TeleopSession`` has external (non-DeviceIO) leaf nodes and, for each recognized leaf, constructs the corresponding ``TensorGroup`` data. + When *target_T_world* is provided, the anchor matrix is left-multiplied + by the rebase transform so that all pipeline poses are expressed in + the target coordinate frame: + ``target_T_world @ world_T_anchor = target_T_anchor``. + Args: anchor_world_matrix_fn: Callable returning the (4, 4) world-to-anchor transform matrix. + target_T_world: Optional (4, 4) rebase transform. See + :meth:`step` for details. Returns: A dict suitable for ``TeleopSession.step(external_inputs=...)``, @@ -425,6 +494,8 @@ def _build_external_inputs(self, anchor_world_matrix_fn: Callable[[], np.ndarray anchor_matrix = anchor_world_matrix_fn() else: anchor_matrix = np.eye(4, dtype=np.float32) + if target_T_world is not None: + anchor_matrix = _to_numpy_4x4(target_T_world) @ anchor_matrix xform_tg = TensorGroup(TransformMatrix()) xform_tg[0] = anchor_matrix external_inputs[leaf_name] = {ValueInput.VALUE: xform_tg} diff --git a/source/isaaclab_teleop/test/test_target_frame_rebase.py b/source/isaaclab_teleop/test/test_target_frame_rebase.py new file mode 100644 index 000000000000..044b5da7d305 --- /dev/null +++ b/source/isaaclab_teleop/test/test_target_frame_rebase.py @@ -0,0 +1,264 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +# pyright: reportPrivateUsage=none + +"""Tests for the target-frame rebase logic, _to_numpy_4x4 helper, and config-driven auto-selection. + +These tests exercise pure math (no Omniverse/Isaac Sim stack required). +""" + +from __future__ import annotations + +import numpy as np +import pytest +import torch +from isaaclab_teleop.session_lifecycle import _to_numpy_4x4 + +# --------------------------------------------------------------------------- +# Fixtures +# --------------------------------------------------------------------------- + + +@pytest.fixture +def identity_4x4() -> np.ndarray: + return np.eye(4, dtype=np.float32) + + +@pytest.fixture +def translation_matrix() -> np.ndarray: + """A pure translation of (1, 2, 3).""" + mat = np.eye(4, dtype=np.float32) + mat[:3, 3] = [1.0, 2.0, 3.0] + return mat + + +@pytest.fixture +def rotation_90z_matrix() -> np.ndarray: + """90-degree rotation about Z axis.""" + mat = np.eye(4, dtype=np.float32) + mat[0, 0] = 0.0 + mat[0, 1] = -1.0 + mat[1, 0] = 1.0 + mat[1, 1] = 0.0 + return mat + + +# --------------------------------------------------------------------------- +# _to_numpy_4x4 conversion tests +# --------------------------------------------------------------------------- + + +class TestToNumpy4x4: + def test_from_ndarray_float32(self, identity_4x4: np.ndarray): + result = _to_numpy_4x4(identity_4x4) + assert isinstance(result, np.ndarray) + assert result.dtype == np.float32 + np.testing.assert_array_equal(result, identity_4x4) + + def test_from_ndarray_float64_casts(self): + mat = np.eye(4, dtype=np.float64) + result = _to_numpy_4x4(mat) + assert result.dtype == np.float32 + np.testing.assert_array_almost_equal(result, np.eye(4, dtype=np.float32)) + + def test_from_torch_cpu(self, translation_matrix: np.ndarray): + tensor = torch.from_numpy(translation_matrix.copy()) + result = _to_numpy_4x4(tensor) + assert isinstance(result, np.ndarray) + assert result.dtype == np.float32 + np.testing.assert_array_almost_equal(result, translation_matrix) + + @pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available") + def test_from_torch_gpu(self, translation_matrix: np.ndarray): + tensor = torch.from_numpy(translation_matrix.copy()).cuda() + result = _to_numpy_4x4(tensor) + assert isinstance(result, np.ndarray) + assert result.dtype == np.float32 + np.testing.assert_array_almost_equal(result, translation_matrix) + + def test_from_duck_typed_numpy(self, rotation_90z_matrix: np.ndarray): + """Simulates a wp.array or similar object with a .numpy() method.""" + + class FakeWarpArray: + def __init__(self, data: np.ndarray): + self._data = data + + def numpy(self) -> np.ndarray: + return self._data + + fake = FakeWarpArray(rotation_90z_matrix.copy()) + result = _to_numpy_4x4(fake) + assert isinstance(result, np.ndarray) + assert result.dtype == np.float32 + np.testing.assert_array_almost_equal(result, rotation_90z_matrix) + + def test_from_list(self): + data = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]] + result = _to_numpy_4x4(data) + assert isinstance(result, np.ndarray) + assert result.dtype == np.float32 + np.testing.assert_array_equal(result, np.eye(4, dtype=np.float32)) + + +# --------------------------------------------------------------------------- +# Matrix multiplication (rebase) tests +# --------------------------------------------------------------------------- + + +class TestRebaseMultiplication: + def test_rebase_identity_is_noop(self, translation_matrix: np.ndarray): + """target_T_world = I should leave anchor_matrix unchanged.""" + identity = np.eye(4, dtype=np.float32) + result = _to_numpy_4x4(identity) @ translation_matrix + np.testing.assert_array_almost_equal(result, translation_matrix) + + def test_rebase_translation(self, identity_4x4: np.ndarray): + """Rebasing by a pure translation offsets the origin.""" + target_T_world = np.eye(4, dtype=np.float32) + target_T_world[:3, 3] = [10.0, 20.0, 30.0] + + world_T_anchor = np.eye(4, dtype=np.float32) + world_T_anchor[:3, 3] = [1.0, 2.0, 3.0] + + result = _to_numpy_4x4(target_T_world) @ world_T_anchor + np.testing.assert_array_almost_equal(result[:3, 3], [11.0, 22.0, 33.0]) + + def test_rebase_rotation(self, rotation_90z_matrix: np.ndarray): + """A 90-deg Z rotation rebase should rotate the anchor translation.""" + world_T_anchor = np.eye(4, dtype=np.float32) + world_T_anchor[:3, 3] = [1.0, 0.0, 0.0] + + result = _to_numpy_4x4(rotation_90z_matrix) @ world_T_anchor + + # After 90-deg Z rotation: (1,0,0) -> (0,1,0) + np.testing.assert_array_almost_equal(result[:3, 3], [0.0, 1.0, 0.0]) + # Rotation part should match the 90-deg Z rotation + np.testing.assert_array_almost_equal(result[:3, :3], rotation_90z_matrix[:3, :3]) + + def test_rebase_with_torch_tensor(self, translation_matrix: np.ndarray): + """target_T_world as a torch.Tensor should work identically.""" + target_T_world = torch.eye(4, dtype=torch.float32) + target_T_world[:3, 3] = torch.tensor([5.0, 5.0, 5.0]) + + result = _to_numpy_4x4(target_T_world) @ translation_matrix + + expected = np.eye(4, dtype=np.float32) + expected[:3, 3] = [6.0, 7.0, 8.0] + np.testing.assert_array_almost_equal(result, expected) + + def test_none_target_leaves_anchor_unchanged(self, translation_matrix: np.ndarray): + """When target_T_world is None, the calling code should skip multiplication.""" + target_T_world = None + anchor_matrix = translation_matrix.copy() + + if target_T_world is not None: + anchor_matrix = _to_numpy_4x4(target_T_world) @ anchor_matrix + + np.testing.assert_array_equal(anchor_matrix, translation_matrix) + + def test_inverse_rebase_recovers_identity(self): + """target_T_world = inv(world_T_anchor) should yield identity.""" + world_T_anchor = np.array( + [ + [0.0, -1.0, 0.0, 3.0], + [1.0, 0.0, 0.0, -1.0], + [0.0, 0.0, 1.0, 2.0], + [0.0, 0.0, 0.0, 1.0], + ], + dtype=np.float32, + ) + target_T_world = np.linalg.inv(world_T_anchor).astype(np.float32) + + result = _to_numpy_4x4(target_T_world) @ world_T_anchor + np.testing.assert_array_almost_equal(result, np.eye(4, dtype=np.float32), decimal=5) + + +# --------------------------------------------------------------------------- +# Config-driven auto-selection tests +# --------------------------------------------------------------------------- + + +def _simulate_advance_selection( + target_T_world: np.ndarray | None, + target_frame_prim_path: str | None, + auto_read_result: np.ndarray | None = None, +) -> tuple[np.ndarray | None, bool]: + """Replicate the auto-selection logic from IsaacTeleopDevice.advance(). + + Returns the target_T_world that would be passed to step(), and whether + _get_target_frame_T_world would have been called. + """ + auto_read_called = False + + def fake_get_target_frame_T_world(): + nonlocal auto_read_called + auto_read_called = True + return auto_read_result + + if target_T_world is None and target_frame_prim_path is not None: + target_T_world = fake_get_target_frame_T_world() + + return target_T_world, auto_read_called + + +class TestConfigDrivenAutoSelection: + """Tests for the advance() auto-selection logic between explicit target_T_world + and config-driven target_frame_prim_path. + + These tests replicate the branching logic from advance() without importing + the full IsaacTeleopDevice (which requires Isaac Sim runtime dependencies). + """ + + def test_no_config_no_explicit_passes_none(self): + """When neither config nor explicit target_T_world is set, step() receives None.""" + result, called = _simulate_advance_selection(target_T_world=None, target_frame_prim_path=None) + assert result is None + assert not called + + def test_explicit_target_is_passed_through(self): + """An explicit target_T_world should be passed directly to step().""" + explicit = np.eye(4, dtype=np.float32) + explicit[:3, 3] = [1.0, 2.0, 3.0] + + result, called = _simulate_advance_selection(target_T_world=explicit, target_frame_prim_path=None) + np.testing.assert_array_equal(result, explicit) + assert not called + + def test_config_prim_triggers_auto_read(self): + """When target_frame_prim_path is set, _get_target_frame_T_world is called.""" + auto_matrix = np.eye(4, dtype=np.float32) + auto_matrix[:3, 3] = [9.0, 8.0, 7.0] + + result, called = _simulate_advance_selection( + target_T_world=None, + target_frame_prim_path="/World/Robot/base_link", + auto_read_result=auto_matrix, + ) + assert called + np.testing.assert_array_equal(result, auto_matrix) + + def test_explicit_overrides_config(self): + """An explicit target_T_world takes precedence over config prim path.""" + explicit = np.eye(4, dtype=np.float32) + explicit[:3, 3] = [42.0, 0.0, 0.0] + + result, called = _simulate_advance_selection( + target_T_world=explicit, + target_frame_prim_path="/World/Robot/base_link", + auto_read_result=np.eye(4, dtype=np.float32), + ) + assert not called + np.testing.assert_array_equal(result, explicit) + + def test_config_prim_returns_none_passes_none(self): + """If the prim read fails (returns None), step() receives None.""" + result, called = _simulate_advance_selection( + target_T_world=None, + target_frame_prim_path="/World/Robot/base_link", + auto_read_result=None, + ) + assert called + assert result is None diff --git a/tools/conftest.py b/tools/conftest.py index 82ba353ff437..ab70e5ac20a2 100644 --- a/tools/conftest.py +++ b/tools/conftest.py @@ -23,10 +23,19 @@ def pytest_ignore_collect(collection_path, config): return True +# TODO: SimulationApp.close() can hang indefinitely in some tests (especially those using +# cameras or render products), causing CI timeouts. A fix that detects test completion via +# the JUnit XML report file and kills the process after a grace period was prototyped in +# https://github.com/isaac-sim/IsaacLab/pull/5097 — see commits: +# 242315b3722 Handle hanging subprocesses causing timeouts +# bd4953019ab Add comment explaining intentional return 0 in shutdown-hang path +# A per-test-file conftest.py using atexit.register(os._exit) was also tried: +# 6840e5a3aeb Force stalled test subprocesses that hang after SimulationApp.close() def capture_test_output_with_timeout(cmd, timeout, env): """Run a command with timeout and capture all output while streaming in real-time.""" stdout_data = b"" stderr_data = b"" + process = None try: # Use Popen to capture output in real-time @@ -91,15 +100,29 @@ def capture_test_output_with_timeout(cmd, timeout, env): time.sleep(0.1) continue - # Get any remaining output - remaining_stdout, remaining_stderr = process.communicate() - stdout_data += remaining_stdout - stderr_data += remaining_stderr + # Drain any output the process wrote before or just after exiting. + # Wrapped in try/except so a pipe error doesn't discard what was already captured. + try: + remaining_stdout, remaining_stderr = process.communicate(timeout=10) + stdout_data += remaining_stdout + stderr_data += remaining_stderr + except Exception: + pass return process.returncode, stdout_data, stderr_data, False except Exception as e: - return -1, str(e).encode(), b"", False + # Kill the process if it is still alive, then drain whatever it wrote. + if process is not None and process.poll() is None: + process.kill() + with contextlib.suppress(Exception): + rem_out, rem_err = process.communicate(timeout=5) + stdout_data += rem_out + stderr_data += rem_err + # Append the exception message so the caller can see what went wrong, + # but preserve any output already captured. + stdout_data += f"\n[capture error: {e}]\n".encode() + return -1, stdout_data, stderr_data, False def create_timeout_test_case(test_file, timeout, stdout_data, stderr_data): @@ -133,6 +156,7 @@ def run_individual_tests(test_files, workspace_root, isaacsim_ci): """Run each test file separately, ensuring one finishes before starting the next.""" failed_tests = [] test_status = {} + xml_reports = [] # in-memory JUnitXml objects, used to build the merged report for test_file in test_files: print(f"\n\n🚀 Running {test_file} independently...\n") @@ -147,7 +171,6 @@ def run_individual_tests(test_files, workspace_root, isaacsim_ci): # Note: Command options matter as they are used for cleanups inside AppLauncher cmd = [ sys.executable, - "-u", "-m", "pytest", "--no-header", @@ -178,6 +201,7 @@ def run_individual_tests(test_files, workspace_root, isaacsim_ci): # Write timeout report report_file = f"tests/test-reports-{str(file_name)}.xml" timeout_report.write(report_file) + xml_reports.append(timeout_report) test_status[test_file] = { "errors": 1, @@ -195,14 +219,46 @@ def run_individual_tests(test_files, workspace_root, isaacsim_ci): # check report for any failures report_file = f"tests/test-reports-{str(file_name)}.xml" if not os.path.exists(report_file): - print(f"Warning: Test report not found at {report_file}") + if returncode < 0: + sig = -returncode + reason = f"Process killed by signal {sig}" + if sig == 9: + reason += " (SIGKILL — likely OOM killed)" + elif sig == 6: + reason += " (SIGABRT)" + print(f"⚠️ {test_file}: {reason}") + else: + reason = f"Process exited with code {returncode} but produced no report" + print(f"Warning: Test report not found at {report_file}") + + crash_suite = TestSuite(name=f"crash_{os.path.splitext(file_name)[0]}") + crash_case = TestCase( + name="test_execution", + classname=os.path.splitext(file_name)[0], + ) + details = f"{reason}\n\n" + if stdout_data: + details += "=== STDOUT (last 2000 chars) ===\n" + details += stdout_data.decode("utf-8", errors="replace")[-2000:] + "\n" + if stderr_data: + details += "=== STDERR (last 2000 chars) ===\n" + details += stderr_data.decode("utf-8", errors="replace")[-2000:] + "\n" + error = Error(message=reason) + error.text = details + crash_case.result = error + crash_suite.add_testcase(crash_case) + crash_report = JUnitXml() + crash_report.add_testsuite(crash_suite) + crash_report.write(report_file) + xml_reports.append(crash_report) + failed_tests.append(test_file) test_status[test_file] = { - "errors": 1, # Assume error since we can't read the report + "errors": 1, "failures": 0, "skipped": 0, - "tests": 0, - "result": "FAILED", + "tests": 1, + "result": "CRASHED", "time_elapsed": 0.0, } continue @@ -219,6 +275,7 @@ def run_individual_tests(test_files, workspace_root, isaacsim_ci): # Write the updated report back report.write(report_file) + xml_reports.append(report) # Parse the integer values with None handling errors = int(report.errors) if report.errors is not None else 0 @@ -254,7 +311,7 @@ def run_individual_tests(test_files, workspace_root, isaacsim_ci): print("~~~~~~~~~~~~ Finished running all tests") - return failed_tests, test_status + return failed_tests, test_status, xml_reports def _collect_test_files( @@ -262,10 +319,8 @@ def _collect_test_files( filter_pattern, exclude_pattern, include_files, - flaky_only, - slightly_flaky_only, + quarantined_only, curobo_only, - cuda_issue_only, ): """Collect test files from source directories, applying all active filters.""" test_files = [] @@ -280,18 +335,12 @@ def _collect_test_files( continue # Mode-exclusive filters (each bypasses TESTS_TO_SKIP) - if flaky_only: - if file not in test_settings.FLAKY_TESTS: - continue - elif slightly_flaky_only: - if file not in test_settings.SLIGHTLY_FLAKY_TESTS: + if quarantined_only: + if file not in test_settings.QUARANTINED_TESTS: continue elif curobo_only: if file not in test_settings.CUROBO_TESTS: continue - elif cuda_issue_only: - if file not in test_settings.CUDA_ISSUE_TESTS: - continue else: # An explicit include_files entry overrides TESTS_TO_SKIP, allowing # dedicated jobs (e.g. test-environments-training) to run tests that @@ -305,7 +354,7 @@ def _collect_test_files( if filter_pattern and filter_pattern not in full_path: print(f"Skipping {full_path} (does not match include pattern: {filter_pattern})") continue - if exclude_pattern and exclude_pattern in full_path: + if exclude_pattern and any(p.strip() in full_path for p in exclude_pattern.split(",")): print(f"Skipping {full_path} (matches exclude pattern: {exclude_pattern})") continue if include_files and file not in include_files: @@ -313,9 +362,31 @@ def _collect_test_files( continue test_files.append(full_path) + + # Apply file-level sharding: sort deterministically, then select every Nth file. + # Skip when include_files is set — in that case the test's own conftest handles + # sharding at the test-item level (e.g. parametrized test cases). + shard_index = os.environ.get("TEST_SHARD_INDEX", "") + shard_count = os.environ.get("TEST_SHARD_COUNT", "") + if shard_index and shard_count and not include_files: + shard_index = int(shard_index) + shard_count = int(shard_count) + test_files.sort() + test_files = [f for i, f in enumerate(test_files) if i % shard_count == shard_index] + print(f"Shard {shard_index}/{shard_count}: selected {len(test_files)} test files") + return test_files +def _write_empty_report(): + """Write an empty JUnit XML report so downstream CI steps find a valid file.""" + os.makedirs("tests", exist_ok=True) + result_file = os.environ.get("TEST_RESULT_FILE", "full_report.xml") + report = JUnitXml() + report.write(f"tests/{result_file}") + print(f"Wrote empty report to tests/{result_file}") + + def pytest_sessionstart(session): """Intercept pytest startup to execute tests in the correct order.""" # Get the workspace root directory (one level up from tools) @@ -329,10 +400,8 @@ def pytest_sessionstart(session): filter_pattern = os.environ.get("TEST_FILTER_PATTERN", "") exclude_pattern = os.environ.get("TEST_EXCLUDE_PATTERN", "") include_files_str = os.environ.get("TEST_INCLUDE_FILES", "") + quarantined_only = os.environ.get("TEST_QUARANTINED_ONLY", "false") == "true" curobo_only = os.environ.get("TEST_CUROBO_ONLY", "false") == "true" - cuda_issue_only = os.environ.get("TEST_CUDA_ISSUE_ONLY", "false") == "true" - flaky_only = os.environ.get("TEST_FLAKY_ONLY", "false") == "true" - slightly_flaky_only = os.environ.get("TEST_SLIGHTLY_FLAKY_ONLY", "false") == "true" isaacsim_ci = os.environ.get("ISAACSIM_CI_SHORT", "false") == "true" @@ -356,17 +425,13 @@ def pytest_sessionstart(session): print(f"Filter pattern: '{filter_pattern}'") print(f"Exclude pattern: '{exclude_pattern}'") print(f"Include files: {include_files if include_files else 'none'}") + print(f"Quarantined-only mode: {quarantined_only}") print(f"Curobo-only mode: {curobo_only}") - print(f"CUDA-issue-only mode: {cuda_issue_only}") - print(f"Flaky-only mode: {flaky_only}") - print(f"Slightly-flaky-only mode: {slightly_flaky_only}") print(f"TEST_FILTER_PATTERN env var: '{os.environ.get('TEST_FILTER_PATTERN', 'NOT_SET')}'") print(f"TEST_EXCLUDE_PATTERN env var: '{os.environ.get('TEST_EXCLUDE_PATTERN', 'NOT_SET')}'") print(f"TEST_INCLUDE_FILES env var: '{os.environ.get('TEST_INCLUDE_FILES', 'NOT_SET')}'") + print(f"TEST_QUARANTINED_ONLY env var: '{os.environ.get('TEST_QUARANTINED_ONLY', 'NOT_SET')}'") print(f"TEST_CUROBO_ONLY env var: '{os.environ.get('TEST_CUROBO_ONLY', 'NOT_SET')}'") - print(f"TEST_CUDA_ISSUE_ONLY env var: '{os.environ.get('TEST_CUDA_ISSUE_ONLY', 'NOT_SET')}'") - print(f"TEST_FLAKY_ONLY env var: '{os.environ.get('TEST_FLAKY_ONLY', 'NOT_SET')}'") - print(f"TEST_SLIGHTLY_FLAKY_ONLY env var: '{os.environ.get('TEST_SLIGHTLY_FLAKY_ONLY', 'NOT_SET')}'") print("=" * 50) # Get all test files in the source directories @@ -375,10 +440,8 @@ def pytest_sessionstart(session): filter_pattern, exclude_pattern, include_files, - flaky_only, - slightly_flaky_only, + quarantined_only, curobo_only, - cuda_issue_only, ) if isaacsim_ci: @@ -390,6 +453,14 @@ def pytest_sessionstart(session): test_files = new_test_files if not test_files: + if quarantined_only: + print("No quarantined tests configured — nothing to run.") + _write_empty_report() + pytest.exit("No quarantined tests configured", returncode=0) + if filter_pattern: + print(f"No test files found matching filter pattern '{filter_pattern}' — nothing to run.") + _write_empty_report() + pytest.exit("No test files found for filter", returncode=0) print("No test files found in source directory") pytest.exit("No test files found", returncode=1) @@ -398,21 +469,20 @@ def pytest_sessionstart(session): print(f" - {test_file}") # Run all tests individually - failed_tests, test_status = run_individual_tests(test_files, workspace_root, isaacsim_ci) + failed_tests, test_status, xml_reports = run_individual_tests(test_files, workspace_root, isaacsim_ci) print("failed tests:", failed_tests) # Collect reports print("~~~~~~~~~ Collecting final report...") - # create new full report + # Merge in-memory report objects collected during the test run. Reading the + # on-disk files again risks losing elements if the junitparser + # read/write round-trip does not preserve them faithfully. full_report = JUnitXml() - # read all reports and merge them - for report in os.listdir("tests"): - if report.endswith(".xml"): - print(report) - report_file = JUnitXml.fromfile(f"tests/{report}") - full_report += report_file + for xml_report in xml_reports: + print(xml_report) + full_report += xml_report print("~~~~~~~~~~~~ Writing final report...") # write content to full report result_file = os.environ.get("TEST_RESULT_FILE", "full_report.xml") @@ -427,6 +497,7 @@ def pytest_sessionstart(session): num_passing = len([test_path for test_path in test_files if test_status[test_path]["result"] == "passed"]) num_failing = len([test_path for test_path in test_files if test_status[test_path]["result"] == "FAILED"]) num_timeout = len([test_path for test_path in test_files if test_status[test_path]["result"] == "TIMEOUT"]) + num_crashed = len([test_path for test_path in test_files if test_status[test_path]["result"] == "CRASHED"]) if num_tests == 0: passing_percentage = 100 @@ -442,6 +513,7 @@ def pytest_sessionstart(session): summary_str += f"Total: {num_tests}\n" summary_str += f"Passing: {num_passing}\n" summary_str += f"Failing: {num_failing}\n" + summary_str += f"Crashed: {num_crashed}\n" summary_str += f"Timeout: {num_timeout}\n" summary_str += f"Passing Percentage: {passing_percentage:.2f}%\n" @@ -482,4 +554,7 @@ def pytest_sessionstart(session): print(summary_str) # Exit pytest after custom execution to prevent normal pytest from overwriting our report - pytest.exit("Custom test execution completed", returncode=0 if num_failing == 0 else 1) + pytest.exit( + "Custom test execution completed", + returncode=0 if (num_failing == 0 and num_timeout == 0 and num_crashed == 0) else 1, + ) diff --git a/tools/test_settings.py b/tools/test_settings.py index a5e9505ef873..12d4bf5bcf97 100644 --- a/tools/test_settings.py +++ b/tools/test_settings.py @@ -15,6 +15,7 @@ DEFAULT_TIMEOUT = 1000 """The default timeout for each test in seconds.""" + PER_TEST_TIMEOUTS = { "test_articulation.py": 1000, "test_stage_in_memory.py": 1000, @@ -46,10 +47,10 @@ "test_sb3_wrapper.py": 1000, "test_skrl_wrapper.py": 1000, "test_action_state_recorder_term.py": 1000, - "test_manager_based_rl_env_obs_spaces.py": 500, + "test_manager_based_rl_env_obs_spaces.py": 1000, "test_visuotactile_sensor.py": 1000, "test_visuotactile_render.py": 1000, - "test_rigid_object_collection.py": 1000, + "test_rigid_object_collection.py": 1500, "test_outdated_sensor.py": 1000, "test_multi_tiled_camera.py": 1000, "test_multirotor.py": 1000, @@ -61,60 +62,47 @@ Note: Any tests not listed here will use the default timeout. """ -CUROBO_TESTS = [ +CUROBO_PLANNER_TESTS = [ "test_curobo_planner_franka.py", "test_curobo_planner_cube_stack.py", + "test_pink_ik.py", +] +"""Tests for the cuRobo motion planner and Pink IK controller. + +These tests are skipped in the base image CI jobs and run in the dedicated +``test-curobo`` CI job which uses the cuRobo Docker image. +""" + +SKILLGEN_TESTS = [ "test_generate_dataset_skillgen.py", "test_environments_skillgen.py", "test_environments_automate.py", - "test_pink_ik.py", ] -"""A list of tests that require cuRobo installation. +"""SkillGen and AutoMate environment tests. -These tests are skipped in the base image CI jobs and run separately in the -dedicated ``test-curobo`` CI job which uses the cuRobo Docker image. +These tests are skipped in the base image CI jobs and run in the dedicated +``test-skillgen`` CI job which uses the cuRobo Docker image. """ -FLAKY_TESTS = [ - # Consistently failing or highly flaky (<60% pass rate across recent CI runs) - "test_rigid_object_collection_iface.py", # 0% - "test_environments_newton.py", # 5.9% - "test_articulation_iface.py", # 7.7% - # "test_articulation.py", # 10.5% - "test_rigid_object_iface.py", # 23.1% - # "test_rigid_object_collection.py", # 26.7% - "test_physx_scene_data_provider_visualizer_contract.py", # 30.8% - "test_shadow_hand_vision_presets.py", # 47.4% - "test_mock_data_properties.py", # 50.0% - # "test_rigid_object.py", # 57.7% - # "test_contact_sensor.py", # 60.0% - "test_robot_load_performance.py", # 60.0% - # Failing in recent CI runs - # "test_camera.py", - "test_logger.py", - "test_multirotor.py", - "test_null_command_term.py", - "test_sb3_wrapper.py", - "test_selection_strategy.py", - "test_spawn_lights.py", +CUROBO_TESTS = [ + *CUROBO_PLANNER_TESTS, + *SKILLGEN_TESTS, ] -"""A list of tests that are known to be flaky (< 60% pass rate). +"""A list of tests that require cuRobo installation. -These tests are skipped in normal CI runs and executed in the dedicated -``test-flaky`` CI job where failures do not block PR merges. +These tests are skipped in the base image CI jobs and run separately in the +dedicated ``test-curobo`` and ``test-skillgen`` CI jobs which use the cuRobo +Docker image. """ -SLIGHTLY_FLAKY_TESTS = [ - # Mildly intermittent (96%+ pass rate across recent CI runs) - # "test_multi_mesh_ray_caster_camera.py", # 96.2% - # "test_ray_caster_camera.py", # 96.2% - "test_surface_gripper.py", # 96.2% - "test_env_cfg_no_forbidden_imports.py", # 96.4% -] -"""A list of tests that are mildly flaky (96%+ pass rate). +QUARANTINED_TESTS: list[str] = [] +"""A list of tests that are quarantined due to known instability. -These tests are skipped in normal CI runs and executed in the dedicated -``test-slightly-flaky`` CI job where failures do not block PR merges. +These tests are skipped in normal CI runs. When the ``test-quarantined`` +CI job is enabled (gated by the ``RUN_QUARANTINED_TESTS`` repository +variable), they run in a dedicated job where failures do not block PR +merges. The job is currently disabled. Add test filenames here to +quarantine them from regular CI. """ TESTS_TO_SKIP = [ @@ -127,14 +115,13 @@ # lab_tasks "test_record_video.py", # Failing "test_tiled_camera_env.py", # Need to improve the logic - # curobo / skillgen - require cuRobo installation; run via the test-curobo CI job + # curobo / skillgen - require cuRobo installation; run via test-curobo and test-skillgen CI jobs *CUROBO_TESTS, - # flaky tests - run in dedicated CI jobs that do not block PR merges - *FLAKY_TESTS, - *SLIGHTLY_FLAKY_TESTS, + # quarantined tests - run in dedicated CI job that does not block PR merges + *QUARANTINED_TESTS, "test_environments_training.py", # Long-running RL training test; runs in dedicated CI job ] -"""A list of tests to skip by run_tests.py""" +"""A list of tests to skip in CI (see conftest.py).""" TEST_RL_ENVS = [ # classic control