hyperonnx 2.0.1__tar.gz → 2.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/PKG-INFO +1 -1
  2. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/__init__.py +1 -1
  3. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/compile/bundle.py +174 -49
  4. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/compile/capture.py +18 -12
  5. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/compile/cutlass.py +1 -1
  6. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/compile/cutlass_kernels/conv.py +45 -15
  7. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/compile/cutlass_kernels/mm.py +3 -0
  8. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/compile/testing.py +64 -22
  9. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/exporter/_onnxscript.py +29 -2
  10. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/exporter/_onnxscript_legacy.py +12 -3
  11. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/exporter/torchscript.py +23 -2
  12. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/function_rewriter.py +25 -15
  13. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/hyper_export.py +70 -22
  14. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/transformers/cache.py +8 -0
  15. hyperonnx-2.1.0/hyperonnx/typing.py +163 -0
  16. hyperonnx-2.0.1/hyperonnx/typing.py +0 -85
  17. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/LICENSE +0 -0
  18. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/README.md +0 -0
  19. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/auto.py +0 -0
  20. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/compile/__init__.py +0 -0
  21. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/compile/cutlass_bundle.py +0 -0
  22. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/compile/cutlass_kernels/__init__.py +0 -0
  23. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/compile/cutlass_kernels/config.py +0 -0
  24. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/compile/cutlass_kernels/extract.py +0 -0
  25. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/compile/cutlass_kernels/run.py +0 -0
  26. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/compile/grid_ast.py +0 -0
  27. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/compile/inductor.py +0 -0
  28. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/compile/typing.py +0 -0
  29. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/exporter/__init__.py +0 -0
  30. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/exporter/dynamo.py +0 -0
  31. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/exporter/utils.py +0 -0
  32. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/torch_export.py +0 -0
  33. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/transformers/__init__.py +0 -0
  34. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/transformers/attention.py +0 -0
  35. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/transformers/mamba.py +0 -0
  36. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/transformers/patch.py +0 -0
  37. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/transformers/recurrent.py +0 -0
  38. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/hyperonnx/utils.py +0 -0
  39. {hyperonnx-2.0.1 → hyperonnx-2.1.0}/pyproject.toml +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hyperonnx
3
- Version: 2.0.1
3
+ Version: 2.1.0
4
4
  Summary: Copyright (C) 2026 The HYPERONNX Authors.
5
5
  Author-email: Wenyi Tang <wenyitang@outlook.com>
6
6
  Requires-Python: >=3.12
@@ -19,4 +19,4 @@ from .hyper_export import export_hyper_onnx
19
19
  from .utils import HYPER_DOMAIN
20
20
 
21
21
  __all__ = ["auto_trace_method", "export_hyper_onnx", "HYPER_DOMAIN"]
22
- __version__ = "2.0.1"
22
+ __version__ = "2.1.0"
@@ -19,6 +19,9 @@ import ast as pyast
19
19
  import importlib
20
20
  import json
21
21
  import re
22
+ from collections import Counter
23
+ from collections.abc import Mapping
24
+ from itertools import groupby
22
25
  from pathlib import Path
23
26
  from typing import TYPE_CHECKING, Any
24
27
 
@@ -120,8 +123,9 @@ def _contiguous_span(shape: list) -> int:
120
123
  return max(1, n)
121
124
 
122
125
 
123
- def _registry_span(entry: BufferEntry) -> int:
124
- """Storage span a registry ``BufferEntry`` demands at replay."""
126
+ def _registry_span(entry: Mapping[str, Any]) -> int:
127
+ """Storage span (in elements) a layout dict demands — registry entry or
128
+ graph-table meta (same shape/stride keys)."""
125
129
  shape = entry.get("shape")
126
130
  if not shape:
127
131
  return 0
@@ -133,6 +137,21 @@ def _registry_span(entry: BufferEntry) -> int:
133
137
  return _contiguous_span(shape)
134
138
 
135
139
 
