Part 1

This is just a straightforward check over all squares. Note you should short-circuit to save time. I was anticipating a “oh that was the compressed and now it’s a million times bigger” part 2 and was thinking we’d switch from the matrix implementation to a set implementation but we didn’t need it here.

function part1(fname = "input.txt")
    mat = stack(readlines(fname); dims = 1) .== '#'

    n_row, n_col = size(mat)

    tot = 0
    for left = 1:(n_row-1), top = 1:(n_col-1)
        mat[left, top] || continue
        for width = 1:min(n_row-left, n_col-top)
            tot +=
                mat[left+width, top] && mat[left, top+width] && mat[left+width, top+width]
        end
    end
    return tot
end

Part 2

Indeed it’s still just the same matrix. Now we just check a couple more squares. Had to be a little more careful with the bounds checks here but otherwise quite straightforward.

function part2(fname = "input.txt")
    mat = stack(readlines(fname); dims = 1) .== '#'

    n_row, n_col = size(mat)

    tot = 0
    for left = 1:(n_row-1), top = 1:(n_col-1)
        mat[left, top] || continue
        for y_offset = 0:(n_col-top)
            left - y_offset < 1 && continue
            for x_offset = 1:min(n_row-left, n_col-top-y_offset)
                tot +=
                    mat[left+x_offset, top+y_offset] &&
                    mat[left+x_offset-y_offset, top+x_offset+y_offset] &&
                    mat[left-y_offset, top+x_offset]
            end
        end
    end
    return tot
end

Something Extra

I had a sense that this is something that can be done efficiently with the GPU. Like it’s just a stencil (basically a mask of “these are corners of a square”) getting passed over the input. Make a stencil for each possible square, pass it over all points, and just add them up!

We can do this in a couple different ways: I got Gemini to do three:

  • CPU stencil. This is basically my solution except we’ve flipped the loop orders so we iterate over the 9870 square offsets in the outerloop and then sweep over the positions in the interloop (with a bitwise &). Note we can apply SIMD operations here to vectorize that addition. This code is kind of ugly; I like mine more. It is performant though: I didn’t know about @simd and too lazy to always add @inbounds.
function count_squares_byte_stencil_cpu(mat_u8::Matrix{UInt8})
    n_row, n_col = size(mat_u8)
    max_span = min(n_row, n_col) - 1
    tot = 0
    @inbounds for dy = 0:(max_span-1), dx = 1:(max_span-dy)
        r_lo, r_hi = 1 + dy, n_row - dx
        sub = 0
        for c = 1:(n_col-dx-dy)
            c1, c2, c3 = c + dy, c + dx + dy, c + dx
            @simd for r = r_lo:r_hi
                sub += Int(
                    mat_u8[r, c] & mat_u8[r+dx, c1] & mat_u8[r+dx-dy, c2] &
                    mat_u8[r-dy, c3],
                )
            end
        end
        tot += sub
    end
    return tot
end
  • CPU with bit packing. We note that since we have just a boolean mask we can pack 32 or 64 horizontal cells together and process them together! Note that the SIMD instruction is working on 8 * 64 = 512 cells/instruction!
function pack_grid(::Type{T}, mat::AbstractMatrix{Bool}) where {T<:Unsigned}
    n_bits = 8 * sizeof(T)
    shift = trailing_zeros(n_bits)
    mask = n_bits - 1
    n_row, n_col = size(mat)
    padded_words = 2 * cld(n_col, n_bits) + 1
    packed = zeros(T, n_row, padded_words)
    @inbounds for col = 1:n_col
        j = col - 1
        word, bit = (j >> shift) + 1, T(1) << (j & mask)
        for row = 1:n_row
            mat[row, col] && (packed[row, word] |= bit)
        end
    end
    return packed
end

@inline function shift_word(grid, r, w, word_shift, bit_shift)
    lo = @inbounds grid[r, w+word_shift]
    iszero(bit_shift) && return lo
    hi = @inbounds grid[r, w+word_shift+one(w)]
    n_bits = oftype(bit_shift, 8 * sizeof(eltype(grid)))
    return (lo >> bit_shift) | (hi << (n_bits - bit_shift))
