446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921 | @irdl_op_definition
class GenericOp(IRDLOperation):
name = "memref_stream.generic"
inputs = var_operand_def()
"""
Pointers to memory buffers or streams to be operated on. The corresponding stride
pattern defines the order in which the elements of the input buffers will be read.
"""
outputs = var_operand_def(MemRefType.constr() | WritableStreamType.constr())
"""
Pointers to memory buffers or streams to be operated on. The corresponding stride
pattern defines the order in which the elements of the input buffers will be written
to.
"""
inits = var_operand_def()
"""
Initial values for outputs. The outputs are at corresponding `init_indices`. The
inits may be set only for the imperfectly nested form.
"""
indexing_maps = prop_def(ArrayAttr[AffineMapAttr])
"""
Stride patterns that define the order of the input and output streams.
Like in linalg.generic, the indexing maps corresponding to inputs are followed by
the indexing maps for the outputs.
"""
bounds = prop_def(ArrayAttr[IntegerAttr[IndexType]])
"""
The bounds of the iteration space, from the outermost loop inwards.
All indexing maps must have the same number of dimensions as the length of `bounds`.
"""
iterator_types = prop_def(ArrayAttr[IteratorTypeAttr])
init_indices = prop_def(ArrayAttr[IntAttr])
"""
Indices into the `outputs` that correspond to the initial values in `inits`.
"""
doc = opt_prop_def(StringAttr)
library_call = opt_prop_def(StringAttr)
body = region_def("single_block")
traits = traits_def(GenericOpHasCanonicalizationPatternsTrait())
irdl_options = (AttrSizedOperandSegments(as_property=True),)
def __init__(
self,
inputs: Sequence[SSAValue],
outputs: Sequence[SSAValue],
inits: Sequence[SSAValue],
body: Region,
indexing_maps: ArrayAttr[AffineMapAttr],
iterator_types: ArrayAttr[Attribute],
bounds: ArrayAttr[IntegerAttr[IndexType]],
init_indices: ArrayAttr[IntAttr],
doc: StringAttr | None = None,
library_call: StringAttr | None = None,
) -> None:
for m in indexing_maps:
if m.data.num_symbols:
raise NotImplementedError(
f"Symbols currently not implemented in {self.name} indexing maps"
)
super().__init__(
operands=[inputs, outputs, inits],
properties={
"bounds": bounds,
"init_indices": init_indices,
"indexing_maps": indexing_maps,
"iterator_types": iterator_types,
"doc": doc,
"library_call": library_call,
},
regions=[body],
)
def get_static_loop_ranges(
self,
) -> tuple[tuple[int, ...], tuple[int, ...]]:
"""
This operation can represent two sets of perfectly nested loops, or one.
If it is one, then the first element of the returned tuple has all the loop
bounds, and the second is empty.
If there are two, then the first element of the returned tuple has the outer
bounds, and the second the inner.
Interleaved iterators are not returned in either tuple.
"""
output_maps = self.indexing_maps.data[len(self.inputs) :]
# min_dims will equal len(self.iterator_types) in the perfect nest case
min_dims = min(m.data.num_dims for m in output_maps)
num_interleaved = sum(
it.data == IteratorType.INTERLEAVED for it in self.iterator_types
)
if num_interleaved:
res = (
tuple(
bound.value.data
for bound in self.bounds.data[: min_dims - num_interleaved]
),
tuple(
bound.value.data
for bound in self.bounds.data[
min_dims - num_interleaved : -num_interleaved
]
),
)
else:
res = (
tuple(bound.value.data for bound in self.bounds.data[:min_dims]),
tuple(
bound.value.data
for bound in self.bounds.data[min_dims - num_interleaved :]
),
)
return res
@property
def is_imperfectly_nested(self) -> bool:
return bool(self.get_static_loop_ranges()[1])
def _print_init(self, printer: Printer, init: SSAValue | None):
if init is None:
printer.print_string("None")
else:
printer.print_ssa_value(init)
printer.print_string(" : ")
printer.print_attribute(init.type)
def print(self, printer: Printer):
printer.print_string(" {")
with printer.indented():
if self.bounds:
printer.print_string("\nbounds = [")
with printer.indented():
printer.print_list(
self.bounds.data,
lambda bound: printer.print_string(f"{bound.value.data}"),
)
printer.print_string("],")
else:
printer.print_string("\nbounds = [],")
if self.indexing_maps:
printer.print_string("\nindexing_maps = [")
with printer.indented():
printer.print_list(
self.indexing_maps.data,
lambda m: printer.print_string(f"\n{m}"),
delimiter=",",
)
printer.print_string("\n],")
else:
printer.print_string("\nindexing_maps = [].")
printer.print_string("\niterator_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(",\ndoc = ")
printer.print_attribute(self.doc)
if self.library_call:
printer.print_string(",\nlibrary_call = ")
printer.print_attribute(self.library_call)
printer.print_string("\n}")
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 self.inits:
printer.print_string(" inits(")
inits: list[SSAValue | None] = [None] * len(self.outputs)
for i, val in zip(self.init_indices, self.inits):
inits[i.data] = val
printer.print_list(
inits,
lambda val: self._print_init(printer, val),
)
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)
@classmethod
def _parse_init(cls, parser: Parser) -> SSAValue | None:
if parser.parse_optional_characters("None"):
return None
unresolved = parser.parse_unresolved_operand()
parser.parse_punctuation(":")
type = parser.parse_type()
return parser.resolve_operand(unresolved, type)
@classmethod
def _parse_inits(
cls, parser: Parser
) -> tuple[tuple[SSAValue, ...], tuple[int, ...]]:
if not parser.parse_optional_characters("inits"):
return ((), ())
parser.parse_punctuation("(")
optional_inits = parser.parse_comma_separated_list(
Parser.Delimiter.NONE, lambda: cls._parse_init(parser)
)
parser.parse_punctuation(")")
enumerated_inits = tuple(
(i, val) for i, val in enumerate(optional_inits) if val is not None
)
inits = tuple(init for _, init in enumerated_inits)
init_indices = tuple(i for i, _ in enumerated_inits)
return (tuple(inits), init_indices)
@classmethod
def parse(cls, parser: Parser) -> Self:
attrs_start_pos = parser.pos
attrs = parser.parse_optional_attr_dict()
attrs_end_pos = parser.pos
if "bounds" in attrs:
bounds = attrs["bounds"]
assert isa(bounds, ArrayAttr[IntegerAttr[IntegerType | IndexType]]), bounds
index = IndexType()
bounds = ArrayAttr(
tuple(IntegerAttr(attr.value, index) for attr in bounds.data)
)
del attrs["bounds"]
else:
parser.raise_error(
"Expected bounds for memref_stream.generic",
attrs_start_pos,
attrs_end_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 memref_stream.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 memref_stream.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_types = ()
outs = ()
inits, init_indices = cls._parse_inits(parser)
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()
generic = cls(
ins,
outs,
inits,
body,
indexing_maps,
ArrayAttr(iterator_types),
bounds,
ArrayAttr(IntAttr(index) for index in init_indices),
doc,
library_call,
)
generic.attributes |= attrs
generic.attributes |= extra_attrs
return generic
def verify_(self) -> None:
if len(self.inits) != len(self.init_indices):
raise VerifyException(
f"Mismatching number of inits and init indices: {len(self.inits)} != {self.init_indices}"
)
# Parallel iterator types must preceed reduction iterators
iterator_types = self.iterator_types.data
num_parallel = iterator_types.count(IteratorTypeAttr.parallel())
num_reduction = iterator_types.count(IteratorTypeAttr.reduction())
num_interleaved = iterator_types.count(IteratorTypeAttr.interleaved())
if IteratorTypeAttr.parallel() in iterator_types[num_parallel:]:
raise VerifyException(
f"Unexpected order of iterator types: {[it.data.value for it in iterator_types]}"
)
if (
IteratorTypeAttr.reduction()
in iterator_types[num_parallel + num_reduction :]
):
raise VerifyException(
f"Unexpected order of iterator types: {[it.data.value for it in iterator_types]}"
)
if num_interleaved > 1:
raise VerifyException(f"Too many interleaved bounds: {num_interleaved}")
assert num_parallel + num_reduction + num_interleaved == len(iterator_types)
if len(self.inputs) + len(self.outputs) != len(self.indexing_maps):
raise VerifyException(
"The number of affine maps must match the number of inputs and outputs"
)
# Whether or not the operation represents an imperfect loop nest, verify that the
# bounds of the outer + inner nests match the domain of the input affine maps
input_count = len(self.inputs)
input_maps = self.indexing_maps.data[:input_count]
for i, m in enumerate(input_maps):
if len(iterator_types) != m.data.num_dims:
raise VerifyException(f"Invalid number of dims in indexing map {i}")
# If the operation represents an imperfect loop nest, the bounds must match the
# number of parallel iterators; otherwise they must match the total number of
# iterators. In either case, they must all be the same.
output_count = len(self.outputs)
output_maps = self.indexing_maps.data[input_count:]
min_dims = min(m.data.num_dims for m in output_maps)
max_dims = max(m.data.num_dims for m in output_maps)
if min_dims != max_dims:
raise VerifyException(
"The number of dims in output indexing maps must all be the same"
)
if min_dims not in (len(iterator_types), num_parallel + num_interleaved):
# To signify that the output is imperfectly nested, the output affine map has
# as many dims as parallel iterators. Otherwise, it has as many dims as
# the total number of iterators.
raise VerifyException(
"The number of dims in output indexing maps must be "
f"{len(iterator_types)} or {num_parallel + num_interleaved}"
)
if len(self.init_indices) != len(self.inits):
raise VerifyException(
"The number of inits and init_indices must be the same"
)
# The values of the inits must correspond to outputs where the domain of the
# affine map has the same number of dimensions as the number of parallel
# iterators.
num_outputs = len(self.outputs)
output_maps = self.indexing_maps.data[-num_outputs:]
for index in self.init_indices:
if not (0 <= index.data <= num_outputs):
raise VerifyException(f"Init index out of bounds: {index.data}")
m = output_maps[index.data]
if m.data.num_dims != (num_parallel + num_interleaved):
raise VerifyException(
"Incompatible affine map and initial value for output at index "
f"{index}"
)
interleave_factor = self.bounds.data[-1].value.data if num_interleaved else 1
# If the operation is interleaved, use the interleaving factor to check
# the number of arguments
init_count = len(self.inits)
# Outputs with initial values correspond to accumulators in the presence of
# reduction
acc_count = output_count if num_reduction else (output_count - init_count)
expected_block_arg_count = (input_count + acc_count) * interleave_factor
if expected_block_arg_count != len(self.body.block.args):
raise VerifyException(
f"Invalid number of arguments in block ({len(self.body.block.args)}), expected {expected_block_arg_count}"
)
|