140
+ _DTYPE_SIZE = {
141
+ "bool": 1,
142
+ "int8": 1,
143
+ "uint8": 1,
144
+ "float16": 2,
145
+ "bfloat16": 2,
146
+ "float32": 4,
147
+ "int32": 4,
148
+ "float64": 8,
149
+ "int64": 8,
150
+ }
151
+ """Element width per dtype string; unknown dtypes fall back to 4 bytes
152
+ (replay's own ``getattr(torch, dtype, torch.float32)`` fallback)."""
153
+
154
+
136
155
  def _static_arg_descriptor(arg: Any, table: dict[str, dict], owner: str) -> dict:
137
156
  """Build a unified ``KernelArgDescriptor`` from a static wrapper arg.
138
157
 
@@ -371,6 +390,7 @@ def _finalize_pipeline(
371
390
  pipeline: list[dict],
372
391
  kernel_entries: list[KernelEntry],
373
392
  runtime_buffers: "list[BufferInfo]",
393
+ symbol_to_traces: "dict[str, list[LaunchTraceEntry]] | None" = None,
374
394
  ) -> list[dict]:
375
395
  """Merge the wrapper pipeline with kernel entries and validate buffers.
376
396
 
@@ -388,10 +408,15 @@ def _finalize_pipeline(
388
408
  (shape, dtype), attaching ``buffer_id`` on match; undefined names
389
409
  are flagged and warned about.
390
410
 
391
- Launch descriptors come directly from ``kernel_entries`` — each entry's
392
- ``args`` were already overlaid with the traced runtime descriptors
393
- (carrying ``buffer_id``\\s) in :func:`write_kernel_bundle`. A symbol
394
- appearing multiple times is seeded only on first occurrence.
411
+ When ``symbol_to_traces`` is given (per-symbol queues of call-site
412
+ traces, in launch order), every ``triton_kernel`` step consumes its
413
+ own call-site trace: the trace's ``args`` (carrying ``buffer_id``\\s)
414
+ seed the table and become the step's launch descriptors, and its
415
+ grid/warps/shared-mem overlay the step's ``launch`` — so repeated
416
+ call sites of one symbol each keep their own buffers and launch
417
+ config. Steps past the end of their queue fall back to table
418
+ resolution (``launch_missing``). Without traces, each entry's
419
+ overlaid ``args`` seed only the first occurrence of their symbol.
395
420
 
396
421
  Mismatches are logged and annotated, never fatal.
397
422
  """
@@ -478,25 +503,39 @@ def _finalize_pipeline(
478
503
 
479
504
  # Resolve graph inputs by FX placeholder target (exact name match).
480
505
  _map_graph_inputs_by_source(table, runtime_buffers, rt_claimed)
481
- # Seed name→buffer_id from kernel entries. Only the FIRST occurrence
482
- # of each symbol is seeded — repeated call sites have different
483
- # buffer ids and must resolve via the table.
506
+ # Seed name→buffer_id per call site. With launch traces, every
507
+ # occurrence of a symbol consumes its own trace (in launch order),
508
+ # so repeated call sites each seed their own buffer ids and launch
509
+ # config. Without traces, only the first occurrence of each symbol
510
+ # is seeded from the entry args; later call sites resolve via the
511
+ # table.
484
512
  seeded_symbols: set[str] = set()
485
513
  for step in kept:
486
514
  if step["type"] != "triton_kernel" or "cubin" not in step:
487
515
  continue
488
- entry = symbol_to_entry.get(step["kernel"])
489
- entry_args = entry["args"] if entry else None
490
516
  kernel_sym = step["kernel"]
491
- if kernel_sym in seeded_symbols:
492
- step["_launch_args"] = None
493
- continue
494
- seeded_symbols.add(kernel_sym)
495
- step["_launch_args"] = entry_args or None
496
- if not entry_args:
517
+ entry = symbol_to_entry.get(kernel_sym)
518
+ trace: LaunchTraceEntry | None = None
519
+ if symbol_to_traces is not None:
520
+ queue = symbol_to_traces.get(kernel_sym)
521
+ trace = queue.pop(0) if queue else None
522
+ launch_args = trace.args if trace is not None else None
523
+ elif kernel_sym in seeded_symbols:
524
+ launch_args = None
525
+ else:
526
+ seeded_symbols.add(kernel_sym)
527
+ launch_args = (entry["args"] if entry else None) or None
528
+ step["_launch_args"] = launch_args or None
529
+ if trace is not None and entry is not None:
530
+ # Per-call-site launch config — a later call site of the
531
+ # same symbol may launch with a different grid.
532
+ launch = dict(entry["launch"])
533
+ _overlay_launch(launch, trace)
534
+ step["launch"] = launch
535
+ if not launch_args:
497
536
  continue
498
537
  static = step["_static_args"]
499
- for i, ka in enumerate(entry_args):
538
+ for i, ka in enumerate(launch_args):
500
539
  if ka.get("kind") != "tensor":
501
540
  continue
502
541
  ka_bid = ka.get("buffer_id")
@@ -610,51 +649,127 @@ def _reconcile_registry_with_allocate(
610
649
  a too-small shape. The full-size ``[2,…]`` shape exists only in the
611
650
  graph-table ``allocate`` entry (from inductor IR ``buf.get_size()``).
612
651
 
613
- For every graph-table entry with ``kind=="allocate"`` and a resolved
614
- ``buffer_id``, compute the allocate's storage span; if the registry
615
- entry for that id has a smaller span, overwrite it with the allocate's
616
- shape/stride (and contiguous fallback) so replay allocates enough
617
- storage for the views the kernels take.
652
+ For every graph-table ``allocate``/``view`` entry with a resolved
653
+ ``buffer_id``, compute the layout's storage span *in bytes* (one
654
+ storage can host allocations of different dtypes across its lifetime —
655
+ e.g. an f32 scratch followed by an fp16 output on the same id — so an
656
+ element-span compare can under-size the storage); if the registry entry
657
+ covers fewer bytes, overwrite its shape with a contiguous layout big
658
+ enough for the widest use, so replay allocates enough storage for every
659
+ view the kernels take. The registry dtype follows the LAST allocate on
660
+ the id (the final writer — the output materialization reads through
661
+ it).
618
662
 
619
663
  This is the only position with full information: launch-trace-side
620
664
  capture cannot observe allocations that never appear as kernel args.
621
665
  Mutates ``registry`` in place.
622
666
  """
623
667
  by_id: dict[int, BufferEntry] = {b["id"]: b for b in registry}
668
+ need_bytes: dict[int, int] = {}
624
669
  for graph in pipeline:
625
670
  table = graph.get("buffers", {})
626
671
  for meta in table.values():
627
- if meta.get("kind") != "allocate":
672
+ if meta.get("kind") not in ("allocate", "view"):
628
673
  continue
629
674
  bid = meta.get("buffer_id")
630
- if bid is None:
631
- continue
632
675
  entry = by_id.get(bid)
633
676
  if entry is None:
634
677
  continue
635
- alloc_shape = meta.get("shape")
636
- if not alloc_shape:
678
+ span = _registry_span(meta)
679
+ if not span:
680
+ continue
681
+ size = _DTYPE_SIZE.get(meta.get("dtype") or entry.get("dtype", ""), 4)
682
+ need_bytes[bid] = max(need_bytes.get(bid, 0), span * size)
683
+ if meta.get("kind") != "allocate":
637
684
  continue
638
685
  alloc_dtype = meta.get("dtype")
639
686
  if alloc_dtype and entry.get("dtype") != alloc_dtype:
640
687
  entry["dtype"] = alloc_dtype
641
- alloc_stride = meta.get("stride")
642
- alloc_span: int
643
- if alloc_stride and len(alloc_stride) == len(alloc_shape):
644
- s = _layout_span(alloc_shape, alloc_stride)
645
- alloc_span = s if s is not None else _contiguous_span(alloc_shape)
646
- else:
647
- alloc_span = _contiguous_span(alloc_shape)
648
- if alloc_span <= _registry_span(entry):
688
+ # Both sides scale by the same (synced) dtype width → bytes
689
+ # cancel; cross-dtype under-sizing is caught by need_bytes below.
690
+ if span <= _registry_span(entry):
649
691
  continue
650
- # Overwrite: registry must hold at least the allocate span.
651
- entry["shape"] = [int(x) for x in alloc_shape]
652
- if alloc_stride and len(alloc_stride) == len(alloc_shape):
692
+ # Overwrite: registry must hold at least the allocate's bytes.
693
+ entry["shape"] = [int(x) for x in meta["shape"]]
694
+ alloc_stride = meta.get("stride")
695
+ if alloc_stride and len(alloc_stride) == len(meta["shape"]):
653
696
  entry["stride"] = [int(x) for x in alloc_stride]
654
697
  elif "stride" in entry:
655
698
  # Old stride was for a smaller shape; drop it so replay
656
699
  # falls back to a contiguous view of the new shape.
657
700
  del entry["stride"]
701
+ # Views / wider-dtype uses no single allocate layout covered (e.g. an
702
+ # f32 scratch on storage whose frozen shape is fp16): grow flat.
703
+ for bid, entry in by_id.items():
704
+ size = _DTYPE_SIZE.get(entry.get("dtype", ""), 4)
705
+ if need_bytes.get(bid, 0) <= _registry_span(entry) * size:
706
+ continue
707
+ entry["shape"] = [-(-need_bytes[bid] // size)]
708
+ entry.pop("stride", None)
709
+
710
+
711
+ def _launch_fingerprint(entry: "LaunchTraceEntry") -> tuple:
712
+ """Arg identity of a launch: tensor args contribute their ``buffer_id``,
713
+ scalar args their ``value``. Benchmark reps of a call site share its
714
+ fingerprint; a launch on different buffers starts a new segment."""
715
+ return tuple(
716
+ ("tensor", a.get("buffer_id"))
717
+ if a.get("kind") == "tensor"
718
+ else ("scalar", a.get("value"))
719
+ for a in entry.args
720
+ )
721
+
722
+
723
+ def _overlay_launch(launch: dict, trace: "LaunchTraceEntry") -> None:
724
+ """Overlay a trace's per-call-site launch config onto a launch dict."""
725
+ launch["captured_grid"] = list(trace.grid)
726
+ launch["shared_mem_bytes"] = trace.shared_mem
727
+ launch["num_warps"] = trace.num_warps
728
+ launch["num_scratch_args"] = trace.num_scratch_args
729
+
730
+
731
+ def _call_site_traces(
732
+ all_launches: "list[LaunchTraceEntry]", step_counts: dict[str, int]
733
+ ) -> "list[LaunchTraceEntry]":
734
+ """Extract the per-call-site production launches from the raw stream.
735
+
736
+ The autotuner fires a benchmark storm before the first call site's
737
+ production launch; later call sites of the same kernel reuse the
738
+ cached winner and launch once each — possibly right after the
739
+ previous site (no other symbol in between), so one call site is not
740
+ one consecutive symbol run. Instead, split each consecutive
741
+ same-symbol run into fingerprint segments: the last launch of every
742
+ segment is a production candidate (benchmark reps share their site's
743
+ fingerprint and precede its production launch inside the segment),
744
+ and the pipeline's per-symbol step count selects the trailing
745
+ candidates — dropping pure-benchmark segments (scratch-buffer
746
+ benchmarks of a site whose production launch carries different
747
+ args). The trailing-n selection spans ALL runs of a symbol (a symbol
748
+ recurs as separate runs whenever other symbols interleave between its
749
+ call sites): selecting per run instead would keep a leading
750
+ storm candidate and shift every site onto the wrong trace. Symbols
751
+ with no pipeline steps contribute no traces.
752
+ """
753
+ cands_by_symbol: dict[str, list[LaunchTraceEntry]] = {}
754
+ for symbol, grp in groupby(all_launches, key=lambda e: e.symbol):
755
+ run = list(grp)
756
+ cands: list[LaunchTraceEntry] = []
757
+ prev_fp: tuple | None = None
758
+ prev: LaunchTraceEntry | None = None
759
+ for e in run:
760
+ fp = _launch_fingerprint(e)
761
+ if prev is not None and fp != prev_fp:
762
+ cands.append(prev)
763
+ prev_fp, prev = fp, e
764
+ if prev is not None:
765
+ cands.append(prev)
766
+ cands_by_symbol.setdefault(symbol, []).extend(cands)
767
+ entries: list[LaunchTraceEntry] = []
768
+ for symbol, cands in cands_by_symbol.items():
769
+ n = step_counts.get(symbol, 0)
770
+ if n:
771
+ entries.extend(cands[-n:])
772
+ return entries
658
773
 
659
774
 
660
775
  def write_kernel_bundle(
@@ -703,15 +818,27 @@ def write_kernel_bundle(
703
818
  bundle_dir.mkdir(parents=True, exist_ok=True)
704
819
 
705
820
  symbol_to_trace: dict[str, LaunchTraceEntry] = {}
821
+ symbol_to_traces: dict[str, list[LaunchTraceEntry]] = {}
706
822
  winning_keys: set[str] | None = None
707
823
  winning_hashes: set[str] = set()
708
824
  if launch_trace is not None:
709
- for e in launch_trace.entries:
710
- symbol_to_trace[e.symbol] = e
711
- winning_keys = {
712
- f"{e.symbol}|{e.shared_mem}|{e.num_warps}" for e in launch_trace.entries
713
- }
714
- winning_hashes = {e.kernel_hash for e in launch_trace.entries if e.kernel_hash}
825
+ if wrapper_graph:
826
+ # Per-call-site traces, in launch order: one per pipeline
827
+ # triton step of the symbol (see _call_site_traces).
828
+ step_counts = Counter(
829
+ step["kernel"]
830
+ for graph in wrapper_graph
831
+ for step in graph["steps"]
832
+ if step.get("type") == "triton_kernel" and step.get("kernel")
833
+ )
834
+ traces = _call_site_traces(launch_trace.all_launches, step_counts)
835
+ else:
836
+ traces = launch_trace.entries
837
+ for e in traces:
838
+ symbol_to_trace.setdefault(e.symbol, e)
839
+ symbol_to_traces.setdefault(e.symbol, []).append(e)
840
+ winning_keys = {f"{e.symbol}|{e.shared_mem}|{e.num_warps}" for e in traces}
841
+ winning_hashes = {e.kernel_hash for e in traces if e.kernel_hash}
715
842
 
716
843
  entries: list[KernelEntry] = []
717
844
  for k in kernels:
@@ -746,10 +873,7 @@ def write_kernel_bundle(
746
873
 
747
874
  trace: LaunchTraceEntry | None = symbol_to_trace.get(k["symbol"])
748
875
  if trace is not None:
749
- launch["captured_grid"] = list(trace.grid)
750
- launch["shared_mem_bytes"] = trace.shared_mem
751
- launch["num_warps"] = trace.num_warps
752
- launch["num_scratch_args"] = trace.num_scratch_args
876
+ _overlay_launch(launch, trace)
753
877
  args = trace.args
754
878
 
755
879
  entries.append(
@@ -795,6 +919,7 @@ def write_kernel_bundle(
795
919
  wrapper_graph,
796
920
  entries,
797
921
  launch_trace.buffers if launch_trace is not None else [],
922
+ symbol_to_traces if launch_trace is not None else None,
798
923
  )
799
924
  else:
800
925
  manifest["pipeline"] = [
@@ -752,19 +752,25 @@ class LaunchTraceSink:
752
752
  self._ptr_to_buf[ptr].kind = "output"
753
753
 
754
754
  def finalize(self) -> None:
755
- """Deduplicate launches, keeping the last-seen config per symbol.
756
-
757
- Triton's autotuner may fire the same kernel several times; replay
758
- wants one entry per symbol (the winning config), so we walk
759
- ``all_launches`` in reverse and keep the first occurrence of each.
755
+ """Collapse autotune runs, keeping one entry per call site.
756
+
757
+ Triton's autotuner benchmarks its configs back-to-back before a
758
+ call site's production launch, then launches the winner once and
759
+ the wrapper moves on to the next kernel — so one call site is
760
+ one consecutive run of its symbol, and the production launch is
761
+ the run's last entry. Benchmark runs may carry different
762
+ (scratch) buffers than production, so neither config nor args
763
+ identify the winner; position does. A symbol launched at
764
+ multiple call sites keeps one entry per call site, in launch
765
+ order, so the bundle can seed each pipeline occurrence from its
766
+ own trace.
760
767
  """
761
- seen: set[str] = set()
762
768
  winners: list[LaunchTraceEntry] = []
763
- for entry in reversed(self.all_launches):
764
- if entry.symbol not in seen:
765
- seen.add(entry.symbol)
769
+ for entry in self.all_launches:
770
+ if winners and winners[-1].symbol == entry.symbol:
771
+ winners[-1] = entry
772
+ else:
766
773
  winners.append(entry)
767
- winners.reverse()
768
774
  self.entries = winners
769
775
 
770
776
  def vendor_lib_gaps(self) -> list[BufferInfo]:
@@ -813,8 +819,8 @@ def capture_launch_trace(
813
819
  input_kwargs: keyword input tensors (optional).
814
820
 
815
821
  Yields:
816
- LaunchTraceSink with ``.entries`` (deduped launch records) and
817
- ``.buffers`` (all device buffers seen).
822
+ LaunchTraceSink with ``.entries`` (one launch record per call
823
+ site) and ``.buffers`` (all device buffers seen).
818
824
 
819
825
  Limitation: only triton launches via ``StaticallyLaunchedCudaKernel.run``
820
826
  are observed. Ops inductor delegates to a vendor library (cuDNN convs,
@@ -110,7 +110,7 @@ def annotate_cutlass_config(
110
110
 
111
111
  try:
112
112
  args = step.get("args", [])
113
- config, bench = tuner(args, buffers, arch)
113
+ config, bench = tuner(args, buffers, arch, kwargs=step.get("kwargs"))
114
114
  # ``cutlass_config`` always carries the best CUTLASS config
115
115
  # (a naive fallback when none is eligible). ``cutlass_bench``
116
116
  # records cuBLAS vs CUTLASS timings and ``winner``; the runner
@@ -17,10 +17,32 @@ CUTLASS convolution config tuner.
17
17
  Only tunes and returns the best config — no cubin export.
18
18
  """
19
19
 
20
+ import ast
21
+ from typing import Any
22
+
20
23
  from .config import CONV_CONFIGS, CutlassConfig
21
24
  from .mm import tune_mm
22
25
 
23
26
 
27
+ def _parse_kwargs(kwarg_strs: list[str] | None) -> dict[str, Any]:
28
+ """Parse ``["stride=(2, 2)", "bias=None"]`` kwarg strings into values."""
29
+ out: dict[str, Any] = {}
30
+ for kw in kwarg_strs or []:
31
+ key, _, value = kw.partition("=")
32
+ try:
33
+ out[key] = ast.literal_eval(value)
34
+ except (ValueError, SyntaxError):
35
+ out[key] = value
36
+ return out
37
+
38
+
39
+ def _norm2(v: int | list | tuple) -> list[int]:
40
+ """Normalize a scalar or pair to a 2-element int list."""
41
+ if isinstance(v, int):
42
+ return [v, v]
43
+ return [int(v[0]), int(v[1])]
44
+
45
+
24
46
  def _extract_conv_shapes(args: list[dict], buffers: dict) -> dict:
25
47
  """Extract convolution parameters from manifest args."""
26
48
  tensor_args = [a for a in args if a.get("kind") == "tensor"]
@@ -50,31 +72,38 @@ def _extract_conv_shapes(args: list[dict], buffers: dict) -> dict:
50
72
  }
51
73
 
52
74
 
53
- def _conv_to_gemm_args(args: list[dict], buffers: dict) -> list[dict]:
54
- """Convert convolution args to equivalent GEMM args for tuning.
75
+ def _conv_to_gemm_args(
76
+ args: list[dict], buffers: dict, kwargs: list[str] | None = None
77
+ ) -> list[dict]:
78
+ """Convert convolution args to the per-group im2col GEMM replay runs.
55
79
 
56
- ponytail: v1 uses im2col expansion — conv(M,N,K) maps to GEMM with
57
- M=N*H_out*W_out, N=K_out, K=C_in*R*S.
80
+ Replay (``run._run_conv``) launches one GEMM per (batch, group):
81
+ weight_g (K_g, Kk) @ col_g (Kk, L), so tune exactly that shape —
82
+ including groups, stride, padding and dilation from the step kwargs.
58
83
  """
59
84
  params = _extract_conv_shapes(args, buffers)
60
85
  input_shape = params["input_shape"]
61
86
  weight_shape = params["weight_shape"]
62
87
 
63
- N_batch = input_shape[0]
64
- C_in = input_shape[1]
88
+ kw = _parse_kwargs(kwargs)
89
+ stride = _norm2(kw.get("stride", 1))
90
+ padding = _norm2(kw.get("padding", 0))
91
+ dilation = _norm2(kw.get("dilation", 1))
92
+ groups = int(kw.get("groups", 1))
93
+
65
94
  K_out = weight_shape[0]
66
95
  R, S = weight_shape[2], weight_shape[3]
67
- # ponytail: assume stride=1, pad=0, dilation=1 for v1
68
- H_out = input_shape[2] - R + 1
69
- W_out = input_shape[3] - S + 1
96
+ H_in, W_in = input_shape[2], input_shape[3]
97
+ H_out = (H_in + 2 * padding[0] - dilation[0] * (R - 1) - 1) // stride[0] + 1
98
+ W_out = (W_in + 2 * padding[1] - dilation[1] * (S - 1) - 1) // stride[1] + 1
99
+ L = H_out * W_out
70
100
 
71
- M = N_batch * H_out * W_out
72
- K = C_in * R * S
73
- N = K_out
101
+ M = K_out // groups
102
+ K = weight_shape[1] * R * S
74
103
 
75
104
  return [
76
105
  {"kind": "tensor", "shape": [M, K], "dtype": args[0].get("dtype", "float16")},
77
- {"kind": "tensor", "shape": [K, N], "dtype": args[0].get("dtype", "float16")},
106
+ {"kind": "tensor", "shape": [K, L], "dtype": args[0].get("dtype", "float16")},
78
107
  ]
79
108
 
80
109
 
@@ -83,11 +112,12 @@ def tune_conv(
83
112
  buffers: dict,
84
113
  arch: str,
85
114
  configs: list[CutlassConfig] | None = None,
115
+ kwargs: list[str] | None = None,
86
116
  ) -> tuple[CutlassConfig | None, dict]:
87
117
  """Autotune convolution configs against the cuDNN/cuBLAS baseline.
88
118
 
89
- Delegates to tune_mm with im2col-expanded shapes; returns
119
+ Delegates to tune_mm with the per-group im2col-expanded shapes; returns
90
120
  ``(None, bench)`` when the vendor library is faster (the common case).
91
121
  """
92
- gemm_args = _conv_to_gemm_args(args, buffers)
122
+ gemm_args = _conv_to_gemm_args(args, buffers, kwargs)
93
123
  return tune_mm(gemm_args, buffers, arch, configs or CONV_CONFIGS)
@@ -753,6 +753,7 @@ def tune_mm(
753
753
  buffers: dict,
754
754
  arch: str,
755
755
  configs: list[CutlassConfig] | None = None,
756
+ kwargs: list[str] | None = None, # noqa: ARG001 — uniform tuner signature
756
757
  ) -> tuple[CutlassConfig, dict]:
757
758
  """Autotune GEMM configs against a cuBLAS baseline.
758
759
 
@@ -761,6 +762,8 @@ def tune_mm(
761
762
  buffers: buffer table from the manifest.
762
763
  arch: GPU arch string (e.g. "sm_120").
763
764
  configs: list of CutlassConfig to benchmark. Defaults to MM_CONFIGS.
765
+ kwargs: step kwargs strings; unused for plain GEMMs (shape comes
766
+ from the args). Accepted so all tuners share one signature.
764
767
 
765
768
  Returns:
766
769
  ``(config, bench)``. ``config`` is always the best CUTLASS config