forked from hw-native-sys/simpler
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscene_test.py
More file actions
1800 lines (1545 loc) · 71.3 KB
/
Copy pathscene_test.py
File metadata and controls
1800 lines (1545 loc) · 71.3 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
# Copyright (c) PyPTO Contributors.
# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
# CANN Open Software License Agreement Version 2.0 (the "License").
# Please refer to the License for details. You may not use this file except in compliance with the License.
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
# See LICENSE in the root of the software repository for the full text of the License.
# -----------------------------------------------------------------------------------------------------------
"""SceneTestCase framework — unified scene test infrastructure.
``@scene_test`` decorator + ``SceneTestCase`` base class.
pytest: ``pytest --platform a2a3sim``
standalone: ``python test_xxx.py -p a2a3sim``
A scene test class declares three things:
CALLABLE: what to compile/prepare
L2: orchestration (C++ source) + incores (C++ kernels)
L3: orchestration (Python DAG fn) + callables (ChipCallable + SubCallable)
CASES: how to run (per-case platform, config, params)
generate_args / compute_golden: data + golden comparison
"""
from __future__ import annotations
import gc
import inspect
import logging
import os
import sys
from contextlib import contextmanager
from pathlib import Path
from typing import Any, NamedTuple
from .log_config import DEFAULT_LOG_LEVEL, LOG_LEVEL_CHOICES, configure_logging
from .pto_isa import ensure_pto_isa_root
logger = logging.getLogger(__name__)
_compile_cache: dict[tuple[str, str, str], object] = {}
def clear_compile_cache() -> None:
"""Drop every cached ``ChipCallable`` and force a GC pass.
The cache keeps nanobind-owned ``ChipCallable`` instances alive for the
whole pytest session. Module-level dicts are cleared by Python in an
order that can outlive the nanobind module destructor, which then
prints ``leaked N instances of type _task_interface.ChipCallable`` to
stderr at interpreter shutdown. Call this from ``pytest_sessionfinish``
(and other session-end paths) so the instances die while the nanobind
module is still wired up.
"""
_compile_cache.clear()
gc.collect()
# ---------------------------------------------------------------------------
# Spec types
# ---------------------------------------------------------------------------
class Tensor(NamedTuple):
"""Tensor argument spec."""
name: str
value: Any # torch.Tensor
class Scalar(NamedTuple):
"""Scalar argument spec (ctypes scalar)."""
name: str
value: Any # ctypes.c_float, ctypes.c_int64, etc.
# ---------------------------------------------------------------------------
# TaskArgsBuilder — ordered container with named access
# ---------------------------------------------------------------------------
class TaskArgsBuilder:
"""Test-side task arguments container.
Maintains insertion order (tensors before scalars) and provides
attribute access by name for use in compute_golden.
Usage::
args = TaskArgsBuilder(
Tensor("a", torch.full((N,), 2.0)),
Tensor("b", torch.full((N,), 3.0)),
Tensor("f", torch.zeros(N)),
Scalar("scale", ctypes.c_float(1.5)),
)
args.a # → tensor
args.f[:] = args.a + args.b # in compute_golden
"""
def __init__(self, *specs):
self._specs: list = []
self._data: dict[str, Any] = {}
self._has_scalar = False
for spec in specs:
if isinstance(spec, Tensor):
self._add_tensor(spec)
elif isinstance(spec, Scalar):
self._add_scalar(spec)
def add_tensor(self, name: str, value: Any) -> None:
"""Add a tensor. Must be called before any add_scalar."""
self._add_tensor(Tensor(name, value))
def add_scalar(self, name: str, value: Any) -> None:
"""Add a scalar. After this, add_tensor is not allowed."""
self._add_scalar(Scalar(name, value))
def _add_tensor(self, spec: Tensor) -> None:
if self._has_scalar:
raise ValueError("Cannot add tensor after scalar (tensor-before-scalar ordering required)")
self._specs.append(spec)
self._data[spec.name] = spec.value
def _add_scalar(self, spec: Scalar) -> None:
self._has_scalar = True
self._specs.append(spec)
self._data[spec.name] = spec.value
def __getattr__(self, name: str) -> Any:
if name.startswith("_"):
raise AttributeError(name)
try:
return self._data[name]
except KeyError:
raise AttributeError(f"TaskArgsBuilder has no argument '{name}'") from None
def clone(self) -> TaskArgsBuilder:
"""Deep clone: all tensors are cloned, scalars copied."""
import torch # noqa: PLC0415
new = TaskArgsBuilder.__new__(TaskArgsBuilder)
new._specs = []
new._data = {}
new._has_scalar = False
for spec in self._specs:
if isinstance(spec, Tensor):
cloned = spec.value.clone() if isinstance(spec.value, torch.Tensor) else spec.value
new_spec = Tensor(spec.name, cloned)
new._specs.append(new_spec)
new._data[spec.name] = cloned
elif isinstance(spec, Scalar):
import copy # noqa: PLC0415
new._has_scalar = True
cloned_val = copy.copy(spec.value)
new_spec = Scalar(spec.name, cloned_val)
new._specs.append(new_spec)
new._data[spec.name] = cloned_val
return new
@property
def specs(self) -> list:
"""Ordered list of Tensor/Scalar specs."""
return self._specs
def tensor_names(self) -> list[str]:
"""Names of all tensor arguments, in order."""
return [s.name for s in self._specs if isinstance(s, Tensor)]
# ---------------------------------------------------------------------------
# CallableNamespace — dot-access container for L3 callables
# ---------------------------------------------------------------------------
class CallableNamespace:
"""Dot-access container for compiled/prepared callables.
Used by L3 orch functions to access callables by name::
callables.vector_kernel # → ChipCallable object
callables.vector_kernel_sig # → signature list
callables.verify # → CallableHandle
Also provides ``keep()`` for lifetime management: L3 orch functions
that build transient Python objects (e.g. ChipStorageTaskArgs) whose
raw pointers are submitted to the C++ scheduler must register them
via ``keep()`` so they outlive the scheduler drain::
def run_dag(w, callables, task_args, config):
chip_args, _ = _build_chip_task_args(task_args, callables.vector_kernel_sig)
callables.keep(chip_args) # survive until drain finishes
...
"""
def __init__(self, entries: dict):
self._entries = dict(entries)
self._keepalive: list = []
def __getattr__(self, name: str):
try:
return self._entries[name]
except KeyError:
raise AttributeError(f"CallableNamespace has no entry '{name}'") from None
def keep(self, *objs):
"""Register objects to keep alive until this namespace is destroyed."""
if not objs:
return None
self._keepalive.extend(objs)
return objs[0] if len(objs) == 1 else objs
# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------
def _build_chip_task_args(test_args: TaskArgsBuilder, orch_signature: list):
"""Build `ChipStorageTaskArgs` (POD) from `TaskArgsBuilder`.
Used by the L2 path (`ChipWorker.run(callable, chip_args, config)`): the
chip worker expects the runtime.so ABI-shaped POD directly (no tags).
Returns:
chip_args: ChipStorageTaskArgs (POD)
output_names: list of tensor names that are OUTPUT or INOUT
"""
from simpler.task_interface import ( # noqa: PLC0415
ArgDirection,
ChipStorageTaskArgs,
scalar_to_uint64,
)
from simpler_setup.torch_interop import make_tensor_arg # noqa: PLC0415
chip_args = ChipStorageTaskArgs()
output_names: list[str] = []
tensor_idx = 0
for spec in test_args.specs:
if isinstance(spec, Tensor):
if tensor_idx >= len(orch_signature):
raise ValueError(
f"Tensor '{spec.name}' at index {tensor_idx} has no matching entry in "
f"orchestration signature (length {len(orch_signature)}). "
f"Update CALLABLE['orchestration']['signature'] to match generate_args()."
)
direction = orch_signature[tensor_idx]
chip_args.add_tensor(make_tensor_arg(spec.value))
if direction in (ArgDirection.OUT, ArgDirection.INOUT):
output_names.append(spec.name)
tensor_idx += 1
elif isinstance(spec, Scalar):
chip_args.add_scalar(scalar_to_uint64(spec.value))
return chip_args, output_names
def _build_l3_task_args(test_args: TaskArgsBuilder, orch_signature: list):
"""Build a tagged `TaskArgs` (vector-backed, with `TensorArgType` tags) from
`TaskArgsBuilder`.
Used by the L3 path (`orch.submit_next_level(callable, args, config)`):
the orchestrator reads the tags to drive dependency inference.
Returns:
chip_args: TaskArgs (tagged)
output_names: list of tensor names that are OUTPUT or INOUT
"""
from simpler.task_interface import ( # noqa: PLC0415
ArgDirection,
TaskArgs,
TensorArgType,
scalar_to_uint64,
)
from simpler_setup.torch_interop import make_tensor_arg # noqa: PLC0415
_DIR_TO_TAG = {
ArgDirection.IN: TensorArgType.INPUT,
ArgDirection.OUT: TensorArgType.OUTPUT_EXISTING,
ArgDirection.INOUT: TensorArgType.INOUT,
}
chip_args = TaskArgs()
output_names: list[str] = []
tensor_idx = 0
for spec in test_args.specs:
if isinstance(spec, Tensor):
if tensor_idx >= len(orch_signature):
raise ValueError(
f"Tensor '{spec.name}' at index {tensor_idx} has no matching entry in "
f"orchestration signature (length {len(orch_signature)}). "
f"Update CALLABLE['orchestration']['signature'] to match generate_args()."
)
direction = orch_signature[tensor_idx]
tag = _DIR_TO_TAG.get(direction, TensorArgType.INPUT)
chip_args.add_tensor(make_tensor_arg(spec.value), tag)
if direction in (ArgDirection.OUT, ArgDirection.INOUT):
output_names.append(spec.name)
tensor_idx += 1
elif isinstance(spec, Scalar):
chip_args.add_scalar(scalar_to_uint64(spec.value))
return chip_args, output_names
@contextmanager
def _temporary_env(env_updates):
"""Temporarily set environment variables."""
if not env_updates:
yield
return
old = {k: os.environ.get(k) for k in env_updates}
for k, v in env_updates.items():
os.environ[k] = v
try:
yield
finally:
for k, v in old.items():
if v is None:
os.environ.pop(k, None)
else:
os.environ[k] = v
def _log_round_timings(timings):
"""Print per-round + summary host/device wall (µs) for multi-round runs.
Replaces the device-log scraping that ``tools/benchmark_rounds.sh`` used to
do — Worker.run now returns the timing directly, so the per-round table
can be emitted by the framework without grep+awk over device logs.
Output goes to ``print`` (not ``logger.info``) because benchmark numbers
are a user-facing artifact and the project's default log level suppresses
INFO in standalone test_*.py runs.
``timings`` is a list of (host_wall_us, device_wall_us) tuples. The device
column reports 0 when the runtime was built without PTO2_PROFILING (the
default build has it on) or when an L3+ DAG is in use (per-task device
cycles aren't aggregated).
"""
if not timings:
return
n = len(timings)
host_vals = sorted(t[0] for t in timings)
dev_vals = sorted(t[1] for t in timings)
host_avg = sum(host_vals) / n
# Device avg averages over non-zero rounds only. When --rounds > 1 the
# framework restricts enable_l2_swimlane (and thus orch_summary capture)
# to round 0, so the other rounds report 0; including those zeros in the
# average would silently halve / quarter the reported device wall and
# mislead the benchmark consumer. dev_count carries the sample size into
# the summary line for transparency.
dev_nonzero = [v for v in dev_vals if v > 0.0]
dev_count = len(dev_nonzero)
dev_avg = (sum(dev_nonzero) / dev_count) if dev_count else 0.0
show_device = dev_count > 0
header = f" {'Round':<6} {'Host (us)':>12}"
if show_device:
header += f" {'Device (us)':>12}"
print(header)
print(" " + "-" * (len(header) - 2))
for i, (h, d) in enumerate(timings):
line = f" {i:<6d} {h:>12.1f}"
if show_device:
line += f" {d:>12.1f}"
print(line)
summary = f" Avg Host: {host_avg:.1f} us"
if show_device:
summary += f" | Avg Device: {dev_avg:.1f} us [{dev_count}/{n} rounds captured]"
summary += f" ({n} rounds)"
print(summary)
trim = 10
if n > 2 * trim:
tc = n - 2 * trim
host_trim = sum(host_vals[trim:-trim]) / tc
msg = f" Trimmed Avg Host: {host_trim:.1f} us"
if show_device and dev_count > 2 * trim:
dev_nonzero_sorted = sorted(dev_nonzero)
dev_trim_count = dev_count - 2 * trim
dev_trim = sum(dev_nonzero_sorted[trim:-trim]) / dev_trim_count
msg += f" | Trimmed Avg Device: {dev_trim:.1f} us"
msg += f" (dropped {trim} low + {trim} high, {tc} rounds used)"
print(msg)
def _resolve_callable_paths(cls, cls_dir):
"""Resolve relative source paths in CALLABLE against cls_dir."""
callable_spec = cls.CALLABLE
if "callables" in callable_spec:
# L3: resolve inside each ChipCallable entry
resolved = []
for entry in callable_spec["callables"]:
if "orchestration" in entry:
entry = dict(entry)
_resolve_chip_entry_paths(entry, cls_dir)
resolved.append(entry)
callable_spec["callables"] = resolved
else:
# L2: resolve orchestration + incores directly
_resolve_chip_entry_paths(callable_spec, cls_dir)
def _resolve_chip_entry_paths(entry, cls_dir):
"""Resolve relative source paths in a chip entry (orchestration + incores)."""
if "orchestration" in entry:
orch = entry["orchestration"]
if isinstance(orch, dict) and "source" in orch and not os.path.isabs(orch["source"]):
entry["orchestration"] = dict(orch)
entry["orchestration"]["source"] = str(cls_dir / orch["source"])
if "incores" in entry:
resolved = []
for k in entry["incores"]:
k = dict(k)
if "source" in k and not os.path.isabs(k["source"]):
k["source"] = str(cls_dir / k["source"])
resolved.append(k)
entry["incores"] = resolved
def _extract_name_map(callable_spec: dict) -> dict:
"""Extract name mapping from a CALLABLE spec.
Each level exports only its own ``callable_id_to_name`` — the mapping
from next-level-down IDs to human-readable names. No cross-level
nesting: the perf data declares its level, the mapping declares its
level, and the tool matches them.
* **L2** — ``callable_id`` = incore ``func_id``::
{"level": 2, "orchestrator_name": "PagedAttn",
"callable_id_to_name": {"0": "QK", "1": "SF"}}
* **L3** — ``callable_id`` = index in ``callables`` list::
{"level": 3, "orchestrator_name": "run_dag",
"callable_id_to_name": {"0": "vec_kernel", "1": "verify"}}
"""
if "callables" not in callable_spec:
# L2: orchestration + incores
callable_id_to_name: dict[str, str] = {}
orch = callable_spec.get("orchestration", {})
orchestrator_name = orch.get("name") if isinstance(orch, dict) else None
for k in callable_spec.get("incores", []):
if "name" in k and "func_id" in k:
callable_id_to_name[str(k["func_id"])] = k["name"]
result: dict = {"level": 2, "orchestrator_name": orchestrator_name}
if callable_id_to_name:
result["callable_id_to_name"] = callable_id_to_name
return result
# L3: Python orch function + callables list
orch = callable_spec.get("orchestration")
orchestrator_name = getattr(orch, "__name__", None) if callable(orch) else None
callable_id_to_name = {}
for idx, entry in enumerate(callable_spec["callables"]):
callable_id_to_name[str(idx)] = entry.get("name", f"callable_{idx}")
result = {"level": 3, "orchestrator_name": orchestrator_name}
if callable_id_to_name:
result["callable_id_to_name"] = callable_id_to_name
return result
def _dump_name_map(mapping: dict, output_path: Path) -> Path | None:
"""Write name mapping to JSON if it contains any names. Returns path or None."""
import json as _json # noqa: PLC0415
if not mapping.get("callable_id_to_name") and not mapping.get("orchestrator_name"):
return None
output_path.parent.mkdir(parents=True, exist_ok=True)
with open(output_path, "w") as f:
_json.dump(mapping, f, indent=2)
return output_path
def _parse_case_selector(value: str) -> tuple[str | None, str | None]:
"""Parse one ``--case`` value into ``(class_name, case_name)``.
``Foo`` -> ``(None, "Foo")`` (any class)
``ClassA::Foo`` -> ``("ClassA", "Foo")``
``ClassA::`` -> ``("ClassA", None)`` (all cases in ClassA)
``::Foo`` -> ``(None, "Foo")``
"""
if "::" in value:
cls_part, case_part = value.split("::", 1)
return (cls_part or None, case_part or None)
return (None, value)
def _match_selectors(cls_name: str, case_name: str, selectors: list[tuple]) -> bool:
"""True if ``(cls_name, case_name)`` matches any selector (empty list means no selector filter)."""
if not selectors:
return True
for sel_cls, sel_case in selectors:
if (sel_cls is None or sel_cls == cls_name) and (sel_case is None or sel_case == case_name):
return True
return False
def _select_cases(test_classes, platform: str, selectors: list[tuple], manual_mode: str):
"""Resolve (class, case) pairs to run. Validates selectors strictly.
Filters: platform match -> selector match -> manual_mode (exclude/include/only).
Raises ``ValueError`` on unknown selector class/case or empty selection.
"""
class_index = {c.__name__: c for c in test_classes}
for sel_cls, _ in selectors:
if sel_cls is not None and sel_cls not in class_index:
available = ", ".join(sorted(class_index)) or "(none)"
raise ValueError(f"--case: unknown class '{sel_cls}'. Available: {available}")
for sel_cls, sel_case in selectors:
if sel_case is None:
continue
scoped = [class_index[sel_cls]] if sel_cls else test_classes
if not any(case["name"] == sel_case for c in scoped for case in c.CASES):
scope = sel_cls or "any class"
raise ValueError(f"--case: case '{sel_case}' not found in {scope}")
selected: list[tuple] = []
for cls in test_classes:
for case in cls.CASES:
if platform not in case["platforms"]:
continue
if not _match_selectors(cls.__name__, case["name"], selectors):
continue
is_manual = bool(case.get("manual"))
if manual_mode == "exclude" and is_manual:
continue
if manual_mode == "only" and not is_manual:
continue
selected.append((cls, case))
if not selected:
if selectors:
sel_str = ", ".join(f"{c or '*'}::{n or '*'}" for c, n in selectors)
hint = " (matches are manual; pass --manual include or only)" if manual_mode == "exclude" else ""
raise ValueError(f"--case: no cases matched [{sel_str}] for platform={platform}{hint}")
raise ValueError(f"No cases matched platform={platform} (manual={manual_mode})")
return selected
def _project_root() -> Path:
return Path(__file__).resolve().parent.parent
def _outputs_dir() -> Path:
"""Root directory under which per-case output prefixes are created."""
return _project_root() / "outputs"
def _build_output_prefix(case_label: str) -> Path:
"""Per-case directory for diagnostic artifacts.
Each case gets its own ``outputs/<case_label>_<timestamp>/`` directory; the
runtime writes ``l2_swimlane_records.json``, ``tensor_dump/``, and ``pmu.csv``
under that root with fixed filenames. Two cases of the same name run in
the same second is not a contemplated scenario (parallel xdist runs differ
by class+method).
The directory is created here: the dep_gen host replay (and any other
writer) ``fopen``s ``<prefix>/<file>`` directly without an mkdir of its
own, so the prefix must exist before the runtime call.
"""
from datetime import datetime # noqa: PLC0415
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
safe_label = _sanitize_for_filename(case_label)
prefix = _outputs_dir() / f"{safe_label}_{timestamp}"
prefix.mkdir(parents=True, exist_ok=True)
return prefix
def _run_swimlane_converter(
input_path: Path | None = None,
func_names_path: Path | None = None,
) -> None:
"""Invoke the bundled swimlane converter as a subprocess.
When ``input_path`` is given, the converter derives its output filename from
the input's timestamp (see ``swimlane_converter._resolve_output_path``).
Without it, the converter auto-selects the latest ``l2_swimlane_records_*.json``.
"""
import logging # noqa: PLC0415
import subprocess # noqa: PLC0415
logger = logging.getLogger(__name__)
cmd = [sys.executable, "-m", "simpler_setup.tools.swimlane_converter"]
if input_path is not None:
cmd.append(str(input_path))
if func_names_path is not None:
cmd += ["--func-names", str(func_names_path)]
try:
result = subprocess.run(cmd, check=True, capture_output=True, text=True)
if result.stdout:
logger.info(result.stdout)
logger.info("Swimlane JSON generation completed")
except subprocess.CalledProcessError as e:
logger.warning(f"Failed to generate swimlane JSON: {e}")
if e.stdout:
logger.debug(f"stdout: {e.stdout}")
if e.stderr:
logger.debug(f"stderr: {e.stderr}")
def _sanitize_for_filename(s: str) -> str:
return "".join(c if c.isalnum() or c in "._-" else "_" for c in s)
def _convert_case_swimlane(
case_label: str,
output_prefix: Path,
callable_spec: dict | None = None,
) -> None:
"""Post-case: invoke the swimlane converter on the perf file the runtime
just wrote into ``<output_prefix>/l2_swimlane_records.json``. No diff/rename
dance — the path is known a priori from CallConfig.output_prefix.
"""
import logging # noqa: PLC0415
logger = logging.getLogger(__name__)
perf_file = output_prefix / "l2_swimlane_records.json"
if not perf_file.exists():
logger.warning(f"[{case_label}] {perf_file} not produced; skipping conversion")
return
# Dump callable name mapping if the CALLABLE spec provides names
func_names_path = None
if callable_spec:
mapping = _extract_name_map(callable_spec)
safe_label = _sanitize_for_filename(case_label)
func_names_path = _dump_name_map(mapping, output_prefix / f"name_map_{safe_label}.json")
_run_swimlane_converter(input_path=perf_file, func_names_path=func_names_path)
def _plot_case_scope_stats(case_label: str, output_prefix: Path) -> None:
"""Post-case: turn ``<output_prefix>/scope_stats/scope_stats.jsonl`` into
the self-contained scope_stats HTML report. Path is known a priori from
CallConfig.output_prefix.
"""
import logging # noqa: PLC0415
logger = logging.getLogger(__name__)
jsonl_file = output_prefix / "scope_stats" / "scope_stats.jsonl"
if not jsonl_file.exists():
logger.warning(f"[{case_label}] {jsonl_file} not produced; skipping scope_stats plot")
return
import sys # noqa: PLC0415
from pathlib import Path as _Path # noqa: PLC0415
tools_dir = _Path(__file__).resolve().parent / "tools"
sys.path.insert(0, str(tools_dir))
try:
import scope_stats_plot # noqa: PLC0415
scope_stats_plot.process(jsonl_file)
finally:
sys.path.remove(str(tools_dir))
def run_class_cases( # noqa: PLR0913 -- shared layer-5 entry; kwargs mirror CLI surface
worker,
cls_inst,
cases,
*,
callable_obj,
sub_handles,
rounds,
skip_golden,
enable_l2_swimlane,
enable_dump_tensor,
enable_pmu,
enable_dep_gen,
enable_scope_stats,
):
"""Execute a pre-filtered list of cases for one class (layers 5-6).
Caller is responsible for platform/selector/manual filtering. Profiling
snapshots wrap each case. Validation failures propagate; caller decides
fail-fast vs collect semantics.
"""
cls_name = type(cls_inst).__name__
callable_spec = getattr(type(cls_inst), "CALLABLE", None)
diagnostics_on = enable_l2_swimlane or enable_dump_tensor or enable_pmu or enable_dep_gen or enable_scope_stats
for case in cases:
case_label = f"{cls_name}_{case['name']}"
# Per-case directory the runtime writes into. Required (non-empty) when
# any diagnostic flag is on; CallConfig::validate() throws otherwise.
# scope_stats now writes <prefix>/scope_stats/scope_stats.jsonl (sibling of
# l2_swimlane_records.json / deps.json), so it pulls output_prefix the
# same way the other DFX flags do.
prefix = _build_output_prefix(case_label) if diagnostics_on else Path("")
try:
cls_inst._run_and_validate(
worker,
callable_obj,
case,
sub_handles=sub_handles,
rounds=rounds,
skip_golden=skip_golden,
enable_l2_swimlane=enable_l2_swimlane,
enable_dump_tensor=enable_dump_tensor,
enable_pmu=enable_pmu,
enable_dep_gen=enable_dep_gen,
enable_scope_stats=enable_scope_stats,
output_prefix=str(prefix) if diagnostics_on else "",
)
finally:
if enable_l2_swimlane:
_convert_case_swimlane(case_label, prefix, callable_spec=callable_spec)
if enable_scope_stats:
_plot_case_scope_stats(case_label, prefix)
def _compare_outputs(test_args, golden_args, output_names, rtol, atol):
"""Compare output tensors against golden values."""
import torch # noqa: PLC0415
for name in output_names:
actual = getattr(test_args, name)
expected = getattr(golden_args, name)
if not torch.allclose(actual, expected, rtol=rtol, atol=atol):
diff = (actual - expected).abs().max().item()
raise AssertionError(f"Golden mismatch on '{name}': max_diff={diff}, rtol={rtol}, atol={atol}")
def _compile_chip_callable_from_spec(spec, platform, runtime, cache_key):
"""Compile a chip entry spec (orchestration + incores) -> ChipCallable. Session-cached."""
if cache_key in _compile_cache:
return _compile_cache[cache_key]
from simpler.task_interface import ChipCallable, CoreCallable # noqa: PLC0415
from .elf_parser import extract_text_section # noqa: PLC0415
from .kernel_compiler import KernelCompiler # noqa: PLC0415
from .pto_isa import ensure_pto_isa_root # noqa: PLC0415
orch = spec["orchestration"]
incores = spec["incores"]
pto_isa_root = ensure_pto_isa_root()
kc = KernelCompiler(platform=platform)
is_sim = platform.endswith("sim")
orch_binary = kc.compile_orchestration(runtime, orch["source"])
inc_dirs = kc.get_orchestration_include_dirs(runtime)
kernel_binaries = []
for k in incores:
incore = kc.compile_incore(
k["source"], core_type=k["core_type"], pto_isa_root=pto_isa_root, extra_include_dirs=inc_dirs
)
if not is_sim:
incore = extract_text_section(incore)
kernel_binaries.append((k["func_id"], CoreCallable.build(signature=k.get("signature", []), binary=incore)))
chip_callable = ChipCallable.build(
signature=orch.get("signature", []),
func_name=orch["function_name"],
binary=orch_binary,
children=kernel_binaries,
config_name=orch.get("config_name", ""),
)
_compile_cache[cache_key] = chip_callable
return chip_callable
# ---------------------------------------------------------------------------
# @scene_test decorator
# ---------------------------------------------------------------------------
def scene_test(level: int, runtime: str):
"""Decorator marking a SceneTestCase with level and runtime.
Platforms are declared per-case in CASES, not here.
"""
def decorator(cls):
cls._st_level = level
cls._st_runtime = runtime
cls_dir = Path(inspect.getfile(cls)).parent
if hasattr(cls, "CALLABLE"):
_resolve_callable_paths(cls, cls_dir)
return cls
return decorator
# ---------------------------------------------------------------------------
# SceneTestCase base class
# ---------------------------------------------------------------------------
class SceneTestCase:
"""Base class for scene tests at any hierarchy level.
Subclasses declare CALLABLE, CASES, generate_args(), compute_golden().
"""
CALLABLE: dict = {}
CASES: list[dict] = []
RTOL: float = 1e-5
ATOL: float = 1e-5
RUNTIME_ENV: dict = {}
def generate_args(self, params) -> TaskArgsBuilder:
"""Return TaskArgsBuilder with ordered Tensor/Scalar specs."""
raise NotImplementedError
def compute_golden(self, args: TaskArgsBuilder, params) -> None:
"""Compute expected outputs in-place on a cloned TaskArgsBuilder."""
raise NotImplementedError
# ------------------------------------------------------------------
# Callable compilation
# ------------------------------------------------------------------
@classmethod
def compile_chip_callable(cls, platform):
"""Compile CALLABLE -> ChipCallable (L2). Session-cached."""
cache_key = (cls.__qualname__, platform, cls._st_runtime)
return _compile_chip_callable_from_spec(cls.CALLABLE, platform, cls._st_runtime, cache_key)
@classmethod
def _compile_l3_callables(cls, platform):
"""Compile all ChipCallable entries in CALLABLE['callables'] (L3)."""
compiled = {}
for entry in cls.CALLABLE["callables"]:
if "orchestration" in entry:
name = entry["name"]
cache_key = (cls.__qualname__, name, platform, cls._st_runtime)
chip = _compile_chip_callable_from_spec(entry, platform, cls._st_runtime, cache_key)
compiled[name] = chip
compiled[f"{name}_sig"] = entry["orchestration"].get("signature", [])
return compiled
# ------------------------------------------------------------------
# Worker creation
# ------------------------------------------------------------------
@classmethod
def _create_worker(cls, platform, device_id=0):
"""Create the L2 Worker for the standalone path.
Mirrors the ``st_worker`` pytest fixture, which yields a ``Worker``
(not a raw ``ChipWorker``) — ``_run_and_validate_l2`` is shared by both
paths and calls ``worker.register(...)`` / ``worker.run(handle, ...)``,
which only the ``Worker`` wrapper exposes.
"""
from simpler.worker import Worker # noqa: PLC0415
w = Worker(level=2, device_id=device_id, platform=platform, runtime=cls._st_runtime)
w.init()
return w
# ------------------------------------------------------------------
# Default build methods
# ------------------------------------------------------------------
def build_callable(self, platform):
"""Build callable for the current level.
L2: returns ChipCallable.
L3: returns dict of {name: ChipCallable, name_sig: signature}.
"""
if self._st_level == 2:
return self.compile_chip_callable(platform)
elif self._st_level == 3:
return self._compile_l3_callables(platform)
raise ValueError(f"Unsupported level: {self._st_level}")
def _build_config(
self,
config_dict,
enable_l2_swimlane=0,
enable_dump_tensor=False,
enable_pmu=0,
enable_dep_gen=False,
enable_scope_stats=False,
*,
output_prefix="",
):
from simpler.task_interface import CallConfig # noqa: PLC0415
config = CallConfig()
# Default to 0 (CallConfig "auto" sentinel) when a case omits
# block_dim — DeviceRunner resolves it to the stream's max capacity
# at run() time. Cases that need a specific value still set it
# explicitly in their config dict.
config.block_dim = config_dict.get("block_dim", 0)
config.aicpu_thread_num = config_dict.get("aicpu_thread_num", 3)
config.enable_l2_swimlane = enable_l2_swimlane
config.enable_dump_tensor = enable_dump_tensor
config.enable_pmu = enable_pmu # 0=disabled, >0=enabled with event type
config.enable_dep_gen = enable_dep_gen
config.enable_scope_stats = enable_scope_stats
# `output_prefix` is required by CallConfig::validate() whenever any
# diagnostic flag is enabled. Caller threads it down from the per-case
# directory built by _build_output_prefix().
if output_prefix:
config.output_prefix = str(output_prefix)
return config
def _resolve_env(self):
env = self.RUNTIME_ENV
if not env:
return {}
cls_dir = Path(inspect.getfile(type(self))).parent
out = {}
for k, v in env.items():
s = str(v)
if (k.endswith("_DIR") or k.endswith("_PATH")) and not Path(s).is_absolute():
s = str((cls_dir / s).resolve())
out[k] = s
return out
# ------------------------------------------------------------------
# Run + validate
# ------------------------------------------------------------------
def _run_and_validate( # noqa: PLR0913 -- threads CLI diagnostic flags + case context
self,
worker,
callable_obj,
case,
sub_handles=None,
rounds=1,
skip_golden=False,
enable_l2_swimlane=0,
enable_dump_tensor=False,
enable_pmu=0,
enable_dep_gen=False,
enable_scope_stats=False,
output_prefix="",
):
if self._st_level == 2:
self._run_and_validate_l2(
worker,
callable_obj,
case,
rounds=rounds,
skip_golden=skip_golden,
enable_l2_swimlane=enable_l2_swimlane,
enable_dump_tensor=enable_dump_tensor,
enable_pmu=enable_pmu,
enable_dep_gen=enable_dep_gen,
enable_scope_stats=enable_scope_stats,
output_prefix=output_prefix,
)
elif self._st_level == 3:
self._run_and_validate_l3(
worker,
callable_obj,
sub_handles or {},
case,
rounds=rounds,
skip_golden=skip_golden,
enable_l2_swimlane=enable_l2_swimlane,
enable_dump_tensor=enable_dump_tensor,
enable_pmu=enable_pmu,
enable_dep_gen=enable_dep_gen,
enable_scope_stats=enable_scope_stats,
output_prefix=output_prefix,
)
def _run_and_validate_l2( # noqa: PLR0913 -- threads CLI diagnostic flags + case context
self,
worker,
callable_obj,
case,
rounds=1,
skip_golden=False,
enable_l2_swimlane=0,
enable_dump_tensor=False,
enable_pmu=0,
enable_dep_gen=False,
enable_scope_stats=False,
output_prefix="",
):
params = case.get("params", {})
config_dict = case.get("config", {})
orch_sig = self.CALLABLE.get("orchestration", {}).get("signature", [])
# The L2 entry point is `Worker.run(handle, args, cfg)`. Reuse the
# handle registered by the st_worker fixture / standalone path.
handle = getattr(type(self), "_st_l2_handle", None)
if handle is None:
handle = worker.register(callable_obj)
type(self)._st_l2_handle = handle
# Build args
test_args = self.generate_args(params)