Skip to content

Do not densify the sparse arguments of a broadcast + or - whose result is empty - #1007

Merged
ViralBShah merged 1 commit into
mainfrom
dense-broadcast-empty
Oct 5, 2026
Merged

ViralBShah merged 1 commit into
mainfrom
dense-broadcast-empty

Conversation

@ViralBShah

Copy link
Copy Markdown
Member

Fixes a regression from #1004, found in review: a broadcast + or - of a sparse array with a dense array converted the sparse arguments to Arrays before looking at the shape of the result, so an empty result cost memory proportional to the size of the sparse argument, and could run out of it.

Before

julia> x, z = spzeros(1_000_000), zeros(1, 0);

julia> size(x .+ z), @allocated(x .+ z)
((1000000, 0), 8011936)

After

julia> size(x .+ z), @allocated(x .+ z)
((1000000, 0), 48)

_densebroadcast now hands the broadcast to the dense kernel as it is when one of its axes is empty: that kernel reads no entry, so the reason to densify (generic broadcast indexing the sparse arrays entry by entry) does not apply. The result type is the same on both paths and stays inferable.

Two assertions that #1004 and #1005 added are removed as duplicates of ones in the older loops of test/higherorderfns.jl: broadcast(+, S, d) (the sums of a sparse matrix with a dense vector in the mixed-argument loop) and cos.(view(S, :, [2, 1])) (the loop over views of sparse arrays, which has a view of columns picked by a vector).

Not a backport candidate: #1004 is on no release branch.

Written by Claude Code.

🤖 Generated with Claude Code

…esult is empty

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Oct 5, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.59%. Comparing base (26dce7e) to head (a12b474).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #1007   +/-   ##
=======================================
  Coverage   95.59%   95.59%           
=======================================
  Files          16       16           
  Lines        9304     9304           
=======================================
  Hits         8894     8894           
  Misses        410      410           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@ViralBShah
ViralBShah merged commit 689b651 into main Oct 5, 2026
10 checks passed
@ViralBShah
ViralBShah deleted the dense-broadcast-empty branch October 5, 2026 18:08
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.

1 participant