-
Notifications
You must be signed in to change notification settings - Fork 368
Expand file tree
/
Copy pathp02.mojo
More file actions
61 lines (51 loc) · 1.76 KB
/
Copy pathp02.mojo
File metadata and controls
61 lines (51 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# ===----------------------------------------------------------------------=== #
#
# This file is Modular Inc proprietary.
#
# ===----------------------------------------------------------------------=== #
from std.memory import Pointer
from std.gpu import thread_idx
from max.gpu.host import DeviceContext
from std.testing import assert_equal
# ANCHOR: add
comptime SIZE = 4
comptime BLOCKS_PER_GRID = 1
comptime THREADS_PER_BLOCK = SIZE
comptime dtype = DType.float32
def add(
output: Pointer[Scalar[dtype], MutAnyOrigin],
a: Pointer[Scalar[dtype], MutAnyOrigin],
b: Pointer[Scalar[dtype], MutAnyOrigin],
):
var i = thread_idx.x
# FILL ME IN (roughly 1 line)
# ANCHOR_END: add
def main() raises:
with DeviceContext() as ctx:
var out = ctx.enqueue_create_buffer[dtype](SIZE)
out.enqueue_fill(0)
var a = ctx.enqueue_create_buffer[dtype](SIZE)
a.enqueue_fill(0)
var b = ctx.enqueue_create_buffer[dtype](SIZE)
b.enqueue_fill(0)
var expected = ctx.enqueue_create_host_buffer[dtype](SIZE)
expected.enqueue_fill(0)
with a.map_to_host() as a_host, b.map_to_host() as b_host:
for i in range(SIZE):
a_host[i] = Scalar[dtype](i)
b_host[i] = Scalar[dtype](i)
expected[i] = a_host[i] + b_host[i]
ctx.enqueue_function[add](
out,
a,
b,
grid_dim=BLOCKS_PER_GRID,
block_dim=THREADS_PER_BLOCK,
)
ctx.synchronize()
with out.map_to_host() as out_host:
print("out:", out_host)
print("expected:", expected)
for i in range(SIZE):
assert_equal(out_host[i], expected[i])
print("Puzzle 02 complete ✅")