end
function count_squares_bit_stencil_cpu(mat::AbstractMatrix{Bool})
    n_row, n_col = size(mat)
    packed = pack_grid(UInt64, mat)
    max_span = min(n_row, n_col) - 1
    tot = 0
    @inbounds for dy = 0:(max_span-1)
        ws1, bs1 = dy >> 6, dy & 63
        for dx = 1:(max_span-dy)
            span = dx + dy
            ws2, bs2 = span >> 6, span & 63
            ws3, bs3 = dx >> 6, dx & 63
            active_words = cld(n_col - span, 64)
            r_lo, r_hi = 1 + dy, n_row - dx
            sub = 0
            for w = 1:active_words
                @simd for r = r_lo:r_hi
                    v =
                        packed[r, w] & shift_word(packed, r + dx, w, ws1, bs1) &
                        shift_word(packed, r + dx - dy, w, ws2, bs2) &
                        shift_word(packed, r - dy, w, ws3, bs3)
                    sub += count_ones(v)
                end
            end
            tot += sub
        end
    end
    return tot
end
  • GPU. And of course the original impetus for this approach was to use the GPU. This is quite easy to do in native Julia using the KernelAbstractions library though I don’t know enough about GPU progamming to have written this myself.
using KernelAbstractions, oneAPI

@kernel function bit_stencil_gpu_kernel!(
    group_totals,
    @Const(packed),
    @Const(offsets),
    n_row::Int32,
    n_col::Int32,
    n_offsets::Int32,
    n_groups::Int32,
    ::Val{MAX_ROWS},
    ::Val{PADDED_WORDS},
    ::Val{WORKGROUP_SIZE},
) where {MAX_ROWS,PADDED_WORDS,WORKGROUP_SIZE}
    wg = @index(Group, Linear)
    tid = @index(Local, Linear)

    sram = @localmem UInt32 (MAX_ROWS, PADDED_WORDS)
    scratch = @localmem Int32 (WORKGROUP_SIZE,)

    total_words = n_row * Int32(PADDED_WORDS)
    idx = Int32(tid)
    @inbounds while idx <= total_words
        sram[mod1(idx, n_row), fld1(idx, n_row)] =
            packed[mod1(idx, n_row), fld1(idx, n_row)]
        idx += Int32(WORKGROUP_SIZE)
    end
    @synchronize()

    acc = Int32(0)
    pair_idx = Int32(wg)
    @inbounds while pair_idx <= n_offsets
        dx, dy = offsets[pair_idx]
        span = dx + dy
        ws1, bs1 = dy >> Int32(5), dy & Int32(31)
        ws2, bs2 = span >> Int32(5), span & Int32(31)
        ws3, bs3 = dx >> Int32(5), dx & Int32(31)
        active_words = (n_col - span + Int32(31)) >> Int32(5)
        r_lo, r_hi = Int32(1) + dy, n_row - dx

        r = r_lo + Int32(tid) - Int32(1)
        while r <= r_hi
            for w = Int32(1):active_words
                v =
                    sram[r, w] & shift_word(sram, r + dx, w, ws1, bs1) &
                    shift_word(sram, r + dx - dy, w, ws2, bs2) &
                    shift_word(sram, r - dy, w, ws3, bs3)
                acc += Int32(count_ones(v))
            end
            r += Int32(WORKGROUP_SIZE)
        end
        pair_idx += n_groups
    end

    @inbounds scratch[tid] = acc
    @synchronize()

    if tid == 1
        wg_sum = Int32(0)
        @inbounds for i = 1:WORKGROUP_SIZE
            wg_sum += scratch[i]
        end
        @inbounds group_totals[wg] = wg_sum
    end
end

We can run them all as a function of the underlying sparsity level of the matrix. Note that our original solution had short-circuiting so it actually benefits from sparsity while all of the other solutions just bruteforce it regardless (because branching is expensive and hard to parallelize).

We see that at low tree density the CPU with branching is very competitive. But as density increases we can’t short-circuit anymore and the stencilling starts destroying it. The stencil solutions are clearly stack except, surpisingly, though the bitpacking CPU actually wins out and is the fastest!

The explanation is basically memory overhead: keeping everything on the CPU lets us go just slightly faster. We can use the AVX-512 VPOPCNTDQ (vpopcntq zmm = 512 cells/instruction) instruction. And it’s comparing against my laptop’s weak integrated GPU which isn’t that fast.