From 05ace7245f5426df22c7ce1fc0f4dc0c9855e64b Mon Sep 17 00:00:00 2001 From: Tim Besard Date: Wed, 2 Dec 2026 17:52:51 +0100 Subject: [PATCH] Give a scalar the right shape in `hcat(::Number, ::AbstractGPUArray)` The scalar was made a column as tall as the other operand, so `hcat(1, AT(ones(2, 3)))` returned a 2x4 array where Base throws a DimensionMismatch, and `hcat(1, AT(ones(1, 2, 3)))` threw where Base fills the scalar across the third dimension. Like Base (and the vcat method next to it), make the scalar one element along the first two dimensions and as long as the other operand along the rest. Fixes #883 --- src/host/base.jl | 5 ++++- test/testsuite/base.jl | 7 ++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/host/base.jl b/src/host/base.jl index 28599c245..fc63272fc 100644 --- a/src/host/base.jl +++ b/src/host/base.jl @@ -175,10 +175,13 @@ end # hacky overloads to make simple vcat and hcat with numbers work as expected. # we can't really make this work in general without Base providing # a dispatch mechanism for output container type. +# +# Like Base, a leading scalar in `vcat` or `hcat` is one element along the first dimension +# and along the dimension being concatenated, and stretches along every other dimension. @inline Base.vcat(a::Number, b::AbstractGPUArray) = vcat(fill!(similar(b, typeof(a), (1,size(b)[2:end]...)), a), b) @inline Base.hcat(a::Number, b::AbstractGPUArray) = - hcat(fill!(similar(b, typeof(a), (size(b)[1:end-1]...,1)), a), b) + hcat(fill!(similar(b, typeof(a), (1, 1, size(b)[3:end]...)), a), b) ## reshape diff --git a/test/testsuite/base.jl b/test/testsuite/base.jl index 414c4b567..4589af9be 100644 --- a/test/testsuite/base.jl +++ b/test/testsuite/base.jl @@ -331,7 +331,11 @@ end @test compare(hcat, AT, rand(Float32, 3), rand(Float32, 3, 3)) @test compare(hcat, AT, rand(Float32, 3, 3), rand(Float32, 3)) @test compare(hcat, AT, rand(Float32, 3, 3), rand(Float32, 3, 3)) - #@test compare(hcat, AT, rand(Float32, ), rand(Float32, 3, 3)) + # like Base, a leading scalar is one row tall and spans the trailing dimensions + @test compare_exact(hcat, AT, rand(Float32), rand(Float32, 1, 2, 3)) + @test compare_exact(hcat, AT, Int16(1), fill(Int32(2), 1, 0, 3, 2)) + @test_throws DimensionMismatch hcat(1f0, AT(rand(Float32, 3, 3))) + @test_throws DimensionMismatch hcat(1f0, AT(rand(Float32, 2, 0))) #@test compare(hcat, AT, rand(Float32, 3, 3), rand(Float32)) @test compare(vcat, AT, rand(Float32, 3), rand(Float32, 3)) @@ -339,6 +343,7 @@ end @test compare(vcat, AT, rand(Float32, ), rand(Float32, 3)) @test compare(vcat, AT, rand(Float32, 3), rand(Float32)) @test compare(vcat, AT, rand(Float32, ), rand(Float32, 3, 3)) + @test compare(vcat, AT, rand(Float32), rand(Float32, 1, 2, 3)) #@test compare(vcat, AT, rand(Float32, 3, 3), rand(Float32)) @test compare((a,b) -> cat(a, b; dims=4), AT, rand(Float32, 3, 4), rand(Float32, 3, 4))