Skip to content

Deterministic CUDA grid_sample backward - #196856

Open
drisspg wants to merge 4 commits into
mainfrom
ptq/20260911-pytorch-adhoc-4d8560
Open

drisspg wants to merge 4 commits into
mainfrom
ptq/20260911-pytorch-adhoc-4d8560

Conversation

@drisspg

@drisspg drisspg commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Human Note

Replaces the backwards witha determnisitic variant. It be much faster insome cases at the cost of extra memory; farming opinions but also I fully replaced we may just want this for determ option I was trying to keep tight so I can add back

Agent Report

Deterministic CUDA grid_sample backward

Use stable destination grouping and fixed reductions for CUDA input gradients when deterministic algorithms are enabled. The original native atomic and cuDNN library backward paths remain the defaults. Under deterministic mode, cuDNN backward delegates to the native deterministic implementation; cuDNN forward is unchanged.

Implementation

  • Support 2D nearest/bilinear/bicubic and 3D nearest/trilinear/bicubic modes (3D bicubic was added upstream in grid_sample: support mode='bicubic' with 5-D input, including its double backward #194787), padding/alignment settings, and FP16/BF16/FP32/FP64.
  • Reuse native coordinate helpers and preserve the existing single-writer grid-gradient math. Direct native backward still computes the grid gradient even when the second output-mask entry is false.
  • Stable-sort contribution IDs by destination, then reduce in a fixed order. Long segments use fixed 256-record partials; one writer owns each final destination/channel result.
  • Process at most 2**20 mapping records per chunk, committed in stream order. Partial payload has a separate 64 MiB cap; larger payload configurations use the direct deterministic reduction. Allocation sizes depend on shapes/dtype/mode, not grid values or collision counts.
  • All four new kernels have launch bounds matching their 256-thread blocks. Current-stream launches, caching-allocator workspace, CUB wrappers, and launch-error checks follow ATen conventions.
  • Preserve schemas and autocast registration; update obsolete determinism alerts/docs. Different floating-point summation order intentionally changes bits relative to old atomic results.

Validation

Current head (rebased onto 630ed2a, which added upstream 3D bicubic): built successfully on GB300, CUDA 13.1, sm_103a. In test_nn.py -k grid_sample, 142 tests passed (52 skips are the CPU instances of CUDA-only tests) along with 4536 subtests. The existing test_grid_sample and test_grid_sample_3d now run every mode, padding and alignment setting in both default and deterministic mode, with bitwise replay checks. 3D bicubic is included. The suite also covers dispatch and profiler routes, gradcheck/gradgradcheck, low-precision long segments, chunk-boundary crossings (2D bilinear, 2D and 3D bicubic), streams, CUDA-graph replay with changed grid values, and gradient output masks.

The test_torch determinism-alert tests (7) and the Inductor codegen tests (4) passed. CUDA grid_sample cases in test_ops_gradients (4) and test_ops (4) also passed. Scoped lint passed. Earlier full-autograd CUDA-graph and sanitizer runs (memcheck/racecheck/synccheck) predate the rebase and were not rerun.

python -m pytest test/test_nn.py -k grid_sample
python -m pytest test/test_torch.py -k grid_sample
python -m pytest test/inductor/test_grid_sampler_codegen.py

Performance: dense shape heatmaps

The deterministic implementation is opt-in. The original native atomic and cuDNN library backward paths remain the defaults; enabling deterministic algorithms selects the new native accumulation algorithm. The following figures measure native CUDA backward, not the cuDNN library backward or whole-model training.

All 440 paired comparisons completed and passed their numerical/replay gates: 11 channel counts × 10 output sampling counts × 2 layouts × 2 candidate policies. Every heatmap cell is measured, with no interpolation or omitted failures. Each figure contains 220 cells: the CF and CL panels for one policy.

The fixed workload is N=1, input spatial shape 24×24, output spatial shape 1×T, FP32 bilinear sampling, zeros padding, align_corners=False, and both gradients. C spans 1, 3, 4, 8, 16, 32, 64, 128, 256, 512, 1024; T spans powers of two from 64 through 32,768. Input/upstream values are random in [-1,1], and contiguous grid coordinates are random in [-1.2,1.2], using seed 20260911. CF and CL use identical logical values. This is a dense grid over C and T within one fixed operator family—not a sweep over all spatial geometries, dtypes or encoder workloads.

Deterministic-mode latency

Ratio = original nondeterministic native latency / current deterministic latency; above 1 means faster. Colors are logarithmic and centered at 1. Large-channel cases show the clearest gains, while small-channel cases are broadly slower. Across the measured grid, ratios range from 0.168× to 5.624× in CF and 0.169× to 2.109× in CL. Near-1 cells should not be read as statistically established wins or selector boundaries.

The largest CF ratio is at C=1024, T=64: 629.02 → 111.84 us. The same shape in CL is 455.39 → 215.90 us. The worst CF cell is C=3, T=2048: 12.19 → 72.62 us. These are specific synthetic operator results, not a universal or workload-weighted speedup.

Dense deterministic backward speedup heatmaps across 11 channel counts and 10 sampling counts in CF and CL layouts

Default-mode latency

Change = 100 × (current / original − 1), percent; lower is better. Across all 220 default-mode cells, the median latency change ranges from −4.48% to +3.95%. The reference and candidate are interleaved within each cell. Small differences in these microsecond-scale measurements do not establish statistical equivalence or a systematic speedup.

Dense default-mode backward latency-change heatmaps; percent change with lower values better

Added eager peak allocation

Added peak = current peak − matched original-native peak, MiB; lower is better. Default mode adds zero bytes in every one of its 220 cells. Deterministic-mode added peak ranges from 0.011 to 7.760 MiB in this fixed input geometry. Memory includes returned gradients and temporary workspace but excludes resident input/grid/upstream tensors; output sizes match. It is not reserved VRAM, CUDA graph pool size, or whole-model memory. The 64 MiB partial-payload cap is not a total-workspace cap.

Dense deterministic backward added-memory heatmaps in MiB across CF and CL layouts

Measurement contract

Measurements used GB300, CUDA 13.1, sm_103a, normal DVFS, and one exclusive GPU reservation. Each cell ran five alternating original/current rounds of 50 warm fixed-pointer CUDA graph samples per variant, with ten uncaptured/ten captured warmups; reported values are medians of the five round medians. fill_uninitialized_memory=True was retained for deterministic mode. Device zeroing, grouping, reduction, grid-gradient work and deterministic initialization fills are included; host allocation, transfers, compilation and graph capture are excluded. Eager peak allocation was measured separately.

Before timing, both returned gradients were checked against an independent CPU FP64 reference with the existing dtype/shape-aware tolerances; input-gradient replay was checked bitwise when deterministic mode was enabled, and grid-gradient replay in both modes. All 44 shards have consistent source/device metadata, all 440 cells retain five rounds of 50 raw samples per variant, and all seven recorded source hashes match the current files. Code revision: c723923d327; the original native reference is frozen from seed ad9365af5a15. No kernels or selector rules were changed during this sweep.

Raw records, numerical errors, kernel names and telemetry are preserved under job-local general/dense-shapes-v1/, including heatmap-values.csv with absolute latencies and summary.json. The frozen contract is general/dense-shapes-contract.md, the driver is general/run_dense_shape_sweep.py, and the renderer is visuals/render_dense_heatmaps.py; these investigation artifacts are not source files included in the PR. The separately measured 16-workload matrix below covers additional dtypes/modes and structured/collision grids; do not combine its ratios with this fixed random-grid sweep as an aggregate training speedup.

Earlier 16-workload matrix: other dtypes, modes, structured grids and collision stress

Earlier 16-workload matrix: default versus deterministic mode

The current implementation is opt-in, not unconditional. With deterministic algorithms disabled, the 16 measured configurations retain the original native backward's allocation footprint and have closely matching latency. With torch.use_deterministic_algorithms(True), performance is shape/layout-dependent: some large-channel or high-contention cases improve, while ordinary small-channel images become slower. These are synthetic native-CUDA backward microbenchmarks, not encoder-training results.

  • Default mode: current/reference median latency changes range from -1.3% to +1.0% across all 16 cases; extra eager peak allocation is zero bytes in every case. Small timing differences are not evidence of a systematic speedup or a statistical equivalence guarantee.
  • Deterministic mode: the C1024 positional-table case is 2.00x faster in CF layout, but only 1.07x in CL layout; the variable-grid holdout is 1.09x. The sampled FP16 bicubic case is 2.10x faster. These ratios compare the old nondeterministic native implementation with the new deterministic implementation.
  • Costs are retained in the table: RGB backward is about 5.9x slower, C32 images 2.2–2.6x slower, and the sampled 3D trilinear case 4.7x slower in deterministic mode. A small hot-grid case is 3.6x slower, whereas the large collision/chunk stress case is 31.30x faster. The latter is a stress result, not a general speedup claim or a measured crossover boundary.
  • Workspace: deterministic-mode added eager peak allocation ranges from 0 MiB for grid-gradient-only work to 38.226 MiB for the large-output stress case; positional-table cases add 0.949–1.948 MiB. This is peak allocated memory above the matched reference, not reserved VRAM or CUDA graph pool size. The 64 MiB partial-payload cap is not a cap on total workspace.

Coverage and how to read the table

All 15 frozen configurations plus one variable-grid holdout are shown, each measured in both candidate modes. The set covers N=1/2, C=1/3/4/8/16/32/1024, 2D/3D sampling, CF/CL layouts, FP16/BF16/FP32/FP64, bilinear/trilinear/bicubic/nearest, all three padding modes, both align settings, and gradient-mask variants. This is a representative matrix, not a dense Cartesian sweep of every combination.

Shapes below are spatial input → spatial output; N and C are separate. CF means ordinary NCHW/NCDHW contiguous; CL means channel stride one for input/upstream. Unless noted, rows use FP32 bilinear, zeros padding, align_corners=False, and both gradients. The trilinear row uses reflection/False; the FP16 and BF16 rows state their exceptions explicitly. Grids are contiguous. mask=(T,F) still includes the native operator's always-computed grid gradient; it is not a grid-gradient-elision optimization.

Backward latency is in microseconds, lower is better. Each timing cell is its own paired old-native → current measurement. Old/deterministic is a speedup ratio; above 1 means the deterministic implementation is faster. Added peak memory is in MiB, lower is better, and applies only to deterministic mode; default added peak is zero for every row. Do not divide across the two independently paired timing columns.

Workload N, C Input → output spatial shape Layout Default: old → current (us) Deterministic: old → current (us) Old/deterministic Added peak (MiB)
Tiny 1, 1 8x8 → 8x8 CF 12.91 → 13.04 13.47 → 35.01 0.38x 0.011
RGB 2, 3 64x64 → 64x64 CF 12.16 → 12.21 12.24 → 72.22 0.17x 1.700
RGB 2, 3 64x64 → 64x64 CL 12.10 → 12.00 12.11 → 71.86 0.17x 1.700
32-channel image 2, 32 64x64 → 64x64 CF 34.37 → 34.27 34.37 → 88.74 0.39x 1.700
32-channel image 2, 32 64x64 → 64x64 CL 44.54 → 44.64 44.54 → 98.42 0.45x 1.700
Positional table 1, 1024 24x24 → 1x8192 CF 581.78 → 583.65 585.97 → 293.25 2.00x 1.948
Positional table 1, 1024 24x24 → 1x8192 CL 696.67 → 696.72 701.14 → 657.22 1.07x 1.948
Positional table, mask=(T,F) 1, 1024 24x24 → 1x8192 CL 697.10 → 696.93 697.78 → 652.48 1.07x 1.948
Small hot grid 1, 4 8x8 → 1x1024 CL 23.30 → 22.99 23.04 → 82.67 0.28x 0.152
Large hot grid / chunk stress 2, 4 2x2 → 1x131075 CF 5158.22 → 5163.10 5179.57 → 165.47 31.30x 38.226
3D trilinear, reflection 2, 4 8x16x16 → 8x12x12 CF 17.74 → 17.71 17.62 → 83.38 0.21x 0.940
FP16 bicubic, reflection, align=True 1, 16 32x32 → 31x29 CL 792.77 → 796.38 791.36 → 376.85 2.10x 0.730
BF16 3D nearest, border, align=True 2, 1 8x16x16 → 8x12x12 CF 12.10 → 12.03 12.03 → 45.66 0.26x 0.112
FP64 bilinear 1, 8 8x8 → 9x11 CF 21.02 → 21.18 20.83 → 43.36 0.48x 0.020
Grid gradient only, mask=(F,T) 2, 32 16x16 → 16x16 CL 24.34 → 24.26 24.14 → 24.35 0.99x 0.000
Variable-grid table holdout 1, 1024 24x24 → 1x3963 CL 695.60 → 695.38 696.27 → 641.09 1.09x 0.949

The positional-table grids repeat eight 32x32 pixel-center grids. The holdout concatenates 24x32, 32x40, 16x48 and 31x37 grids (3963 sites), with a fixed 2**-13 normalized-coordinate offset to avoid one-sided derivatives at integer-pixel knots. It was added after the frozen 15-case matrix as confirmation, without dropping/reweighting cases or using it for tuning. These are synthetic table workloads, not an identified production NaViT callsite.

Measurement contract and provenance

NVIDIA GB300, CUDA 13.1, target sm_103a; normal DVFS, no clock/power changes. CPU fixture seed 20260911, nontrivial random input/upstream values, random/central-hot/structured grids as labeled. Each policy used five alternating old/current rounds with 50 warm fixed-pointer CUDA graph samples per variant per round and ten uncaptured/ten captured warmups. Numbers are medians of the five round medians, not a single best run. The two policy matrices ran in one GPU reservation. Observed before/after telemetry ranges: SM clock 2070–2070 MHz, power 191.3–276.5 W, temperature 44–46 C; these sparse snapshots are not continuous clock-stability measurements.

Device zeroing, grouping, reduction, grid-gradient work, and deterministic-mode initialization fills are included. fill_uninitialized_memory=True was retained for deterministic runs. Host allocation, transfers, compilation and graph capture are excluded from replay latency. Eager peak memory was measured separately, including returned gradients and workspace but excluding resident input/grid/upstream tensors. Forward code is unchanged; no forward speedup is claimed. These timings exercise native CUDA backward, not the cuDNN library backward or end-to-end autograd/training overhead.

The old-native reference is from seed ad9365af5a15, rebuilt for the same sm_103a target. Raw result metadata records 36b911315de plus the then-uncommitted mode-gating changes; SHA256 checks of the input-gradient kernel and native/cuDNN dispatch sources match the current c723923d327 checkout. These 16-case measurements predate the separate dense shape sweep above. Correctness was gated independently against CPU FP64 before timing, including both returned gradients and dtype-appropriate error checks; kernel names and repeated-gradient checks are retained in the raw records.

Deterministic timing dispersion: min–max of the five round medians (us; lower is better)

These ranges describe round-to-round variation, not confidence intervals.

Recorded case Current deterministic round-median range (us)
tiny 33.97–35.49
rgb_cf 72.11–72.98
rgb_cl 71.09–72.24
image32_cf 88.58–89.06
image32_cl 98.26–98.70
navit_cf 291.81–294.10
navit_cl 652.83–660.64
navit_input_only 652.42–660.43
collision4 81.70–83.39
long_collision 164.10–167.06
volume 82.78–84.42
bicubic_half 376.37–379.63
nearest_bf16 44.61–45.82
double 43.01–43.89
grid_only 23.84–24.59
navit_varlen_holdout 640.56–642.21

Raw samples, matching source hashes, per-round telemetry, numerical errors and memory measurements are preserved in job-local general/results-mode-gate-final-default.json and general/results-mode-gate-final-deterministic.json, with the fixture/contract in general/benchmark-contract.md. They are not files included in the source PR. Hardware coverage is GB300 only; no claim is made about older GPUs/toolkits, a dense crossover sweep, or real encoder throughput. No aggregate speedup is reported because these cases do not have a production workload weighting.

How it works

How deterministic grid_sample backward works

With the flag off, the default path scatters each sample's weighted contribution with atomics, so values that share an input cell are summed in whatever order threads arrive. With the flag on, every (sample, tap) contribution becomes a record. A stable radix sort groups the records by input destination, and one warp per segment and channel tile reduces each group with a fixed tree. Each input cell is therefore written once, and the bits are identical from run to run. Records are processed in fixed chunks of 2**20, committed in stream order. The native grid-gradient kernel then runs as a compile-time grid-only variant.

Review boundaries

Runtime coverage is GB300 only. No new Hopper/Blackwell-specific instruction dependency was found, but other GPU generations, older toolkit variants, ROCm, CPU-only builds, and full repository CI remain unverified. No cross-architecture/version bitwise identity guarantee is claimed. Larger workspace can affect memory-constrained workloads.

Full measurements, the workspace equation/examples, and development history are preserved in the job workspace rather than embedded in this PR. The source patch contains 10 files, 806 additions and 69 deletions (rebased onto 630ed2a).

Agent Worklog

Current state

Branch ptq/20260911-pytorch-adhoc-4d8560, commit 36b911315de, based on ad9365af5a15. The user's PTQ submission committed and pushed the code, then PR creation failed because the generated body exceeded GitHub's 65,536-character limit. This follow-up compacted local body inputs only; no code edits, additional commits/pushes, or GitHub operations were performed.

Evidence index

Paths below are job-local artifacts, not files included in the source PR:

  • report-detailed.md: full implementation, performance, memory, and compatibility report before body compaction.
  • worklog-history.md: complete chronological investigation/build/test history.
  • memory-workspace.md: allocation equation, realistic worked examples, all measured memory deltas, and configuration-versus-value distinction.
  • general/results-public-launch-bounds.json: all 16 final source-matched benchmark cases and raw samples; contract in general/benchmark-contract.md.
  • public-tests-launch-bounds.log, public-inductor-launch-bounds.log: latest 152 public and four compiled tests.
  • public-autograd-capture-corrected.log, public-autograd-capture-async-allocator.log: six full-autograd capture cases.
  • public-legacy-release.log, public-release-{memcheck,racecheck,synccheck}.log: earlier legacy/sanitizer evidence, predating launch-bound annotations.
  • build-public.log, build-public.exit, lint-launch-bounds.log: latest successful build and scoped lint.
  • workspace-value-independence.log: unchanged peak allocation across three grid-value distributions at each fixed configuration.

Body compaction

PTQ concatenates report.md, worklog.md, and repro.py without a size budget. The previous body was about 81,700 characters before the human note. Detailed documents were archived rather than discarded. The original 10 KiB repro asserted pre-fix nondeterminism guards; it was preserved as repro-investigation.py so it is no longer automatically embedded as a current repro. Retained tests in the patch are the current runnable correctness/determinism checks.

The saved human note was empty after the failed submission, so the retry may ask for it again. It was not replaced or invented. Full notes, memory equations, and raw evidence remain available locally. No agent-notes or shared configuration changes.


This PR was generated by ptq with human review.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

@pytorch-bot

pytorch-bot Bot commented Sep 12, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/196856

Note: Links to docs will display an error until the docs builds have been completed.

✅ No Failures

As of commit 1af77aa with merge base 42d36d3 (image):
💚 Looks good so far! There are no failures yet. 💚

🟡 GREEN LIGHT - PR requires human review:

  • Triviality
    • New ~416-line CUDA algorithm in GridSamplerBackward.cu (make_records, radix sort, partial_gradients, reduce_segments) fits no trivial change class
    • Native backward kernels in cuda/GridSampler.cu gain a compute_input template parameter and a deterministic dispatch branch
  • User-facing surface
    • torch.use_deterministic_algorithms docs in torch/__init__.py move grid_sample from the erroring list to the deterministic list
    • alertNotDeterministic calls removed for grid_sampler_{2,3}d_backward_cuda and cudnn_grid_sampler_backward, changing what deterministic mode does
  • Dispatch and numerics
    • cudnn_grid_sampler_backward now reroutes to at::grid_sampler_2d_backward under deterministic mode, with a new fixed-order reduction
    • Needs a human review of the kernel's indexing, workspace bounds and the cuDNN delegation

reason: not_trivial
Reviewed commit: 1af77aa

Inference job

🐛 Report a wrong verdict

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 12, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-15T19:30:37.189694Z c723923 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@drisspg drisspg changed the title Fix from 20260911-pytorch-adhoc-4d8560 Deterministic CUDA grid_sample backward Sep 12, 2026
@drisspg
drisspg marked this pull request as draft September 12, 2026 05:50
@drisspg drisspg added the topic: not user facing topic category label Sep 14, 2026
@drisspg
drisspg marked this pull request as ready for review September 15, 2026 19:22
@drisspg

drisspg commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

@claude Please do a deep review focused on subtle correctness bugs and regressions that are easy for human reviewers to miss. Prioritize findings over summary. I dont care about anything that isnt a real bug drop all the noise but that, if you there isnt anything to report just say so with a small comment

@claude

claude Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Claude encountered an error after 51m 2s —— View job


Deep correctness review

  • Read full diff (GridSamplerBackward.cu, dispatch, cuDNN path)
  • Audit new kernels for indexing/overflow/race/ordering bugs
  • Audit gating + cuDNN delegation for behavior regressions
  • Report findings
    · branch ptq/20260911-pytorch-adhoc-4d8560

@drisspg
drisspg force-pushed the ptq/20260911-pytorch-adhoc-4d8560 branch from c723923 to 88e9fde Compare November 3, 2026 02:12
@drisspg

drisspg commented Nov 3, 2026

Copy link
Copy Markdown
Contributor Author

@claude Please do a deep review focused on subtle correctness bugs and regressions that are easy for human reviewers to miss. Prioritize findings over summary. I dont care about anything that isnt a real bug drop all the noise but that, if you there isnt anything to report just say so with a small comment

@claude

claude Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Claude finished @drisspg's task in 5m 6s —— View job


I didn't find any real correctness bugs or regressions in this PR.

What I checked
  • Record generation (make_records): corner order, weights, and rounding order match the native kernels for 2D bilinear/nearest/bicubic and 3D trilinear/nearest/bicubic. That covers the scalar_t vs opmath products, compute_coordinates/resolve_cubic_taps tap validity, and NaN/huge-coordinate handling, which comes out as the same invalid tap as native. Key layout matches the key % input_spatial decode in reduce_segments. sample_offsets works with non-contiguous and expanded grad_output.
  • Sort and grouping: get_num_bits(destinations) covers the invalid sentinel key. CUB radix sort is stable. unique_by_key with a counting iterator gives segment starts. max_segments = min(records, destinations + 1) is a valid upper bound.
  • Partials: the <= 2*ceil(R/256) bound holds for segments longer than 256. The upper-bound binary search over prefix always lands on a segment with a non-zero count. Uninitialized offsets past num_segments are never read. Every early continue is uniform across the warp, so the logical-32-lane shuffles (including width-32 on ROCm wave64) are safe.
  • Final write: there is one writer per (destination, channel) per chunk, and chunks are ordered on the stream. The index math assumes a contiguous grad_input, and both callers (grid_sampler_{2,3}d_backward_cuda) allocate it with zeros_like(..., LEGACY_CONTIGUOUS_MEMORY_FORMAT). The native kernel launched afterwards never touches grad_input when compute_input=false.
  • Gating: the default path only gains the compute_input=true template parameter, so behavior is unchanged. Under deterministic mode, output_mask[0]=false still skips the input gradient, and the grid gradient (including nearest zeros) is still written.
  • cuDNN delegation: the argument order (grad_output, input, grid) and the hard-coded bilinear/zeros/align_corners=True match the only conditions under which at::grid_sampler selects cuDNN. The double-backward formula is unchanged.

This was a static review only. I did not build anything or run the tests.

· branch `ptq/20260911-pytorch-adhoc-4d8560`

@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Nov 3, 2026
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Nov 10, 2026
…ding

## Summary (human-written)
Add deterministic grid_sample backward. We will switch to pytorch/pytorch#196856 once it lands. However, the wrapper to turn on deterministic mode is still needed.

## Why
NaViT samples its position table with F.grid_sample. The CUDA grid_sample backward accumulates with atomic adds, so the input grad changes from run to run. positional_embedding_vlm is invariant over TP and CP, so on main every rank computes a different grad and the copies drift. Deterministic mode does not help: it raises on this op.

**Example.**
```
NaViT-sized table [1, 1536, 32, 32], sampled at a 37x37 grid, same inputs, two backward runs
before (F.grid_sample): input grads differ between runs
after (this op):        input grads bitwise equal over 10 eager runs and one compiled run
```

## What changed
- Add torchtitan::deterministic_grid_sample (torchtitan/ops/grid_sample.py): bilinear, zeros padding, align_corners=False. The forward is F.grid_sample. The backward builds a dense bilinear weight matrix (P x H*W, 4 nonzeros per row) and computes the input grad as one matmul in at least fp32, with no gather, scatter or atomics. It raises ValueError if the grid needs a gradient.
- NaViT samples its position table with the op.
- The unused grid_sample_mode config field is removed; only bilinear was used.
- TODO in code: switch to the upstream deterministic grid_sample backward once pytorch/pytorch#196856 lands.

## Alternatives considered
- A scatter_add backward on corner indices: also deterministic, but needs 528-535 MiB per frame at a 37x37 grid (1554-1578 MiB at 64x64) and is 4-11x slower.

## Numerics
The NaViT position-embedding input grad accumulates in fp32 and is deterministic. At a 37x37 grid it differs from native grid_sample by up to 0.64 in bf16 (native accumulates in bf16 with atomics) and by up to 7.2e-7 in fp32. In fp64 the difference is 1.3e-15. The forward is unchanged.

| Config | Hardware | Result |
| --- | --- | --- |
| Spark debug_mm CP2 and TP2, full FT, global deterministic mode off, 60 steps | 2 x H100 | replicated params (including positional_embedding_vlm) bitwise equal, grad_norm identical per rank, every step |

## Performance
Peak backward memory for one frame (1536 channels, 32x32 table): 43-51 MiB at a 37x37 grid and 54-78 MiB at 64x64. The matrix is P x H*W, so the cost grows with the table size.

## Testing
- CPU tests: fp64 forward equal and backward within 1e-12 of F.grid_sample (with out-of-bounds points), gradcheck, opcheck (fake and autograd registration), and grid-grad rejection. They catch wrong bilinear weights, wrong padding, and a broken fake or autograd registration.
- GPU test: the input grad of a NaViT-sized table is bitwise equal over 10 eager runs and one compiled run, in fp32 and bf16. It catches a non-deterministic backward.
- CPU tests at this commit: tests/unit_tests/cpu/ops and models/muse_spark, 37 passed, 3 xfailed.

stack-info: PR: pytorch/torchtitan#5892, branch: fegin/stack/21
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Nov 10, 2026
…ding

## Summary (human-written)
Add deterministic grid_sample backward. We will switch to pytorch/pytorch#196856 once it lands. However, the wrapper to turn on deterministic mode is still needed.

## Why
NaViT samples its position table with F.grid_sample. The CUDA grid_sample backward accumulates with atomic adds, so the input grad changes from run to run. positional_embedding_vlm is invariant over TP and CP, so on main every rank computes a different grad and the copies drift. Deterministic mode does not help: it raises on this op.

**Example.**
```
NaViT-sized table [1, 1536, 32, 32], sampled at a 37x37 grid, same inputs, two backward runs
before (F.grid_sample): input grads differ between runs
after (this op):        input grads bitwise equal over 10 eager runs, and over 2 compiled runs
```

## What changed
- Add torchtitan::deterministic_grid_sample (torchtitan/ops/grid_sample.py): bilinear, zeros padding, align_corners=False. The forward is F.grid_sample. The backward builds a dense bilinear weight matrix (P x H*W, 4 nonzeros per row) and computes the input grad as one matmul in at least fp32, with no gather, scatter or atomics. It raises ValueError if the grid needs a gradient.
- NaViT samples its position table with the op.
- The unused grid_sample_mode config field is removed; only bilinear was used.
- TODO in code: switch to the upstream deterministic grid_sample backward once pytorch/pytorch#196856 lands.

## Alternatives considered
- A scatter_add backward on corner indices: also deterministic, but needs 528-535 MiB per frame at a 37x37 grid (1554-1578 MiB at 64x64) and is 4-11x slower.

## Numerics
The NaViT position-embedding input grad accumulates in fp32 and is deterministic. At a 37x37 grid it differs from native grid_sample by up to 0.64 in bf16 (native accumulates in bf16 with atomics) and by up to 7.2e-7 in fp32. In fp64 the difference is 1.3e-15. The forward is unchanged.

| Config | Hardware | Result |
| --- | --- | --- |
| Spark debug_mm CP2 and TP2, full FT, global deterministic mode off, 60 steps | 2 x H100 | replicated params (including positional_embedding_vlm) bitwise equal, grad_norm identical per rank, every step |

## Performance
Peak backward memory for one frame (1536 channels, 32x32 table): 43-51 MiB at a 37x37 grid and 54-78 MiB at 64x64. The matrix is P x H*W, so the cost grows with the table size.

## Testing
- CPU tests: fp64 forward equal and backward within 1e-12 of F.grid_sample (with out-of-bounds points), gradcheck, opcheck (fake and autograd registration), and grid-grad rejection. They catch wrong bilinear weights, wrong padding, and a broken fake or autograd registration.
- GPU test: the input grad of a NaViT-sized table is bitwise equal over 10 eager runs, and over 2 compiled runs, in fp32 and bf16. Eager and compiled are not compared to each other, since Inductor may round differently. It catches a non-deterministic backward.
- CPU tests at this commit: tests/unit_tests/cpu/ops and models/muse_spark, 37 passed, 3 xfailed.

stack-info: PR: pytorch/torchtitan#5892, branch: fegin/stack/21
fegin added a commit to pytorch/torchtitan that referenced this pull request Nov 10, 2026
…ding

## Summary (human-written)
Add deterministic grid_sample backward. We will switch to pytorch/pytorch#196856 once it lands. However, the wrapper to turn on deterministic mode is still needed.

## Why
NaViT samples its position table with F.grid_sample. The CUDA grid_sample backward accumulates with atomic adds, so the input grad changes from run to run. positional_embedding_vlm is invariant over TP and CP, so on main every rank computes a different grad and the copies drift. Deterministic mode does not help: it raises on this op.

**Example.**
```
NaViT-sized table [1, 1536, 32, 32], sampled at a 37x37 grid, same inputs, two backward runs
before (F.grid_sample): input grads differ between runs
after (this op):        input grads bitwise equal over 10 eager runs, and over 2 compiled runs
```

## What changed
- Add torchtitan::deterministic_grid_sample (torchtitan/ops/grid_sample.py): bilinear, zeros padding, align_corners=False. The forward is F.grid_sample. The backward builds a dense bilinear weight matrix (P x H*W, 4 nonzeros per row) and computes the input grad as one matmul in at least fp32, with no gather, scatter or atomics. It raises ValueError if the grid needs a gradient.
- NaViT samples its position table with the op.
- The unused grid_sample_mode config field is removed; only bilinear was used.
- TODO in code: switch to the upstream deterministic grid_sample backward once pytorch/pytorch#196856 lands.

## Alternatives considered
- A scatter_add backward on corner indices: also deterministic, but needs 528-535 MiB per frame at a 37x37 grid (1554-1578 MiB at 64x64) and is 4-11x slower.

## Numerics
The NaViT position-embedding input grad accumulates in fp32 and is deterministic. At a 37x37 grid it differs from native grid_sample by up to 0.64 in bf16 (native accumulates in bf16 with atomics) and by up to 7.2e-7 in fp32. In fp64 the difference is 1.3e-15. The forward is unchanged.

| Config | Hardware | Result |
| --- | --- | --- |
| Spark debug_mm CP2 and TP2, full FT, global deterministic mode off, 60 steps | 2 x H100 | replicated params (including positional_embedding_vlm) bitwise equal, grad_norm identical per rank, every step |

## Performance
Peak backward memory for one frame (1536 channels, 32x32 table): 43-51 MiB at a 37x37 grid and 54-78 MiB at 64x64. The matrix is P x H*W, so the cost grows with the table size.

## Testing
- CPU tests: fp64 forward equal and backward within 1e-12 of F.grid_sample (with out-of-bounds points), gradcheck, opcheck (fake and autograd registration), and grid-grad rejection. They catch wrong bilinear weights, wrong padding, and a broken fake or autograd registration.
- GPU test: the input grad of a NaViT-sized table is bitwise equal over 10 eager runs, and over 2 compiled runs, in fp32 and bf16. Eager and compiled are not compared to each other, since Inductor may round differently. It catches a non-deterministic backward.
- CPU tests at this commit: tests/unit_tests/cpu/ops and models/muse_spark, 37 passed, 3 xfailed.

stack-info: PR: #5892, branch: fegin/stack/21

@drisspg drisspg left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@claude Please do a deep review focused on subtle correctness bugs and regressions that are easy for human reviewers to miss. Prioritize findings over summary. I dont care about anything that isnt a real bug drop all the noise but that, if you there isnt anything to report just say so with a small comment

fegin added a commit to pytorch/torchtitan that referenced this pull request Nov 10, 2026
…ding

## Summary (human-written)
Add deterministic grid_sample backward. We will switch to pytorch/pytorch#196856 once it lands. However, the wrapper to turn on deterministic mode is still needed.

## Why
NaViT samples its position table with F.grid_sample. The CUDA grid_sample backward accumulates with atomic adds, so the input grad changes from run to run. positional_embedding_vlm is invariant over TP and CP, so on main every rank computes a different grad and the copies drift. Deterministic mode does not help: it raises on this op.

**Example.**
```
NaViT-sized table [1, 1536, 32, 32], sampled at a 37x37 grid, same inputs, two backward runs
before (F.grid_sample): input grads differ between runs
after (this op):        input grads bitwise equal over 10 eager runs, and over 2 compiled runs
```

## What changed
- Add torchtitan::deterministic_grid_sample (torchtitan/ops/grid_sample.py): bilinear, zeros padding, align_corners=False. The forward is F.grid_sample. The backward builds a dense bilinear weight matrix (P x H*W, 4 nonzeros per row) and computes the input grad as one matmul in at least fp32, with no gather, scatter or atomics. It raises ValueError if the grid needs a gradient.
- NaViT samples its position table with the op.
- The unused grid_sample_mode config field is removed; only bilinear was used.
- TODO in code: switch to the upstream deterministic grid_sample backward once pytorch/pytorch#196856 lands.

## Alternatives considered
- A scatter_add backward on corner indices: also deterministic, but needs 528-535 MiB per frame at a 37x37 grid (1554-1578 MiB at 64x64) and is 4-11x slower.

## Numerics
The NaViT position-embedding input grad accumulates in fp32 and is deterministic. At a 37x37 grid it differs from native grid_sample by up to 0.64 in bf16 (native accumulates in bf16 with atomics) and by up to 7.2e-7 in fp32. In fp64 the difference is 1.3e-15. The forward is unchanged.

| Config | Hardware | Result |
| --- | --- | --- |
| Spark debug_mm CP2 and TP2, full FT, global deterministic mode off, 60 steps | 2 x H100 | replicated params (including positional_embedding_vlm) bitwise equal, grad_norm identical per rank, every step |

## Performance
Peak backward memory for one frame (1536 channels, 32x32 table): 43-51 MiB at a 37x37 grid and 54-78 MiB at 64x64. The matrix is P x H*W, so the cost grows with the table size.

## Testing
- CPU tests: fp64 forward equal and backward within 1e-12 of F.grid_sample (with out-of-bounds points), gradcheck, opcheck (fake and autograd registration), and grid-grad rejection. They catch wrong bilinear weights, wrong padding, and a broken fake or autograd registration.
- GPU test: the input grad of a NaViT-sized table is bitwise equal over 10 eager runs, and over 2 compiled runs, in fp32 and bf16. Eager and compiled are not compared to each other, since Inductor may round differently. It catches a non-deterministic backward.
- CPU tests at this commit: tests/unit_tests/cpu/ops and models/muse_spark, 37 passed, 3 xfailed.

stack-info: PR: #5892, branch: fegin/stack/21
fegin added a commit to pytorch/torchtitan that referenced this pull request Nov 11, 2026
…ding

## Summary (human-written)
Add deterministic grid_sample backward. We will switch to pytorch/pytorch#196856 once it lands. However, the wrapper to turn on deterministic mode is still needed.

## Why
NaViT samples its position table with F.grid_sample. The CUDA grid_sample backward accumulates with atomic adds, so the input grad changes from run to run. positional_embedding_vlm is invariant over TP and CP, so on main every rank computes a different grad and the copies drift. Deterministic mode does not help: it raises on this op.

**Example.**
```
NaViT-sized table [1, 1536, 32, 32], sampled at a 37x37 grid, same inputs, two backward runs
before (F.grid_sample): input grads differ between runs
after (this op):        input grads bitwise equal over 10 eager runs, and over 2 compiled runs
```

## What changed
- Add torchtitan::deterministic_grid_sample (torchtitan/ops/grid_sample.py): bilinear, zeros padding, align_corners=False. The forward is F.grid_sample. The backward builds a dense bilinear weight matrix (P x H*W, 4 nonzeros per row) and computes the input grad as one matmul in at least fp32, with no gather, scatter or atomics. It raises ValueError if the grid needs a gradient.
- NaViT samples its position table with the op.
- The unused grid_sample_mode config field is removed; only bilinear was used.
- TODO in code: switch to the upstream deterministic grid_sample backward once pytorch/pytorch#196856 lands.

## Alternatives considered
- A scatter_add backward on corner indices: also deterministic, but needs 528-535 MiB per frame at a 37x37 grid (1554-1578 MiB at 64x64) and is 4-11x slower.

## Numerics
The NaViT position-embedding input grad accumulates in fp32 and is deterministic. At a 37x37 grid it differs from native grid_sample by up to 0.64 in bf16 (native accumulates in bf16 with atomics) and by up to 7.2e-7 in fp32. In fp64 the difference is 1.3e-15. The forward is unchanged.

| Config | Hardware | Result |
| --- | --- | --- |
| Spark debug_mm CP2 and TP2, full FT, global deterministic mode off, 60 steps | 2 x H100 | replicated params (including positional_embedding_vlm) bitwise equal, grad_norm identical per rank, every step |

## Performance
Peak backward memory for one frame (1536 channels, 32x32 table): 43-51 MiB at a 37x37 grid and 54-78 MiB at 64x64. The matrix is P x H*W, so the cost grows with the table size.

## Testing
- CPU tests: fp64 forward equal and backward within 1e-12 of F.grid_sample (with out-of-bounds points), gradcheck, opcheck (fake and autograd registration), and grid-grad rejection. They catch wrong bilinear weights, wrong padding, and a broken fake or autograd registration.
- GPU test: the input grad of a NaViT-sized table is bitwise equal over 10 eager runs, and over 2 compiled runs, in fp32 and bf16. Eager and compiled are not compared to each other, since Inductor may round differently. It catches a non-deterministic backward.
- CPU tests at this commit: tests/unit_tests/cpu/ops and models/muse_spark, 37 passed, 3 xfailed.

stack-info: PR: #5892, branch: fegin/stack/21
fegin added a commit to pytorch/torchtitan that referenced this pull request Nov 11, 2026
…ding (#5892)

## Summary (human-written)
Add deterministic grid_sample backward. We will switch to pytorch/pytorch#196856 once it lands. However, the wrapper to turn on deterministic mode is still needed.

## Why
NaViT samples its position table with F.grid_sample. The CUDA grid_sample backward accumulates with atomic adds, so the input grad changes from run to run. positional_embedding_vlm is invariant over TP and CP, so on main every rank computes a different grad and the copies drift. Deterministic mode does not help: it raises on this op.

**Example.**
```
NaViT-sized table [1, 1536, 32, 32], sampled at a 37x37 grid, same inputs, two backward runs
before (F.grid_sample): input grads differ between runs
after (this op):        input grads bitwise equal over 10 eager runs, and over 2 compiled runs
```

## What changed
- Add torchtitan::deterministic_grid_sample (torchtitan/ops/grid_sample.py): bilinear, zeros padding, align_corners=False. The forward is F.grid_sample. The backward builds a dense bilinear weight matrix (P x H*W, 4 nonzeros per row) and computes the input grad as one matmul in at least fp32, with no gather, scatter or atomics. It raises ValueError if the grid needs a gradient.
- NaViT samples its position table with the op.
- The unused grid_sample_mode config field is removed; only bilinear was used.
- TODO in code: switch to the upstream deterministic grid_sample backward once pytorch/pytorch#196856 lands.

## Alternatives considered
- A scatter_add backward on corner indices: also deterministic, but needs 528-535 MiB per frame at a 37x37 grid (1554-1578 MiB at 64x64) and is 4-11x slower.

## Numerics
The NaViT position-embedding input grad accumulates in fp32 and is deterministic. At a 37x37 grid it differs from native grid_sample by up to 0.64 in bf16 (native accumulates in bf16 with atomics) and by up to 7.2e-7 in fp32. In fp64 the difference is 1.3e-15. The forward is unchanged.

| Config | Hardware | Result |
| --- | --- | --- |
| Spark debug_mm CP2 and TP2, full FT, global deterministic mode off, 60 steps | 2 x H100 | replicated params (including positional_embedding_vlm) bitwise equal, grad_norm identical per rank, every step |

## Performance
Peak backward memory for one frame (1536 channels, 32x32 table): 43-51 MiB at a 37x37 grid and 54-78 MiB at 64x64. The matrix is P x H*W, so the cost grows with the table size.

## Testing
- CPU tests: fp64 forward equal and backward within 1e-12 of F.grid_sample (with out-of-bounds points), gradcheck, opcheck (fake and autograd registration), and grid-grad rejection. They catch wrong bilinear weights, wrong padding, and a broken fake or autograd registration.
- GPU test: the input grad of a NaViT-sized table is bitwise equal over 10 eager runs, and over 2 compiled runs, in fp32 and bf16. Eager and compiled are not compared to each other, since Inductor may round differently. It catches a non-deterministic backward.
- CPU tests at this commit: tests/unit_tests/cpu/ops and models/muse_spark, 37 passed, 3 xfailed.
@drisspg
drisspg force-pushed the ptq/20260911-pytorch-adhoc-4d8560 branch from 78c1591 to 29f9d08 Compare November 12, 2026 15:16
Retain the original native atomic and cuDNN backward paths by default, and
select fixed-order input-gradient accumulation only in deterministic mode.
Share the native grid-gradient math through a grid-only specialization.
Cover off, strict, and warn-only dispatch, document the opt-in behavior, and
include the new test file in the CODEOWNERS taxonomy.

Test Plan:

```sh
spin lint -a CODEOWNERS aten/src/ATen/native/cuda/GridSampler.cu aten/src/ATen/native/cuda/GridSampler.cuh aten/src/ATen/native/cudnn/GridSampler.cpp docs/source/notes/randomness.md test/test_grid_sampler.py torch/__init__.py torch/nn/functional.py
git diff --check
```

Prior validation of the unchanged implementation recorded 161 public tests,
158 legacy-reference cases, four Inductor tests, and targeted sanitizer checks
passing on GB300. This submission reran lint; it did not rerun GPU tests.
Exercise default and deterministic CUDA backward in the existing numerical
fixtures, reusing their CPU references and checking exact replay. Retain
focused dispatch, gradient, reduction-boundary, stream, and graph coverage in
the existing device test class, and remove the duplicate standalone suite.

Test Plan:

Both expanded existing tests and all 39 focused CUDA cases passed on GB300:

```sh
gpu-run --no-wait auto -- timeout --signal=TERM --kill-after=5s 60s .venv/bin/python pytorch/test/test_nn.py TestNN.test_grid_sample TestNN.test_grid_sample_3d -v
gpu-run --no-wait auto -- timeout --signal=TERM --kill-after=5s 60s .venv/bin/python pytorch/test/test_nn.py TestNNDeviceTypeCUDA -k grid_sample_dispatch -k grid_sample_gradcheck -k grid_sample_expanded_streams_and_graph -k grid_sample_long_segments -k grid_sample_chunk_boundary -k grid_sample_backward_output_mask -v
```

Pre-commit checks from the source worktree:

```sh
spin lint -a -- --skip CODEOWNERS_TAXONOMY test/test_nn.py CODEOWNERS
git diff --check
```

The HEAD-based taxonomy check must run after committing the paired test-file
and CODEOWNERS-rule deletion.
@drisspg
drisspg force-pushed the ptq/20260911-pytorch-adhoc-4d8560 branch from 29f9d08 to 1af77aa Compare November 18, 2026 12:30

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

ciflow/inductor GL/human GreenLight marked as needing human review module: inductor topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant