Skip to content

Linalg

linalg

Linalg = Dialect('linalg', [GenericOp, YieldOp, IndexOp, AddOp, ExpOp, LogOp, SubOp, SqrtOp, SelectOp, FillOp, CopyOp, MaxOp, MinOp, MulOp, TransposeOp, MatmulOp, QuantizedMatmulOp, PoolingNchwMaxOp, Conv2DNchwFchwOp, Conv2DNhwgcGfhwcOp, Conv2DNhwc_HwcfOp, Conv2DNgchwGfchwOp, Conv2DNgchwFgchwOp, Conv2DNhwc_FhwcOp, BroadcastOp, ReduceOp], [IteratorTypeAttr]) module-attribute

IteratorType

Bases: StrEnum

Iterator type for linalg trait

Source code in xdsl/dialects/linalg.py
66
67
68
69
70
71
class IteratorType(StrEnum):
    "Iterator type for linalg trait"

    PARALLEL = auto()
    REDUCTION = auto()
    WINDOW = auto()

PARALLEL = auto() class-attribute instance-attribute

REDUCTION = auto() class-attribute instance-attribute

WINDOW = auto() class-attribute instance-attribute

IteratorTypeAttr dataclass

Bases: EnumAttribute[IteratorType]

Source code in xdsl/dialects/linalg.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
@irdl_attr_definition
class IteratorTypeAttr(EnumAttribute[IteratorType]):
    name = "linalg.iterator_type"

    @classmethod
    def parallel(cls) -> IteratorTypeAttr:
        return IteratorTypeAttr(IteratorType.PARALLEL)

    @classmethod
    def reduction(cls) -> IteratorTypeAttr:
        return IteratorTypeAttr(IteratorType.REDUCTION)

    @classmethod
    def window(cls) -> IteratorTypeAttr:
        return IteratorTypeAttr(IteratorType.WINDOW)

    @classmethod
    def parse_parameter(cls, parser: AttrParser) -> IteratorType:
        with parser.in_angle_brackets():
            return super().parse_parameter(parser)

    def print_parameter(self, printer: Printer) -> None:
        with printer.in_angle_brackets():
            super().print_parameter(printer)

name = 'linalg.iterator_type' class-attribute instance-attribute

parallel() -> IteratorTypeAttr classmethod

Source code in xdsl/dialects/linalg.py
78
79
80
@classmethod
def parallel(cls) -> IteratorTypeAttr:
    return IteratorTypeAttr(IteratorType.PARALLEL)

reduction() -> IteratorTypeAttr classmethod

Source code in xdsl/dialects/linalg.py
82
83
84
@classmethod
def reduction(cls) -> IteratorTypeAttr:
    return IteratorTypeAttr(IteratorType.REDUCTION)

window() -> IteratorTypeAttr classmethod

Source code in xdsl/dialects/linalg.py
86
87
88
@classmethod
def window(cls) -> IteratorTypeAttr:
    return IteratorTypeAttr(IteratorType.WINDOW)

parse_parameter(parser: AttrParser) -> IteratorType classmethod

Source code in xdsl/dialects/linalg.py
90
91
92
93
@classmethod
def parse_parameter(cls, parser: AttrParser) -> IteratorType:
    with parser.in_angle_brackets():
        return super().parse_parameter(parser)

print_parameter(printer: Printer) -> None

Source code in xdsl/dialects/linalg.py
95
96
97
def print_parameter(self, printer: Printer) -> None:
    with printer.in_angle_brackets():
        super().print_parameter(printer)

LinalgStructuredOperation dataclass

Bases: IRDLOperation, ABC

Abstract base class for structured linalg operations, allowing them to be processed via a unified interface.

Source code in xdsl/dialects/linalg.py
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
class LinalgStructuredOperation(IRDLOperation, ABC):
    """
    Abstract base class for structured linalg operations, allowing them to be processed
    via a unified interface.
    """

    inputs = var_operand_def()
    """
    The operands that won't be mutated.
    """
    outputs = var_operand_def(ShapedType)
    """
    The operands that will be accumulated into.
    These inputs may be `memref`s, which will be mutated in-place, or `tensor`s, which will be returned as results.
    """

    res = var_result_def(TensorType)
    """
    The updated `outputs`, empty if the inputs are memrefs.
    """

    body = region_def("single_block")
    """
    The body implementing the combination of scalar elements of the inputs, and
    yielding the scalar elements of the outputs.
    """

    @abstractmethod
    def get_indexing_maps(self) -> ArrayAttr[AffineMapAttr]:
        """
        Get the indexing maps corresponding to this operation's operands, in order.
        """

    @abstractmethod
    def get_iterator_types(self) -> ArrayAttr[IteratorTypeAttr]:
        """
        Get the iterator types corresponding to this operation's loop, in order.
        """

    def get_num_loops(self) -> int:
        return self.get_indexing_maps().data[0].data.num_dims

    def get_loops_to_shapes_map(self) -> AffineMap:
        """
        Returns a map to answer the question: "given an iteration space over
        the codomain, what are the subshapes of the operands involved in the
        computation".
        The default behavior is to just concatenate all the indexing maps.
        """
        indexing_maps = tuple(attr.data for attr in self.get_indexing_maps())
        result_exprs = tuple(res for map in indexing_maps for res in map.results)

        dims = self.get_num_loops()

        # FIXME: Support symbols.
        for map in indexing_maps:
            if map.num_symbols != 0:
                raise NotImplementedError(
                    "Indexing maps with symbols not supported for now."
                )

        syms = 0
        return AffineMap(dims, syms, result_exprs)

    def get_shapes_to_loops_map(self) -> AffineMap:
        """
        Returns a map to answer the question: "Given a list of operand ranges,
        what is the subportion of the iteration space involved in the
        computation". This is the inverse problem of `get_loops_to_shapes_map`.
        Return the empty AffineMap when such an AffineMap cannot be
        constructed. The default behavior is based on a very simple inference
        procedure that only works with permutation affine maps. A more advanced
        Tensor-Comprehension like inference is possible but has proven to be
        ambiguous in unfavorable case. A safer and more robust alternative is
        to allow each op to define its own AffineMap.
        """
        loops_to_shapes = self.get_loops_to_shapes_map()
        inverse = loops_to_shapes.inverse_permutation()
        if not inverse:
            raise NotImplementedError(
                "Non-invertible maps need dynamic shapes, which are not implemented."
            )
        return inverse

    def get_static_shapes(self) -> list[int]:
        return [
            dim
            for operand in self.operands
            if isinstance(operand.type, ShapedType)
            for dim in operand.type.get_shape()
        ]

    def get_static_loop_ranges(self) -> tuple[int, ...]:
        shapes_to_loops = self.get_shapes_to_loops_map()
        static_shapes = self.get_static_shapes()
        return shapes_to_loops.eval(static_shapes, [])

inputs = var_operand_def() class-attribute instance-attribute

The operands that won't be mutated.

outputs = var_operand_def(ShapedType) class-attribute instance-attribute

The operands that will be accumulated into. These inputs may be memrefs, which will be mutated in-place, or tensors, which will be returned as results.

res = var_result_def(TensorType) class-attribute instance-attribute

The updated outputs, empty if the inputs are memrefs.

body = region_def('single_block') class-attribute instance-attribute

The body implementing the combination of scalar elements of the inputs, and yielding the scalar elements of the outputs.

get_indexing_maps() -> ArrayAttr[AffineMapAttr] abstractmethod

Get the indexing maps corresponding to this operation's operands, in order.

Source code in xdsl/dialects/linalg.py
127
128
129
130
131
@abstractmethod
def get_indexing_maps(self) -> ArrayAttr[AffineMapAttr]:
    """
    Get the indexing maps corresponding to this operation's operands, in order.
    """

get_iterator_types() -> ArrayAttr[IteratorTypeAttr] abstractmethod

Get the iterator types corresponding to this operation's loop, in order.

Source code in xdsl/dialects/linalg.py
133
134
135
136
137
@abstractmethod
def get_iterator_types(self) -> ArrayAttr[IteratorTypeAttr]:
    """
    Get the iterator types corresponding to this operation's loop, in order.
    """

get_num_loops() -> int

Source code in xdsl/dialects/linalg.py
139
140
def get_num_loops(self) -> int:
    return self.get_indexing_maps().data[0].data.num_dims

get_loops_to_shapes_map() -> AffineMap

Returns a map to answer the question: "given an iteration space over the codomain, what are the subshapes of the operands involved in the computation". The default behavior is to just concatenate all the indexing maps.

Source code in xdsl/dialects/linalg.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def get_loops_to_shapes_map(self) -> AffineMap:
    """
    Returns a map to answer the question: "given an iteration space over
    the codomain, what are the subshapes of the operands involved in the
    computation".
    The default behavior is to just concatenate all the indexing maps.
    """
    indexing_maps = tuple(attr.data for attr in self.get_indexing_maps())
    result_exprs = tuple(res for map in indexing_maps for res in map.results)

    dims = self.get_num_loops()

    # FIXME: Support symbols.
    for map in indexing_maps:
        if map.num_symbols != 0:
            raise NotImplementedError(
                "Indexing maps with symbols not supported for now."
            )

    syms = 0
    return AffineMap(dims, syms, result_exprs)

get_shapes_to_loops_map() -> AffineMap

Returns a map to answer the question: "Given a list of operand ranges, what is the subportion of the iteration space involved in the computation". This is the inverse problem of get_loops_to_shapes_map. Return the empty AffineMap when such an AffineMap cannot be constructed. The default behavior is based on a very simple inference procedure that only works with permutation affine maps. A more advanced Tensor-Comprehension like inference is possible but has proven to be ambiguous in unfavorable case. A safer and more robust alternative is to allow each op to define its own AffineMap.

Source code in xdsl/dialects/linalg.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def get_shapes_to_loops_map(self) -> AffineMap:
    """
    Returns a map to answer the question: "Given a list of operand ranges,
    what is the subportion of the iteration space involved in the
    computation". This is the inverse problem of `get_loops_to_shapes_map`.
    Return the empty AffineMap when such an AffineMap cannot be
    constructed. The default behavior is based on a very simple inference
    procedure that only works with permutation affine maps. A more advanced
    Tensor-Comprehension like inference is possible but has proven to be
    ambiguous in unfavorable case. A safer and more robust alternative is
    to allow each op to define its own AffineMap.
    """
    loops_to_shapes = self.get_loops_to_shapes_map()
    inverse = loops_to_shapes.inverse_permutation()
    if not inverse:
        raise NotImplementedError(
            "Non-invertible maps need dynamic shapes, which are not implemented."
        )
    return inverse

get_static_shapes() -> list[int]

Source code in xdsl/dialects/linalg.py
184
185
186
187
188
189
190
def get_static_shapes(self) -> list[int]:
    return [
        dim
        for operand in self.operands
        if isinstance(operand.type, ShapedType)
        for dim in operand.type.get_shape()
    ]

get_static_loop_ranges() -> tuple[int, ...]

Source code in xdsl/dialects/linalg.py
192
193
194
195
def get_static_loop_ranges(self) -> tuple[int, ...]:
    shapes_to_loops = self.get_shapes_to_loops_map()
    static_shapes = self.get_static_shapes()
    return shapes_to_loops.eval(static_shapes, [])

GenericOp

Bases: LinalgStructuredOperation

Source code in xdsl/dialects/linalg.py
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
@irdl_op_definition
class GenericOp(LinalgStructuredOperation):
    name = "linalg.generic"

    # Trait attributes
    indexing_maps = prop_def(ArrayAttr[AffineMapAttr])
    iterator_types = prop_def(ArrayAttr[IteratorTypeAttr])
    doc = opt_prop_def(StringAttr)
    library_call = opt_prop_def(StringAttr)

    irdl_options = (AttrSizedOperandSegments(as_property=True),)

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue],
        body: Region,
        indexing_maps: Sequence[AffineMapAttr] | ArrayAttr[AffineMapAttr],
        iterator_types: Sequence[Attribute] | ArrayAttr[Attribute],
        result_types: Sequence[Attribute] = (),
        doc: StringAttr | None = None,
        library_call: StringAttr | None = None,
    ) -> None:
        super().__init__(
            operands=[inputs, outputs],
            result_types=[result_types],
            properties={
                "indexing_maps": ArrayAttr(indexing_maps),
                "iterator_types": ArrayAttr(iterator_types),
                "doc": doc,
                "library_call": library_call,
            },
            regions=[body],
        )

    def get_indexing_maps(self) -> ArrayAttr[AffineMapAttr]:
        return self.indexing_maps

    def get_iterator_types(self) -> ArrayAttr[IteratorTypeAttr]:
        return self.iterator_types

    def print(self, printer: Printer):
        printer.print_string(" {indexing_maps = ")
        printer.print_attribute(self.indexing_maps)
        printer.print_string(", iterator_types = [")
        printer.print_list(
            self.iterator_types,
            lambda iterator_type: printer.print_string_literal(iterator_type.data),
        )
        printer.print_string("]")
        if self.doc:
            printer.print_string(", doc = ")
            printer.print_attribute(self.doc)
        if self.library_call:
            printer.print_string(", library_call = ")
            printer.print_attribute(self.library_call)
        printer.print_string("}")

        if self.inputs:
            printer.print_string(" ins(")
            printer.print_list(self.inputs, printer.print_ssa_value)
            printer.print_string(" : ")
            printer.print_list(self.inputs.types, printer.print_attribute)
            printer.print_string(")")

        if self.outputs:
            printer.print_string(" outs(")
            printer.print_list(self.outputs, printer.print_ssa_value)
            printer.print_string(" : ")
            printer.print_list(self.outputs.types, printer.print_attribute)
            printer.print_string(")")

        extra_attrs = self.attributes.copy()
        if "indexing_maps" in extra_attrs:
            del extra_attrs["indexing_maps"]
        if "iterator_types" in extra_attrs:
            del extra_attrs["iterator_types"]
        if "doc" in extra_attrs:
            del extra_attrs["doc"]
        if "library_call" in extra_attrs:
            del extra_attrs["library_call"]

        if extra_attrs:
            printer.print_string(" attrs = ")
            printer.print_op_attributes(extra_attrs)

        printer.print_string(" ")
        printer.print_region(self.body)

        if self.res:
            printer.print_string(" -> ")
            if len(self.res) == 1:
                printer.print_attribute(self.res[0].type)
            else:
                with printer.in_parens():
                    printer.print_list(
                        self.res, lambda res: printer.print_attribute(res.type)
                    )

    @classmethod
    def parse(cls, parser: Parser) -> Self:
        attrs_start_pos = parser.pos
        attrs = parser.parse_optional_attr_dict()
        attrs_end_pos = parser.pos

        if "indexing_maps" in attrs:
            indexing_maps = attrs["indexing_maps"]
            assert isinstance(indexing_maps, ArrayAttr)
            indexing_maps = cast(ArrayAttr[AffineMapAttr], indexing_maps)
            del attrs["indexing_maps"]
        else:
            parser.raise_error(
                "Expected indexing_maps for linalg.generic",
                attrs_start_pos,
                attrs_end_pos,
            )

        if "iterator_types" in attrs:
            # Get iterator types and make sure they're an ArrayAttr
            parsed_iterator_types = attrs["iterator_types"]
            assert isinstance(parsed_iterator_types, ArrayAttr)
            parsed_iterator_types = cast(ArrayAttr[Attribute], parsed_iterator_types)
            del attrs["iterator_types"]

            # Make sure they're iterator types
            iterator_types: list[IteratorTypeAttr] = []
            for iterator_type in parsed_iterator_types:
                match iterator_type:
                    case IteratorTypeAttr():
                        iterator_types.append(iterator_type)
                    case StringAttr():
                        iterator_type = IteratorTypeAttr(
                            IteratorType(iterator_type.data)
                        )
                        iterator_types.append(iterator_type)
                    case _:
                        parser.raise_error(
                            f"Unknown iterator type {iterator_type}",
                            attrs_start_pos,
                            attrs_end_pos,
                        )
        else:
            parser.raise_error(
                "Expected iterator_types for linalg.generic",
                attrs_start_pos,
                attrs_end_pos,
            )

        if "doc" in attrs:
            doc = attrs["doc"]
            assert isinstance(doc, StringAttr)
            del attrs["doc"]
        else:
            doc = None

        if "library_call" in attrs:
            library_call = attrs["library_call"]
            assert isinstance(library_call, StringAttr)
            del attrs["library_call"]
        else:
            library_call = None

        pos = parser.pos
        if parser.parse_optional_characters("ins"):
            parser.parse_punctuation("(")
            unresolved_ins = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_unresolved_operand
            )
            parser.parse_punctuation(":")
            ins_types = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_type
            )
            parser.parse_punctuation(")")
            ins = parser.resolve_operands(unresolved_ins, ins_types, pos)
        else:
            ins = ()

        pos = parser.pos
        if parser.parse_optional_characters("outs"):
            parser.parse_punctuation("(")
            unresolved_outs = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_unresolved_operand
            )
            parser.parse_punctuation(":")
            outs_types = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_type
            )
            parser.parse_punctuation(")")
            outs = parser.resolve_operands(unresolved_outs, outs_types, pos)
        else:
            outs = ()

        if parser.parse_optional_keyword("attrs"):
            parser.parse_punctuation("=")
            extra_attrs = parser.expect(
                parser.parse_optional_attr_dict, "expect extra attributes"
            )
        else:
            extra_attrs = {}

        body = parser.parse_region()

        if parser.parse_optional_punctuation("->"):
            res_types = parser.parse_comma_separated_list(
                parser.Delimiter.NONE, parser.parse_attribute
            )
        else:
            res_types = ()

        generic = cls(
            ins,
            outs,
            body,
            indexing_maps,
            iterator_types,
            res_types,
            doc,
            library_call,
        )
        generic.attributes |= extra_attrs

        return generic

name = 'linalg.generic' class-attribute instance-attribute

indexing_maps = prop_def(ArrayAttr[AffineMapAttr]) class-attribute instance-attribute

iterator_types = prop_def(ArrayAttr[IteratorTypeAttr]) class-attribute instance-attribute

doc = opt_prop_def(StringAttr) class-attribute instance-attribute

library_call = opt_prop_def(StringAttr) class-attribute instance-attribute

irdl_options = (AttrSizedOperandSegments(as_property=True),) class-attribute instance-attribute

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue], body: Region, indexing_maps: Sequence[AffineMapAttr] | ArrayAttr[AffineMapAttr], iterator_types: Sequence[Attribute] | ArrayAttr[Attribute], result_types: Sequence[Attribute] = (), doc: StringAttr | None = None, library_call: StringAttr | None = None) -> None

Source code in xdsl/dialects/linalg.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue],
    body: Region,
    indexing_maps: Sequence[AffineMapAttr] | ArrayAttr[AffineMapAttr],
    iterator_types: Sequence[Attribute] | ArrayAttr[Attribute],
    result_types: Sequence[Attribute] = (),
    doc: StringAttr | None = None,
    library_call: StringAttr | None = None,
) -> None:
    super().__init__(
        operands=[inputs, outputs],
        result_types=[result_types],
        properties={
            "indexing_maps": ArrayAttr(indexing_maps),
            "iterator_types": ArrayAttr(iterator_types),
            "doc": doc,
            "library_call": library_call,
        },
        regions=[body],
    )

get_indexing_maps() -> ArrayAttr[AffineMapAttr]

Source code in xdsl/dialects/linalg.py
233
234
def get_indexing_maps(self) -> ArrayAttr[AffineMapAttr]:
    return self.indexing_maps

get_iterator_types() -> ArrayAttr[IteratorTypeAttr]

Source code in xdsl/dialects/linalg.py
236
237
def get_iterator_types(self) -> ArrayAttr[IteratorTypeAttr]:
    return self.iterator_types

print(printer: Printer)

Source code in xdsl/dialects/linalg.py
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
def print(self, printer: Printer):
    printer.print_string(" {indexing_maps = ")
    printer.print_attribute(self.indexing_maps)
    printer.print_string(", iterator_types = [")
    printer.print_list(
        self.iterator_types,
        lambda iterator_type: printer.print_string_literal(iterator_type.data),
    )
    printer.print_string("]")
    if self.doc:
        printer.print_string(", doc = ")
        printer.print_attribute(self.doc)
    if self.library_call:
        printer.print_string(", library_call = ")
        printer.print_attribute(self.library_call)
    printer.print_string("}")

    if self.inputs:
        printer.print_string(" ins(")
        printer.print_list(self.inputs, printer.print_ssa_value)
        printer.print_string(" : ")
        printer.print_list(self.inputs.types, printer.print_attribute)
        printer.print_string(")")

    if self.outputs:
        printer.print_string(" outs(")
        printer.print_list(self.outputs, printer.print_ssa_value)
        printer.print_string(" : ")
        printer.print_list(self.outputs.types, printer.print_attribute)
        printer.print_string(")")

    extra_attrs = self.attributes.copy()
    if "indexing_maps" in extra_attrs:
        del extra_attrs["indexing_maps"]
    if "iterator_types" in extra_attrs:
        del extra_attrs["iterator_types"]
    if "doc" in extra_attrs:
        del extra_attrs["doc"]
    if "library_call" in extra_attrs:
        del extra_attrs["library_call"]

    if extra_attrs:
        printer.print_string(" attrs = ")
        printer.print_op_attributes(extra_attrs)

    printer.print_string(" ")
    printer.print_region(self.body)

    if self.res:
        printer.print_string(" -> ")
        if len(self.res) == 1:
            printer.print_attribute(self.res[0].type)
        else:
            with printer.in_parens():
                printer.print_list(
                    self.res, lambda res: printer.print_attribute(res.type)
                )

parse(parser: Parser) -> Self classmethod

Source code in xdsl/dialects/linalg.py
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
@classmethod
def parse(cls, parser: Parser) -> Self:
    attrs_start_pos = parser.pos
    attrs = parser.parse_optional_attr_dict()
    attrs_end_pos = parser.pos

    if "indexing_maps" in attrs:
        indexing_maps = attrs["indexing_maps"]
        assert isinstance(indexing_maps, ArrayAttr)
        indexing_maps = cast(ArrayAttr[AffineMapAttr], indexing_maps)
        del attrs["indexing_maps"]
    else:
        parser.raise_error(
            "Expected indexing_maps for linalg.generic",
            attrs_start_pos,
            attrs_end_pos,
        )

    if "iterator_types" in attrs:
        # Get iterator types and make sure they're an ArrayAttr
        parsed_iterator_types = attrs["iterator_types"]
        assert isinstance(parsed_iterator_types, ArrayAttr)
        parsed_iterator_types = cast(ArrayAttr[Attribute], parsed_iterator_types)
        del attrs["iterator_types"]

        # Make sure they're iterator types
        iterator_types: list[IteratorTypeAttr] = []
        for iterator_type in parsed_iterator_types:
            match iterator_type:
                case IteratorTypeAttr():
                    iterator_types.append(iterator_type)
                case StringAttr():
                    iterator_type = IteratorTypeAttr(
                        IteratorType(iterator_type.data)
                    )
                    iterator_types.append(iterator_type)
                case _:
                    parser.raise_error(
                        f"Unknown iterator type {iterator_type}",
                        attrs_start_pos,
                        attrs_end_pos,
                    )
    else:
        parser.raise_error(
            "Expected iterator_types for linalg.generic",
            attrs_start_pos,
            attrs_end_pos,
        )

    if "doc" in attrs:
        doc = attrs["doc"]
        assert isinstance(doc, StringAttr)
        del attrs["doc"]
    else:
        doc = None

    if "library_call" in attrs:
        library_call = attrs["library_call"]
        assert isinstance(library_call, StringAttr)
        del attrs["library_call"]
    else:
        library_call = None

    pos = parser.pos
    if parser.parse_optional_characters("ins"):
        parser.parse_punctuation("(")
        unresolved_ins = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_unresolved_operand
        )
        parser.parse_punctuation(":")
        ins_types = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_type
        )
        parser.parse_punctuation(")")
        ins = parser.resolve_operands(unresolved_ins, ins_types, pos)
    else:
        ins = ()

    pos = parser.pos
    if parser.parse_optional_characters("outs"):
        parser.parse_punctuation("(")
        unresolved_outs = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_unresolved_operand
        )
        parser.parse_punctuation(":")
        outs_types = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_type
        )
        parser.parse_punctuation(")")
        outs = parser.resolve_operands(unresolved_outs, outs_types, pos)
    else:
        outs = ()

    if parser.parse_optional_keyword("attrs"):
        parser.parse_punctuation("=")
        extra_attrs = parser.expect(
            parser.parse_optional_attr_dict, "expect extra attributes"
        )
    else:
        extra_attrs = {}

    body = parser.parse_region()

    if parser.parse_optional_punctuation("->"):
        res_types = parser.parse_comma_separated_list(
            parser.Delimiter.NONE, parser.parse_attribute
        )
    else:
        res_types = ()

    generic = cls(
        ins,
        outs,
        body,
        indexing_maps,
        iterator_types,
        res_types,
        doc,
        library_call,
    )
    generic.attributes |= extra_attrs

    return generic

YieldOp dataclass

Bases: AbstractYieldOperation[Attribute]

Source code in xdsl/dialects/linalg.py
422
423
424
425
426
@irdl_op_definition
class YieldOp(AbstractYieldOperation[Attribute]):
    name = "linalg.yield"

    traits = traits_def(IsTerminator())

name = 'linalg.yield' class-attribute instance-attribute

traits = traits_def(IsTerminator()) class-attribute instance-attribute

IndexOp

Bases: IRDLOperation

Source code in xdsl/dialects/linalg.py
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
@irdl_op_definition
class IndexOp(IRDLOperation):
    name = "linalg.index"

    dim = prop_def(IntegerAttr[i64])

    result = result_def(IndexTypeConstr)

    traits = traits_def(HasParent(GenericOp))

    assembly_format = "$dim attr-dict `:` type($result)"

    def __init__(
        self,
        dim: int,
    ):
        dim_attr = IntegerAttr(dim, i64)
        super().__init__(properties={"dim": dim_attr}, result_types=[IndexType()])

name = 'linalg.index' class-attribute instance-attribute

dim = prop_def(IntegerAttr[i64]) class-attribute instance-attribute

result = result_def(IndexTypeConstr) class-attribute instance-attribute

traits = traits_def(HasParent(GenericOp)) class-attribute instance-attribute

assembly_format = '$dim attr-dict `:` type($result)' class-attribute instance-attribute

__init__(dim: int)

Source code in xdsl/dialects/linalg.py
441
442
443
444
445
446
def __init__(
    self,
    dim: int,
):
    dim_attr = IntegerAttr(dim, i64)
    super().__init__(properties={"dim": dim_attr}, result_types=[IndexType()])

NamedOperation

Bases: LinalgStructuredOperation, ABC

Abstract base class for named ops with hidden region.

Source code in xdsl/dialects/linalg.py
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
class NamedOperation(LinalgStructuredOperation, ABC):
    """
    Abstract base class for named ops with hidden region.
    """

    irdl_options = (
        AttrSizedOperandSegments(as_property=True),
        ParsePropInAttrDict(),
    )

    PRINT_ATTRS_IN_FRONT: ClassVar[bool] = False

    def __init__(
        self,
        ins: Sequence[SSAValue],
        outs: Sequence[SSAValue],
        result_types: Sequence[Attribute | Sequence[Attribute] | None] | None = None,
        properties: Mapping[str, Attribute | None] | None = None,
        attributes: Mapping[str, Attribute | None] | None = None,
        hidden_region: Region | None = None,
    ):
        super().__init__(
            operands=[ins, outs],
            result_types=(
                result_types
                if result_types is not None and len(result_types) > 0
                else [[]]
            ),
            properties=properties,
            attributes=attributes,
            regions=[hidden_region],
        )

    @classmethod
    def parse(cls, parser: Parser):
        pos = parser.pos
        if cls.PRINT_ATTRS_IN_FRONT:
            attrs = parser.parse_optional_attr_dict()
        else:
            attrs = {}
        if parser.parse_optional_characters("ins"):
            parser.parse_punctuation("(")
            unresolved_ins = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_unresolved_operand
            )
            parser.parse_punctuation(":")
            ins_types = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_type
            )
            parser.parse_punctuation(")")
            ins = parser.resolve_operands(unresolved_ins, ins_types, pos)
        else:
            ins = ()

        pos = parser.pos
        if parser.parse_optional_characters("outs"):
            parser.parse_punctuation("(")
            unresolved_outs = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_unresolved_operand
            )
            parser.parse_punctuation(":")
            outs_types = parser.parse_comma_separated_list(
                Parser.Delimiter.NONE, parser.parse_type
            )
            parser.parse_punctuation(")")
            outs = parser.resolve_operands(unresolved_outs, outs_types, pos)
        else:
            outs = ()

        if not cls.PRINT_ATTRS_IN_FRONT:
            if parser.parse_optional_keyword("attrs"):
                parser.parse_punctuation("=")
                attrs = parser.expect(
                    parser.parse_optional_attr_dict, "expect extra attributes"
                )
            else:
                attrs = {}

        if parser.parse_optional_punctuation("->"):
            res_types = parser.parse_optional_comma_separated_list(
                parser.Delimiter.PAREN, parser.parse_attribute
            )
            if res_types is None:
                res_types = [parser.parse_attribute()]
        else:
            res_types = ()

        prop_names = cls.get_irdl_definition().properties

        properties = {k: v for k, v in attrs.items() if k in prop_names}
        # Drop the values in properties from attrs
        for k in properties:
            if k in attrs:
                del attrs[k]

        try:
            return cls.build(
                operands=(ins, outs),
                result_types=(res_types,),
                properties=properties,
                attributes=attrs,
                regions=(cls.get_hidden_region(ins, outs),),
            )
        except ValueError:
            parser.raise_error("Could not build linalg op")

    def print(self, printer: Printer):
        extra_attrs = {**self.attributes, **self.properties}
        if "indexing_maps" in extra_attrs:
            del extra_attrs["indexing_maps"]
        if "linalg.memoized_indexing_maps" in extra_attrs:
            del extra_attrs["linalg.memoized_indexing_maps"]
        if "iterator_types" in extra_attrs:
            del extra_attrs["iterator_types"]
        if "doc" in extra_attrs:
            del extra_attrs["doc"]
        if "library_call" in extra_attrs:
            del extra_attrs["library_call"]
        if "operandSegmentSizes" in extra_attrs:
            del extra_attrs["operandSegmentSizes"]

        if extra_attrs and self.PRINT_ATTRS_IN_FRONT:
            printer.print_op_attributes(extra_attrs)
        if self.inputs:
            printer.print_string(" ins(")
            printer.print_list(self.inputs, printer.print_ssa_value)
            printer.print_string(" : ")
            printer.print_list(self.inputs.types, printer.print_attribute)
            printer.print_string(")")

        if self.outputs:
            printer.print_string(" outs(")
            printer.print_list(self.outputs, printer.print_ssa_value)
            printer.print_string(" : ")
            printer.print_list(self.outputs.types, printer.print_attribute)
            printer.print_string(")")

        if extra_attrs and not self.PRINT_ATTRS_IN_FRONT:
            printer.print_string(" attrs = ")
            printer.print_op_attributes(extra_attrs)

        if self.res:
            printer.print_string(" -> ")
            if len(self.res) == 1:
                printer.print_attribute(self.res[0].type)
            else:
                with printer.in_parens():
                    printer.print_list(
                        self.res, lambda res: printer.print_attribute(res.type)
                    )

    @staticmethod
    def body_arg_types(
        operands: Sequence[SSAValue],
    ) -> Sequence[AnyFloat | IntegerType]:
        """
        Return the element types of the arguments of the body of this operation
        """

        result: Sequence[AnyFloat | IntegerType] = []

        for op in operands:
            op_type = op.type
            if isa(op_type, MemRefType | TensorType):
                element_type = op_type.get_element_type()
            else:  # int or float
                element_type = op_type
            assert isa(element_type, AnyFloat | IntegerType)
            result.append(element_type)

        return result

    @classmethod
    @abstractmethod
    def get_hidden_region(
        cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
    ) -> Region:
        """
        The hidden region for this linalg NamedOperation.
        """
        raise NotImplementedError

    @abstractmethod
    def get_default_indexing_maps(self) -> Sequence[AffineMap]:
        """
        Get the default indexing maps corresponding to this operation's operands, in order.
        """

    def get_indexing_maps(self) -> ArrayAttr[AffineMapAttr]:
        return ArrayAttr(
            AffineMapAttr(map_) for map_ in self.get_default_indexing_maps()
        )

irdl_options = (AttrSizedOperandSegments(as_property=True), ParsePropInAttrDict()) class-attribute instance-attribute

PRINT_ATTRS_IN_FRONT: bool = False class-attribute

__init__(ins: Sequence[SSAValue], outs: Sequence[SSAValue], result_types: Sequence[Attribute | Sequence[Attribute] | None] | None = None, properties: Mapping[str, Attribute | None] | None = None, attributes: Mapping[str, Attribute | None] | None = None, hidden_region: Region | None = None)

Source code in xdsl/dialects/linalg.py
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
def __init__(
    self,
    ins: Sequence[SSAValue],
    outs: Sequence[SSAValue],
    result_types: Sequence[Attribute | Sequence[Attribute] | None] | None = None,
    properties: Mapping[str, Attribute | None] | None = None,
    attributes: Mapping[str, Attribute | None] | None = None,
    hidden_region: Region | None = None,
):
    super().__init__(
        operands=[ins, outs],
        result_types=(
            result_types
            if result_types is not None and len(result_types) > 0
            else [[]]
        ),
        properties=properties,
        attributes=attributes,
        regions=[hidden_region],
    )

parse(parser: Parser) classmethod

Source code in xdsl/dialects/linalg.py
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
@classmethod
def parse(cls, parser: Parser):
    pos = parser.pos
    if cls.PRINT_ATTRS_IN_FRONT:
        attrs = parser.parse_optional_attr_dict()
    else:
        attrs = {}
    if parser.parse_optional_characters("ins"):
        parser.parse_punctuation("(")
        unresolved_ins = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_unresolved_operand
        )
        parser.parse_punctuation(":")
        ins_types = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_type
        )
        parser.parse_punctuation(")")
        ins = parser.resolve_operands(unresolved_ins, ins_types, pos)
    else:
        ins = ()

    pos = parser.pos
    if parser.parse_optional_characters("outs"):
        parser.parse_punctuation("(")
        unresolved_outs = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_unresolved_operand
        )
        parser.parse_punctuation(":")
        outs_types = parser.parse_comma_separated_list(
            Parser.Delimiter.NONE, parser.parse_type
        )
        parser.parse_punctuation(")")
        outs = parser.resolve_operands(unresolved_outs, outs_types, pos)
    else:
        outs = ()

    if not cls.PRINT_ATTRS_IN_FRONT:
        if parser.parse_optional_keyword("attrs"):
            parser.parse_punctuation("=")
            attrs = parser.expect(
                parser.parse_optional_attr_dict, "expect extra attributes"
            )
        else:
            attrs = {}

    if parser.parse_optional_punctuation("->"):
        res_types = parser.parse_optional_comma_separated_list(
            parser.Delimiter.PAREN, parser.parse_attribute
        )
        if res_types is None:
            res_types = [parser.parse_attribute()]
    else:
        res_types = ()

    prop_names = cls.get_irdl_definition().properties

    properties = {k: v for k, v in attrs.items() if k in prop_names}
    # Drop the values in properties from attrs
    for k in properties:
        if k in attrs:
            del attrs[k]

    try:
        return cls.build(
            operands=(ins, outs),
            result_types=(res_types,),
            properties=properties,
            attributes=attrs,
            regions=(cls.get_hidden_region(ins, outs),),
        )
    except ValueError:
        parser.raise_error("Could not build linalg op")

print(printer: Printer)

Source code in xdsl/dialects/linalg.py
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
def print(self, printer: Printer):
    extra_attrs = {**self.attributes, **self.properties}
    if "indexing_maps" in extra_attrs:
        del extra_attrs["indexing_maps"]
    if "linalg.memoized_indexing_maps" in extra_attrs:
        del extra_attrs["linalg.memoized_indexing_maps"]
    if "iterator_types" in extra_attrs:
        del extra_attrs["iterator_types"]
    if "doc" in extra_attrs:
        del extra_attrs["doc"]
    if "library_call" in extra_attrs:
        del extra_attrs["library_call"]
    if "operandSegmentSizes" in extra_attrs:
        del extra_attrs["operandSegmentSizes"]

    if extra_attrs and self.PRINT_ATTRS_IN_FRONT:
        printer.print_op_attributes(extra_attrs)
    if self.inputs:
        printer.print_string(" ins(")
        printer.print_list(self.inputs, printer.print_ssa_value)
        printer.print_string(" : ")
        printer.print_list(self.inputs.types, printer.print_attribute)
        printer.print_string(")")

    if self.outputs:
        printer.print_string(" outs(")
        printer.print_list(self.outputs, printer.print_ssa_value)
        printer.print_string(" : ")
        printer.print_list(self.outputs.types, printer.print_attribute)
        printer.print_string(")")

    if extra_attrs and not self.PRINT_ATTRS_IN_FRONT:
        printer.print_string(" attrs = ")
        printer.print_op_attributes(extra_attrs)

    if self.res:
        printer.print_string(" -> ")
        if len(self.res) == 1:
            printer.print_attribute(self.res[0].type)
        else:
            with printer.in_parens():
                printer.print_list(
                    self.res, lambda res: printer.print_attribute(res.type)
                )

body_arg_types(operands: Sequence[SSAValue]) -> Sequence[AnyFloat | IntegerType] staticmethod

Return the element types of the arguments of the body of this operation

Source code in xdsl/dialects/linalg.py
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
@staticmethod
def body_arg_types(
    operands: Sequence[SSAValue],
) -> Sequence[AnyFloat | IntegerType]:
    """
    Return the element types of the arguments of the body of this operation
    """

    result: Sequence[AnyFloat | IntegerType] = []

    for op in operands:
        op_type = op.type
        if isa(op_type, MemRefType | TensorType):
            element_type = op_type.get_element_type()
        else:  # int or float
            element_type = op_type
        assert isa(element_type, AnyFloat | IntegerType)
        result.append(element_type)

    return result

get_hidden_region(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]) -> Region abstractmethod classmethod

The hidden region for this linalg NamedOperation.

Source code in xdsl/dialects/linalg.py
621
622
623
624
625
626
627
628
629
@classmethod
@abstractmethod
def get_hidden_region(
    cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
) -> Region:
    """
    The hidden region for this linalg NamedOperation.
    """
    raise NotImplementedError

get_default_indexing_maps() -> Sequence[AffineMap] abstractmethod

Get the default indexing maps corresponding to this operation's operands, in order.

Source code in xdsl/dialects/linalg.py
631
632
633
634
635
@abstractmethod
def get_default_indexing_maps(self) -> Sequence[AffineMap]:
    """
    Get the default indexing maps corresponding to this operation's operands, in order.
    """

get_indexing_maps() -> ArrayAttr[AffineMapAttr]

Source code in xdsl/dialects/linalg.py
637
638
639
640
def get_indexing_maps(self) -> ArrayAttr[AffineMapAttr]:
    return ArrayAttr(
        AffineMapAttr(map_) for map_ in self.get_default_indexing_maps()
    )

ElementwiseOperation dataclass

Bases: NamedOperation, ABC

Source code in xdsl/dialects/linalg.py
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
class ElementwiseOperation(NamedOperation, ABC):
    def get_default_indexing_maps(self) -> Sequence[AffineMap]:
        assert all(isinstance(t, ShapedType) for t in self.operand_types), (
            "Assume that all named linalg pointwise operations have matching shaped "
            "types."
        )
        operand_types = cast(Sequence[ShapedType], self.operand_types)
        shapes = tuple(t.get_shape() for t in operand_types)
        assert all(shape == shapes[0] for shape in shapes[1:]), (
            "All shapes must be equal"
        )

        return (AffineMap.identity(len(shapes[0])),) * len(operand_types)

    def get_iterator_types(self) -> ArrayAttr[IteratorTypeAttr]:
        num_loops = self.get_num_loops()
        return ArrayAttr((IteratorTypeAttr.parallel(),) * num_loops)

get_default_indexing_maps() -> Sequence[AffineMap]

Source code in xdsl/dialects/linalg.py
644
645
646
647
648
649
650
651
652
653
654
655
def get_default_indexing_maps(self) -> Sequence[AffineMap]:
    assert all(isinstance(t, ShapedType) for t in self.operand_types), (
        "Assume that all named linalg pointwise operations have matching shaped "
        "types."
    )
    operand_types = cast(Sequence[ShapedType], self.operand_types)
    shapes = tuple(t.get_shape() for t in operand_types)
    assert all(shape == shapes[0] for shape in shapes[1:]), (
        "All shapes must be equal"
    )

    return (AffineMap.identity(len(shapes[0])),) * len(operand_types)

get_iterator_types() -> ArrayAttr[IteratorTypeAttr]

Source code in xdsl/dialects/linalg.py
657
658
659
def get_iterator_types(self) -> ArrayAttr[IteratorTypeAttr]:
    num_loops = self.get_num_loops()
    return ArrayAttr((IteratorTypeAttr.parallel(),) * num_loops)

AddOp

Bases: ElementwiseOperation

Adds two tensors elementwise.

See external documentation.

Source code in xdsl/dialects/linalg.py
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
@irdl_op_definition
class AddOp(ElementwiseOperation):
    """
    Adds two tensors elementwise.

    See external [documentation](https://mlir.llvm.org/docs/Dialects/Linalg/#linalgadd-linalgaddop).
    """

    name = "linalg.add"

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue] = (),
        res: Sequence[Attribute] | None = None,
        attributes: dict[str, Attribute] | None = None,
    ):
        if res is None:
            result_types = tuple(output.type for output in outputs)
        else:
            result_types = res

        super().__init__(
            ins=inputs,
            outs=outputs,
            result_types=result_types,
            attributes=attributes,
            hidden_region=self.get_hidden_region(inputs, outputs),
        )

    @classmethod
    def get_hidden_region(
        cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
    ) -> Region:
        arg_types = cls.body_arg_types((*inputs, *outputs))
        add = arith.AddfOp if isinstance(arg_types[-1], AnyFloat) else arith.AddiOp

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            result = add(args[0], args[1])
            YieldOp(result)

        return hidden_region

name = 'linalg.add' class-attribute instance-attribute

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue] = (), res: Sequence[Attribute] | None = None, attributes: dict[str, Attribute] | None = None)

Source code in xdsl/dialects/linalg.py
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue] = (),
    res: Sequence[Attribute] | None = None,
    attributes: dict[str, Attribute] | None = None,
):
    if res is None:
        result_types = tuple(output.type for output in outputs)
    else:
        result_types = res

    super().__init__(
        ins=inputs,
        outs=outputs,
        result_types=result_types,
        attributes=attributes,
        hidden_region=self.get_hidden_region(inputs, outputs),
    )

get_hidden_region(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]) -> Region classmethod

Source code in xdsl/dialects/linalg.py
692
693
694
695
696
697
698
699
700
701
702
703
704
@classmethod
def get_hidden_region(
    cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
) -> Region:
    arg_types = cls.body_arg_types((*inputs, *outputs))
    add = arith.AddfOp if isinstance(arg_types[-1], AnyFloat) else arith.AddiOp

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        result = add(args[0], args[1])
        YieldOp(result)

    return hidden_region

ExpOp

Bases: NamedOperation

Applies exp(x) elementwise.

See external documentation.

Source code in xdsl/dialects/linalg.py
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
@irdl_op_definition
class ExpOp(NamedOperation):
    """
    Applies exp(x) elementwise.

    See external [documentation](https://mlir.llvm.org/docs/Dialects/Linalg/#linalgexp-linalgexpop).
    """

    name = "linalg.exp"

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue] = (),
        res: Sequence[Attribute] | None = None,
        attributes: dict[str, Attribute] | None = None,
    ):
        if res is None:
            result_types = tuple(output.type for output in outputs)
        else:
            result_types = res

        super().__init__(
            ins=inputs,
            outs=outputs,
            result_types=result_types,
            attributes=attributes,
            hidden_region=self.get_hidden_region(inputs, outputs),
        )

    @classmethod
    def get_hidden_region(
        cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
    ) -> Region:
        arg_types = cls.body_arg_types((*inputs, *outputs))

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            result = math.ExpOp(args[0])
            YieldOp(result)

        return hidden_region

name = 'linalg.exp' class-attribute instance-attribute

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue] = (), res: Sequence[Attribute] | None = None, attributes: dict[str, Attribute] | None = None)

Source code in xdsl/dialects/linalg.py
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue] = (),
    res: Sequence[Attribute] | None = None,
    attributes: dict[str, Attribute] | None = None,
):
    if res is None:
        result_types = tuple(output.type for output in outputs)
    else:
        result_types = res

    super().__init__(
        ins=inputs,
        outs=outputs,
        result_types=result_types,
        attributes=attributes,
        hidden_region=self.get_hidden_region(inputs, outputs),
    )

get_hidden_region(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]) -> Region classmethod

Source code in xdsl/dialects/linalg.py
737
738
739
740
741
742
743
744
745
746
747
748
@classmethod
def get_hidden_region(
    cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
) -> Region:
    arg_types = cls.body_arg_types((*inputs, *outputs))

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        result = math.ExpOp(args[0])
        YieldOp(result)

    return hidden_region

LogOp

Bases: NamedOperation

Applies log(x) elementwise.

See external documentation.

Source code in xdsl/dialects/linalg.py
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
@irdl_op_definition
class LogOp(NamedOperation):
    """
    Applies log(x) elementwise.

    See external [documentation](https://mlir.llvm.org/docs/Dialects/Linalg/#linalglog-linalglogop).
    """

    name = "linalg.log"

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue] = (),
        res: Sequence[Attribute] | None = None,
        attributes: dict[str, Attribute] | None = None,
    ):
        if res is None:
            result_types = tuple(output.type for output in outputs)
        else:
            result_types = res

        super().__init__(
            ins=inputs,
            outs=outputs,
            result_types=result_types,
            attributes=attributes,
            hidden_region=self.get_hidden_region(inputs, outputs),
        )

    @classmethod
    def get_hidden_region(
        cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
    ) -> Region:
        arg_types = cls.body_arg_types((*inputs, *outputs))

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            result = math.LogOp(args[0])
            YieldOp(result)

        return hidden_region

name = 'linalg.log' class-attribute instance-attribute

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue] = (), res: Sequence[Attribute] | None = None, attributes: dict[str, Attribute] | None = None)

Source code in xdsl/dialects/linalg.py
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue] = (),
    res: Sequence[Attribute] | None = None,
    attributes: dict[str, Attribute] | None = None,
):
    if res is None:
        result_types = tuple(output.type for output in outputs)
    else:
        result_types = res

    super().__init__(
        ins=inputs,
        outs=outputs,
        result_types=result_types,
        attributes=attributes,
        hidden_region=self.get_hidden_region(inputs, outputs),
    )

get_hidden_region(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]) -> Region classmethod

Source code in xdsl/dialects/linalg.py
781
782
783
784
785
786
787
788
789
790
791
792
@classmethod
def get_hidden_region(
    cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
) -> Region:
    arg_types = cls.body_arg_types((*inputs, *outputs))

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        result = math.LogOp(args[0])
        YieldOp(result)

    return hidden_region

SubOp

Bases: ElementwiseOperation

Subtracts two tensors elementwise.

See external documentation.

Source code in xdsl/dialects/linalg.py
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
@irdl_op_definition
class SubOp(ElementwiseOperation):
    """
    Subtracts two tensors elementwise.

    See external [documentation](https://mlir.llvm.org/docs/Dialects/Linalg/#linalgsub-linalgsubop).
    """

    name = "linalg.sub"

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue] = (),
        res: Sequence[Attribute] | None = None,
        attributes: dict[str, Attribute] | None = None,
    ):
        if res is None:
            result_types = tuple(output.type for output in outputs)
        else:
            result_types = res

        self.body_arg_types((*inputs, *outputs))

        super().__init__(
            ins=inputs,
            outs=outputs,
            result_types=result_types,
            attributes=attributes,
            hidden_region=self.get_hidden_region(inputs, outputs),
        )

    @classmethod
    def get_hidden_region(
        cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
    ) -> Region:
        arg_types = cls.body_arg_types((*inputs, *outputs))
        sub = arith.SubfOp if isinstance(arg_types[-1], AnyFloat) else arith.SubiOp

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            result = sub(args[0], args[1])
            YieldOp(result)

        return hidden_region

name = 'linalg.sub' class-attribute instance-attribute

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue] = (), res: Sequence[Attribute] | None = None, attributes: dict[str, Attribute] | None = None)

Source code in xdsl/dialects/linalg.py
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue] = (),
    res: Sequence[Attribute] | None = None,
    attributes: dict[str, Attribute] | None = None,
):
    if res is None:
        result_types = tuple(output.type for output in outputs)
    else:
        result_types = res

    self.body_arg_types((*inputs, *outputs))

    super().__init__(
        ins=inputs,
        outs=outputs,
        result_types=result_types,
        attributes=attributes,
        hidden_region=self.get_hidden_region(inputs, outputs),
    )

get_hidden_region(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]) -> Region classmethod

Source code in xdsl/dialects/linalg.py
827
828
829
830
831
832
833
834
835
836
837
838
839
@classmethod
def get_hidden_region(
    cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
) -> Region:
    arg_types = cls.body_arg_types((*inputs, *outputs))
    sub = arith.SubfOp if isinstance(arg_types[-1], AnyFloat) else arith.SubiOp

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        result = sub(args[0], args[1])
        YieldOp(result)

    return hidden_region

SqrtOp

Bases: NamedOperation

Applies sqrt(x) elementwise.

See external documentation.

Source code in xdsl/dialects/linalg.py
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
@irdl_op_definition
class SqrtOp(NamedOperation):
    """
    Applies sqrt(x) elementwise.

    See external [documentation](https://mlir.llvm.org/docs/Dialects/Linalg/#linalgsqrt-linalgsqrtop).
    """

    name = "linalg.sqrt"

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue] = (),
        res: Sequence[Attribute] | None = None,
        attributes: dict[str, Attribute] | None = None,
    ):
        if res is None:
            result_types = tuple(output.type for output in outputs)
        else:
            result_types = res

        super().__init__(
            ins=inputs,
            outs=outputs,
            result_types=result_types,
            attributes=attributes,
            hidden_region=self.get_hidden_region(inputs, outputs),
        )

    @classmethod
    def get_hidden_region(
        cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
    ) -> Region:
        arg_types = cls.body_arg_types((*inputs, *outputs))

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            result = math.SqrtOp(args[0])
            YieldOp(result)

        return hidden_region

name = 'linalg.sqrt' class-attribute instance-attribute

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue] = (), res: Sequence[Attribute] | None = None, attributes: dict[str, Attribute] | None = None)

Source code in xdsl/dialects/linalg.py
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue] = (),
    res: Sequence[Attribute] | None = None,
    attributes: dict[str, Attribute] | None = None,
):
    if res is None:
        result_types = tuple(output.type for output in outputs)
    else:
        result_types = res

    super().__init__(
        ins=inputs,
        outs=outputs,
        result_types=result_types,
        attributes=attributes,
        hidden_region=self.get_hidden_region(inputs, outputs),
    )

get_hidden_region(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]) -> Region classmethod

Source code in xdsl/dialects/linalg.py
872
873
874
875
876
877
878
879
880
881
882
883
@classmethod
def get_hidden_region(
    cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
) -> Region:
    arg_types = cls.body_arg_types((*inputs, *outputs))

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        result = math.SqrtOp(args[0])
        YieldOp(result)

    return hidden_region

SelectOp

Bases: NamedOperation

Chooses one value based on a binary condition supplied as its first operand.

See external documentation.

Source code in xdsl/dialects/linalg.py
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
@irdl_op_definition
class SelectOp(NamedOperation):
    """
    Chooses one value based on a binary condition supplied as its first operand.

    See external [documentation](https://mlir.llvm.org/docs/Dialects/Linalg/#linalgselect-linalgselectop).
    """

    name = "linalg.select"

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue] = (),
        res: Sequence[Attribute] | None = None,
        attributes: dict[str, Attribute] | None = None,
    ):
        if res is None:
            result_types = tuple(output.type for output in outputs)
        else:
            result_types = res

        super().__init__(
            ins=inputs,
            outs=outputs,
            result_types=result_types,
            attributes=attributes,
            hidden_region=self.get_hidden_region(inputs, outputs),
        )

    @classmethod
    def get_hidden_region(
        cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
    ) -> Region:
        arg_types = cls.body_arg_types((*inputs, *outputs))

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            result = arith.SelectOp(*args[: len(inputs)])
            YieldOp(result)

        return hidden_region

name = 'linalg.select' class-attribute instance-attribute

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue] = (), res: Sequence[Attribute] | None = None, attributes: dict[str, Attribute] | None = None)

Source code in xdsl/dialects/linalg.py
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue] = (),
    res: Sequence[Attribute] | None = None,
    attributes: dict[str, Attribute] | None = None,
):
    if res is None:
        result_types = tuple(output.type for output in outputs)
    else:
        result_types = res

    super().__init__(
        ins=inputs,
        outs=outputs,
        result_types=result_types,
        attributes=attributes,
        hidden_region=self.get_hidden_region(inputs, outputs),
    )

get_hidden_region(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]) -> Region classmethod

Source code in xdsl/dialects/linalg.py
916
917
918
919
920
921
922
923
924
925
926
927
@classmethod
def get_hidden_region(
    cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
) -> Region:
    arg_types = cls.body_arg_types((*inputs, *outputs))

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        result = arith.SelectOp(*args[: len(inputs)])
        YieldOp(result)

    return hidden_region

FillOp

Bases: NamedOperation

Fills the output tensor with the given value.

Works for arbitrary ranked output tensors since the operation performs scalar accesses only and is thus rank polymorphic. Numeric casting is performed on the value operand, promoting it to the same data type as the output.

See external documentation.

Source code in xdsl/dialects/linalg.py
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
@irdl_op_definition
class FillOp(NamedOperation):
    """
    Fills the output tensor with the given value.

    Works for arbitrary ranked output tensors since the operation performs scalar accesses
    only and is thus rank polymorphic. Numeric casting is performed on the value operand,
    promoting it to the same data type as the output.

    See external [documentation](https://mlir.llvm.org/docs/Dialects/Linalg/#linalgfill-linalgfillop).
    """

    name = "linalg.fill"

    PRINT_ATTRS_IN_FRONT: ClassVar[bool] = True

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue] = (),
        res: Sequence[Attribute] | None = None,
        attributes: dict[str, Attribute] | None = None,
    ):
        if res is None:
            assert isa(outputs, Sequence[SSAValue]), "cannot infer result_types"
            result_types = tuple(output.type for output in outputs)
        else:
            result_types = res

        super().__init__(
            ins=inputs,
            outs=outputs,
            result_types=result_types,
            attributes=attributes,
            hidden_region=self.get_hidden_region(inputs, outputs),
        )

    def verify_(self) -> None:
        # Check the that the inputs are of scalar type (f32, f64, etc)
        for value in self.inputs:
            if not isinstance(value.type, AnyFloat | IntegerType):
                raise VerifyException(
                    f"Input type is {value.type} but must be an instance of AnyFloat or IntegerType."
                )

    @classmethod
    def get_hidden_region(
        cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
    ) -> Region:
        arg_types = cls.body_arg_types((*inputs, *outputs))

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            YieldOp(args[0])

        return hidden_region

    def get_default_indexing_maps(self) -> Sequence[AffineMap]:
        raise NotImplementedError

    def get_iterator_types(self) -> ArrayAttr[IteratorTypeAttr]:
        raise NotImplementedError

name = 'linalg.fill' class-attribute instance-attribute

PRINT_ATTRS_IN_FRONT: bool = True class-attribute

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue] = (), res: Sequence[Attribute] | None = None, attributes: dict[str, Attribute] | None = None)

Source code in xdsl/dialects/linalg.py
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue] = (),
    res: Sequence[Attribute] | None = None,
    attributes: dict[str, Attribute] | None = None,
):
    if res is None:
        assert isa(outputs, Sequence[SSAValue]), "cannot infer result_types"
        result_types = tuple(output.type for output in outputs)
    else:
        result_types = res

    super().__init__(
        ins=inputs,
        outs=outputs,
        result_types=result_types,
        attributes=attributes,
        hidden_region=self.get_hidden_region(inputs, outputs),
    )

verify_() -> None

Source code in xdsl/dialects/linalg.py
967
968
969
970
971
972
973
def verify_(self) -> None:
    # Check the that the inputs are of scalar type (f32, f64, etc)
    for value in self.inputs:
        if not isinstance(value.type, AnyFloat | IntegerType):
            raise VerifyException(
                f"Input type is {value.type} but must be an instance of AnyFloat or IntegerType."
            )

get_hidden_region(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]) -> Region classmethod

Source code in xdsl/dialects/linalg.py
975
976
977
978
979
980
981
982
983
984
985
@classmethod
def get_hidden_region(
    cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
) -> Region:
    arg_types = cls.body_arg_types((*inputs, *outputs))

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        YieldOp(args[0])

    return hidden_region

get_default_indexing_maps() -> Sequence[AffineMap]

Source code in xdsl/dialects/linalg.py
987
988
def get_default_indexing_maps(self) -> Sequence[AffineMap]:
    raise NotImplementedError

get_iterator_types() -> ArrayAttr[IteratorTypeAttr]

Source code in xdsl/dialects/linalg.py
990
991
def get_iterator_types(self) -> ArrayAttr[IteratorTypeAttr]:
    raise NotImplementedError

CopyOp

Bases: ElementwiseOperation

Copies the tensor elementwise.

Numeric casting is performed on the input operand, promoting it to the same data type as the accumulator/output.

See external documentation.

Source code in xdsl/dialects/linalg.py
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
@irdl_op_definition
class CopyOp(ElementwiseOperation):
    """
    Copies the tensor elementwise.

    Numeric casting is performed on the input operand, promoting it to the same data type as the accumulator/output.

    See external [documentation](https://mlir.llvm.org/docs/Dialects/Linalg/#linalgcopy-linalgcopyop).
    """

    name = "linalg.copy"

    PRINT_ATTRS_IN_FRONT: ClassVar[bool] = True

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue] = (),
        res: Sequence[Attribute] | None = None,
        attributes: dict[str, Attribute] | None = None,
    ):
        if res is None:
            assert isa(outputs, Sequence[SSAValue]), "cannot infer result_types"
            result_types = tuple(output.type for output in outputs)
        else:
            result_types = res

        super().__init__(
            ins=inputs,
            outs=outputs,
            result_types=result_types,
            attributes=attributes,
            hidden_region=self.get_hidden_region(inputs, outputs),
        )

    @classmethod
    def get_hidden_region(
        cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
    ) -> Region:
        arg_types = cls.body_arg_types((*inputs, *outputs))

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            YieldOp(args[0])

        return hidden_region

name = 'linalg.copy' class-attribute instance-attribute

PRINT_ATTRS_IN_FRONT: bool = True class-attribute

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue] = (), res: Sequence[Attribute] | None = None, attributes: dict[str, Attribute] | None = None)

Source code in xdsl/dialects/linalg.py
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue] = (),
    res: Sequence[Attribute] | None = None,
    attributes: dict[str, Attribute] | None = None,
):
    if res is None:
        assert isa(outputs, Sequence[SSAValue]), "cannot infer result_types"
        result_types = tuple(output.type for output in outputs)
    else:
        result_types = res

    super().__init__(
        ins=inputs,
        outs=outputs,
        result_types=result_types,
        attributes=attributes,
        hidden_region=self.get_hidden_region(inputs, outputs),
    )

get_hidden_region(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]) -> Region classmethod

Source code in xdsl/dialects/linalg.py
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
@classmethod
def get_hidden_region(
    cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
) -> Region:
    arg_types = cls.body_arg_types((*inputs, *outputs))

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        YieldOp(args[0])

    return hidden_region

MaxOp

Bases: ElementwiseOperation

Takes the max (signed) between two inputs, elementwise.

See external documentation.

Source code in xdsl/dialects/linalg.py
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
@irdl_op_definition
class MaxOp(ElementwiseOperation):
    """
    Takes the max (signed) between two inputs, elementwise.

    See external [documentation](https://mlir.llvm.org/docs/Dialects/Linalg/#linalgmax-linalgmaxop).
    """

    name = "linalg.max"

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue] = (),
        res: Sequence[Attribute] | None = None,
        attributes: dict[str, Attribute] | None = None,
    ):
        if res is None:
            result_types = tuple(output.type for output in outputs)
        else:
            result_types = res

        super().__init__(
            ins=inputs,
            outs=outputs,
            result_types=result_types,
            attributes=attributes,
            hidden_region=self.get_hidden_region(inputs, outputs),
        )

    @classmethod
    def get_hidden_region(
        cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
    ) -> Region:
        arg_types = cls.body_arg_types((*inputs, *outputs))
        maxop = (
            arith.MaximumfOp if isinstance(arg_types[-1], AnyFloat) else arith.MaxSIOp
        )

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            result = maxop(args[0], args[1])
            YieldOp(result)

        return hidden_region

name = 'linalg.max' class-attribute instance-attribute

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue] = (), res: Sequence[Attribute] | None = None, attributes: dict[str, Attribute] | None = None)

Source code in xdsl/dialects/linalg.py
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue] = (),
    res: Sequence[Attribute] | None = None,
    attributes: dict[str, Attribute] | None = None,
):
    if res is None:
        result_types = tuple(output.type for output in outputs)
    else:
        result_types = res

    super().__init__(
        ins=inputs,
        outs=outputs,
        result_types=result_types,
        attributes=attributes,
        hidden_region=self.get_hidden_region(inputs, outputs),
    )

get_hidden_region(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]) -> Region classmethod

Source code in xdsl/dialects/linalg.py
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
@classmethod
def get_hidden_region(
    cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
) -> Region:
    arg_types = cls.body_arg_types((*inputs, *outputs))
    maxop = (
        arith.MaximumfOp if isinstance(arg_types[-1], AnyFloat) else arith.MaxSIOp
    )

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        result = maxop(args[0], args[1])
        YieldOp(result)

    return hidden_region

MinOp

Bases: ElementwiseOperation

Takes the max (signed) between two inputs, elementwise.

See external documentation.

Source code in xdsl/dialects/linalg.py
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
@irdl_op_definition
class MinOp(ElementwiseOperation):
    """
    Takes the max (signed) between two inputs, elementwise.

    See external [documentation](https://mlir.llvm.org/docs/Dialects/Linalg/#linalgmax-linalgmaxop).
    """

    name = "linalg.min"

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue] = (),
        res: Sequence[Attribute] | None = None,
        attributes: dict[str, Attribute] | None = None,
    ):
        if res is None:
            result_types = tuple(output.type for output in outputs)
        else:
            result_types = res

        super().__init__(
            ins=inputs,
            outs=outputs,
            result_types=result_types,
            attributes=attributes,
            hidden_region=self.get_hidden_region(inputs, outputs),
        )

    @classmethod
    def get_hidden_region(
        cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
    ) -> Region:
        arg_types = cls.body_arg_types((*inputs, *outputs))
        minop = (
            arith.MinimumfOp if isinstance(arg_types[-1], AnyFloat) else arith.MinSIOp
        )

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            result = minop(args[0], args[1])
            YieldOp(result)

        return hidden_region

name = 'linalg.min' class-attribute instance-attribute

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue] = (), res: Sequence[Attribute] | None = None, attributes: dict[str, Attribute] | None = None)

Source code in xdsl/dialects/linalg.py
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue] = (),
    res: Sequence[Attribute] | None = None,
    attributes: dict[str, Attribute] | None = None,
):
    if res is None:
        result_types = tuple(output.type for output in outputs)
    else:
        result_types = res

    super().__init__(
        ins=inputs,
        outs=outputs,
        result_types=result_types,
        attributes=attributes,
        hidden_region=self.get_hidden_region(inputs, outputs),
    )

get_hidden_region(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]) -> Region classmethod

Source code in xdsl/dialects/linalg.py
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
@classmethod
def get_hidden_region(
    cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
) -> Region:
    arg_types = cls.body_arg_types((*inputs, *outputs))
    minop = (
        arith.MinimumfOp if isinstance(arg_types[-1], AnyFloat) else arith.MinSIOp
    )

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        result = minop(args[0], args[1])
        YieldOp(result)

    return hidden_region

MulOp

Bases: ElementwiseOperation

Multiplies two tensors elementwise.

See external documentation.

Source code in xdsl/dialects/linalg.py
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
@irdl_op_definition
class MulOp(ElementwiseOperation):
    """
    Multiplies two tensors elementwise.

    See external [documentation](https://mlir.llvm.org/docs/Dialects/Linalg/#linalgmul-linalgmulop).
    """

    name = "linalg.mul"

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue] = (),
        res: Sequence[Attribute] | None = None,
        attributes: dict[str, Attribute] | None = None,
    ):
        if res is None:
            result_types = tuple(output.type for output in outputs)
        else:
            result_types = res

        super().__init__(
            ins=inputs,
            outs=outputs,
            result_types=result_types,
            attributes=attributes,
            hidden_region=self.get_hidden_region(inputs, outputs),
        )

    @classmethod
    def get_hidden_region(
        cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
    ) -> Region:
        arg_types = cls.body_arg_types((*inputs, *outputs))
        mul = arith.MulfOp if isinstance(arg_types[-1], AnyFloat) else arith.MuliOp

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            result = mul(args[0], args[1])
            YieldOp(result)

        return hidden_region

name = 'linalg.mul' class-attribute instance-attribute

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue] = (), res: Sequence[Attribute] | None = None, attributes: dict[str, Attribute] | None = None)

Source code in xdsl/dialects/linalg.py
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue] = (),
    res: Sequence[Attribute] | None = None,
    attributes: dict[str, Attribute] | None = None,
):
    if res is None:
        result_types = tuple(output.type for output in outputs)
    else:
        result_types = res

    super().__init__(
        ins=inputs,
        outs=outputs,
        result_types=result_types,
        attributes=attributes,
        hidden_region=self.get_hidden_region(inputs, outputs),
    )

get_hidden_region(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]) -> Region classmethod

Source code in xdsl/dialects/linalg.py
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
@classmethod
def get_hidden_region(
    cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
) -> Region:
    arg_types = cls.body_arg_types((*inputs, *outputs))
    mul = arith.MulfOp if isinstance(arg_types[-1], AnyFloat) else arith.MuliOp

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        result = mul(args[0], args[1])
        YieldOp(result)

    return hidden_region

TransposeOp

Bases: IRDLOperation

Transpose operator

See external documentation.

Source code in xdsl/dialects/linalg.py
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
@irdl_op_definition
class TransposeOp(IRDLOperation):
    """
    Transpose operator

    See external [documentation](https://mlir.llvm.org/docs/Dialects/Linalg/#linalgtranspose-linalgtransposeop).
    """

    name = "linalg.transpose"

    input = operand_def(base(MemRefType) | base(AnyTensorType))
    init = operand_def(base(MemRefType) | base(AnyTensorType))
    result = var_result_def(AnyTensorType)

    hidden_region = region_def("single_block")

    permutation = prop_def(DenseArrayBase.constr(i64))

    def __init__(
        self,
        input: SSAValue,
        init: SSAValue,
        permutation: Attribute,
        result: Attribute | None = None,
    ):
        if result is None:
            if isa(init.type, TensorType):
                results = (init.type,)
            else:
                results = ()
        else:
            results = (result,)

        arg_types = NamedOperation.body_arg_types((input, init))

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            YieldOp(args[0])

        super().__init__(
            properties={
                "permutation": permutation,
            },
            operands=(input, init),
            result_types=(results,),
            regions=(hidden_region,),
        )

    def verify_(self) -> None:
        assert isinstance(input_type := self.input.type, TensorType | MemRefType)
        assert isinstance(init_type := self.init.type, TensorType | MemRefType)

        input_shape = input_type.get_shape()
        init_shape = init_type.get_shape()

        if (input_rank := len(input_shape)) != (init_rank := len(init_shape)):
            raise VerifyException(
                f"Input rank ({input_rank}) does not match output rank ({init_rank})"
            )
        if (input_rank := len(input_shape)) != (
            permutation_size := len(self.permutation)
        ):
            raise VerifyException(
                f"Input rank ({input_rank}) does not match size of permutation ({permutation_size})"
            )

        permutation_shape = self.permutation.get_values()

        for i in range(len(input_shape)):
            input_dimension = input_shape[permutation_shape[i]]
            init_dimension = init_shape[i]

            if input_dimension != init_dimension:
                raise VerifyException(
                    f"dim(result, {i}) = {init_dimension} "
                    f"doesn't match dim(input, permutation[{i}]) = {input_dimension}"
                )

    def print(self, printer: Printer):
        printer.print_string(" ins")
        with printer.in_parens():
            printer.print_ssa_value(self.input)
            printer.print_string(":")
            printer.print_attribute(self.input.type)
        printer.print_string(" outs")
        with printer.in_parens():
            printer.print_ssa_value(self.init)
            printer.print_string(":")
            printer.print_attribute(self.init.type)
        printer.print_string(" permutation = ")
        with printer.in_square_brackets():
            printer.print_list(self.permutation.get_values(), printer.print_int)

    @classmethod
    def parse(cls, parser: Parser) -> Self:
        parser.parse_characters("ins")
        parser.parse_punctuation("(")
        input = parser.parse_operand()
        parser.parse_punctuation(":")
        parser.parse_type()
        parser.parse_punctuation(")")
        parser.parse_characters("outs")
        parser.parse_punctuation("(")
        init = parser.parse_operand()
        parser.parse_punctuation(":")
        parser.parse_type()
        parser.parse_punctuation(")")
        parser.parse_keyword("permutation")
        parser.parse_punctuation("=")
        permutation = parser.parse_comma_separated_list(
            parser.Delimiter.SQUARE, parser.parse_integer
        )
        transpose = cls(
            input,
            init,
            DenseArrayBase.from_list(i64, permutation),
        )
        return transpose

name = 'linalg.transpose' class-attribute instance-attribute

input = operand_def(base(MemRefType) | base(AnyTensorType)) class-attribute instance-attribute

init = operand_def(base(MemRefType) | base(AnyTensorType)) class-attribute instance-attribute

result = var_result_def(AnyTensorType) class-attribute instance-attribute

hidden_region = region_def('single_block') class-attribute instance-attribute

permutation = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

__init__(input: SSAValue, init: SSAValue, permutation: Attribute, result: Attribute | None = None)

Source code in xdsl/dialects/linalg.py
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init__(
    self,
    input: SSAValue,
    init: SSAValue,
    permutation: Attribute,
    result: Attribute | None = None,
):
    if result is None:
        if isa(init.type, TensorType):
            results = (init.type,)
        else:
            results = ()
    else:
        results = (result,)

    arg_types = NamedOperation.body_arg_types((input, init))

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        YieldOp(args[0])

    super().__init__(
        properties={
            "permutation": permutation,
        },
        operands=(input, init),
        result_types=(results,),
        regions=(hidden_region,),
    )

verify_() -> None

Source code in xdsl/dialects/linalg.py
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
def verify_(self) -> None:
    assert isinstance(input_type := self.input.type, TensorType | MemRefType)
    assert isinstance(init_type := self.init.type, TensorType | MemRefType)

    input_shape = input_type.get_shape()
    init_shape = init_type.get_shape()

    if (input_rank := len(input_shape)) != (init_rank := len(init_shape)):
        raise VerifyException(
            f"Input rank ({input_rank}) does not match output rank ({init_rank})"
        )
    if (input_rank := len(input_shape)) != (
        permutation_size := len(self.permutation)
    ):
        raise VerifyException(
            f"Input rank ({input_rank}) does not match size of permutation ({permutation_size})"
        )

    permutation_shape = self.permutation.get_values()

    for i in range(len(input_shape)):
        input_dimension = input_shape[permutation_shape[i]]
        init_dimension = init_shape[i]

        if input_dimension != init_dimension:
            raise VerifyException(
                f"dim(result, {i}) = {init_dimension} "
                f"doesn't match dim(input, permutation[{i}]) = {input_dimension}"
            )

print(printer: Printer)

Source code in xdsl/dialects/linalg.py
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
def print(self, printer: Printer):
    printer.print_string(" ins")
    with printer.in_parens():
        printer.print_ssa_value(self.input)
        printer.print_string(":")
        printer.print_attribute(self.input.type)
    printer.print_string(" outs")
    with printer.in_parens():
        printer.print_ssa_value(self.init)
        printer.print_string(":")
        printer.print_attribute(self.init.type)
    printer.print_string(" permutation = ")
    with printer.in_square_brackets():
        printer.print_list(self.permutation.get_values(), printer.print_int)

parse(parser: Parser) -> Self classmethod

Source code in xdsl/dialects/linalg.py
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
@classmethod
def parse(cls, parser: Parser) -> Self:
    parser.parse_characters("ins")
    parser.parse_punctuation("(")
    input = parser.parse_operand()
    parser.parse_punctuation(":")
    parser.parse_type()
    parser.parse_punctuation(")")
    parser.parse_characters("outs")
    parser.parse_punctuation("(")
    init = parser.parse_operand()
    parser.parse_punctuation(":")
    parser.parse_type()
    parser.parse_punctuation(")")
    parser.parse_keyword("permutation")
    parser.parse_punctuation("=")
    permutation = parser.parse_comma_separated_list(
        parser.Delimiter.SQUARE, parser.parse_integer
    )
    transpose = cls(
        input,
        init,
        DenseArrayBase.from_list(i64, permutation),
    )
    return transpose

MatmulOp

Bases: NamedOperation

Performs a matrix multiplication of two 2D inputs.

See external documentation.

Source code in xdsl/dialects/linalg.py
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
@irdl_op_definition
class MatmulOp(NamedOperation):
    """
    Performs a matrix multiplication of two 2D inputs.

    See external [documentation](https://mlir.llvm.org/docs/Dialects/Linalg/#linalgmatmul-linalgmatmulop).
    """

    name = "linalg.matmul"

    PRINT_ATTRS_IN_FRONT: ClassVar[bool] = True

    indexing_maps = prop_def(
        ArrayAttr[AffineMapAttr],
        default_value=ArrayAttr(
            [
                AffineMapAttr(AffineMap.from_callable(lambda i, _, k: (i, k))),
                AffineMapAttr(AffineMap.from_callable(lambda _, j, k: (k, j))),
                AffineMapAttr(AffineMap.from_callable(lambda i, j, _: (i, j))),
            ]
        ),
    )

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue] = (),
        res: Sequence[Attribute] | None = None,
        attributes: dict[str, Attribute] | None = None,
    ):
        if res is None:
            result_types = tuple(
                cast(AnyTensorType, output_type)
                for output in outputs
                if isinstance(output_type := output.type, TensorType)
            )
        else:
            result_types = res

        super().__init__(
            ins=inputs,
            outs=outputs,
            result_types=result_types,
            attributes=attributes,
            hidden_region=self.get_hidden_region(inputs, outputs),
        )

    @classmethod
    def get_hidden_region(
        cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
    ) -> Region:
        arg_types = cls.body_arg_types((*inputs, *outputs))
        add, mul = (
            (arith.AddfOp, arith.MulfOp)
            if isinstance(arg_types[-1], AnyFloat)
            else (arith.AddiOp, arith.MuliOp)
        )

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            result = mul(args[0], args[1])
            mac = add(result, args[2])
            YieldOp(mac)

        return hidden_region

    def get_default_indexing_maps(self) -> Sequence[AffineMap]:
        return tuple(m.data for m in self.indexing_maps.data)

    def get_indexing_maps(self) -> ArrayAttr[AffineMapAttr]:
        return self.indexing_maps

    def get_iterator_types(self) -> ArrayAttr[IteratorTypeAttr]:
        return ArrayAttr(
            [
                IteratorTypeAttr.parallel(),
                IteratorTypeAttr.parallel(),
                IteratorTypeAttr.reduction(),
            ]
        )

name = 'linalg.matmul' class-attribute instance-attribute

PRINT_ATTRS_IN_FRONT: bool = True class-attribute

indexing_maps = prop_def(ArrayAttr[AffineMapAttr], default_value=(ArrayAttr([AffineMapAttr(AffineMap.from_callable(lambda i, _, k: (i, k))), AffineMapAttr(AffineMap.from_callable(lambda _, j, k: (k, j))), AffineMapAttr(AffineMap.from_callable(lambda i, j, _: (i, j)))]))) class-attribute instance-attribute

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue] = (), res: Sequence[Attribute] | None = None, attributes: dict[str, Attribute] | None = None)

Source code in xdsl/dialects/linalg.py
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue] = (),
    res: Sequence[Attribute] | None = None,
    attributes: dict[str, Attribute] | None = None,
):
    if res is None:
        result_types = tuple(
            cast(AnyTensorType, output_type)
            for output in outputs
            if isinstance(output_type := output.type, TensorType)
        )
    else:
        result_types = res

    super().__init__(
        ins=inputs,
        outs=outputs,
        result_types=result_types,
        attributes=attributes,
        hidden_region=self.get_hidden_region(inputs, outputs),
    )

get_hidden_region(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]) -> Region classmethod

Source code in xdsl/dialects/linalg.py
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
@classmethod
def get_hidden_region(
    cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
) -> Region:
    arg_types = cls.body_arg_types((*inputs, *outputs))
    add, mul = (
        (arith.AddfOp, arith.MulfOp)
        if isinstance(arg_types[-1], AnyFloat)
        else (arith.AddiOp, arith.MuliOp)
    )

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        result = mul(args[0], args[1])
        mac = add(result, args[2])
        YieldOp(mac)

    return hidden_region

get_default_indexing_maps() -> Sequence[AffineMap]

Source code in xdsl/dialects/linalg.py
1367
1368
def get_default_indexing_maps(self) -> Sequence[AffineMap]:
    return tuple(m.data for m in self.indexing_maps.data)

get_indexing_maps() -> ArrayAttr[AffineMapAttr]

Source code in xdsl/dialects/linalg.py
1370
1371
def get_indexing_maps(self) -> ArrayAttr[AffineMapAttr]:
    return self.indexing_maps

get_iterator_types() -> ArrayAttr[IteratorTypeAttr]

Source code in xdsl/dialects/linalg.py
1373
1374
1375
1376
1377
1378
1379
1380
def get_iterator_types(self) -> ArrayAttr[IteratorTypeAttr]:
    return ArrayAttr(
        [
            IteratorTypeAttr.parallel(),
            IteratorTypeAttr.parallel(),
            IteratorTypeAttr.reduction(),
        ]
    )

QuantizedMatmulOp

Bases: NamedOperation

Performs a matrix multiplication of two 2D inputs.

See external documentation.

Source code in xdsl/dialects/linalg.py
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
@irdl_op_definition
class QuantizedMatmulOp(NamedOperation):
    """
    Performs a matrix multiplication of two 2D inputs.

    See external [documentation](https://mlir.llvm.org/docs/Dialects/Linalg/#linalgquantized_matmul-linalgquantizedmatmulop).
    """

    name = "linalg.quantized_matmul"

    PRINT_ATTRS_IN_FRONT: ClassVar[bool] = True

    memoized_indexing_maps = attr_def(
        ArrayAttr[AffineMapAttr],
        default_value=ArrayAttr(
            [
                AffineMapAttr(AffineMap.from_callable(lambda i, _, k: (i, k))),
                AffineMapAttr(AffineMap.from_callable(lambda _, j, k: (k, j))),
                AffineMapAttr(AffineMap(3, 0, ())),
                AffineMapAttr(AffineMap(3, 0, ())),
                AffineMapAttr(AffineMap.from_callable(lambda i, j, _: (i, j))),
            ]
        ),
        attr_name="linalg.memoized_indexing_maps",
    )

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue] = (),
        res: Sequence[Attribute] | None = None,
        attributes: dict[str, Attribute] | None = None,
    ):
        if res is None:
            result_types = tuple(
                cast(AnyTensorType, output_type)
                for output in outputs
                if isinstance(output_type := output.type, TensorType)
            )
        else:
            result_types = res

        super().__init__(
            ins=inputs,
            outs=outputs,
            result_types=result_types,
            attributes=attributes,
            hidden_region=self.get_hidden_region(inputs, outputs),
        )

    @classmethod
    def get_hidden_region(
        cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
    ) -> Region:
        arg_types = cls.body_arg_types((*inputs, *outputs))

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            o1 = arith.ExtSIOp(args[0], IntegerType(32))
            o2 = arith.SubiOp(o1, args[2])
            o3 = arith.ExtSIOp(args[1], IntegerType(32))
            o4 = arith.SubiOp(o3, args[3])
            o5 = arith.MuliOp(o2, o4)
            o6 = arith.AddiOp(args[4], o5)
            YieldOp(o6)

        return hidden_region

    def get_default_indexing_maps(self) -> Sequence[AffineMap]:
        return tuple(m.data for m in self.memoized_indexing_maps.data)

    def get_indexing_maps(self) -> ArrayAttr[AffineMapAttr]:
        return self.memoized_indexing_maps

    def get_iterator_types(self) -> ArrayAttr[IteratorTypeAttr]:
        return ArrayAttr(
            [
                IteratorTypeAttr.parallel(),
                IteratorTypeAttr.parallel(),
                IteratorTypeAttr.reduction(),
            ]
        )

name = 'linalg.quantized_matmul' class-attribute instance-attribute

PRINT_ATTRS_IN_FRONT: bool = True class-attribute

memoized_indexing_maps = attr_def(ArrayAttr[AffineMapAttr], default_value=(ArrayAttr([AffineMapAttr(AffineMap.from_callable(lambda i, _, k: (i, k))), AffineMapAttr(AffineMap.from_callable(lambda _, j, k: (k, j))), AffineMapAttr(AffineMap(3, 0, ())), AffineMapAttr(AffineMap(3, 0, ())), AffineMapAttr(AffineMap.from_callable(lambda i, j, _: (i, j)))])), attr_name='linalg.memoized_indexing_maps') class-attribute instance-attribute

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue] = (), res: Sequence[Attribute] | None = None, attributes: dict[str, Attribute] | None = None)

Source code in xdsl/dialects/linalg.py
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue] = (),
    res: Sequence[Attribute] | None = None,
    attributes: dict[str, Attribute] | None = None,
):
    if res is None:
        result_types = tuple(
            cast(AnyTensorType, output_type)
            for output in outputs
            if isinstance(output_type := output.type, TensorType)
        )
    else:
        result_types = res

    super().__init__(
        ins=inputs,
        outs=outputs,
        result_types=result_types,
        attributes=attributes,
        hidden_region=self.get_hidden_region(inputs, outputs),
    )

