Repository navigation
Expand file tree
/
Copy pathexercise_3.py
More file actions
93 lines (72 loc) · 2.7 KB
/
Copy pathexercise_3.py
File metadata and controls
93 lines (72 loc) · 2.7 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# exercise_3.py -*- Python -*-
#
# Copyright (C) 2025 Advanced Micro Devices, Inc.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
import sys
import numpy as np
from aie.iron import Out, In, CompileTime, Program, Runtime, Worker, ObjectFifo
from aie.iron.controlflow import range_
import aie.iron as iron
@iron.jit
def exercise_3(
input0: In,
output: Out,
*,
data_size: CompileTime[int],
element_type: CompileTime[type],
):
data_ty = np.ndarray[(data_size,), np.dtype[element_type]]
# Dataflow with ObjectFifos
of_in = ObjectFifo(data_ty, name="in")
of_out = ObjectFifo(data_ty, name="out")
# Task for the core to perform
def core_fn(of_in, of_out):
elem_in = of_in.acquire(1)
elem_out = of_out.acquire(1)
for i in range_(data_size):
elem_out[i] = elem_in[i]
of_in.release(1)
of_out.release(1)
# Create a worker to perform the task
my_worker = Worker(core_fn, [of_in.cons(), of_out.prod()])
# To/from AIE-array runtime data movement
def sequence(a_in, c_out, in_h, out_h):
in_h.fill(a_in)
out_h.drain(c_out, wait=True)
rt = Runtime(sequence, [data_ty, data_ty, of_in.prod(), of_out.cons()])
# Create the program from the device type and runtime
my_program = Program(iron.get_current_device(), rt, workers=[my_worker])
# Place components (assign them resources on the device) and generate an MLIR module
return my_program.resolve_program()
def main():
# Define tensor shapes and data types
data_size = 48
element_type = np.int32
# Construct an input tensor and an output zeroed tensor
# The two tensors are in memory accessible to the NPU
input0 = iron.arange(data_size, dtype=element_type, device="npu")
output = iron.zeros_like(input0)
# JIT-compile the kernel then launches the kernel with the given arguments. Future calls
# to the kernel will use the same compiled kernel and loaded code objects
exercise_3(input0, output, data_size=output.numel(), element_type=output.dtype)
# Check the correctness of the result
e = np.equal(input0.numpy(), output.numpy())
errors = np.size(e) - np.count_nonzero(e)
# Print the results
print(f"{'input0':>4} = {'output':>4}")
print("-" * 34)
count = input0.numel()
for idx, (a, c) in enumerate(zip(input0[:count], output[:count])):
print(f"{idx:2}: {a:4} = {c:4}")
# If the result is correct, exit with a success code.
# Otherwise, exit with a failure code
if not errors:
print("\nPASS!\n")
sys.exit(0)
else:
print("\nError count: ", errors)
print("\nfailed.\n")
sys.exit(1)
if __name__ == "__main__":
main()