Skip to content

Fix closures on aarch64; add macOS CI - #37

Open
lazarusA wants to merge 1 commit into
JuliaDiff:mainfrom
lazarusA:fix-arm64-macos
Open

lazarusA wants to merge 1 commit into
JuliaDiff:mainfrom
lazarusA:fix-arm64-macos

Conversation

@lazarusA

Copy link
Copy Markdown
Contributor

This issue has been annoying me for a while now. With some 🤖 assistance here is a solution.

🤖

Cause

Polyester builds a @cfunction from the batch body. The do block captured
f (and check), so when f carries data the block is not a singleton. Polyester
then needs a runtime closure cfunction, which Julia only supports on x86/x86_64.

Changes

  • src: pass f and check through batch's argument tuple instead of
    capturing them. The do block captures nothing and stays a singleton on every
    platform. No behaviour change on x86.
  • test: new closures capturing data test set that covers threaded_gradient!
    and both threaded_jacobian! methods with data-capturing closures, with
    Val{false}() and Val{true}(), a length that isn't a multiple of the chunk
    size, and repeated runs with an allocating loss.
  • CI: add macos-latest (aarch64) jobs for Julia 1 and ~1.10.0-0. The new
    tests only catch this bug on Arm with more than one thread, and the existing
    matrix is Linux x86/x64 only. The jobs use the same JULIA_NUM_THREADS=5.

Testing

Locally on Apple silicon (Julia 1.13.4): the new tests error with the message
above on the old code and pass with the fix, with both 8 threads and 1 thread.

closes #36

@codecov

codecov Bot commented Nov 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.22%. Comparing base (694f6e1) to head (51f6787).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main      #37   +/-   ##
=======================================
  Coverage   96.22%   96.22%           
=======================================
  Files           1        1           
  Lines         106      106           
=======================================
  Hits          102      102           
  Misses          4        4           

☔ 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.

@lazarusA

Copy link
Copy Markdown
Contributor Author

@ChrisRackauckas let's roll-up an agent review on my agent assisted PR. Should be fine, but another check doesn't hurt, well, additional energy consumption.

@ChrisRackauckas-Claude

Copy link
Copy Markdown

🤖 Automated comment from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris.

Review round 1 · Upstream fix requested · 51f67873
Risk: high (H1)
Verdict: UPSTREAM

  • [P2] [regression] src/PolyesterForwardDiff.jl:65, src/PolyesterForwardDiff.jl:123, and src/PolyesterForwardDiff.jl:182 must preserve the callable supplied to threaded_gradient! and both threaded_jacobian! methods so the documented ForwardDiff-compatible API still accepts callable dense arrays. The head passes the callable through the same Polyester argument conversion as the work arrays. With five threads, Polyester replaces a callable DenseVector with a non-callable …
Evidence and checks

PR: #37

Reviewed head: 51f6787
Raw SHA-256: 10097c76fd67e991cf8bbc04ffafaaa21459f337bcdef68b9f85e51d19133b5b
Source SHA-256: 933edca20095b8d1887468df306e97ae679fda78d1d131b4df58ff3e2799b637
Source: standard-review-v1 (harness-log)
Reviewer session: 01a2427f-c47b-7202-926d-7f0e54deea90
Slot: 1
Confidence: unknown
Own risk fixed before author rating/discussion: yes
Redaction: ran (substitutions=0)

Risk assessment

  • Risk: high (H1)
  • Verdict: UPSTREAM
  • Reviewed head: 51f6787

Review report

VERDICT: UPSTREAM
Round: 1
Head: 51f6787
Base: 682697c
Slot: 1
CI: green
Session: 01a2427f-c47b-7202-926d-7f0e54deea90
Reviewer: codex-cli 0.172.0; model: gpt-6.2-sol
Review triage: {"families":["callable-array-conversion"],"nonblocking":[],"contract":false}

  • Blocking priorities: P2
  • Must fix before merge: yes

Risk

high (H1: all three threaded differentiation entry points reject previously accepted callable inputs when Polyester uses workers)