get_hidden_region(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]) -> Region classmethod

Source code in xdsl/dialects/linalg.py
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
@classmethod
def get_hidden_region(
    cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
) -> Region:
    arg_types = cls.body_arg_types((*inputs, *outputs))

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        o1 = arith.ExtSIOp(args[0], IntegerType(32))
        o2 = arith.SubiOp(o1, args[2])
        o3 = arith.ExtSIOp(args[1], IntegerType(32))
        o4 = arith.SubiOp(o3, args[3])
        o5 = arith.MuliOp(o2, o4)
        o6 = arith.AddiOp(args[4], o5)
        YieldOp(o6)

    return hidden_region

get_default_indexing_maps() -> Sequence[AffineMap]

Source code in xdsl/dialects/linalg.py
1451
1452
def get_default_indexing_maps(self) -> Sequence[AffineMap]:
    return tuple(m.data for m in self.memoized_indexing_maps.data)

get_indexing_maps() -> ArrayAttr[AffineMapAttr]

Source code in xdsl/dialects/linalg.py
1454
1455
def get_indexing_maps(self) -> ArrayAttr[AffineMapAttr]:
    return self.memoized_indexing_maps

get_iterator_types() -> ArrayAttr[IteratorTypeAttr]

Source code in xdsl/dialects/linalg.py
1457
1458
1459
1460
1461
1462
1463
1464
def get_iterator_types(self) -> ArrayAttr[IteratorTypeAttr]:
    return ArrayAttr(
        [
            IteratorTypeAttr.parallel(),
            IteratorTypeAttr.parallel(),
            IteratorTypeAttr.reduction(),
        ]
    )

PoolingOperation

Bases: NamedOperation, ABC

Base class for linalg pooling operations.

Source code in xdsl/dialects/linalg.py
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
class PoolingOperation(NamedOperation, ABC):
    """Base class for linalg pooling operations."""

    PRINT_ATTRS_IN_FRONT: ClassVar[bool] = True

    strides = prop_def(DenseIntElementsAttr)
    dilations = prop_def(DenseIntElementsAttr)

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue] = (),
        res: Sequence[Attribute] | None = None,
        attributes: dict[str, Attribute] | None = None,
        *,
        strides: DenseIntElementsAttr,
        dilations: DenseIntElementsAttr,
    ):
        super().__init__(
            ins=inputs,
            outs=outputs,
            result_types=res,
            attributes=attributes,
            properties={"strides": strides, "dilations": dilations},
            hidden_region=self.get_hidden_region(inputs, outputs),
        )

    def get_default_indexing_maps(self) -> Sequence[AffineMap]:
        raise NotImplementedError

    def get_iterator_types(self) -> ArrayAttr[IteratorTypeAttr]:
        raise NotImplementedError

PRINT_ATTRS_IN_FRONT: bool = True class-attribute

strides = prop_def(DenseIntElementsAttr) class-attribute instance-attribute

dilations = prop_def(DenseIntElementsAttr) class-attribute instance-attribute

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue] = (), res: Sequence[Attribute] | None = None, attributes: dict[str, Attribute] | None = None, *, strides: DenseIntElementsAttr, dilations: DenseIntElementsAttr)

Source code in xdsl/dialects/linalg.py
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue] = (),
    res: Sequence[Attribute] | None = None,
    attributes: dict[str, Attribute] | None = None,
    *,
    strides: DenseIntElementsAttr,
    dilations: DenseIntElementsAttr,
):
    super().__init__(
        ins=inputs,
        outs=outputs,
        result_types=res,
        attributes=attributes,
        properties={"strides": strides, "dilations": dilations},
        hidden_region=self.get_hidden_region(inputs, outputs),
    )

get_default_indexing_maps() -> Sequence[AffineMap]

Source code in xdsl/dialects/linalg.py
1494
1495
def get_default_indexing_maps(self) -> Sequence[AffineMap]:
    raise NotImplementedError

get_iterator_types() -> ArrayAttr[IteratorTypeAttr]

Source code in xdsl/dialects/linalg.py
1497
1498
def get_iterator_types(self) -> ArrayAttr[IteratorTypeAttr]:
    raise NotImplementedError

PoolingNchwMaxOp dataclass

Bases: PoolingOperation

Performs max pooling

See external documentation.

Source code in xdsl/dialects/linalg.py
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
@irdl_op_definition
class PoolingNchwMaxOp(PoolingOperation):
    """
    Performs max pooling

    See external [documentation](https://mlir.llvm.org/docs/Dialects/Linalg/#linalgpooling_nchw_max-linalgpoolingnchwmaxop).
    """

    name = "linalg.pooling_nchw_max"

    @classmethod
    def get_hidden_region(
        cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
    ) -> Region:
        arg_types = cls.body_arg_types((*inputs, *outputs))
        max_op = (
            arith.MaximumfOp if isinstance(arg_types[-1], AnyFloat) else arith.MaxSIOp
        )

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            result = max_op(args[0], args[1])
            YieldOp(result)

        return hidden_region

name = 'linalg.pooling_nchw_max' class-attribute instance-attribute

get_hidden_region(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]) -> Region classmethod

Source code in xdsl/dialects/linalg.py
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
@classmethod
def get_hidden_region(
    cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
) -> Region:
    arg_types = cls.body_arg_types((*inputs, *outputs))
    max_op = (
        arith.MaximumfOp if isinstance(arg_types[-1], AnyFloat) else arith.MaxSIOp
    )

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        result = max_op(args[0], args[1])
        YieldOp(result)

    return hidden_region

ConvOperation

Bases: NamedOperation, ABC

Base class for linalg convolution operations.

Source code in xdsl/dialects/linalg.py
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
class ConvOperation(NamedOperation, ABC):
    """Base class for linalg convolution operations."""

    PRINT_ATTRS_IN_FRONT: ClassVar[bool] = True

    strides = prop_def(DenseIntElementsAttr)
    dilations = prop_def(DenseIntElementsAttr)

    def __init__(
        self,
        inputs: Sequence[SSAValue],
        outputs: Sequence[SSAValue] = (),
        res: Sequence[Attribute] | None = None,
        attributes: dict[str, Attribute] | None = None,
        *,
        strides: DenseIntElementsAttr,
        dilations: DenseIntElementsAttr,
    ):
        super().__init__(
            ins=inputs,
            outs=outputs,
            attributes=attributes,
            result_types=res,
            properties={"strides": strides, "dilations": dilations},
            hidden_region=self.get_hidden_region(inputs, outputs),
        )

    @classmethod
    def get_hidden_region(
        cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
    ) -> Region:
        arg_types = cls.body_arg_types((*inputs, *outputs))
        add, mul = (
            (arith.AddfOp, arith.MulfOp)
            if isinstance(arg_types[-1], AnyFloat)
            else (arith.AddiOp, arith.MuliOp)
        )

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            if arg_types[0] != arg_types[-1]:
                assert isinstance(arg_types[-1], IntegerType)
                a = arith.ExtSIOp(args[0], arg_types[-1])
                b = arith.ExtSIOp(args[1], arg_types[-1])
            else:
                a = args[0]
                b = args[1]
            result = mul(a, b)
            mac = add(result, args[2])
            YieldOp(mac)

        return hidden_region

    def get_default_indexing_maps(self) -> Sequence[AffineMap]:
        raise NotImplementedError

    def get_iterator_types(self) -> ArrayAttr[IteratorTypeAttr]:
        raise NotImplementedError

PRINT_ATTRS_IN_FRONT: bool = True class-attribute

strides = prop_def(DenseIntElementsAttr) class-attribute instance-attribute

dilations = prop_def(DenseIntElementsAttr) class-attribute instance-attribute

__init__(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue] = (), res: Sequence[Attribute] | None = None, attributes: dict[str, Attribute] | None = None, *, strides: DenseIntElementsAttr, dilations: DenseIntElementsAttr)

Source code in xdsl/dialects/linalg.py
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
def __init__(
    self,
    inputs: Sequence[SSAValue],
    outputs: Sequence[SSAValue] = (),
    res: Sequence[Attribute] | None = None,
    attributes: dict[str, Attribute] | None = None,
    *,
    strides: DenseIntElementsAttr,
    dilations: DenseIntElementsAttr,
):
    super().__init__(
        ins=inputs,
        outs=outputs,
        attributes=attributes,
        result_types=res,
        properties={"strides": strides, "dilations": dilations},
        hidden_region=self.get_hidden_region(inputs, outputs),
    )

get_hidden_region(inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]) -> Region classmethod

Source code in xdsl/dialects/linalg.py
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
@classmethod
def get_hidden_region(
    cls, inputs: Sequence[SSAValue], outputs: Sequence[SSAValue]
) -> Region:
    arg_types = cls.body_arg_types((*inputs, *outputs))
    add, mul = (
        (arith.AddfOp, arith.MulfOp)
        if isinstance(arg_types[-1], AnyFloat)
        else (arith.AddiOp, arith.MuliOp)
    )

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        if arg_types[0] != arg_types[-1]:
            assert isinstance(arg_types[-1], IntegerType)
            a = arith.ExtSIOp(args[0], arg_types[-1])
            b = arith.ExtSIOp(args[1], arg_types[-1])
        else:
            a = args[0]
            b = args[1]
        result = mul(a, b)
        mac = add(result, args[2])
        YieldOp(mac)

    return hidden_region

get_default_indexing_maps() -> Sequence[AffineMap]

Source code in xdsl/dialects/linalg.py
1581
1582
def get_default_indexing_maps(self) -> Sequence[AffineMap]:
    raise NotImplementedError

get_iterator_types() -> ArrayAttr[IteratorTypeAttr]

Source code in xdsl/dialects/linalg.py
1584
1585
def get_iterator_types(self) -> ArrayAttr[IteratorTypeAttr]:
    raise NotImplementedError

Conv2DNchwFchwOp dataclass

Bases: ConvOperation

Performs 2-D convolution

See external documentation.

Source code in xdsl/dialects/linalg.py
1588
1589
1590
1591
1592
1593
1594
1595
1596
@irdl_op_definition
class Conv2DNchwFchwOp(ConvOperation):
    """
    Performs 2-D convolution

    See external [documentation](https://mlir.llvm.org/docs/Dialects/Linalg/#linalgconv_2d_nchw_fchw-linalgconv2dnchwfchwop).
    """

    name = "linalg.conv_2d_nchw_fchw"

name = 'linalg.conv_2d_nchw_fchw' class-attribute instance-attribute

Conv2DNgchwFgchwOp dataclass

Bases: ConvOperation

Source code in xdsl/dialects/linalg.py
1599
1600
1601
@irdl_op_definition
class Conv2DNgchwFgchwOp(ConvOperation):
    name = "linalg.conv_2d_ngchw_fgchw"

name = 'linalg.conv_2d_ngchw_fgchw' class-attribute instance-attribute

Conv2DNgchwGfchwOp dataclass

Bases: ConvOperation

Source code in xdsl/dialects/linalg.py
1604
1605
1606
@irdl_op_definition
class Conv2DNgchwGfchwOp(ConvOperation):
    name = "linalg.conv_2d_ngchw_gfchw"

name = 'linalg.conv_2d_ngchw_gfchw' class-attribute instance-attribute

Conv2DNhwc_FhwcOp dataclass

Bases: ConvOperation

Source code in xdsl/dialects/linalg.py
1609
1610
1611
@irdl_op_definition
class Conv2DNhwc_FhwcOp(ConvOperation):
    name = "linalg.conv_2d_nhwc_fhwc"

name = 'linalg.conv_2d_nhwc_fhwc' class-attribute instance-attribute

Conv2DNhwc_HwcfOp dataclass

Bases: ConvOperation

Source code in xdsl/dialects/linalg.py
1614
1615
1616
@irdl_op_definition
class Conv2DNhwc_HwcfOp(ConvOperation):
    name = "linalg.conv_2d_nhwc_hwcf"

name = 'linalg.conv_2d_nhwc_hwcf' class-attribute instance-attribute

Conv2DNhwgcGfhwcOp dataclass

Bases: ConvOperation

Source code in xdsl/dialects/linalg.py
1619
1620
1621
@irdl_op_definition
class Conv2DNhwgcGfhwcOp(ConvOperation):
    name = "linalg.conv_2d_nhwgc_gfhwc"

name = 'linalg.conv_2d_nhwgc_gfhwc' class-attribute instance-attribute

BroadcastOp

Bases: IRDLOperation

Static broadcast operator

Broadcast the input into the given shape by adding dimensions

