-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathtest_autotuner.py
More file actions
2229 lines (1931 loc) · 85.2 KB
/
test_autotuner.py
File metadata and controls
2229 lines (1931 loc) · 85.2 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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
from contextlib import contextmanager
from contextlib import nullcontext
import csv
from itertools import count
import logging
import math
import multiprocessing as mp
import operator
import os
from pathlib import Path
import pickle
import random
import tempfile
from types import SimpleNamespace
from typing import Callable
from typing import Sequence
import unittest
from unittest import skip
from unittest.mock import patch
import pytest
import torch
import helion
from helion import _compat
from helion import exc
from helion._testing import DEVICE
from helion._testing import RefEagerTestDisabled
from helion._testing import TestCase
from helion._testing import assert_close_with_mismatch_tolerance
from helion._testing import import_path
from helion._testing import onlyBackends
from helion._testing import skipIfCudaCapabilityLessThan
from helion._testing import skipIfRefEager
from helion._testing import skipIfRocm
from helion._testing import skipIfTileIR
from helion._testing import skipIfXPU
from helion.autotuner import DESurrogateHybrid
from helion.autotuner import DifferentialEvolutionSearch
from helion.autotuner import LFBOPatternSearch
from helion.autotuner import LFBOTreeSearch
from helion.autotuner import PatternSearch
from helion.autotuner.base_search import BaseSearch
from helion.autotuner.base_search import PopulationMember
from helion.autotuner.config_fragment import BooleanFragment
from helion.autotuner.config_fragment import EnumFragment
from helion.autotuner.config_fragment import IntegerFragment
from helion.autotuner.config_fragment import ListOf
from helion.autotuner.config_fragment import PermutationFragment
from helion.autotuner.config_fragment import PowerOfTwoFragment
from helion.autotuner.config_generation import ConfigGeneration
from helion.autotuner.effort_profile import get_effort_profile
from helion.autotuner.finite_search import FiniteSearch
from helion.autotuner.local_cache import LocalAutotuneCache
from helion.autotuner.local_cache import StrictLocalAutotuneCache
from helion.autotuner.logger import AutotuneLogEntry
from helion.autotuner.logger import AutotuningLogger
from helion.autotuner.metrics import AutotuneMetrics
from helion.autotuner.random_search import RandomSearch
import helion.language as hl
from helion.language import loops
from helion.runtime.settings import Settings
datadir = Path(__file__).parent / "data"
basic_kernels = import_path(datadir / "basic_kernels.py")
examples_dir = Path(__file__).parent.parent / "examples"
def _get_examples_matmul():
"""Lazy accessor to avoid CUDA init during pytest-xdist collection."""
return import_path(examples_dir / "matmul.py").matmul
@contextmanager
def without_env_var(name: str):
sentinel = object()
previous = os.environ.pop(name, sentinel)
try:
yield
finally:
if previous is not sentinel:
os.environ[name] = previous
class RecordingRandomSearch(RandomSearch):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.samples: list[float] = []
def _autotune(self):
self.samples.append(random.random())
return super()._autotune()
@onlyBackends(["triton"])
class TestAutotuneIgnoreErrors(TestCase):
def _make_search(
self, settings: Settings, *, args: tuple[object, ...] = ()
) -> BaseSearch:
search = BaseSearch.__new__(BaseSearch)
search.settings = settings
search.kernel = SimpleNamespace(
format_kernel_decorator=lambda config, s: "decorator",
to_triton_code=lambda config: "code",
maybe_log_repro=lambda log_func, args, config=None: None,
)
search.args = args
search._autotune_metrics = AutotuneMetrics()
search.log = AutotuningLogger(settings)
search._mutated_arg_indices = []
search.best_perf_so_far = float("inf")
tempdir = tempfile.TemporaryDirectory()
self.addCleanup(tempdir.cleanup)
search._precompile_tmpdir = tempdir
search._precompile_args_path = None
search._precompile_result_counter = count()
search._prepared = True
return search
def test_settings_flag_from_env(self):
with patch.dict(
os.environ, {"HELION_AUTOTUNE_IGNORE_ERRORS": "1"}, clear=False
):
settings = Settings()
self.assertTrue(settings.autotune_ignore_errors)
def test_benchmark_raise_includes_hint(self):
settings = Settings(
autotune_ignore_errors=False,
autotune_log_level=logging.CRITICAL,
)
search = self._make_search(settings)
def bad_fn(*_args):
raise RuntimeError("boom")
with patch("torch.accelerator.synchronize", autospec=True) as sync:
sync.return_value = None
with pytest.raises(exc.TritonError) as err:
search.benchmark_function("cfg", bad_fn)
assert "HELION_AUTOTUNE_IGNORE_ERRORS" in str(err.value)
def test_llvm_translation_failure_skips_config(self):
settings = Settings(
autotune_ignore_errors=False,
autotune_log_level=logging.CRITICAL,
)
search = self._make_search(settings)
def bad_fn(*_args):
raise RuntimeError("failed to translate module to LLVM IR")
with patch("torch.accelerator.synchronize", autospec=True) as sync:
sync.return_value = None
result = search.benchmark_function("cfg", bad_fn)
self.assertEqual(result, float("inf"))
self.assertEqual(search._autotune_metrics.num_compile_failures, 1)
def test_ignore_errors_skips_logging_and_raise(self):
settings = Settings(
autotune_ignore_errors=True,
autotune_log_level=logging.CRITICAL,
)
search = self._make_search(settings)
def bad_fn(*_args):
raise RuntimeError("boom")
with patch("torch.accelerator.synchronize", autospec=True) as sync:
sync.return_value = None
with patch.object(search.log, "warning") as warn:
result = search.benchmark_function("cfg", bad_fn)
self.assertEqual(result, float("inf"))
warn.assert_not_called()
def test_traceback_cleared_str(self):
"""Test that str(e) still has meaningful content after e.__traceback__ = None."""
settings = Settings(
autotune_ignore_errors=False,
autotune_log_level=logging.CRITICAL,
)
search = self._make_search(settings)
def bad_fn(*_args):
raise RuntimeError("test error with meaningful message")
with (
patch("torch.accelerator.synchronize", autospec=True) as sync,
patch(
"helion.autotuner.base_search.classify_triton_exception",
return_value="raise",
),
):
sync.return_value = None
with pytest.raises(exc.TritonError) as err:
search.benchmark_function("cfg", bad_fn)
# Verify the traceback was cleared
assert err.value.__cause__.__traceback__ is None
# Verify the error message is still accessible and meaningful
assert "RuntimeError: test error with meaningful message" in str(err.value)
def test_traceback_cleared_raise_from(self):
"""Test that 'raise ... from e' still has meaningful stack after e.__traceback__ = None."""
settings = Settings(
autotune_ignore_errors=False,
autotune_log_level=logging.CRITICAL,
)
search = self._make_search(settings)
original_exception = RuntimeError("original error in except block")
def bad_fn(*_args):
raise original_exception
with (
patch("torch.accelerator.synchronize", autospec=True) as sync,
patch(
"helion.autotuner.base_search.classify_triton_exception",
return_value="raise",
),
):
sync.return_value = None
with pytest.raises(exc.TritonError) as err:
search.benchmark_function("cfg", bad_fn)
# Verify the traceback was cleared
assert err.value.__cause__.__traceback__ is None
# Verify the exception chain is preserved even after __traceback__ = None
assert err.value.__cause__ is original_exception
assert str(original_exception) == "original error in except block"
# Verify we can still get the error type and message
assert type(err.value.__cause__).__name__ == "RuntimeError"
def test_autotune_log_sink_writes_csv_and_log(self):
tmpdir = tempfile.TemporaryDirectory()
self.addCleanup(tmpdir.cleanup)
base_path = Path(tmpdir.name) / "autotune_run"
settings = Settings(
autotune_log=str(base_path),
autotune_log_level=logging.CRITICAL,
)
logger = AutotuningLogger(settings)
with logger.autotune_logging():
entry = AutotuneLogEntry(
generation=5,
status="ok",
perf_ms=1.234,
compile_time=0.5,
config=helion.Config(foo=1, bar=[2, 3]),
)
logger.record_autotune_entry(entry)
logger("finalized entry", level=logging.CRITICAL)
csv_path = base_path.with_suffix(".csv")
log_path = base_path.with_suffix(".log")
self.assertTrue(csv_path.exists())
self.assertTrue(log_path.exists())
rows = list(csv.reader(csv_path.read_text().splitlines()))
self.assertEqual(
rows[0],
[
"timestamp_s",
"config_index",
"generation",
"status",
"perf_ms",
"compile_time_s",
"config",
],
)
self.assertEqual(rows[1][1], "1")
self.assertEqual(rows[1][2], "5")
self.assertEqual(rows[1][3], "ok")
self.assertEqual(rows[1][4], "1.234000")
log_text = log_path.read_text()
self.assertIn("finalized entry", log_text)
def test_differential_evolution_immediate_iter_uses_batch_helper(self):
search = DifferentialEvolutionSearch.__new__(DifferentialEvolutionSearch)
search.immediate_update = True
search.population = [object(), object(), object()]
calls: list[list[int]] = []
def batch(indices: Sequence[int]) -> list[PopulationMember]:
calls.append(list(indices))
members: list[PopulationMember] = []
for idx in indices:
members.append(
PopulationMember(
lambda *args, **kwargs: None,
[float(idx)],
[],
SimpleNamespace(config={"idx": idx}),
status="ok",
)
)
return members
search._benchmark_mutation_batch = batch # type: ignore[assignment]
candidates = list(search.iter_candidates())
self.assertEqual(calls, [[0], [1], [2]])
self.assertEqual([idx for idx, _ in candidates], [0, 1, 2])
def test_differential_evolution_parallel_iter_uses_batch_helper(self):
search = DifferentialEvolutionSearch.__new__(DifferentialEvolutionSearch)
search.immediate_update = False
search.population = [object(), object()]
def batch(indices: Sequence[int]) -> list[PopulationMember]:
members: list[PopulationMember] = []
for idx in indices:
members.append(
PopulationMember(
lambda *args, **kwargs: None,
[float(idx)],
[],
SimpleNamespace(config={"idx": idx}),
status="ok",
)
)
return members
calls: list[list[int]] = []
def recording_batch(indices: Sequence[int]) -> list[PopulationMember]:
calls.append(list(indices))
return batch(indices)
search._benchmark_mutation_batch = recording_batch # type: ignore[assignment]
candidates = list(search.iter_candidates())
self.assertEqual(calls, [[0, 1]])
self.assertEqual([idx for idx, _ in candidates], [0, 1])
@pytest.mark.skipif(
"fork" not in mp.get_all_start_methods(),
reason="fork start method is unavailable on this platform",
)
def test_fork_precompile_avoids_cuda_reinit(self):
settings = Settings(
autotune_precompile="fork",
autotune_log_level=logging.CRITICAL,
autotune_compile_timeout=5,
)
search = self._make_search(settings, args=("arg0",))
parent_pid = os.getpid()
lazy_calls: list[int] = []
def fake_lazy_init() -> None:
lazy_calls.append(os.getpid())
def fake_make_precompiler(_kernel_obj, _config, _bound_kernel):
def binder(*_args: object, **_kwargs: object):
def run() -> None:
return None
return run
return binder
def fake_compiled_fn(
*fn_args: object, _launcher: Callable[..., object]
) -> None:
torch.cuda._lazy_init()
_launcher("fake_kernel", (1,), *fn_args)
with (
patch(
"helion.autotuner.precompile_future.make_precompiler",
side_effect=fake_make_precompiler,
),
patch("torch.cuda._lazy_init", side_effect=fake_lazy_init),
):
future = search.create_precompile_future("cfg", fake_compiled_fn)
self.assertTrue(future())
self.assertEqual(set(lazy_calls), {parent_pid})
def _run_autotuner_and_check_logging(
self, search_factory: Callable[[object, tuple[object, ...]], BaseSearch]
) -> None:
"""Helper to verify started/completion logging for any autotuner."""
tmpdir = tempfile.TemporaryDirectory()
self.addCleanup(tmpdir.cleanup)
base_path = Path(tmpdir.name) / "autotune_run"
with patch.dict(
os.environ,
{
"HELION_AUTOTUNE_LOG": str(base_path),
"HELION_AUTOTUNE_LOG_LEVEL": "0",
},
):
@helion.kernel()
def add(a, b):
out = torch.empty_like(a)
for tile in hl.tile(out.size()):
out[tile] = a[tile] + b[tile]
return out
args = (
torch.randn([64], device=DEVICE),
torch.randn([64], device=DEVICE),
)
bound_kernel = add.bind(args)
random.seed(123)
search = search_factory(bound_kernel, args)
search.autotune()
csv_path = base_path.with_suffix(".csv")
self.assertTrue(csv_path.exists())
rows = list(csv.reader(csv_path.read_text().splitlines()))
statuses = [row[3] for row in rows[1:]] # skip header
started_count = sum(1 for s in statuses if s == "started")
completed_count = sum(1 for s in statuses if s in ("ok", "error", "timeout"))
self.assertGreater(started_count, 0, "Should log started entries")
self.assertEqual(
started_count, completed_count, "Each started should have completion"
)
@skipIfRefEager("Autotuning not supported in ref eager mode")
@skipIfXPU("maxnreg parameter not supported on XPU backend")
def test_autotune_log_started_completed(self):
"""Test started/completion logging with all autotuning algorithms."""
configs = [
helion.Config(block_sizes=[32], num_warps=4),
helion.Config(block_sizes=[64], num_warps=8),
]
search_factories = [
(
"FiniteSearch",
lambda kernel, args: FiniteSearch(kernel, args, configs=configs),
),
("RandomSearch", lambda kernel, args: RandomSearch(kernel, args, count=3)),
(
"PatternSearch",
lambda kernel, args: PatternSearch(
kernel, args, initial_population=3, max_generations=1, copies=1
),
),
(
"DifferentialEvolutionSearch",
lambda kernel, args: DifferentialEvolutionSearch(
kernel, args, population_size=3, max_generations=1
),
),
]
for name, factory in search_factories:
with self.subTest(algorithm=name):
self._run_autotuner_and_check_logging(factory)
@onlyBackends(["triton"])
class TestAutotuner(RefEagerTestDisabled, TestCase):
def setUp(self):
super().setUp()
random.seed(112)
@patch.object(_compat, "_supports_tensor_descriptor", lambda: True)
@patch.object(_compat, "_min_dot_size", lambda *args: (16, 16, 16))
@patch.object(_compat, "_supports_maxnreg", lambda: True)
@patch.object(loops, "_supports_warp_specialize", lambda: True)
@skipIfRocm("config space differs on ROCm")
def test_config_fragment0(self):
args = (
torch.randn([512, 512], device=DEVICE),
torch.randn([512, 512], device=DEVICE),
)
spec = _get_examples_matmul().bind(args).config_spec
configs = ConfigGeneration(spec).random_population(10)
self.assertExpectedJournal("\n".join(map(repr, configs)))
@patch(
"helion.autotuner.config_generation.warps_to_threads",
lambda num_warps: num_warps * 32,
)
@patch.object(_compat, "_supports_maxnreg", lambda: True)
@patch.object(_compat, "_supports_tensor_descriptor", lambda: True)
@patch.object(loops, "_supports_warp_specialize", lambda: True)
@patch("torch.version.hip", None)
@patch("torch.version.xpu", None)
@skipIfRocm("config space differs on ROCm")
def test_config_fragment1(self):
args = (
torch.randn([8, 512, 512], device=DEVICE),
torch.randn([8, 512, 512], device=DEVICE),
)
spec = basic_kernels.add.bind(args).config_spec
configs = ConfigGeneration(spec).random_population(10)
self.assertExpectedJournal("\n".join(map(repr, configs)))
@patch(
"helion.autotuner.config_generation.warps_to_threads",
lambda num_warps: num_warps * 32,
)
@patch.object(_compat, "_supports_maxnreg", lambda: True)
@patch.object(_compat, "_supports_tensor_descriptor", lambda: True)
@patch.object(loops, "_supports_warp_specialize", lambda: True)
@patch("torch.version.hip", None)
@patch("torch.version.xpu", None)
@skipIfTileIR("tileir backend will ignore `warp specialization` hint")
@skipIfRocm("config space differs on ROCm")
def test_config_warp_specialize_unroll(self):
args = (
torch.randn([8, 512, 512], device=DEVICE),
torch.randn([8, 512, 512], device=DEVICE),
)
spec = basic_kernels.add.bind(args).config_spec
overrides = {"range_unroll_factors": [4], "range_warp_specializes": ([True])}
# We expect all the unroll factors to be set to 0
configs = ConfigGeneration(spec, overrides=overrides).random_population(10)
self.assertExpectedJournal("\n".join(map(repr, configs)))
@patch.object(_compat, "_supports_tensor_descriptor", lambda: True)
def test_config_generation_overrides(self):
args = (
torch.randn([8, 512, 512], device=DEVICE),
torch.randn([8, 512, 512], device=DEVICE),
)
spec = basic_kernels.add.bind(args).config_spec
overrides = {"indexing": "tensor_descriptor"}
gen = ConfigGeneration(spec, overrides=overrides)
flat = gen.default_flat()
config = gen.unflatten([*flat])
self.assertEqual(config["indexing"], "tensor_descriptor")
configs = [gen.unflatten(gen.random_flat()) for _ in range(3)]
self.assertEqual({cfg["indexing"] for cfg in configs}, {"tensor_descriptor"})
indexing_choices = spec.valid_indexing_types()
indexing_index = next(
i
for i, fragment in enumerate(gen.flat_spec)
if isinstance(fragment, ListOf)
and isinstance(fragment.inner, EnumFragment)
and fragment.inner.choices == tuple(indexing_choices)
)
mutated = gen.random_flat()
mutated[indexing_index] = "pointer"
new_config = gen.unflatten(mutated)
self.assertEqual(new_config["indexing"], "tensor_descriptor")
self.assertEqual(mutated[indexing_index], "pointer")
@patch.object(_compat, "_supports_tensor_descriptor", lambda: False)
def test_save_load_config(self):
config = helion.Config(
block_sizes=[64, 64, 32],
loop_orders=[[1, 0]],
num_warps=2,
num_stages=1,
indexing="block_ptr",
l2_grouping=32,
)
with tempfile.NamedTemporaryFile() as f:
config.save(f.name)
loaded_config = helion.Config.load(f.name)
self.assertEqual(config, loaded_config)
self.assertExpectedJournal(config.to_json())
def test_config_pickle_roundtrip(self):
config = helion.Config(
block_sizes=[64, 64, 32],
loop_orders=[[1, 0]],
num_warps=4,
num_stages=2,
indexing="tensor_descriptor",
extra_metadata={"nested": [1, 2, 3]},
)
restored = pickle.loads(pickle.dumps(config))
self.assertIsInstance(restored, helion.Config)
self.assertEqual(config, restored)
self.assertIsNot(config, restored)
self.assertIsNot(config.config, restored.config)
def test_run_fixed_config(self):
@helion.kernel(
config=helion.Config(
block_sizes=[1024, 1, 1],
flatten_loops=[True],
loop_orders=[[0, 2, 1]],
num_warps=8,
)
)
def add(a, b):
out = torch.empty_like(a)
for tile in hl.tile(out.size()):
out[tile] = a[tile] + b[tile]
return out
args = (
torch.randn([8, 512, 512], device=DEVICE),
torch.randn([8, 512, 512], device=DEVICE),
)
torch.testing.assert_close(add(*args), sum(args))
def test_finite_search_all_configs_fail_raises(self):
"""Test that when all configs fail, the error is re-raised.
Without this, compile failures would be silently swallowed and the
autotuner would return no results. We must surface the error so
users know their configs are incompatible with the input shape.
"""
@helion.kernel(
configs=[
helion.Config(block_sizes=[64]),
helion.Config(block_sizes=[128]),
],
autotune_log_level=0,
)
def add(a, b):
out = torch.empty_like(a)
for tile in hl.tile(out.size()):
out[tile] = a[tile] + b[tile]
return out
args = (
torch.randn([8, 512, 512], device=DEVICE),
torch.randn([8, 512, 512], device=DEVICE),
)
with self.assertRaises(exc.InvalidConfig):
add(*args)
def test_run_finite_search(self):
@helion.kernel(
configs=[
helion.Config(
block_sizes=[1024, 1, 1],
flatten_loops=[True],
loop_orders=[[0, 2, 1]],
num_warps=8,
),
helion.Config(
block_sizes=[1024, 1, 1], flatten_loops=[True], num_warps=8
),
helion.Config(block_sizes=[1, 64, 64], num_warps=8),
helion.Config(block_sizes=[1, 1, 512], num_warps=8),
],
autotune_log_level=0,
)
def add(a, b):
out = torch.empty_like(a)
for tile in hl.tile(out.size()):
out[tile] = a[tile] + b[tile]
return out
args = (
torch.randn([8, 512, 512], device=DEVICE),
torch.randn([8, 512, 512], device=DEVICE),
)
torch.testing.assert_close(add(*args), sum(args))
torch.testing.assert_close(add(*args), sum(args))
def test_finite_search_skips_bad_configs(self):
"""Test that configs that fail to compile are skipped.
Uses a config with wrong number of block_sizes (1 instead of 3)
placed between two good configs, to verify the skip logic doesn't
disrupt processing of subsequent valid configs.
"""
@helion.kernel(
configs=[
# Good config
helion.Config(block_sizes=[1, 64, 64], num_warps=8),
# Bad config: insufficient block_sizes for a 3D kernel
helion.Config(block_sizes=[64]),
# Good config after bad one — must still work
helion.Config(block_sizes=[1, 1, 512], num_warps=8),
],
autotune_log_level=0,
)
def add(a, b):
out = torch.empty_like(a)
for tile in hl.tile(out.size()):
out[tile] = a[tile] + b[tile]
return out
args = (
torch.randn([8, 512, 512], device=DEVICE),
torch.randn([8, 512, 512], device=DEVICE),
)
# Bad config (block_sizes=[64]) has wrong number of block_sizes for
# 3D input and should fail to compile. The surrounding good configs
# should allow autotuning to succeed.
torch.testing.assert_close(add(*args), sum(args))
@skipIfXPU("maxnreg parameter not supported on XPU backend")
def test_random_search(self):
args = (
torch.randn([512, 512], device=DEVICE),
torch.randn([512, 512], device=DEVICE),
)
bound_kernel = _get_examples_matmul().bind(args)
bound_kernel.settings.autotune_precompile = None
random.seed(123)
best = RandomSearch(bound_kernel, args, 20).autotune()
fn = bound_kernel.compile_config(best)
torch.testing.assert_close(fn(*args), args[0] @ args[1], rtol=1e-2, atol=1e-1)
@skip("too slow")
def test_differential_evolution_search(self):
args = (
torch.randn([512, 512], device=DEVICE),
torch.randn([512, 512], device=DEVICE),
)
bound_kernel = _get_examples_matmul().bind(args)
random.seed(123)
best = DifferentialEvolutionSearch(
bound_kernel, args, 5, max_generations=3
).autotune()
fn = bound_kernel.compile_config(best)
torch.testing.assert_close(fn(*args), args[0] @ args[1], rtol=1e-2, atol=1e-1)
@skip("too slow")
def test_de_surrogate_hybrid(self):
args = (
torch.randn([512, 512], device=DEVICE),
torch.randn([512, 512], device=DEVICE),
)
bound_kernel = _get_examples_matmul().bind(args)
random.seed(123)
best = DESurrogateHybrid(
bound_kernel, args, population_size=5, max_generations=3
).autotune()
fn = bound_kernel.compile_config(best)
torch.testing.assert_close(fn(*args), args[0] @ args[1], rtol=1e-2, atol=1e-1)
def test_differential_evolution_early_stopping_parameters(self):
"""Test that early stopping is disabled by default and can be enabled."""
args = (
torch.randn([64, 64], device=DEVICE),
torch.randn([64, 64], device=DEVICE),
)
bound_kernel = basic_kernels.add.bind(args)
# Test 1: Default parameters (early stopping disabled)
search = DifferentialEvolutionSearch(
bound_kernel, args, population_size=5, max_generations=3
)
self.assertIsNone(search.min_improvement_delta)
self.assertIsNone(search.patience)
# Test 2: Enable early stopping with custom parameters
search_custom = DifferentialEvolutionSearch(
bound_kernel,
args,
population_size=5,
max_generations=3,
min_improvement_delta=0.01,
patience=5,
)
self.assertEqual(search_custom.min_improvement_delta, 0.01)
self.assertEqual(search_custom.patience, 5)
def test_de_surrogate_early_stopping_parameters(self):
"""Test that DE-Surrogate early stopping parameters are optional with correct defaults."""
args = (
torch.randn([64, 64], device=DEVICE),
torch.randn([64, 64], device=DEVICE),
)
bound_kernel = basic_kernels.add.bind(args)
# Test 1: Default parameters (optional)
search = DESurrogateHybrid(
bound_kernel, args, population_size=5, max_generations=3
)
self.assertEqual(search.min_improvement_delta, 0.001)
self.assertEqual(search.patience, 3)
# Test 2: Custom parameters
search_custom = DESurrogateHybrid(
bound_kernel,
args,
population_size=5,
max_generations=3,
min_improvement_delta=0.01,
patience=5,
)
self.assertEqual(search_custom.min_improvement_delta, 0.01)
self.assertEqual(search_custom.patience, 5)
@skip("too slow")
def test_pattern_search(self):
args = (
torch.randn([64, 64], device=DEVICE),
torch.randn([64, 64], device=DEVICE),
)
bound_kernel = basic_kernels.add.bind(args)
random.seed(123)
best = PatternSearch(
bound_kernel, args, initial_population=10, max_generations=2, copies=1
).autotune()
fn = bound_kernel.compile_config(best)
torch.testing.assert_close(fn(*args), sum(args), rtol=1e-2, atol=1e-1)
def test_pattern_search_neighbor_values(self):
self.assertEqual(
PowerOfTwoFragment(1, 128, 32).pattern_neighbors(32),
[16, 64],
)
self.assertEqual(
sorted(IntegerFragment(1, 5, 3).pattern_neighbors(3)),
[2, 4],
)
self.assertEqual(BooleanFragment().pattern_neighbors(True), [False])
self.assertEqual(
sorted(EnumFragment(("a", "b", "c")).pattern_neighbors("b")),
["a", "c"],
)
def test_pattern_search_neighbor_values_radius(self):
# PowerOfTwoFragment: radius=2 should return 2 steps in exponent space
self.assertEqual(
PowerOfTwoFragment(1, 128, 32).pattern_neighbors(32, radius=2),
[8, 16, 64, 128],
)
# PowerOfTwoFragment: radius=2 clamped at lower boundary
self.assertEqual(
PowerOfTwoFragment(16, 128, 16).pattern_neighbors(16, radius=2),
[32, 64],
)
# PowerOfTwoFragment: radius=2 clamped at upper boundary
self.assertEqual(
PowerOfTwoFragment(1, 64, 64).pattern_neighbors(64, radius=2),
[16, 32],
)
# IntegerFragment: radius=2 returns ±2 neighbors
self.assertEqual(
sorted(IntegerFragment(1, 10, 5).pattern_neighbors(5, radius=2)),
[3, 4, 6, 7],
)
# IntegerFragment: radius=2 clamped at boundaries
self.assertEqual(
sorted(IntegerFragment(1, 5, 1).pattern_neighbors(1, radius=2)),
[2, 3],
)
# BooleanFragment: radius is ignored, always returns [not current]
self.assertEqual(BooleanFragment().pattern_neighbors(True, radius=3), [False])
# EnumFragment: radius is ignored, always returns all other choices
self.assertEqual(
sorted(EnumFragment(("a", "b", "c")).pattern_neighbors("b", radius=5)),
["a", "c"],
)
# ListOf: radius is forwarded to inner fragment
list_frag = ListOf(inner=IntegerFragment(1, 10, 5), length=2)
neighbors = list_frag.pattern_neighbors([5, 5], radius=2)
# Each position yields 4 neighbors (3,4,6,7), total 8
self.assertEqual(len(neighbors), 8)
# All neighbors differ from base in exactly one position
for neighbor in neighbors:
diffs = sum(1 for a, b in zip(neighbor, [5, 5], strict=True) if a != b)
self.assertEqual(diffs, 1)
def test_pattern_search_block_size_pair_neighbors(self):
search = PatternSearch.__new__(PatternSearch)
search._visited = set()
search.config_gen = SimpleNamespace(
flat_spec=[
PowerOfTwoFragment(16, 128, 32),
PowerOfTwoFragment(16, 128, 64),
EnumFragment(("a", "b")),
],
block_size_indices=[0, 1],
overridden_flat_indices=set(),
)
search.num_neighbors_cap = -1
base = [32, 64, "a"]
neighbors = search._generate_neighbors(base)
def diff_count(flat):
return sum(
1
for current, original in zip(flat, base, strict=False)
if current != original
)
pair_neighbors = [
flat for flat in neighbors if diff_count(flat) == 2 and flat[2] == "a"
]
expected = [
[16, 32, "a"],
[16, 128, "a"],
[64, 32, "a"],
[64, 128, "a"],
]
self.assertEqual(sorted(pair_neighbors), sorted(expected))
def test_pattern_search_skips_overridden_indices(self):
"""Neighbors are not generated along overridden (frozen) indices."""
search = PatternSearch.__new__(PatternSearch)
search._visited = set()
search.config_gen = SimpleNamespace(
flat_spec=[
PowerOfTwoFragment(16, 128, 32), # block_size[0] — index 0
PowerOfTwoFragment(16, 128, 64), # block_size[1] — index 1
EnumFragment(("a", "b")), # some enum — index 2
],
block_size_indices=[0, 1],
overridden_flat_indices={1}, # freeze block_size[1]
)
search.num_neighbors_cap = -1
base = [32, 64, "a"]
neighbors = search._generate_neighbors(base)
# No neighbor should change index 1 (frozen)
for flat in neighbors:
self.assertEqual(flat[1], 64)
# Neighbors should still vary indices 0 and 2
changed_indices = set()
for flat in neighbors:
for i, (v, b) in enumerate(zip(flat, base, strict=False)):
if v != b:
changed_indices.add(i)
self.assertIn(0, changed_indices)
self.assertIn(2, changed_indices)
self.assertNotIn(1, changed_indices)
# No block-size pair neighbors should be generated (only 1 non-frozen block index)
pair_neighbors = [
flat
for flat in neighbors
if sum(1 for v, b in zip(flat, base, strict=False) if v != b) == 2
]
self.assertEqual(pair_neighbors, [])
def test_differential_mutation_skips_overridden_indices(self):
"""Differential mutation does not mutate overridden indices."""
random.seed(42)
args = (
torch.randn([8, 512, 512], device=DEVICE),
torch.randn([8, 512, 512], device=DEVICE),
)
spec = basic_kernels.add.bind(args).config_spec
overrides = {"num_warps": 8}
gen = ConfigGeneration(spec, overrides=overrides)
# Find the num_warps flat index
warp_idx = gen.num_warps_index
self.assertIn(warp_idx, gen.overridden_flat_indices)
base = gen.default_flat()
a = gen.random_flat()
b = gen.random_flat()
c = gen.random_flat()
# Run many mutations — overridden index should never change
for _ in range(50):
result = gen.differential_mutation(base, a, b, c, crossover_rate=0.9)
self.assertEqual(result[warp_idx], base[warp_idx])
def test_lfbo_pattern_search_skips_overridden_indices(self):
"""LFBOPatternSearch._generate_neighbors skips overridden indices."""
random.seed(123)
search = LFBOPatternSearch.__new__(LFBOPatternSearch)
search.num_neighbors = 50
search.radius = 2
search.config_gen = SimpleNamespace(
flat_spec=[
PowerOfTwoFragment(16, 128, 32), # block_size[0]
PowerOfTwoFragment(16, 128, 64), # block_size[1]
PowerOfTwoFragment(2, 16, 4), # num_warps
EnumFragment(("a", "b", "c")), # some enum
BooleanFragment(), # some boolean
],
block_size_indices=[0, 1],
num_warps_index=2,
overridden_flat_indices={1, 2}, # freeze block_size[1] and num_warps
)
search.num_neighbors_cap = -1
base = [32, 64, 4, "b", True]
neighbors = search._generate_neighbors(base)
# No neighbor should change indices 1 or 2
for flat in neighbors:
self.assertEqual(flat[1], 64)
self.assertEqual(flat[2], 4)
def test_lfbo_pattern_search_generate_neighbors(self):
"""Test LFBOPatternSearch._generate_neighbors method."""
random.seed(123)
search = LFBOPatternSearch.__new__(LFBOPatternSearch)
search.num_neighbors = 50
search.radius = 2
search.config_gen = SimpleNamespace(
flat_spec=[
PowerOfTwoFragment(16, 128, 32), # block_size[0]
PowerOfTwoFragment(16, 128, 64), # block_size[1]
PowerOfTwoFragment(2, 16, 4), # num_warps