Blocking findings

  • [P2] [regression] src/PolyesterForwardDiff.jl:65, src/PolyesterForwardDiff.jl:123, and src/PolyesterForwardDiff.jl:182 must preserve the callable supplied to threaded_gradient! and both threaded_jacobian! methods so the documented ForwardDiff-compatible API still accepts callable dense arrays. The head passes the callable through the same Polyester argument conversion as the work arrays. With five threads, Polyester replaces a callable DenseVector with a non-callable StrideArraysCore.PtrArray. With one thread, the serial branch passes through the original object. Both tag settings reproduced the difference on all three entry points.

    Implementation fix

    For any downstream implementation that passes the callable explicitly, put f or f! in a plain parametric struct with a callable::F field before passing it to batch in all three methods. Read the field inside the worker and pass the original object to the existing evaluator so dispatch and tag construction use its original type. An isolated Polyester probe preserved the callable this way in 20/20 five-thread runs. In test/runtests.jl, exercise a callable dense vector in all three entry points under both tag settings with enough chunks to use workers. Assert the exact gradient 6 .* x, objective 3 * sum(abs2, x), both Jacobians with diagonal 3 and off-diagonal 0, and the in-place output 3 .* x. The compatibility promise is in README.md under “Example calls.”

    Run with Julia 1.10.11 and --threads=5. The base passed both assertions. The head raised MethodError: objects of type StrideArraysCore.PtrArray{…} are not callable.

    using ForwardDiff, PolyesterForwardDiff
    
    struct Weights <: DenseVector{Float64}
        data::Vector{Float64}
    end
    Base.size(w::Weights) = size(w.data)
    Base.IndexStyle(::Type{Weights}) = IndexLinear()
    Base.getindex(w::Weights, i::Int) = w.data[i]
    Base.strides(w::Weights) = strides(w.data)
    Base.unsafe_convert(::Type{Ptr{Float64}}, w::Weights) =
        Base.unsafe_convert(Ptr{Float64}, w.data)
    (w::Weights)(x) = sum(w.data .* x.^2)
    
    x = Float64.(1:41)
    w = Weights(fill(3.0, length(x)))
    dx = similar(x)
    @assert PolyesterForwardDiff.threaded_gradient!(w, dx, x, ForwardDiff.Chunk{8}()) == 3 * sum(abs2, x)
    @assert dx == 6 .* x

Non-blocking findings

None.

Upstream redirect

Upstream repo: JuliaSIMD/Polyester.jl
Upstream target: new
Upstream title: Support capturing callbacks in threaded batch on ARM64
Root cause: [pre-existing] Polyester 0.7.19 generates a runtime @cfunction($bc, ...) for a batch callback that captures state. Julia 1.10.11 on emulated ARM64 Linux rejects that form with cfunction: closures are not supported on this platform. The same failure occurs without ForwardDiff or PolyesterForwardDiff. The head avoids that branch for the original closure case and passes its new ARM64 tests. Fix batch_closure and _batch_no_reserve in Polyester's src/batch.jl by dispatching through a static C function and carrying the original callable in the GC-preserved worker payload. Add the capturing callback to Polyester's test/runtests.jl on ARM64 and assert all 97 outputs with five threads.
Isolated MWE:

using Polyester

function captured!(out, f)
    batch((length(out), Threads.nthreads()), out) do (out,), lo, hi
        for i in lo:hi
            out[i] = f(i)
        end
    end
end

function probe()
    data = [2, 7]
    f = i -> data[1] * i + data[2]
    out = zeros(Int, 97)
    captured!(out, f)
    @assert out == 2 .* (1:97) .+ 7
end

probe()

With five threads, the capturing form passed on x86-64 and errored inside batch_closure on emulated ARM64. The explicit-argument control produced 97/97 correct outputs on both architectures.

Downstream follow-up: After the Polyester fix is released, retain the ARM64 matrix and capturing-callable tests against the fixed dependency. Include the callable-array regression test when verifying the downstream integration.

What I ran

  • Native x86-64 Julia 1.10.11 with five threads and the same resolved dependency versions on base and head. Pkg.test(; allow_reresolve=false) passed on both with Polyester 0.7.19 and ForwardDiff 1.5.0. The suite also passed on both with ForwardDiff 0.10.39. The head's closure testset reported 207/207 in both environments.
  • Emulated ARM64 Linux, Julia 1.10.11 with five threads, Polyester 0.7.19 and ForwardDiff 1.5.0. Each revision passed its own suite. The head suite against the base implementation errored on its first capturing gradient call with cfunction: closures are not supported on this platform. The same suite on the head implementation passed all 207 closure assertions.
  • Exact analytic probes on native x86-64 for reference and array captures, functors, strided input and output, full and partial chunks, and both tag settings. Both revisions passed 1128/1128 with one and five threads. The callable-array probe passed all three entry points at both thread counts on base. On head it passed all one-thread cases and threw MethodError in all six five-thread cases across the two tag settings.
  • git diff --check passed and the checkout stayed clean. The only workflow change adds two macOS ARM64 entries to the existing test and coverage job in .github/workflows/CI.yml:23. The other changes are package source and tests.
  • uv run --locked python --version reported Python 3.12.13 and warned that --locked has no effect outside a uv project. Julia ran the package tests and probes.

What I did not verify

Native macOS, 32-bit Julia, the newest Julia CI entry, and the remote CI logs. The CI status is supplied review metadata. The exact linked issue text was outside the blind review inputs.

AUTHOR_GRADE: {"task":"bugfix","score":3,"difficulty":3,"rounds":1,"author_harness":"unknown","author_model":"unknown","note":"The ARM64 closure tests fail on the base and pass on the head. The change bypasses an isolated Polyester callback failure and breaks callable dense arrays in all three threaded entry points."}

Head link: 51f6787


🤖 Posted by an AI agent — harness: codex-cli 0.172.0 · model: gpt-6.2-sol
Conversation: local session 01a2427f-c47b-7202-926d-7f0e54deea90 (no session URL)

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.

threaded_gradient! / threaded_jacobian! fail on Apple silicon (aarch64) when f is a closure

2 participants