Skip to content

Fix frac and vector mod gradients (GH-2280) - #2281

Open
Lynn-hh wants to merge 1 commit into
NVIDIA:mainfrom
Lynn-hh:lynn-hh/frac-vec-mod-grad
Open

Lynn-hh wants to merge 1 commit into
NVIDIA:mainfrom
Lynn-hh:lynn-hh/frac-vec-mod-grad

Conversation

@Lynn-hh

@Lynn-hh Lynn-hh commented Nov 10, 2026

Copy link
Copy Markdown

What problem are you trying to solve?

tape.backward() silently returns zero gradients through wp.frac() and through wp.mod() on vectors. Away from the discontinuities, d/dx frac(x) is 1, and each component of the vector mod(a, b) has derivative 1 with respect to a. I use Warp through Newton for differentiable robot simulation, where patterns like trajectory interpolation at wp.frac(t) or wrapping vec3 positions into a periodic box lose their gradient without any warning. Details and a reproducer are in the issue.

Closes #2280

What does this change?

  • wp.frac() and the vector overloads of wp.mod() are no longer registered with is_differentiable=False, so codegen emits their reverse calls.
  • adj_frac() in builtin.h accumulates the incoming adjoint, since frac(x) = x - trunc(x) and trunc() is piecewise constant.
  • The three vector adj_mod() overloads in vec.h call the scalar adj_mod() for each component, the same way the vector adj_min() and adj_max() do. Scalar and vector modulo now share one gradient rule. Integer vectors keep the empty integer adjoint, and float16/bfloat16 use the same scalar code as their forward pass.
  • test_float_to_int now also checks the frac output, which it previously skipped, and expects a unit gradient there. test_modulo builds its kernel with backward enabled for float types and checks the gradient with respect to the dividend for vector lengths 2 to 5.

