Key concepts
In this puzzle, you’ll learn about:
- Working with 2D thread indices (
thread_idx.x
,thread_idx.y
) - Converting 2D coordinates to 1D memory indices
- Handling boundary checks in two dimensions
The key insight is understanding how to map from 2D thread coordinates \((i,j)\) to elements in a row-major matrix of size \(n \times n\), while ensuring thread indices are within bounds.
- 2D indexing: Each thread has a unique \((i,j)\) position
- Memory layout: Row-major ordering maps 2D to 1D memory
- Guard condition: Need bounds checking in both dimensions
- Thread bounds: More threads \((3 \times 3)\) than matrix elements \((2 \times 2)\)
Code to complete
alias SIZE = 2
alias BLOCKS_PER_GRID = 1
alias THREADS_PER_BLOCK = (3, 3)
alias dtype = DType.float32
fn add_10_2d(
out: UnsafePointer[Scalar[dtype]],
a: UnsafePointer[Scalar[dtype]],
size: Int,
):
local_i = thread_idx.x
local_j = thread_idx.y
# FILL ME IN (roughly 2 lines)
View full file: problems/p04/p04.mojo
Tips
- Get 2D indices:
local_i = thread_idx.x
,local_j = thread_idx.y
- Add guard:
if local_i < size and local_j < size
- Inside guard:
out[local_j * size + local_i] = a[local_j * size + local_i] + 10.0
Running the code
To test your solution, run the following command in your terminal:
magic run p04
Your output will look like this if the puzzle isn’t solved yet:
out: HostBuffer([0.0, 0.0, 0.0, 0.0])
expected: HostBuffer([10.0, 11.0, 12.0, 13.0])
Solution
fn add_10_2d(
out: UnsafePointer[Scalar[dtype]],
a: UnsafePointer[Scalar[dtype]],
size: Int,
):
local_i = thread_idx.x
local_j = thread_idx.y
if local_i < size and local_j < size:
out[local_j * size + local_i] = a[local_j * size + local_i] + 10.0
This solution:
- Gets 2D thread indices with
local_i = thread_idx.x
,local_j = thread_idx.y
- Guards against out-of-bounds with
if local_i < size and local_j < size
- Inside guard: adds 10 to input value using row-major indexing