|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import sys |
| 4 | +from pathlib import Path |
| 5 | +from typing import Union, Sequence, Dict |
| 6 | +from pprint import pprint |
| 7 | + |
| 8 | + |
| 9 | +# Enable automagically finding TPP-MLIR's python modules (which include |
| 10 | +# and extend MLIR's Python bindings). |
| 11 | +python_packages_path = Path(__file__).parent.parent / "python_packages" |
| 12 | +if python_packages_path.exists(): |
| 13 | + sys.path = [str(python_packages_path)] + sys.path |
| 14 | + |
| 15 | + |
| 16 | +from mlir import ir |
| 17 | +from mlir.dialects import transform |
| 18 | +from mlir.dialects.transform import tune as transform_tune |
| 19 | + |
| 20 | + |
| 21 | +def walker(f): |
| 22 | + def wrapper(op: Union[ir.OpView, ir.Operation]): |
| 23 | + f(op) |
| 24 | + for region in op.regions: |
| 25 | + for block in region.blocks: |
| 26 | + for child_op in block: |
| 27 | + wrapper(child_op) |
| 28 | + |
| 29 | + return wrapper |
| 30 | + |
| 31 | + |
| 32 | +def autotune(choices: Dict[str, Sequence[ir.Attribute]]) -> Dict[str, ir.Attribute]: |
| 33 | + # Aint tuning easy!! |
| 34 | + return {key: values[0] for key, values in choices.items()} |
| 35 | + |
| 36 | + |
| 37 | +file = sys.stdin |
| 38 | +if len(sys.argv) > 1 and sys.argv[1] != "-": |
| 39 | + file = open(sys.argv[1]) |
| 40 | + |
| 41 | + |
| 42 | +with ir.Context(), ir.Location.unknown(): |
| 43 | + schedule = ir.Module.parse(file.read()) |
| 44 | + |
| 45 | + choices = {} |
| 46 | + |
| 47 | + @walker |
| 48 | + def choices_finder(op): |
| 49 | + if isinstance(op, transform_tune.TuneSelectOp): |
| 50 | + choices[op.name] = tuple(op.options) |
| 51 | + |
| 52 | + choices_finder(schedule.operation) |
| 53 | + |
| 54 | + pprint(choices, stream=sys.stderr) |
| 55 | + |
| 56 | + selected = autotune(choices) |
| 57 | + |
| 58 | + @walker |
| 59 | + def selected_rewriter(op: Union[ir.OpView, ir.Operation]): |
| 60 | + if isinstance(op, transform_tune.TuneSelectOp): |
| 61 | + with ir.InsertionPoint(op): |
| 62 | + param = transform.param_constant( |
| 63 | + transform.AnyParamType.get(), selected[op.name] |
| 64 | + ) |
| 65 | + for use in op.result.uses: |
| 66 | + use.owner.operands[use.operand_number] = param |
| 67 | + |
| 68 | + selected_rewriter(schedule.operation) |
| 69 | + |
| 70 | + print(schedule) |
0 commit comments