Source code in xdsl/dialects/linalg.py
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
@irdl_op_definition
class BroadcastOp(IRDLOperation):
    """
    Static broadcast operator

    Broadcast the input into the given shape by adding dimensions
    """

    name = "linalg.broadcast"

    input = operand_def(base(MemRefType) | base(AnyTensorType))
    init = operand_def(base(MemRefType) | base(AnyTensorType))
    result = var_result_def(AnyTensorType)

    hidden_region = region_def("single_block")

    dimensions = prop_def(DenseArrayBase.constr(i64))

    def __init__(
        self,
        input: SSAValue,
        init: SSAValue,
        dimensions: Attribute,
        result: Attribute | None = None,
    ):
        if result is None:
            if isa(init.type, TensorType):
                results = (init.type,)
            else:
                results = ()
        else:
            results = (result,)

        arg_types = NamedOperation.body_arg_types((input, init))

        @Builder.implicit_region(arg_types)
        def hidden_region(args: tuple[BlockArgument, ...]) -> None:
            YieldOp(args[0])

        super().__init__(
            properties={
                "dimensions": dimensions,
            },
            operands=(input, init),
            result_types=(results,),
            regions=(hidden_region,),
        )

    def verify_(self) -> None:
        assert isinstance(input_type := self.input.type, TensorType | MemRefType)
        assert isinstance(init_type := self.init.type, TensorType | MemRefType)

        dimensions_shape = self.dimensions.get_values()

        input_shape = input_type.get_shape()
        init_shape = init_type.get_shape()

        if (input_and_dims_rank := (len(input_shape) + len(dimensions_shape))) != (
            init_rank := len(init_shape)
        ):
            raise VerifyException(
                f"Input rank plus added dimensions ({input_and_dims_rank}) does not match output rank ({init_rank})"
            )

        for index, dim in enumerate(dimensions_shape):
            if dim < 0 or dim >= init_rank:
                raise VerifyException(
                    f"Dimension {index} is out of range.  Expected range: [0, {init_rank - 1}], got: {dim}"
                )

        # intialise an array to store the dimensions being mapped
        dimensions_map: list[int] = []
        for dim in range(init_rank):
            if dim not in dimensions_shape:
                dimensions_map.append(dim)

        for input_dim_index, init_dim_index in enumerate(dimensions_map):
            if input_shape[input_dim_index] != init_shape[init_dim_index]:
                raise VerifyException(
                    f"input dimension {input_dim_index} should match output dimension {init_dim_index}. "
                    f"input: {input_shape[input_dim_index]}, output: {init_shape[init_dim_index]}"
                )

    def print(self, printer: Printer):
        printer.print_string(" ins")
        with printer.in_parens():
            printer.print_ssa_value(self.input)
            printer.print_string(":")
            printer.print_attribute(self.input.type)
        printer.print_string(" outs")
        with printer.in_parens():
            printer.print_ssa_value(self.init)
            printer.print_string(":")
            printer.print_attribute(self.init.type)
        printer.print_string(" dimensions = ")
        with printer.in_square_brackets():
            printer.print_list(self.dimensions.get_values(), printer.print_int)

    @classmethod
    def parse(cls, parser: Parser) -> Self:
        parser.parse_characters("ins")
        parser.parse_punctuation("(")
        input = parser.parse_operand()
        parser.parse_punctuation(":")
        parser.parse_type()
        parser.parse_punctuation(")")
        parser.parse_characters("outs")
        parser.parse_punctuation("(")
        init = parser.parse_operand()
        parser.parse_punctuation(":")
        parser.parse_type()
        parser.parse_punctuation(")")
        parser.parse_keyword("dimensions")
        parser.parse_punctuation("=")
        dimensions = parser.parse_comma_separated_list(
            parser.Delimiter.SQUARE, parser.parse_integer
        )
        broadcast = cls(
            input,
            init,
            DenseArrayBase.from_list(i64, dimensions),
        )
        return broadcast

name = 'linalg.broadcast' class-attribute instance-attribute

input = operand_def(base(MemRefType) | base(AnyTensorType)) class-attribute instance-attribute

init = operand_def(base(MemRefType) | base(AnyTensorType)) class-attribute instance-attribute

result = var_result_def(AnyTensorType) class-attribute instance-attribute

hidden_region = region_def('single_block') class-attribute instance-attribute

dimensions = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

__init__(input: SSAValue, init: SSAValue, dimensions: Attribute, result: Attribute | None = None)

Source code in xdsl/dialects/linalg.py
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
def __init__(
    self,
    input: SSAValue,
    init: SSAValue,
    dimensions: Attribute,
    result: Attribute | None = None,
):
    if result is None:
        if isa(init.type, TensorType):
            results = (init.type,)
        else:
            results = ()
    else:
        results = (result,)

    arg_types = NamedOperation.body_arg_types((input, init))

    @Builder.implicit_region(arg_types)
    def hidden_region(args: tuple[BlockArgument, ...]) -> None:
        YieldOp(args[0])

    super().__init__(
        properties={
            "dimensions": dimensions,
        },
        operands=(input, init),
        result_types=(results,),
        regions=(hidden_region,),
    )

verify_() -> None

Source code in xdsl/dialects/linalg.py
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
def verify_(self) -> None:
    assert isinstance(input_type := self.input.type, TensorType | MemRefType)
    assert isinstance(init_type := self.init.type, TensorType | MemRefType)

    dimensions_shape = self.dimensions.get_values()

    input_shape = input_type.get_shape()
    init_shape = init_type.get_shape()

    if (input_and_dims_rank := (len(input_shape) + len(dimensions_shape))) != (
        init_rank := len(init_shape)
    ):
        raise VerifyException(
            f"Input rank plus added dimensions ({input_and_dims_rank}) does not match output rank ({init_rank})"
        )

    for index, dim in enumerate(dimensions_shape):
        if dim < 0 or dim >= init_rank:
            raise VerifyException(
                f"Dimension {index} is out of range.  Expected range: [0, {init_rank - 1}], got: {dim}"
            )

    # intialise an array to store the dimensions being mapped
    dimensions_map: list[int] = []
    for dim in range(init_rank):
        if dim not in dimensions_shape:
            dimensions_map.append(dim)

    for input_dim_index, init_dim_index in enumerate(dimensions_map):
        if input_shape[input_dim_index] != init_shape[init_dim_index]:
            raise VerifyException(
                f"input dimension {input_dim_index} should match output dimension {init_dim_index}. "
                f"input: {input_shape[input_dim_index]}, output: {init_shape[init_dim_index]}"
            )

print(printer: Printer)

Source code in xdsl/dialects/linalg.py
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
def print(self, printer: Printer):
    printer.print_string(" ins")
    with printer.in_parens():
        printer.print_ssa_value(self.input)
        printer.print_string(":")
        printer.print_attribute(self.input.type)
    printer.print_string(" outs")
    with printer.in_parens():
        printer.print_ssa_value(self.init)
        printer.print_string(":")
        printer.print_attribute(self.init.type)
    printer.print_string(" dimensions = ")
    with printer.in_square_brackets():
        printer.print_list(self.dimensions.get_values(), printer.print_int)

parse(parser: Parser) -> Self classmethod

Source code in xdsl/dialects/linalg.py
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
@classmethod
def parse(cls, parser: Parser) -> Self:
    parser.parse_characters("ins")
    parser.parse_punctuation("(")
    input = parser.parse_operand()
    parser.parse_punctuation(":")
    parser.parse_type()
    parser.parse_punctuation(")")
    parser.parse_characters("outs")
    parser.parse_punctuation("(")
    init = parser.parse_operand()
    parser.parse_punctuation(":")
    parser.parse_type()
    parser.parse_punctuation(")")
    parser.parse_keyword("dimensions")
    parser.parse_punctuation("=")
    dimensions = parser.parse_comma_separated_list(
        parser.Delimiter.SQUARE, parser.parse_integer
    )
    broadcast = cls(
        input,
        init,
        DenseArrayBase.from_list(i64, dimensions),
    )
    return broadcast

ReduceOp

Bases: IRDLOperation

Source code in xdsl/dialects/linalg.py
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
@irdl_op_definition
class ReduceOp(IRDLOperation):
    name = "linalg.reduce"

    input = operand_def(base(MemRefType) | base(AnyTensorType))
    init = operand_def(base(MemRefType) | base(AnyTensorType))
    result = var_result_def(AnyTensorType)

    region: Region = region_def("single_block")

    dimensions = prop_def(DenseArrayBase.constr(i64))

    def __init__(
        self,
        input: SSAValue,
        init: SSAValue,
        dimensions: Attribute,
        region: Region,
    ):
        if isa(init.type, TensorType):
            result = (init.type,)
        else:
            result = ()

        super().__init__(
            properties={
                "dimensions": dimensions,
            },
            operands=(input, init),
            regions=[region],
            result_types=[result],
        )

    def verify_(self) -> None:
        assert isinstance(input_type := self.input.type, TensorType | MemRefType)
        assert isinstance(init_type := self.init.type, TensorType | MemRefType)

        if input_type.get_element_type() != init_type.get_element_type():
            raise VerifyException(
                f"Reduction element types must be equal, but input is {input_type.get_element_type()} "
                f"and init is {init_type.get_element_type()}"
            )

        dimensions_shape = self.dimensions.get_values()
        input_shape = input_type.get_shape()
        init_shape = init_type.get_shape()

        if len(init_shape) != len(input_shape) - len(dimensions_shape):
            raise VerifyException(
                "Output rank must equal input rank minus number of dimensions being reduced over"
            )

        init_index = 0
        for input_index in range(len(input_shape)):
            if input_index not in dimensions_shape:
                if input_shape[input_index] != init_shape[init_index]:
                    raise VerifyException(
                        f"Non-reduced input dimension {input_index} must equal output dimension {init_index}"
                    )
                init_index += 1

    def print(self, printer: Printer):
        printer.print_string(" ins")
        with printer.in_parens():
            printer.print_ssa_value(self.input)
            printer.print_string(":")
            printer.print_attribute(self.input.type)
        printer.print_string(" outs")
        with printer.in_parens():
            printer.print_ssa_value(self.init)
            printer.print_string(":")
            printer.print_attribute(self.init.type)
        printer.print_string(" dimensions = ")
        with printer.in_square_brackets():
            printer.print_list(self.dimensions.get_values(), printer.print_int)
        printer.print_string("\n")
        with printer.in_parens():
            printer.print_list(self.region.blocks[0].args, printer.print_block_argument)
        printer.print_string(" ")
        printer.print_region(self.region, print_entry_block_args=False)

    @classmethod
    def parse(cls, parser: Parser) -> Self:
        parser.parse_characters("ins")
        parser.parse_punctuation("(")
        input = parser.parse_operand()
        parser.parse_punctuation(":")
        parser.parse_type()
        parser.parse_punctuation(")")
        parser.parse_characters("outs")
        parser.parse_punctuation("(")
        init = parser.parse_operand()
        parser.parse_punctuation(":")
        parser.parse_type()
        parser.parse_punctuation(")")
        parser.parse_keyword("dimensions")
        parser.parse_punctuation("=")
        dimensions = parser.parse_comma_separated_list(
            parser.Delimiter.SQUARE, parser.parse_integer
        )
        entry_args = parser.parse_comma_separated_list(
            parser.Delimiter.PAREN, parser.parse_argument
        )
        region = parser.parse_region(entry_args)
        reduction = cls(
            input,
            init,
            DenseArrayBase.from_list(i64, dimensions),
            region,
        )
        return reduction

name = 'linalg.reduce' class-attribute instance-attribute

input = operand_def(base(MemRefType) | base(AnyTensorType)) class-attribute instance-attribute

init = operand_def(base(MemRefType) | base(AnyTensorType)) class-attribute instance-attribute

result = var_result_def(AnyTensorType) class-attribute instance-attribute

region: Region = region_def('single_block') class-attribute instance-attribute

dimensions = prop_def(DenseArrayBase.constr(i64)) class-attribute instance-attribute

__init__(input: SSAValue, init: SSAValue, dimensions: Attribute, region: Region)

Source code in xdsl/dialects/linalg.py
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
def __init__(
    self,
    input: SSAValue,
    init: SSAValue,
    dimensions: Attribute,
    region: Region,
):
    if isa(init.type, TensorType):
        result = (init.type,)
    else:
        result = ()

    super().__init__(
        properties={
            "dimensions": dimensions,
        },
        operands=(input, init),
        regions=[region],
        result_types=[result],
    )

verify_() -> None

Source code in xdsl/dialects/linalg.py
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
def verify_(self) -> None:
    assert isinstance(input_type := self.input.type, TensorType | MemRefType)
    assert isinstance(init_type := self.init.type, TensorType | MemRefType)

    if input_type.get_element_type() != init_type.get_element_type():
        raise VerifyException(
            f"Reduction element types must be equal, but input is {input_type.get_element_type()} "
            f"and init is {init_type.get_element_type()}"
        )

    dimensions_shape = self.dimensions.get_values()
    input_shape = input_type.get_shape()
    init_shape = init_type.get_shape()

    if len(init_shape) != len(input_shape) - len(dimensions_shape):
        raise VerifyException(
            "Output rank must equal input rank minus number of dimensions being reduced over"
        )

    init_index = 0
    for input_index in range(len(input_shape)):
        if input_index not in dimensions_shape:
            if input_shape[input_index] != init_shape[init_index]:
                raise VerifyException(
                    f"Non-reduced input dimension {input_index} must equal output dimension {init_index}"
                )
            init_index += 1

print(printer: Printer)

Source code in xdsl/dialects/linalg.py
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
def print(self, printer: Printer):
    printer.print_string(" ins")
    with printer.in_parens():
        printer.print_ssa_value(self.input)
        printer.print_string(":")
        printer.print_attribute(self.input.type)
    printer.print_string(" outs")
    with printer.in_parens():
        printer.print_ssa_value(self.init)
        printer.print_string(":")
        printer.print_attribute(self.init.type)
    printer.print_string(" dimensions = ")
    with printer.in_square_brackets():
        printer.print_list(self.dimensions.get_values(), printer.print_int)
    printer.print_string("\n")
    with printer.in_parens():
        printer.print_list(self.region.blocks[0].args, printer.print_block_argument)
    printer.print_string(" ")
    printer.print_region(self.region, print_entry_block_args=False)

parse(parser: Parser) -> Self classmethod

Source code in xdsl/dialects/linalg.py
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
@classmethod
def parse(cls, parser: Parser) -> Self:
    parser.parse_characters("ins")
    parser.parse_punctuation("(")
    input = parser.parse_operand()
    parser.parse_punctuation(":")
    parser.parse_type()
    parser.parse_punctuation(")")
    parser.parse_characters("outs")
    parser.parse_punctuation("(")
    init = parser.parse_operand()
    parser.parse_punctuation(":")
    parser.parse_type()
    parser.parse_punctuation(")")
    parser.parse_keyword("dimensions")
    parser.parse_punctuation("=")
    dimensions = parser.parse_comma_separated_list(
        parser.Delimiter.SQUARE, parser.parse_integer
    )
    entry_args = parser.parse_comma_separated_list(
        parser.Delimiter.PAREN, parser.parse_argument
    )
    region = parser.parse_region(entry_args)
    reduction = cls(
        input,
        init,
        DenseArrayBase.from_list(i64, dimensions),
        region,
    )
    return reduction