Skip to content

Metal: run 1D convolutions through MPSGraph as 2D convolutions - #953

Open
hmedel wants to merge 1 commit into
FluxML:masterfrom
hmedel:metal-conv1d
Open

hmedel wants to merge 1 commit into
FluxML:masterfrom
hmedel:metal-conv1d

Conversation

@hmedel

@hmedel hmedel commented Dec 4, 2026

Copy link
Copy Markdown

Problem

The Metal extension implements conv!, ∇conv_data! and ∇conv_filter! with MPSGraph for
DenseConvDims{2} (4-dimensional arrays). For 1D convolutions (DenseConvDims{1}, 3-dimensional
arrays) there is no method, so they go to the generic im2col path. That path calls CPU BLAS with
Metal pointers:

using NNlib, Metal
x, w = MtlArray(randn(Float32, 50, 6, 3)), MtlArray(randn(Float32, 3, 6, 10))
NNlib.conv(x, w, DenseConvDims(x, w))
# MethodError: no method matching gemm!(::Val{false}, ::Val{false}, ::Int64, ::Int64, ::Int64,
#     ::Float32, ::Metal.MtlPtr{Float32}, ::Int64, ::Metal.MtlPtr{Float32}, ...)

Lux hits this in the backward pass of any 1D Conv on Metal. Its forward pass uses its own fallback,
but the gradients go through NNlib.∇conv_data/∇conv_filter.

Change

A 1D convolution is a 2D convolution with a singleton second spatial dimension: (W, C, N) becomes
(W, 1, C, N) and the kernel (k, Cin, Cout) becomes (k, 1, Cin, Cout), with stride 1, padding 0
and dilation 1 in that dimension. reshape on an MtlArray shares the buffer, so nothing is copied.
Grouped and flipped kernels carry over unchanged.

# 1D convolutions as 2D convolutions with a singleton second spatial dimension, so they also use
# MPSGraph (the im2col fallback calls CPU BLAS with Metal pointers).
_as_2d(a::MtlArray{T, 3}) where {T} = reshape(a, size(a, 1), 1, size(a, 2), size(a, 3))

function _cdims_2d(cdims::NNlib.DenseConvDims{1}, x4, w4)
    return NNlib.DenseConvDims(x4, w4; stride=(NNlib.stride(cdims)..., 1),
                               padding=(NNlib.padding(cdims)..., 0, 0),
                               dilation=(NNlib.dilation(cdims)..., 1),
                               groups=NNlib.groupcount(cdims),
                               flipkernel=NNlib.flipkernel(cdims))
end

function NNlib.conv!(y::MtlFloatArray{T, 3}, x::MtlFloatArray{T, 3},
                     w::MtlFloatArray{T, 3}, cdims::NNlib.DenseConvDims{1};
                     kwargs...) where {T}
    isempty(kwargs) || return NNlib.conv_im2col!(y, x, w, cdims; kwargs...)
    x4, w4 = _as_2d(x), _as_2d(w)
    NNlib.conv!(_as_2d(y), x4, w4, _cdims_2d(cdims, x4, w4))
    return y
end

function NNlib.∇conv_data!(dx::MtlFloatArray{T, 3}, dy::MtlFloatArray{T, 3},
                            w::MtlFloatArray{T, 3}, cdims::NNlib.DenseConvDims{1};
                            kwargs...) where {T}
    isempty(kwargs) || return NNlib.∇conv_data_im2col!(dx, dy, w, cdims; kwargs...)
    dx4, w4 = _as_2d(dx), _as_2d(w)
    NNlib.∇conv_data!(dx4, _as_2d(dy), w4, _cdims_2d(cdims, dx4, w4))
    return dx
end

function NNlib.∇conv_filter!(dw::MtlFloatArray{T, 3}, x::MtlFloatArray{T, 3},
                              dy::MtlFloatArray{T, 3}, cdims::NNlib.DenseConvDims{1};
                              kwargs...) where {T}
    isempty(kwargs) || return NNlib.∇conv_filter_im2col!(dw, x, dy, cdims; kwargs...)
    x4, dw4 = _as_2d(x), _as_2d(dw)
    NNlib.∇conv_filter!(dw4, x4, _as_2d(dy), _cdims_2d(cdims, x4, dw4))
    return dw
end

These methods go in ext/NNlibMetalExt.jl, after the 2D methods. With kwargs (the alpha
and beta of conv!) they keep today's behavior, like the 2D methods.

Tests (added to test/gpu/metal/conv_pool.jl)

These follow the format of the existing 2D tests. They pass on an Apple M6 (macOS 27.0.1, Julia 1.13.4,
Metal.jl 1.12.1): 48/48. All of test/gpu/metal/conv_pool.jl on this branch passes too:
102/102.

@testset "1D conv forward and backward" begin
    for T in (Float16, Float32)
        configs = (
            (randn(T, 9, 2, 3), randn(T, 3, 2, 4), 1),
            (randn(T, 9, 4, 3), randn(T, 3, 2, 6), 2),
        )
        for (x, w, groups) in configs, flipkernel in (false, true)
            cdims = DenseConvDims(size(x), size(w); stride=2, padding=(1, 0), dilation=1,
                                  groups, flipkernel)
            y = conv(x, w, cdims)
            @test Array(conv(DEVICE(x), DEVICE(w), cdims)) ≈ y
            gout = similar(DEVICE(x), size(y))
            conv!(gout, DEVICE(x), DEVICE(w), cdims)
            @test Array(gout) ≈ y

            dy = randn(T, size(y))
            dx = ∇conv_data(dy, w, cdims)
            @test Array(∇conv_data(DEVICE(dy), DEVICE(w), cdims)) ≈ dx
            gout = similar(DEVICE(x))
            ∇conv_data!(gout, DEVICE(dy), DEVICE(w), cdims)
            @test Array(gout) ≈ dx

            dw = ∇conv_filter(x, dy, cdims)
            @test Array(∇conv_filter(DEVICE(x), DEVICE(dy), cdims)) ≈ dw
            gout = similar(DEVICE(w))
            ∇conv_filter!(gout, DEVICE(x), DEVICE(dy), cdims)
            @test Array(gout) ≈ dw
        end
    end
end

Results

  • Correctness against the CPU. Max relative difference ≤ 2e-7 for conv, ∇conv_data and
    ∇conv_filter, with k = 3, 4, 5, stride 1–3, asymmetric padding (2, 1), dilation 2 and flipkernel.
  • Lux 1D Conv on Metal (forward plus gradients of x and W), which errors today:
    • Conv((5,), 64=>128, relu; pad=2) on 256×64×64 now takes 6.3 ms and matches the CPU to 7e-7;
    • with stride 2, padding (2, 1) and dilation 2 it matches to 2e-7.
  • Out of scope: 3D convolutions (5-dimensional arrays) and DepthwiseConvDims. Both still go to
    the generic path.

🤖 Generated with Claude Code

The Metal extension only implemented conv!, ∇conv_data! and ∇conv_filter! for
DenseConvDims{2}. 1D convolutions went to the generic im2col path, which calls
CPU BLAS with Metal pointers and errors (MethodError: no method matching gemm!).

Run them as 2D convolutions with a singleton second spatial dimension (reshape
shares the buffer). Adds 1D forward/backward tests to test/gpu/metal/conv_pool.jl
(Float16/Float32, groups 1 and 2, flipkernel), mirroring the 2D tests.

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

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.

1 participant