The divisor gradient of scalar wp.mod() is a separate bug (#2223) that #2225 fixes. Because the vector adjoint calls the scalar one, the vector divisor gradient becomes correct once #2225 lands, and the two pull requests touch different code.

Existing pull requests

Validation

  • Regression validation: the updated test_float_to_int (float16, float32, float64) and test_modulo (float16, float32, float64) fail on main without this change, with zero gradients where 1 is expected. They pass with it, along with the integer variants. The reproducer in Gradients of wp.frac() and vector wp.mod() are always zero #2280 prints [0. 0. 0.] before the change and [1. 1. 1.] after it. A finite-difference sweep over about 90 differentiable built-ins with wp.autograd.jacobian() and jacobian_fd() in float64 agrees for frac and for the vector mod dividend after the change.
  • NVIDIA GPU: not tested on an NVIDIA GPU. I tested on the CPU device only (Apple M3, macOS). The change is in header code shared by the CPU and CUDA backends and has no CUDA-specific paths.
  • Other validation: test_arithmetic, test_vec_scalar_ops, test_grad, test_grad_debug, test_bf16, test_fp16, test_rounding, test_vec, test_math and test_external_build pass on CPU. ruff, ruff-format, clang-format and typos are clean at the versions pinned in .pre-commit-config.yaml. The generated exports.h and __init__.pyi do not depend on is_differentiable, so they are unchanged.

Checklist

  • I have read and followed the Contributing Guidelines.
  • This pull request does not bundle unrelated changes unless a maintainer agreed to the broader scope.
  • My branch is up to date with main and contains one commit, unless a maintainer agreed to keep the change as multiple commits.
  • I included any required changelog fragments and used a + prefix only for changes that do not require a GitHub issue.

@copy-pr-bot

copy-pr-bot Bot commented Nov 10, 2026

Copy link
Copy Markdown

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

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@greptile-apps

greptile-apps Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge within its stated scope.

Summary

Fixes gradients through wp.frac() and the dividend of vector wp.mod().

  • wp.frac() passes its gradient back to the input.
  • Vector wp.mod() passes gradients back to its dividend.

Lynn-hh explicitly defers the known divisor-gradient issue to #2225. No new actionable issues were found. Tests were not run during this review.

Reviews (3) · Last reviewed commit: "Fix frac and vector mod gradients (GH-22..." · Reviewed by Greptile

@coderabbitai

coderabbitai Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Bug Fixes
    • Corrected gradients for frac() and vector mod() operations. Gradients now propagate correctly for floating-point inputs, including componentwise gradients for vector modulo.

The change enables gradients for wp.frac() and vector wp.mod(). Native adjoints propagate those gradients, and tests check the resulting gradients.

Changes: frac and vector mod gradients

Layer / File(s) Summary
Enable and implement gradients
warp/_src/builtins.py, warp/native/builtin.h, warp/native/vec.h
The built-in registrations enable differentiation for frac and vector mod. The frac adjoint accumulates the incoming gradient into its input. Vector mod adjoints apply the scalar modulo adjoint componentwise.
Test and document gradients
warp/tests/test_arithmetic.py, warp/tests/test_vec_scalar_ops.py, changelog/2280.fixed.md
Arithmetic tests expect a gradient of 1 for frac and zero for the other tested operations. Floating-point vector modulo tests check component gradients. The changelog records the fix.

Suggested reviewers: c0d1f1ed, shi-eric, daedalus5, alecjacobson

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: Minimal · up to d387c

This change makes gradients flow through wp.frac() and vector wp.mod(), which previously returned zeros. Regression tests cover the new behavior. No merge-blocking risk was identified.

Architecture risk: Low · up to d387c

The change affects 2 systems.

Changed systems: warp, changelog

Architecture concerns
No architecture-level concerns identified.

Review details

Systems and components

  • observed — warp (service) was modified; 5 changed files map to changed impact.
  • observed — changelog (service) was modified; 1 changed file maps to changed impact.

Before / after behavior

  • observed — Modified behavior in changelog/2280.fixed.md: Adds a changelog entry stating that gradients of wp.frac() and wp.mod() on vectors were always zero and are fixed.
  • observed — Modified behavior in warp/tests/test_arithmetic.py: test_float_to_int documents the expected piecewise-constant gradients for the first five operations and the unit gradient of frac between integers. The gradient loop now includes all six output rows and checks an explicitly constructed expected gradient array, setting the frac entry to 1.0 while retaining zero expectations for the other operations.
  • observed — Modified behavior in warp/tests/test_vec_scalar_ops.py: The modulo test now enables backward-kernel generation for floating-point dtypes; other dtypes still disable it.
  • observed — Modified behavior in warp/tests/test_vec_scalar_ops.py: Adds floating-point-only modulo gradient checks: each output loss is backpropagated, the concatenated input gradients are expected to be zero except for a value of 2 at the matching component, and the tape is cleared after each check.
Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the two operations whose gradients were fixed, wp.frac() and vector wp.mod(). It matches the main change in the changeset. It is concise and specific, and it includes the issue referen…
Description check Passed The description states the problem (zero gradients through wp.frac() and vector wp.mod()), lists the code changes in builtin.h, vec.h, builtins.py, and the tests, and gives validation details. It is d…
Linked Issues check Passed Issue #2280 requires nonzero gradients through wp.frac() and the vector overloads of wp.mod(), away from discontinuities, plus regression coverage. The whole-PR diff (merge base to head) shows: (1…
Out of Scope Changes check Passed Every changed file supports the #2280 fix: warp/_src/builtins.py (differentiability flags for frac and vector mod), warp/native/builtin.h (adj_frac), warp/native/vec.h (vector adj_mod ov…
Full details: Title check

Explanation

The title names the two operations whose gradients were fixed, wp.frac() and vector wp.mod(). It matches the main change in the changeset. It is concise and specific, and it includes the issue reference.

Full details: Description check

Explanation

The description states the problem (zero gradients through wp.frac() and vector wp.mod()), lists the code changes in builtin.h, vec.h, builtins.py, and the tests, and gives validation details. It is directly related to the changeset.

Full details: Linked Issues check

Explanation

Issue #2280 requires nonzero gradients through wp.frac() and the vector overloads of wp.mod(), away from discontinuities, plus regression coverage. The whole-PR diff (merge base to head) shows: (1) is_differentiable=False removed from the frac and vector mod registrations in warp/_src/builtins.py, so reverse calls are generated; (2) adj_frac() in warp/native/builtin.h now performs adj_x += adj_ret, which matches frac(x) = x - trunc(x) with piecewise-constant trunc; (3) the generic, 2-component, and 3-component vector adj_mod() overloads in warp/native/vec.h call the scalar adj_mod() per component. Regression tests: test_float_to_int in test_arithmetic.py now expects a unit gradient for the frac output (j == 5) and zero for the other five; test_modulo in test_vec_scalar_ops.py enables backward for float dtypes and checks the dividend gradient for vector outputs. The scalar divisor-gradient issue (#2223) is excluded by #2280, so the scalar adjoint's divisor term is not a requirement here. The incremental diff from the previous reviewed head could not be read, so this verdict rests on the whole-PR diff at the current head, which is sufficient. No automated run was performed in this review; the PR's reported CPU test results are not independently verified.

Full details: Out of Scope Changes check

Explanation

Every changed file supports the #2280 fix: warp/_src/builtins.py (differentiability flags for frac and vector mod), warp/native/builtin.h (adj_frac), warp/native/vec.h (vector adj_mod overloads delegating to scalar adj_mod), warp/tests/test_arithmetic.py (frac gradient regression), warp/tests/test_vec_scalar_ops.py (vector modulo backward regression), and changelog/2280.fixed.md. The vector adjoint inherits the scalar divisor-gradient behavior, but the PR does not modify the scalar divisor term, which is tracked separately in #2223/#2225. No unrelated change was found in the whole-PR diff. The incremental diff could not be read, so the assessment covers the whole-PR diff at the current head.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

  • Source mode: Auto
  • Repository: NVIDIA/warp
  • Branch: main
  • File: .coderabbit.yml
  • Commit: b304405
  • Layers: Repository YAML
  • Review profile: CHILL
  • Plan: Enterprise
  • Run ID: cef29030-5de7-4e2b-bd76-e2ef037efb31
Commits

Reviewing files that changed from the base of the PR and between fde96e9 and d387c09.

Files selected for processing: 3

  • warp/_src/builtins.py
  • warp/native/builtin.h
  • warp/native/vec.h
Files with no reviewable changes: 1

  • warp/_src/builtins.py

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

Comment thread warp/native/vec.h Outdated
// MISSINGADJOINT: element-wise: adj_a[i] += adj_ret[i]; adj_b[i] -= floor(a[i] / b[i]) *
// adj_ret[i]
for (unsigned i = 0; i < Length; ++i) {
adj_mod(a[i], b[i], adj_a[i], adj_b[i], adj_ret[i]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

There’s a small CPU vectorization opportunity here. In warmed graph replays over 262,144 float32 vectors with retained nonzero gradient seeds, copying adj_ret locally reduced CPU backward times by roughly 9–12% for vec2–vec4 on x86. CUDA timings stayed within ~1%.

Could you snapshot the incoming gradient before the component updates?

const vec_t<Length, Type> grad = adj_ret;
for (unsigned i = 0; i < Length; ++i) {
    adj_mod(a[i], b[i], adj_a[i], adj_b[i], grad[i]);
}

Please apply the same local copy to the vec2/vec3 overloads and verify whether it improves CPU backward performance on your Apple M3. CUDA validation can be handled separately.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Forgot to mention that for any subsequent changes, please keep the branch's changes squashed to a single commit and rebased with main, which aids in merging this.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Thanks! Applied to the generic overload and to the vec2/vec3 specializations, squashed into one commit and rebased onto main.

On an Apple M3 I don't see a measurable difference. I timed warmed CPU graph replays of the backward launch over 262,144 float32 vectors with a retained nonzero gradient seed, alternating the two versions over three runs. Median times in ms, before and after:

before after
vec2 0.462 0.462
vec3 0.577 0.582
vec4 0.520 0.527

The differences are within run-to-run noise on this machine, so the gain looks specific to x86, and nothing regresses on arm64. The frac and modulo tests still pass on CPU.

wp.frac() and the vector overloads of wp.mod() were registered as
non-differentiable and their native adjoints were empty stubs, so
tape.backward() silently returned zero gradients through them.

frac(x) = x - trunc(x) has a unit gradient between integers. The vector
adj_mod() now calls the scalar adj_mod() for each component, so scalar
and vector modulo share one gradient rule, including the divisor term
tracked in NVIDIAGH-2223.

Signed-off-by: Lynn <[email protected]>
@Lynn-hh
Lynn-hh force-pushed the lynn-hh/frac-vec-mod-grad branch from fde96e9 to d387c09 Compare November 16, 2026 04:09

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Gradients of wp.frac() and vector wp.mod() are always zero

2 participants