Repository navigation
Expand file tree
/
Copy pathcustom.py
More file actions
211 lines (178 loc) · 7.53 KB
/
Copy pathcustom.py
File metadata and controls
211 lines (178 loc) · 7.53 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
# ===----------------------------------------------------------------------=== #
# Copyright (c) 2026, Modular Inc. All rights reserved.
#
# Licensed under the Apache License v2.0 with LLVM Exceptions:
# https://llvm.org/LICENSE.txt
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ===----------------------------------------------------------------------=== #
"""Operations for invoking user-defined operations."""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from typing import Any
from max import mlir
from max._core import graph as _graph
from max._core.dialects import builtin
from max._mlir_context import default_mlir_context
from max.dtype import DType
from max.mlir import BoolAttr, DictAttr, IndexType, IntegerAttr, StringAttr
from max.mlir.dialects import mo
from ...driver import Device
from ..graph import Graph
from ..type import DeviceRef, Type, _ChainType
from ..value import (
BufferValue,
TensorValue,
Value,
_is_strong_tensor_value_like,
_OpaqueValue,
)
from .rms_norm import _float32_attr
def _parameter_attribute(
param: bool | float | str | DType,
) -> mlir.Attribute:
"""Converts a Python type to an MLIR attribute to parametrize a kernel."""
context = default_mlir_context()
if isinstance(param, bool):
return BoolAttr.get(param, context)
if isinstance(param, int):
return IntegerAttr.get(IndexType.get(context), param)
if isinstance(param, float):
# Same rank-0 f32 encoding the RMS norm ops use: `max._core`'s
# bytecode writer does not recognize a `FloatAttr` (GEX-4052).
# `_float32_attr` returns a `max._core`-family attribute; re-own it
# as an `mlir.Attribute`, as `graph._add_op_get_op_with_results`
# does for every `_core` attribute it stages.
float32_attr = _float32_attr(param)
return mlir.Attribute._CAPICreate(float32_attr._CAPIPtr) # type: ignore
if isinstance(param, str):
return StringAttr.get(param, context)
if isinstance(param, DType):
# Wrap the MLIR type corresponding to dtype in a TypeAttr,
# which MOToKGENLowering expects.
dtype = _graph.dtype_to_type(param)
attr = builtin.TypeAttr(dtype)
return mlir.Attribute._CAPICreate(attr._CAPIPtr) # type: ignore
raise TypeError(f"unsupported parameter type {type(param)} for custom op")
def custom(
name: str,
device: Device | DeviceRef,
values: Sequence[Value[Any]],
out_types: Sequence[Type[Any]],
parameters: Mapping[str, bool | int | float | str | DType] | None = None,
) -> list[Value[Any]]:
"""Creates a node to execute a custom graph operation in the graph.
The custom op should be registered by annotating a function with the
[`@extensibility.register`](/api/mojo/extensibility/decorators/register/)
decorator.
Args:
name: The op name provided to ``@extensibility.register``.
values: The op function's arguments.
out_types: The list of op function's return type.
parameters: Dictionary of extra parameters expected by the kernel.
device: Device that the op is assigned to.
This becomes a `target` parameter to the kernel.
Returns:
Symbolic values representing the outputs of the op in the graph.
These correspond 1:1 with the types passed as ``out_types``.
"""
graph = Graph.current
context = default_mlir_context()
symbol_attr = StringAttr.get(name, context)
device = DeviceRef.from_device(device)
if any(isinstance(val, BufferValue | _OpaqueValue) for val in values):
raise TypeError(
"custom ops that take buffers or opaque values to do in-place "
"updates should use ops.inplace_custom instead"
)
values = [
TensorValue(v) if _is_strong_tensor_value_like(v) else v for v in values
]
results, custom_op = graph._add_op_get_op_with_results(
mo.custom, [t.to_mlir() for t in out_types], values, symbol=symbol_attr
)
if parameters is not None:
custom_op.parameters = DictAttr.get(
{
name: _parameter_attribute(param)
for name, param in parameters.items()
},
context,
)
custom_op.device = mlir.Attribute._CAPICreate( # type: ignore
device.to_mlir()._CAPIPtr
)
# Call the verifier, will throw if the call is invalid.
graph._kernel_library.verify_custom_op(custom_op)
return results
def inplace_custom(
name: str,
device: Device | DeviceRef,
values: Sequence[Value[Any]],
out_types: Sequence[Type[Any]] | None = None,
parameters: Mapping[str, bool | int | float | str | DType] | None = None,
) -> list[Value[Any]]:
"""Creates a node to execute an in-place custom graph operation in the graph.
The custom op should be registered by annotating a function with the
[`@extensibility.register`](/api/mojo/extensibility/decorators/register/)
decorator.
Args:
name: The op name provided to ``@extensibility.register``.
device: Device that the op is assigned to.
This becomes a `target` parameter to the kernel.
values: The op function's arguments.
out_types: Optional sequence of output types for the op.
parameters: Dictionary of extra parameters expected by the kernel.
"""
# Unfortunately there's no existing way to mark a particular NDBuffer input
# as needing to be backed by a `mo.buffer` value at the graph level.
#
# This will change as the new kernel API matures and has support added for
# marking particular inputs as mutable.
#
# Until that switch is made check that at least one input to the custom op
# is a BufferValue to provide some level of safety.
has_buffer_operand = any(isinstance(val, BufferValue) for val in values)
if not has_buffer_operand and not any(
isinstance(val, _OpaqueValue) for val in values
):
raise TypeError(
"expected at least one BufferValue or _OpaqueValue as input to an "
"in-place custom op"
)
# Pass empty out_types if unspecified.
out_mlir_types = [t.to_mlir() for t in out_types] if out_types else []
graph = Graph.current
values = [
TensorValue(v) if _is_strong_tensor_value_like(v) else v for v in values
]
device = DeviceRef.from_device(device)
chain_operand = graph.device_chains[device]
context = default_mlir_context()
symbol_attr = StringAttr.get(name, context)
(*results, out_chain), custom_op = graph._add_op_get_op_with_results(
mo.custom,
results_=[*out_mlir_types, _ChainType().to_mlir()],
operands_=[*values, chain_operand],
symbol=symbol_attr,
)
graph.device_chains[device] = out_chain
if parameters is not None:
custom_op.parameters = DictAttr.get(
{
name: _parameter_attribute(param)
for name, param in parameters.items()
},
context,
)
custom_op.device = mlir.Attribute._CAPICreate( # type: ignore
device.to_mlir()._CAPIPtr
)
# Call the verifier, will throw if the call is invalid.
graph._kernel_library.verify_custom_op(custom_op)
return results
# TODO(GEX-2471): Cleanup the API for mo.custom with non-default chains.