-
Notifications
You must be signed in to change notification settings - Fork 181
Expand file tree
/
Copy pathjit_extern_functions.py
More file actions
873 lines (751 loc) · 29.1 KB
/
jit_extern_functions.py
File metadata and controls
873 lines (751 loc) · 29.1 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
# This file is licensed under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# (c) Copyright 2025 AMD Inc.
# RUN: %run_on_npu1% %pytest %s
# RUN: %run_on_npu2% %pytest %s
import numpy as np
import os
import tempfile
import pytest
import aie.iron as iron
from aie.iron import ExternalFunction, jit
from aie.iron import ObjectFifo, Worker, Runtime, Program
from aie.iron.placers import SequentialPlacer
from aie.iron.controlflow import range_
@jit(is_placed=False)
def transform(input, output, func):
"""Transform kernel that applies a function to input tensor and stores result in output tensor."""
if input.shape != output.shape:
raise ValueError(
f"Input shapes are not the equal ({input.shape} != {output.shape})."
)
num_elements = np.size(input)
# Extract tile size from ExternalFunction (using first argument)
tile_size = func.tile_size(0)
# Assert that input and output arrays have the same tile size
assert func.tile_size(0) == func.tile_size(
1
), f"Input and output tile sizes must match: {func.tile_size(0)} != {func.tile_size(1)}"
if num_elements % tile_size != 0:
raise ValueError(
f"Number of elements ({num_elements}) must be a multiple of {tile_size}."
)
num_tiles = num_elements // tile_size
if input.dtype != output.dtype:
raise ValueError(
f"Input data types are not the same ({input.dtype} != {output.dtype})."
)
dtype = input.dtype
# Define tensor types
tensor_ty = np.ndarray[(num_elements,), np.dtype[dtype]]
tile_ty = np.ndarray[(tile_size,), np.dtype[dtype]]
# AIE-array data movement with object fifos
of_in = ObjectFifo(tile_ty, name="in")
of_out = ObjectFifo(tile_ty, name="out")
# Define a task that will run on a compute tile
def core_body(of_in, of_out, func_to_apply):
# Extract tile size from ExternalFunction (using first argument)
tile_size = func_to_apply.tile_size(0)
# Number of sub-vector "tile" iterations
for i in range_(num_tiles):
elem_in = of_in.acquire(1)
elem_out = of_out.acquire(1)
func_to_apply(elem_in, elem_out, tile_size)
of_in.release(1)
of_out.release(1)
# Create a worker to run the task on a compute tile
worker = Worker(core_body, fn_args=[of_in.cons(), of_out.prod(), func])
# Runtime operations to move data to/from the AIE-array
rt = Runtime()
with rt.sequence(tensor_ty, tensor_ty) as (A, B):
rt.start(worker)
rt.fill(of_in.prod(), A)
rt.drain(of_out.cons(), B, wait=True)
# Place program components (assign them resources on the device) and generate an MLIR module
return Program(iron.get_current_device(), rt).resolve_program(SequentialPlacer())
def test_simple_add_one():
"""Test basic ExternalFunction with simple add_one operation."""
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
initial_tensor = input_tensor.numpy().copy()
# Create ExternalFunction for adding one
add_one = ExternalFunction(
"add_one",
source_string="""extern "C" {
void add_one(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + 1;
}
}
}""",
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
)
# Apply the transform
transform(input_tensor, output_tensor, add_one)
# Verify results
expected = initial_tensor + 1
actual = output_tensor.numpy()
np.testing.assert_array_equal(actual, expected)
@pytest.mark.parametrize("tile_size", [8, 16, 32, 64])
def test_different_tile_sizes(tile_size):
"""Test ExternalFunction with different tile sizes."""
# Create input and output tensors
num_elements = 1024
input_tensor = iron.randint(0, 100, (num_elements,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((num_elements,), dtype=np.int32, device="npu")
initial_tensor = input_tensor.numpy().copy()
# Create ExternalFunction with specific tile size
add_one = ExternalFunction(
"add_one",
source_string="""extern "C" {
void add_one(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + 1;
}
}
}""",
arg_types=[
np.ndarray[(tile_size,), np.dtype[np.int32]],
np.ndarray[(tile_size,), np.dtype[np.int32]],
np.int32,
],
)
# Apply the transform
transform(input_tensor, output_tensor, add_one)
# Verify results
expected = initial_tensor + 1
actual = output_tensor.numpy()
np.testing.assert_array_equal(actual, expected)
@pytest.mark.parametrize(
"dtype,c_type",
[
(np.int32, "int"),
(np.float32, "float"),
],
)
def test_different_data_types(dtype, c_type):
"""Test ExternalFunction with different data types."""
# Create input and output tensors
input_tensor = iron.rand((1024,), dtype=dtype, device="npu")
output_tensor = iron.zeros((1024,), dtype=dtype, device="npu")
initial_tensor = input_tensor.numpy().copy()
# Create ExternalFunction with specific data type
add_one = ExternalFunction(
"add_one",
source_string=f"""extern "C" {{
void add_one({c_type}* input, {c_type}* output, int tile_size) {{
for (int i = 0; i < tile_size; i++) {{
output[i] = input[i] + 1.0f;
}}
}}
}}""",
arg_types=[
np.ndarray[(16,), np.dtype[dtype]],
np.ndarray[(16,), np.dtype[dtype]],
np.int32,
],
)
# Apply the transform
transform(input_tensor, output_tensor, add_one)
# Verify results
expected = initial_tensor + 1.0
actual = output_tensor.numpy()
np.testing.assert_array_almost_equal(actual, expected, decimal=5)
@pytest.mark.parametrize("value", [5, 42])
def test_define_values(value):
"""Test ExternalFunction with different define values."""
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
initial_tensor = input_tensor.numpy().copy()
add_value = ExternalFunction(
"add_value",
source_string="""extern "C" {
void add_value(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + ADD_VALUE;
}
}
}""",
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
compile_flags=[f"-DADD_VALUE={value}"],
)
# Apply the transform
transform(input_tensor, output_tensor, add_value)
# Verify results
expected = initial_tensor + value
actual = output_tensor.numpy()
np.testing.assert_array_equal(actual, expected)
def test_multiple_defines():
"""Test ExternalFunction with multiple defines."""
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
initial_tensor = input_tensor.numpy().copy()
# Create ExternalFunction with multiple defines
complex_op = ExternalFunction(
"complex_op",
source_string="""extern "C" {
void complex_op(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
#ifdef FLAG2
output[i] = input[i] + ADD_VALUE + FLAG2_OFFSET;
#else
output[i] = input[i] + ADD_VALUE;
#endif
}
}
}""",
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
compile_flags=["-DADD_VALUE=5", "-DFLAG2", "-DFLAG2_OFFSET=10"],
)
# Apply the transform
transform(input_tensor, output_tensor, complex_op)
# Verify results (should add 15: 5 + 10 due to FLAG2 define)
expected = initial_tensor + 15
actual = output_tensor.numpy()
np.testing.assert_array_equal(actual, expected)
def test_include_directories():
"""Test ExternalFunction with include directories."""
# Create a temporary directory with a header file
with tempfile.TemporaryDirectory() as temp_dir:
# Create a header file
header_file = os.path.join(temp_dir, "math_ops.h")
with open(header_file, "w") as f:
f.write(
"""
#ifndef MATH_OPS_H
#define MATH_OPS_H
#define ADD_VALUE 42
#endif
"""
)
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
initial_tensor = input_tensor.numpy().copy()
# Create ExternalFunction that includes the header
add_value = ExternalFunction(
"add_value",
source_string="""extern "C" {
#include "math_ops.h"
void add_value(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + ADD_VALUE;
}
}
}""",
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
include_dirs=[temp_dir],
)
# Apply the transform
transform(input_tensor, output_tensor, add_value)
# Verify results
expected = initial_tensor + 42
actual = output_tensor.numpy()
np.testing.assert_array_equal(actual, expected)
def test_multiple_include_directories():
"""Test ExternalFunction with multiple include directories."""
# Create temporary directories with header files
with tempfile.TemporaryDirectory() as temp_dir1, tempfile.TemporaryDirectory() as temp_dir2:
# Create header files
header1 = os.path.join(temp_dir1, "ops1.h")
with open(header1, "w") as f:
f.write("#define VALUE1 10\n")
header2 = os.path.join(temp_dir2, "ops2.h")
with open(header2, "w") as f:
f.write("#define VALUE2 20\n")
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
initial_tensor = input_tensor.numpy().copy()
# Create ExternalFunction that includes both headers
add_values = ExternalFunction(
"add_values",
source_string="""extern "C" {
#include "ops1.h"
#include "ops2.h"
void add_values(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + VALUE1 + VALUE2;
}
}
}""",
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
include_dirs=[temp_dir1, temp_dir2],
)
# Apply the transform
transform(input_tensor, output_tensor, add_values)
# Verify results
expected = initial_tensor + 30 # 10 + 20
actual = output_tensor.numpy()
np.testing.assert_array_equal(actual, expected)
def test_caching_same_source():
"""Test that same source code produces same cached result."""
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
initial_tensor = input_tensor.numpy().copy()
# Create two ExternalFunctions with identical source
add_one_1 = ExternalFunction(
"add_one_1",
source_string="""extern "C" {
void add_one_1(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + 1;
}
}
}""",
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
)
add_one_2 = ExternalFunction(
"add_one_2",
source_string="""extern "C" {
void add_one_2(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + 1;
}
}
}""",
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
)
# Apply both transforms
transform(input_tensor, output_tensor, add_one_1)
result1 = output_tensor.numpy().copy()
output_tensor.fill_(0)
transform(input_tensor, output_tensor, add_one_2)
result2 = output_tensor.numpy()
# Verify both produce same results
np.testing.assert_array_equal(result1, result2)
def test_context_manager():
"""Test ExternalFunction with context manager syntax."""
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
initial_tensor = input_tensor.numpy().copy()
# Create ExternalFunction and use it with context manager
with ExternalFunction(
"add_one_context",
source_string="""extern "C" {
void add_one_context(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + 1;
}
}
}""",
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
) as add_one:
# Apply the transform
transform(input_tensor, output_tensor, add_one)
# Verify results
expected = initial_tensor + 1
actual = output_tensor.numpy()
np.testing.assert_array_equal(actual, expected)
def test_context_manager_with_compiler_options():
"""Test ExternalFunction with context manager and compiler options."""
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
initial_tensor = input_tensor.numpy().copy()
# Create ExternalFunction with compiler options using context manager
with ExternalFunction(
"add_value_context",
source_string="""extern "C" {
void add_value_context(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + ADD_VALUE;
}
}
}""",
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
compile_flags=["-DADD_VALUE=42"],
) as add_value:
# Apply the transform
transform(input_tensor, output_tensor, add_value)
# Verify results
expected = initial_tensor + 42
actual = output_tensor.numpy()
np.testing.assert_array_equal(actual, expected)
def test_source_file():
"""Test ExternalFunction with source_file instead of source_string."""
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
initial_tensor = input_tensor.numpy().copy()
# Create a temporary source file
with tempfile.NamedTemporaryFile(mode="w", suffix=".cc", delete=False) as f:
source_content = """extern "C" {
void add_one_from_file(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + 1;
}
}
}"""
f.write(source_content)
source_file_path = f.name
try:
# Create ExternalFunction using source_file
add_one_from_file = ExternalFunction(
"add_one_from_file",
source_file=source_file_path,
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
)
# Apply the transform
transform(input_tensor, output_tensor, add_one_from_file)
# Verify results
expected = initial_tensor + 1
actual = output_tensor.numpy()
np.testing.assert_array_equal(actual, expected)
finally:
# Clean up the temporary file
os.unlink(source_file_path)
def test_source_file_with_compiler_options():
"""Test ExternalFunction with source_file and compiler options."""
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
initial_tensor = input_tensor.numpy().copy()
# Create a temporary source file with defines
with tempfile.NamedTemporaryFile(mode="w", suffix=".cc", delete=False) as f:
source_content = """extern "C" {
void add_value_from_file(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + ADD_VALUE;
}
}
}"""
f.write(source_content)
source_file_path = f.name
try:
# Create ExternalFunction using source_file with compiler options
add_value_from_file = ExternalFunction(
"add_value_from_file",
source_file=source_file_path,
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
compile_flags=["-DADD_VALUE=25"],
)
# Apply the transform
transform(input_tensor, output_tensor, add_value_from_file)
# Verify results
expected = initial_tensor + 25
actual = output_tensor.numpy()
np.testing.assert_array_equal(actual, expected)
finally:
# Clean up the temporary file
os.unlink(source_file_path)
def test_transform_with_internal_func():
"""Test transform function that creates ExternalFunction internally."""
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
initial_tensor = input_tensor.numpy().copy()
# Create ExternalFunction dynamically but pass it as argument
internal_func = ExternalFunction(
"internal_add_one",
source_string="""extern "C" {
void internal_add_one(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + 1;
}
}
}""",
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
)
# Apply the transform (ExternalFunction is passed as argument)
transform(input_tensor, output_tensor, internal_func)
# Verify results
expected = initial_tensor + 1
actual = output_tensor.numpy()
np.testing.assert_array_equal(actual, expected)
def test_caching_different_flags():
"""Test that different compile flags produce different cached results."""
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
initial_tensor = input_tensor.numpy().copy()
# Create ExternalFunctions with same source but different flags
add_value_5 = ExternalFunction(
"add_value",
source_string="""extern "C" {
void add_value(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + ADD_VALUE;
}
}
}""",
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
compile_flags=["-DADD_VALUE=5"],
)
add_value_10 = ExternalFunction(
"add_value",
source_string="""extern "C" {
void add_value(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + ADD_VALUE;
}
}
}""",
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
compile_flags=["-DADD_VALUE=10"],
)
# Apply transforms
transform(input_tensor, output_tensor, add_value_5)
result_5 = output_tensor.numpy().copy()
output_tensor.fill_(0)
transform(input_tensor, output_tensor, add_value_10)
result_10 = output_tensor.numpy()
# Verify different results
expected_5 = initial_tensor + 5
expected_10 = initial_tensor + 10
np.testing.assert_array_equal(result_5, expected_5)
np.testing.assert_array_equal(result_10, expected_10)
np.testing.assert_raises(
AssertionError, np.testing.assert_array_equal, result_5, result_10
)
@pytest.mark.parametrize(
"invalid_source",
[
# Missing semicolon
"""extern "C" {
void invalid_func(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + 1 // Missing semicolon
}
}
}""",
# Undefined variable
"""extern "C" {
void invalid_func(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + undefined_var;
}
}
}""",
# Syntax error
"""extern "C" {
void invalid_func(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + 1;
} // Missing closing brace
}""",
],
)
def test_invalid_source(invalid_source):
"""Test error handling for invalid C++ source."""
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
# Create ExternalFunction with invalid C++ source
invalid_func = ExternalFunction(
"invalid_func",
source_string=invalid_source,
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
)
# Should raise an error during compilation
with pytest.raises(Exception):
transform(input_tensor, output_tensor, invalid_func)
@pytest.mark.parametrize(
"input_tile_size,output_tile_size",
[
(16, 32), # Different tile sizes
(8, 16), # Different tile sizes
(64, 32), # Different tile sizes
],
)
def test_mismatched_tile_sizes(input_tile_size, output_tile_size):
"""Test error handling for mismatched tile sizes."""
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
# Create ExternalFunction with mismatched tile sizes
mismatched_func = ExternalFunction(
"mismatched_func",
source_string="""extern "C" {
void mismatched_func(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + 1;
}
}
}""",
arg_types=[
np.ndarray[(input_tile_size,), np.dtype[np.int32]],
np.ndarray[(output_tile_size,), np.dtype[np.int32]],
np.int32,
],
)
# Should raise an assertion error
with pytest.raises(AssertionError, match="Input and output tile sizes must match"):
transform(input_tensor, output_tensor, mismatched_func)
@pytest.mark.parametrize(
"invalid_include",
[
"/nonexistent/directory",
"/tmp/nonexistent_header_dir",
"/usr/local/include/nonexistent",
],
)
def test_invalid_include_directory(invalid_include):
"""Test error handling for invalid include directory."""
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
# Create ExternalFunction with invalid include directory
invalid_include_func = ExternalFunction(
"invalid_include_func",
source_string="""extern "C" {
#include "nonexistent.h"
void invalid_include_func(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + 1;
}
}
}""",
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
include_dirs=[invalid_include],
)
# Should raise an error during compilation
with pytest.raises(Exception):
transform(input_tensor, output_tensor, invalid_include_func)
@pytest.mark.parametrize(
"compile_flags,expected_value",
[
(["-DADD_VALUE=5"], 5),
(["-DADD_VALUE=10", "-DMULTIPLIER=2"], 20), # 10 * 2
(["-DADD_VALUE=3", "-DOFFSET=7"], 10), # 3 + 7
(["-DADD_VALUE=1", "-DFLAG2", "-DFLAG2_OFFSET=9"], 10), # 1 + 9 (FLAG2 enabled)
],
)
def test_compiler_flag_combinations(compile_flags, expected_value):
"""Test ExternalFunction with different combinations of compiler flags."""
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
initial_tensor = input_tensor.numpy().copy()
# Create source that uses the defines
source_template = """extern "C" {
void complex_op(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
#ifdef MULTIPLIER
output[i] = input[i] + ADD_VALUE * MULTIPLIER;
#elif defined(FLAG2)
output[i] = input[i] + ADD_VALUE + FLAG2_OFFSET;
#elif defined(OFFSET)
output[i] = input[i] + ADD_VALUE + OFFSET;
#else
output[i] = input[i] + ADD_VALUE;
#endif
}
}
}"""
complex_op = ExternalFunction(
"complex_op",
source_string=source_template,
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
compile_flags=compile_flags,
)
# Apply the transform
transform(input_tensor, output_tensor, complex_op)
# Verify results
expected = initial_tensor + expected_value
actual = output_tensor.numpy()
np.testing.assert_array_equal(actual, expected)
def test_object_file_name():
"""Test ExternalFunction with explicit object file name."""
# Create input and output tensors
input_tensor = iron.randint(0, 100, (1024,), dtype=np.int32, device="npu")
output_tensor = iron.zeros((1024,), dtype=np.int32, device="npu")
initial_tensor = input_tensor.numpy().copy()
# Create ExternalFunction for adding one
add_one = ExternalFunction(
"add_one",
object_file_name="my_add_one.o",
source_string="""extern "C" {
void add_one(int* input, int* output, int tile_size) {
for (int i = 0; i < tile_size; i++) {
output[i] = input[i] + 1;
}
}
}""",
arg_types=[
np.ndarray[(16,), np.dtype[np.int32]],
np.ndarray[(16,), np.dtype[np.int32]],
np.int32,
],
)
# Apply the transform
transform(input_tensor, output_tensor, add_one)
# Verify results
expected = initial_tensor + 1
actual = output_tensor.numpy()
np.testing.assert_array_equal(actual, expected)