forked from triton-lang/triton
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtriton.cc
More file actions
2081 lines (1994 loc) · 88.1 KB
/
triton.cc
File metadata and controls
2081 lines (1994 loc) · 88.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
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
922
923
924
925
926
927
928
929
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
992
993
994
995
996
997
998
999
1000
#include <mutex>
#include <stack>
#include <unordered_map>
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/Verifier.h"
#include "mlir/Bytecode/BytecodeWriter.h"
#include "mlir/Conversion/Passes.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Pass/PassManager.h"
#include "mlir/Transforms/Passes.h"
#include "mlir/Parser/Parser.h"
#include "mlir/Support/FileUtilities.h"
#include "mlir/Dialect/ControlFlow/IR/ControlFlow.h"
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
#include "mlir/Dialect/Index/IR/IndexDialect.h"
#include "mlir/Dialect/Index/IR/IndexOps.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "triton/Analysis/Allocation.h"
#include "triton/Conversion/NVGPUToLLVM/NVGPUToLLVMPass.h"
#include "triton/Conversion/TritonGPUToLLVM/TritonGPUToLLVMPass.h"
#include "triton/Conversion/TritonToTritonGPU/TritonToTritonGPUPass.h"
#include "triton/Dialect/NVGPU/IR/Dialect.h"
#include "triton/Dialect/Triton/IR/Dialect.h"
#include "triton/Dialect/Triton/IR/Types.h"
#include "triton/Dialect/Triton/Transforms/Passes.h"
#include "triton/Dialect/TritonGPU/Transforms/Passes.h"
#include "triton/Dialect/TritonNvidiaGPU/IR/Dialect.h"
#include "triton/Dialect/TritonNvidiaGPU/Transforms/Passes.h"
#include "triton/Target/LLVMIR/LLVMIRTranslation.h"
#include "triton/Target/PTX/PTXTranslation.h"
#include "triton/Target/PTX/TmaMetadata.h"
#include "triton/Tools/Sys/GetEnv.hpp"
#include "triton/Tools/Sys/GetPlatform.hpp"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/FileUtilities.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SourceMgr.h"
#include <Python.h>
#include <cctype>
#include <fstream>
#include <optional>
#include <pybind11/buffer_info.h>
#include <pybind11/embed.h>
#include <pybind11/functional.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>
#include <regex>
#include <signal.h>
#include <sstream>
#include <stdexcept>
#include <string>
#include <pybind11/numpy.h>
namespace py = pybind11;
using namespace mlir;
PYBIND11_MAKE_OPAQUE(mlir::triton::gpu::TMAMetadataTy);
enum backend_t {
HOST,
CUDA,
ROCM,
};
void init_triton_runtime(py::module &&m) {
// wrap backend_t
py::enum_<backend_t>(m, "backend", py::module_local())
.value("HOST", HOST)
.value("CUDA", CUDA)
.value("ROCM", ROCM)
.export_values();
py::enum_<mlir::triton::Target>(m, "TARGET")
.value("NVVM", mlir::triton::NVVM)
.value("ROCDL", mlir::triton::ROCDL)
.export_values();
}
// A custom op builder that keeps track of the last location
class TritonOpBuilder {
public:
TritonOpBuilder(mlir::MLIRContext *context) {
builder = std::make_unique<mlir::OpBuilder>(context);
lastLoc = std::make_unique<mlir::Location>(builder->getUnknownLoc());
}
mlir::OpBuilder &getBuilder() { return *builder; }
bool isLineInfoEnabled() { return lineInfoEnabled; }
void setLastLoc(mlir::Location loc) {
if (lineInfoEnabled)
lastLoc = std::make_unique<mlir::Location>(loc);
}
void setLastLoc(const std::string &fileName, int line, int column) {
auto context = builder->getContext();
setLastLoc(mlir::FileLineColLoc::get(context, fileName, line, column));
}
mlir::Location getLastLoc() {
assert(lastLoc);
return *lastLoc;
}
void setInsertionPointToStart(mlir::Block &block) {
if (!block.empty())
setLastLoc(block.begin()->getLoc());
else
setLastLoc(builder->getUnknownLoc());
builder->setInsertionPointToStart(&block);
}
void setInsertionPointToEnd(mlir::Block &block) {
if (!block.empty())
setLastLoc(block.back().getLoc());
else
setLastLoc(builder->getUnknownLoc());
builder->setInsertionPointToEnd(&block);
}
void setInsertionPointAfter(mlir::Operation &op) {
setLastLoc(op.getLoc());
builder->setInsertionPointAfter(&op);
}
void restoreInsertionPoint(mlir::OpBuilder::InsertPoint pt) {
if (pt.isSet() && pt.getPoint() != pt.getBlock()->end())
setLastLoc(pt.getPoint()->getLoc());
else
setLastLoc(builder->getUnknownLoc());
builder->restoreInsertionPoint(pt);
}
template <typename OpTy, typename... Args> OpTy create(Args &&...args) {
auto loc = getLastLoc();
return builder->create<OpTy>(loc, std::forward<Args>(args)...);
}
// Overload to create or fold a single result operation.
template <typename OpTy, typename... Args>
std::enable_if_t<OpTy::template hasTrait<mlir::OpTrait::OneResult>(),
mlir::Value>
createOrFold(Args &&...args) {
auto loc = getLastLoc();
return builder->createOrFold<OpTy>(loc, std::forward<Args>(args)...);
}
// Overload to create or fold a zero result operation.
template <typename OpTy, typename... Args>
std::enable_if_t<OpTy::template hasTrait<mlir::OpTrait::ZeroResults>(), OpTy>
createOrFold(Args &&...args) {
auto loc = getLastLoc();
return builder->createOrFold<OpTy>(loc, std::forward<Args>(args)...);
}
private:
std::unique_ptr<mlir::OpBuilder> builder;
std::unique_ptr<mlir::Location> lastLoc;
bool lineInfoEnabled = !::triton::tools::getBoolEnv("TRITON_DISABLE_LINE_INFO");
};
static std::string locationToString(mlir::Location loc) {
std::string str;
llvm::raw_string_ostream os(str);
loc.print(os);
os.flush(); // Make sure all the content is dumped into the 'str' string
return str;
}
static void outputWarning(mlir::Location loc, const std::string &msg) {
std::string locStr = locationToString(loc);
PyErr_WarnEx(PyExc_UserWarning, (locStr + ": " + msg).c_str(),
/*stack_level=*/2);
}
/*****************************************************************************/
/* Python bindings for triton::ir */
/*****************************************************************************/
void init_triton_ir(py::module &&m) {
using ret = py::return_value_policy;
using namespace pybind11::literals;
py::enum_<mlir::triton::PaddingOption>(m, "PADDING_OPTION",
py::module_local())
.value("PAD_ZERO", mlir::triton::PaddingOption::PAD_ZERO)
.value("PAD_NAN", mlir::triton::PaddingOption::PAD_NAN)
.export_values();
py::enum_<mlir::triton::CacheModifier>(m, "CACHE_MODIFIER",
py::module_local())
.value("NONE", mlir::triton::CacheModifier::NONE)
.value("CA", mlir::triton::CacheModifier::CA)
.value("CG", mlir::triton::CacheModifier::CG)
.value("WB", mlir::triton::CacheModifier::WB)
.value("CS", mlir::triton::CacheModifier::CS)
.value("WT", mlir::triton::CacheModifier::WT)
.export_values();
py::enum_<mlir::triton::MemSemantic>(m, "MEM_SEMANTIC", py::module_local())
.value("ACQUIRE_RELEASE", mlir::triton::MemSemantic::ACQUIRE_RELEASE)
.value("ACQUIRE", mlir::triton::MemSemantic::ACQUIRE)
.value("RELEASE", mlir::triton::MemSemantic::RELEASE)
.value("RELAXED", mlir::triton::MemSemantic::RELAXED)
.export_values();
py::enum_<mlir::triton::MemSyncScope>(m, "MEM_SYNC_SCOPE", py::module_local())
.value("GPU", mlir::triton::MemSyncScope::GPU)
.value("CTA", mlir::triton::MemSyncScope::CTA)
.value("SYSTEM", mlir::triton::MemSyncScope::SYSTEM)
.export_values();
py::enum_<mlir::triton::EvictionPolicy>(m, "EVICTION_POLICY",
py::module_local())
.value("NORMAL", mlir::triton::EvictionPolicy::NORMAL)
.value("EVICT_FIRST", mlir::triton::EvictionPolicy::EVICT_FIRST)
.value("EVICT_LAST", mlir::triton::EvictionPolicy::EVICT_LAST)
.export_values();
py::enum_<mlir::triton::RMWOp>(m, "ATOMIC_OP", py::module_local())
.value("ADD", mlir::triton::RMWOp::ADD)
.value("FADD", mlir::triton::RMWOp::FADD)
.value("AND", mlir::triton::RMWOp::AND)
.value("OR", mlir::triton::RMWOp::OR)
.value("XOR", mlir::triton::RMWOp::XOR)
.value("XCHG", mlir::triton::RMWOp::XCHG)
.value("MAX", mlir::triton::RMWOp::MAX)
.value("MIN", mlir::triton::RMWOp::MIN)
.value("UMIN", mlir::triton::RMWOp::UMIN)
.value("UMAX", mlir::triton::RMWOp::UMAX);
py::class_<mlir::MLIRContext>(m, "context", py::module_local())
.def(py::init<>())
.def("load_triton", [](mlir::MLIRContext &self) {
self.getOrLoadDialect<mlir::triton::TritonDialect>();
self.getOrLoadDialect<mlir::index::IndexDialect>();
self.getOrLoadDialect<mlir::triton::TritonDialect>();
self.getOrLoadDialect<mlir::gpu::GPUDialect>();
// we load LLVM because the frontend uses LLVM.undef for
// some placeholders
self.getOrLoadDialect<mlir::LLVM::LLVMDialect>();
self.getOrLoadDialect<mlir::tensor::TensorDialect>();
});
// .def(py::init([](){
// mlir::MLIRContext context;
// context.getOrLoadDialect<mlir::triton.TritonDialect>();
// // TODO: should we return a (raw/unique) pointer here?
// return context;
// }));
// py::class_<ir::value>(m, "value")
// .def("multiple_of", [](ir::value *self, int val) {
// if (auto *instr = dynamic_cast<ir::instruction*>(self)) {
// instr->set_metadata(ir::metadata::multiple_of, val);
// } else
// throw std::runtime_error("multiple_of");
// })
// .def("max_contiguous", [](ir::value *self, int val) {
// if (auto *instr = dynamic_cast<ir::instruction*>(self)) {
// instr->set_metadata(ir::metadata::max_contiguous, val);
// } else
// throw std::runtime_error("max_contiguous");
// })
// .def("set_fdiv_ieee_rounding", [](ir::value *self, bool val) {
// if (auto *instr = dynamic_cast<ir::binary_operator*>(self))
// instr->set_fdiv_ieee_rounding(val);
// else
// throw std::runtime_error("set_fdiv_ieee_rounding");
// })
// .def("ops", [](ir::value *self) {
// if (auto *instr = dynamic_cast<ir::instruction*>(self)) {
// return instr->ops();
// }
// throw std::runtime_error("cannot use ops()");
// })
// .def("replace_all_uses_with", &ir::value::replace_all_uses_with)
// .def("erase_from_parent", [](ir::value *self) {
// if (auto *instr = dynamic_cast<ir::instruction*>(self))
// return instr->erase_from_parent();
// throw std::runtime_error("cannot use erase_from_parent");
// })
// .def_property("name", &ir::value::get_name, &ir::value::set_name)
// .def_property_readonly("type", &ir::value::get_type);
// // // Do we need under in TritonIR ?
// // py::class_<ir::undef_value, ir::constant>(m, "undef")
// // .def("get", &ir::undef_value::get, ret::reference);
py::class_<mlir::Type>(m, "type", py::module_local())
.def("is_integer", &mlir::Type::isInteger)
.def("is_fp16", &mlir::Type::isF16)
.def("__str__", [](mlir::Type &self) {
std::string str;
llvm::raw_string_ostream os(str);
self.print(os);
return os.str();
});
py::class_<mlir::FunctionType>(m, "function_type", py::module_local())
.def("param_types", [](mlir::FunctionType &self) {
return std::vector<mlir::Type>(self.getInputs().begin(),
self.getInputs().end());
});
py::class_<mlir::Location>(m, "location", py::module_local())
.def("__str__", [](mlir::Location &self) {
std::string str;
llvm::raw_string_ostream os(str);
self.print(os);
return os.str();
});
py::class_<mlir::Value>(m, "value", py::module_local())
.def("set_attr",
[](mlir::Value &self, std::string &name,
mlir::Attribute &attr) -> void {
if (mlir::Operation *definingOp = self.getDefiningOp())
definingOp->setAttr(name, attr);
else {
auto arg = self.cast<mlir::BlockArgument>();
int id = arg.getArgNumber();
std::string attrName = name + "_arg" + std::to_string(id);
mlir::Block *owner = arg.getOwner();
if (owner->isEntryBlock() &&
!mlir::isa<mlir::triton::FuncOp>(owner->getParentOp())) {
owner->getParentOp()->setAttr(attrName, attr);
}
}
})
.def("get_context", &mlir::Value::getContext)
.def("replace_all_uses_with",
[](mlir::Value &self, mlir::Value &newValue) {
self.replaceAllUsesWith(newValue);
})
.def("get_type", &mlir::Value::getType)
.def("id", [](Value &self) {
// The Value is identified by and compared with
// other Values via the underlying ValueImpl
return (uint64_t)self.getImpl();
});
py::class_<OpResult, Value>(m, "op_result", py::module_local());
py::class_<mlir::BlockArgument, mlir::Value>(m, "block_argument",
py::module_local());
py::class_<mlir::Region>(m, "region", py::module_local())
.def("get_parent_region", &mlir::Region::getParentRegion, ret::reference)
.def("size", [](mlir::Region &self) { return self.getBlocks().size(); })
.def("empty", &mlir::Region::empty)
.def("id", [](Region &self) { return (uint64_t)&self; });
py::class_<mlir::Block>(m, "block", py::module_local())
.def("arg",
[](mlir::Block &self, int index) -> mlir::BlockArgument {
return self.getArgument(index);
})
.def("add_argument",
[](mlir::Block &self, mlir::Type ty) {
auto loc = mlir::UnknownLoc::get(ty.getContext());
self.addArgument(ty, loc);
})
.def("get_num_arguments", &mlir::Block::getNumArguments)
.def("get_argument", &Block::getArgument)
.def("dump", &mlir::Block::dump)
.def("move_before", &mlir::Block::moveBefore)
.def("insert_before", &mlir::Block::insertBefore)
.def("get_parent", &mlir::Block::getParent, ret::reference)
.def("merge_block_before",
[](mlir::Block &self, mlir::Block &dst) {
// ref: RewriterBase::mergeBlocks()
if (self.getNumArguments() != 0)
throw std::runtime_error(
"This block has arguments, don't merge");
dst.getOperations().splice(dst.begin(), self.getOperations());
self.dropAllUses();
self.erase();
})
.def("replace_use_in_block_with",
[](mlir::Block &self, mlir::Value &v, mlir::Value &newVal) {
v.replaceUsesWithIf(newVal, [&](mlir::OpOperand &operand) {
mlir::Operation *user = operand.getOwner();
mlir::Block *currentBlock = user->getBlock();
while (currentBlock) {
if (currentBlock == &self)
return true;
// Move up one level
currentBlock =
currentBlock->getParent()->getParentOp()->getBlock();
}
return false;
});
})
.def("__str__",
[](mlir::Block &self) {
std::string str;
llvm::raw_string_ostream os(str);
self.print(os);
return str;
})
.def("has_terminator",
[](mlir::Block &self) {
return !self.empty() &&
self.back().hasTrait<mlir::OpTrait::IsTerminator>();
})
.def("has_return",
[](mlir::Block &self) {
return !self.empty() &&
self.back().hasTrait<mlir::OpTrait::ReturnLike>();
})
.def("erase", [](mlir::Block &self) { self.erase(); })
.def("id", [](Block &self) { return (uint64_t)&self; });
// using eattr = ir::attribute_kind_t;
// py::enum_<eattr>(m, "attribute_kind")
// .value("readonly", eattr::readonly)
// .value("writeonly", eattr::writeonly)
// .value("noalias", eattr::noalias)
// .value("aligned", eattr::aligned)
// .value("multiple_of", eattr::multiple_of)
// .value("retune", eattr::retune)
// .value("not_implemented", eattr::not_implemented);
py::class_<mlir::Attribute>(m, "attribute", py::module_local());
py::class_<mlir::IntegerAttr, mlir::Attribute>(m, "integer_attr",
py::module_local());
py::class_<mlir::BoolAttr, mlir::Attribute>(m, "bool_attr",
py::module_local());
// Ops
py::class_<mlir::OpState>(m, "OpState", py::module_local())
.def("set_attr",
[](mlir::OpState &self, std::string &name,
mlir::Attribute &attr) -> void { self->setAttr(name, attr); })
.def(
"get_num_results",
[](mlir::OpState &self) -> unsigned { return self->getNumResults(); })
.def("get_result",
[](mlir::OpState &self, unsigned idx) -> mlir::Value {
return self->getResult(idx);
})
.def(
"get_region",
[](mlir::OpState &self, unsigned idx) -> mlir::Region & {
return self->getRegion(idx);
},
ret::reference)
.def(
"get_body",
[](mlir::scf::ForOp &self, unsigned idx) -> mlir::Block * {
return self.getBody(idx);
},
ret::reference)
.def("dump", [](mlir::OpState &self) { self->dump(); })
.def("__str__",
[](mlir::OpState &self) -> std::string {
std::string str;
llvm::raw_string_ostream os(str);
auto printingFlags = mlir::OpPrintingFlags();
printingFlags.enableDebugInfo();
self->print(os, printingFlags);
return str;
})
.def("append_operand",
[](mlir::OpState &self, mlir::Value &val) {
self->insertOperands(self->getNumOperands(), val);
})
.def("verify", [](mlir::OpState &self) -> bool {
return mlir::succeeded(mlir::verify(self.getOperation()));
});
// scf Ops
py::class_<mlir::scf::ForOp, mlir::OpState>(m, "ForOp", py::module_local())
.def("get_induction_var", &mlir::scf::ForOp::getInductionVar);
py::class_<mlir::scf::IfOp, mlir::OpState>(m, "IfOp", py::module_local())
.def("get_then_block", &mlir::scf::IfOp::thenBlock, ret::reference)
.def("get_else_block", &mlir::scf::IfOp::elseBlock, ret::reference)
.def("get_then_yield", &mlir::scf::IfOp::thenYield)
.def("get_else_yield", &mlir::scf::IfOp::elseYield);
py::class_<mlir::scf::YieldOp, mlir::OpState>(m, "YieldOp",
py::module_local());
py::class_<mlir::scf::WhileOp, mlir::OpState>(m, "WhileOp",
py::module_local())
.def("get_before", &mlir::scf::WhileOp::getBefore, ret::reference)
.def("get_after", &mlir::scf::WhileOp::getAfter, ret::reference);
py::class_<mlir::scf::ConditionOp, mlir::OpState>(m, "ConditionOp",
py::module_local());
py::class_<Operation, std::unique_ptr<Operation, py::nodelete>>(
m, "operation", py::module_local())
.def("get_name",
[](Operation &self) {
llvm::StringRef opName = self.getName().getStringRef();
return opName.str();
})
.def("get_num_operands", &Operation::getNumOperands)
.def("get_operand", &Operation::getOperand)
.def("get_num_results", &Operation::getNumResults)
.def("get_result", &Operation::getResult)
.def("get_num_regions", &Operation::getNumRegions)
.def("get_region", &Operation::getRegion, ret::reference)
.def("get_block", &Operation::getBlock, ret::reference)
.def("get_str_attr",
[](Operation &self, const std::string &name) -> py::object {
auto ret = self.getAttrOfType<StringAttr>(name);
if (!ret)
return py::none();
return py::str(ret.getValue().str());
})
.def("get_flat_symbol_ref_attr",
[](Operation &self, const std::string &name) -> py::object {
auto ret = self.getAttrOfType<FlatSymbolRefAttr>(name);
if (!ret)
return py::none();
return py::str(ret.getValue().str());
});
// dynamic_attr is used to transfer ownership of the MLIR context to the
// module
py::class_<mlir::ModuleOp, mlir::OpState>(m, "module", py::module_local(),
py::dynamic_attr())
.def("dump", &mlir::ModuleOp::dump)
.def("str",
[](mlir::ModuleOp &self) -> std::string {
std::string str;
llvm::raw_string_ostream os(str);
auto printingFlags = mlir::OpPrintingFlags();
printingFlags.enableDebugInfo();
self.print(os, printingFlags);
return str;
})
.def("bytecode",
[](mlir::ModuleOp &self) -> py::bytearray {
std::string bytecode;
llvm::raw_string_ostream os(bytecode);
if (failed(mlir::writeBytecodeToFile(self, os)))
throw std::runtime_error("Failed to write module bytecode");
return py::bytearray(bytecode);
})
.def("push_back",
[](mlir::ModuleOp &self, mlir::triton::FuncOp &funcOp) -> void {
self.push_back(funcOp);
})
.def("has_function",
[](mlir::ModuleOp &self, std::string &funcName) -> bool {
if (self.lookupSymbol(funcName))
return true;
return false;
})
.def("get_function",
[](mlir::ModuleOp &self,
std::string &funcName) -> mlir::triton::FuncOp {
return self.lookupSymbol<mlir::triton::FuncOp>(funcName);
})
.def("get_single_function",
[](mlir::ModuleOp &self) -> mlir::triton::FuncOp {
llvm::SmallVector<mlir::triton::FuncOp> funcs;
self.walk(
[&](mlir::triton::FuncOp func) { funcs.push_back(func); });
if (funcs.size() != 1)
throw std::runtime_error("Expected a single function");
return funcs[0];
})
.def("get_int_attr",
[](ModuleOp &self, std::string name) -> py::object {
auto ret = self->getAttrOfType<IntegerAttr>(name);
if (!ret)
return py::none();
return py::int_(ret.getInt());
})
.def("walk",
[](ModuleOp &self, const std::function<void(Operation *)> &fn) {
self.walk(fn);
});
m.def("make_attr",
[](const std::vector<int> &values, mlir::MLIRContext &context) {
return mlir::DenseIntElementsAttr::get(
mlir::RankedTensorType::get(
{static_cast<int64_t>(values.size())},
mlir::IntegerType::get(&context, 32)),
values)
.cast<mlir::Attribute>();
});
m.def(
"parse_mlir_module",
[](const std::string &inputFilename, mlir::MLIRContext &context) {
// initialize registry
// note: we initialize llvm for undef
mlir::DialectRegistry registry;
registry.insert<
mlir::triton::TritonDialect, mlir::triton::gpu::TritonGPUDialect,
mlir::triton::nvidia_gpu::TritonNvidiaGPUDialect,
mlir::triton::nvgpu::NVGPUDialect, mlir::math::MathDialect,
mlir::arith::ArithDialect, mlir::index::IndexDialect,
mlir::scf::SCFDialect, mlir::cf::ControlFlowDialect,
mlir::LLVM::LLVMDialect>();
context.appendDialectRegistry(registry);
context.loadAllAvailableDialects();
// parse module
mlir::OwningOpRef<mlir::ModuleOp> module =
mlir::parseSourceFile<mlir::ModuleOp>(inputFilename, &context);
if (!module)
throw std::runtime_error("Parse MLIR file failed.");
// locations are incompatible with ptx < 7.5 !
module->walk([](mlir::Operation *op) {
op->setLoc(mlir::UnknownLoc::get(op->getContext()));
});
return module->clone();
},
ret::take_ownership);
py::class_<mlir::triton::FuncOp, mlir::OpState>(m, "function",
py::module_local())
// .def_property_readonly("attrs", &ir::function::attrs)
// .def("add_attr", &ir::function::add_attr);
.def("args",
[](mlir::triton::FuncOp &self, unsigned idx) -> mlir::BlockArgument {
return self.getArgument(idx);
})
.def(
"add_entry_block",
[](mlir::triton::FuncOp &self) -> mlir::Block * {
return self.addEntryBlock();
},
ret::reference)
.def(
"set_arg_attr",
[](mlir::triton::FuncOp &self, int arg_no, const std::string &name,
int val) {
// set arg attributes "name" to value "val"
auto attrTy = mlir::IntegerType::get(self.getContext(), 32);
self.setArgAttr(arg_no, name, mlir::IntegerAttr::get(attrTy, val));
},
ret::reference)
.def("finalize",
[](mlir::triton::FuncOp &self) -> void {
// Remove dead code
// 1. Unreachable code after return
self.walk([&](mlir::Block *block) {
mlir::Operation *retOp = nullptr;
// It's better to not use walk here because we only want to
// check operations in the current block
for (auto &op : block->getOperations()) {
if (mlir::isa<mlir::triton::ReturnOp>(op))
if (retOp == nullptr) {
retOp = &op;
break;
}
}
if (retOp && retOp != &block->back()) {
auto pos = retOp->getIterator();
pos++;
auto *newBlock = block->splitBlock(pos);
newBlock->erase();
}
});
// 2. Check if the result of tl.advance is used
self.walk([&](mlir::Operation *op) {
if (mlir::isa<mlir::triton::AdvanceOp>(op) &&
op->getResult(0).use_empty())
outputWarning(op->getLoc(), "The result of tl.advance is not "
"being used. Note that tl.advance "
"does not have any side effects. "
"To move the block pointer, you "
"need to assign the result of "
"tl.advance to a variable.");
});
})
.def_property_readonly("type", &mlir::triton::FuncOp::getFunctionType)
.def("reset_type", &mlir::triton::FuncOp::setType);
py::class_<mlir::OpBuilder::InsertPoint>(m, "InsertPoint",
py::module_local());
py::class_<TritonOpBuilder>(m, "builder", py::module_local(),
py::dynamic_attr())
.def(py::init<mlir::MLIRContext *>())
// getters
.def("create_module",
[](TritonOpBuilder &self) -> mlir::ModuleOp {
return self.create<mlir::ModuleOp>();
})
// insertion block/point
.def("set_insertion_point_to_start",
[](TritonOpBuilder &self, mlir::Block &block) -> void {
self.setInsertionPointToStart(block);
})
.def("set_insertion_point_to_end",
[](TritonOpBuilder &self, mlir::Block &block) {
self.setInsertionPointToEnd(block);
})
.def("set_insertion_point_after",
[](TritonOpBuilder &self, mlir::Operation &op) {
self.setInsertionPointAfter(op);
})
.def(
"get_insertion_block",
[](TritonOpBuilder &self) -> mlir::Block * {
return self.getBuilder().getInsertionBlock();
},
ret::reference)
.def("get_insertion_point",
[](TritonOpBuilder &self) {
return self.getBuilder().saveInsertionPoint();
})
.def("restore_insertion_point",
[](TritonOpBuilder &self, mlir::OpBuilder::InsertPoint pt) {
self.restoreInsertionPoint(pt);
})
// Attr
.def("get_bool_attr",
[](TritonOpBuilder &self, bool value) {
return self.getBuilder().getBoolAttr(value);
})
.def("get_int32_attr",
[](TritonOpBuilder &self, int32_t value) {
return self.getBuilder().getI32IntegerAttr(value);
})
// Use arith.ConstantOp to create constants
// Constants
.def("get_int1",
[](TritonOpBuilder &self, bool v) -> mlir::Value {
return mlir::Value(self.create<mlir::arith::ConstantIntOp>(
v, self.getBuilder().getI1Type()));
})
.def("get_int8",
[](TritonOpBuilder &self, int64_t v) -> mlir::Value {
return mlir::Value(self.create<mlir::arith::ConstantIntOp>(
v, self.getBuilder().getI8Type()));
})
.def("get_int16",
[](TritonOpBuilder &self, int64_t v) -> mlir::Value {
return mlir::Value(self.create<mlir::arith::ConstantIntOp>(
v, self.getBuilder().getI16Type()));
})
.def("get_int32",
[](TritonOpBuilder &self, int64_t v) -> mlir::Value {
return mlir::Value(self.create<mlir::arith::ConstantIntOp>(
v, self.getBuilder().getI32Type()));
})
.def("get_int64",
[](TritonOpBuilder &self, int64_t v) -> mlir::Value {
return mlir::Value(self.create<mlir::arith::ConstantIntOp>(
v, self.getBuilder().getI64Type()));
})
.def("get_uint8",
[](TritonOpBuilder &self, uint64_t v) -> mlir::Value {
return mlir::Value(self.create<mlir::arith::ConstantIntOp>(
v, self.getBuilder().getI8Type()));
})
.def("get_uint16",
[](TritonOpBuilder &self, uint64_t v) -> mlir::Value {
return mlir::Value(self.create<mlir::arith::ConstantIntOp>(
v, self.getBuilder().getI16Type()));
})
.def("get_uint32",
[](TritonOpBuilder &self, uint64_t v) -> mlir::Value {
return mlir::Value(self.create<mlir::arith::ConstantIntOp>(
v, self.getBuilder().getI32Type()));
})
.def("get_uint64",
[](TritonOpBuilder &self, uint64_t v) -> mlir::Value {
return mlir::Value(self.create<mlir::arith::ConstantIntOp>(
v, self.getBuilder().getI64Type()));
})
.def("get_bf16",
[](TritonOpBuilder &self, float v) -> mlir::Value {
auto type = self.getBuilder().getBF16Type();
return self.create<mlir::arith::ConstantFloatOp>(
mlir::APFloat(type.getFloatSemantics(), std::to_string(v)),
type);
})
.def("get_fp16",
[](TritonOpBuilder &self, float v) -> mlir::Value {
return self.create<mlir::arith::ConstantOp>(
self.getBuilder().getF16FloatAttr(v));
})
.def("get_fp32",
[](TritonOpBuilder &self, float v) -> mlir::Value {
return self.create<mlir::arith::ConstantOp>(
self.getBuilder().getF32FloatAttr(v));
})
.def("get_fp64",
[](TritonOpBuilder &self, double v) -> mlir::Value {
return self.create<mlir::arith::ConstantOp>(
self.getBuilder().getF64FloatAttr(v));
})
.def("get_null_value",
[](TritonOpBuilder &self, mlir::Type type) -> mlir::Value {
if (auto floatTy = type.dyn_cast<mlir::FloatType>())
return self.create<mlir::arith::ConstantFloatOp>(
mlir::APFloat(floatTy.getFloatSemantics(), 0), floatTy);
else if (auto intTy = type.dyn_cast<mlir::IntegerType>())
return self.create<mlir::arith::ConstantIntOp>(0, intTy);
else
throw std::runtime_error("Not implemented");
})
.def("get_all_ones_value",
[](TritonOpBuilder &self, mlir::Type type) -> mlir::Value {
uint64_t val = 0xFFFFFFFFFFFFFFFF;
if (auto intTy = type.dyn_cast<mlir::IntegerType>())
return self.create<mlir::arith::ConstantIntOp>(val, intTy);
else
throw std::runtime_error("Not implemented");
})
// Types
.def("get_void_ty",
[](TritonOpBuilder &self) -> mlir::Type {
return self.getBuilder().getNoneType();
})
.def("get_int1_ty",
[](TritonOpBuilder &self) -> mlir::Type {
return self.getBuilder().getI1Type();
}) // or ret::copy?
.def("get_int8_ty",
[](TritonOpBuilder &self) -> mlir::Type {
return self.getBuilder().getI8Type();
})
.def("get_int16_ty",
[](TritonOpBuilder &self) -> mlir::Type {
return self.getBuilder().getType<mlir::IntegerType>(16);
})
.def("get_int32_ty",
[](TritonOpBuilder &self) -> mlir::Type {
return self.getBuilder().getI32Type();
})
.def("get_int64_ty",
[](TritonOpBuilder &self) -> mlir::Type {
return self.getBuilder().getI64Type();
})
.def("get_fp8e4nv_ty",
[](TritonOpBuilder &self) -> mlir::Type {
return self.getBuilder().getType<mlir::Float8E4M3FNUZType>();
})
.def("get_fp8e4b15_ty",
[](TritonOpBuilder &self) -> mlir::Type {
// TODO: upstream FP8E4B15 into MLIR, or find a way to externally
// have a float-like type compatible with float only native ops
return self.getBuilder().getType<mlir::Float8E4M3B11FNUZType>();
})
.def("get_fp8e4b15x4_ty",
[](TritonOpBuilder &self) -> mlir::Type {
// TODO: upstream FP8E4B15 into MLIR, or find a way to externally
// have a float-like type compatible with float only native ops
return self.getBuilder().getType<mlir::Float8E4M3FNType>();
})
.def("get_fp8e5_ty",
[](TritonOpBuilder &self) -> mlir::Type {
return self.getBuilder().getType<mlir::Float8E5M2Type>();
})
.def("get_half_ty",
[](TritonOpBuilder &self) -> mlir::Type {
return self.getBuilder().getF16Type();
})
.def("get_bf16_ty",
[](TritonOpBuilder &self) -> mlir::Type {
return self.getBuilder().getBF16Type();
})
.def("get_float_ty",
[](TritonOpBuilder &self) -> mlir::Type {
return self.getBuilder().getF32Type();
})
.def("get_double_ty",
[](TritonOpBuilder &self) -> mlir::Type {
return self.getBuilder().getF64Type();
})
.def("get_ptr_ty",
[](TritonOpBuilder &self, mlir::Type &type,
int addrSpace) -> mlir::Type {
return mlir::triton::PointerType::get(type, addrSpace);
})
.def("get_block_ty",
[](TritonOpBuilder &self, mlir::Type &elementType,
std::vector<int64_t> &shape) -> mlir::Type {
return mlir::RankedTensorType::get(shape, elementType);
})
.def("get_function_ty",
[](TritonOpBuilder &self, std::vector<mlir::Type> inTypes,
std::vector<mlir::Type> outTypes) -> mlir::Type {
return self.getBuilder().getFunctionType(inTypes, outTypes);
})
// locs
.def("set_loc", [](TritonOpBuilder &self,
mlir::Location loc) { self.setLastLoc(loc); })
.def("set_loc",
[](TritonOpBuilder &self, const std::string &fileName, int line,
int column) { self.setLastLoc(fileName, line, column); })
.def("get_loc",
[](TritonOpBuilder &self) -> mlir::Location {
return self.getLastLoc();
})
// Ops
.def("get_or_insert_function",
[](TritonOpBuilder &self, mlir::ModuleOp &module,
std::string &funcName, mlir::Type &funcType,
std::string &visibility, bool noinline) -> mlir::triton::FuncOp {
if (mlir::Operation *funcOperation = module.lookupSymbol(funcName))
return llvm::dyn_cast<mlir::triton::FuncOp>(funcOperation);
if (auto funcTy = funcType.dyn_cast<mlir::FunctionType>()) {
llvm::SmallVector<mlir::NamedAttribute> attrs = {
mlir::NamedAttribute(
self.getBuilder().getStringAttr("sym_visibility"),
self.getBuilder().getStringAttr(visibility)),
mlir::NamedAttribute(
self.getBuilder().getStringAttr("noinline"),
self.getBuilder().getBoolAttr(noinline))};
return self.create<mlir::triton::FuncOp>(funcName, funcTy,
attrs);
}
throw std::runtime_error("invalid function type");
})
.def(
"create_block",
[](TritonOpBuilder &self) -> mlir::Block * {
mlir::Region *parent = self.getBuilder().getBlock()->getParent();
return self.getBuilder().createBlock(parent);
},
ret::reference)
.def(
"create_block_with_parent",
[](TritonOpBuilder &self, mlir::Region &parent,
std::vector<mlir::Type> &argTypes) -> mlir::Block * {
// TODO: update arg loc
auto loc = self.getBuilder().getUnknownLoc();
llvm::SmallVector<mlir::Location, 8> argLocs(argTypes.size(), loc);
return self.getBuilder().createBlock(&parent, {}, argTypes,
argLocs);
},
ret::reference)
.def(
"new_block",
[](TritonOpBuilder &self) -> mlir::Block * {
return new mlir::Block();
},
ret::reference)
// Function
.def("ret",
[](TritonOpBuilder &self,
std::vector<mlir::Value> &vals) -> mlir::OpState {
return self.create<mlir::triton::ReturnOp>(vals);
})
.def("call",
[](TritonOpBuilder &self, mlir::triton::FuncOp &func,
std::vector<mlir::Value> &args) -> mlir::OpState {
return self.create<mlir::triton::CallOp>(func, args);
})
// Unstructured control flow
.def("create_cond_branch",
[](TritonOpBuilder &self, mlir::Value condition,
mlir::Block *trueDest, mlir::Block *falseDest) -> mlir::OpState {
return self.create<mlir::cf::CondBranchOp>(condition, trueDest,
falseDest);
})
.def("create_branch",
[](TritonOpBuilder &self, mlir::Block *dest,
std::vector<mlir::Value> &args) -> mlir::OpState {
return self.create<mlir::cf::BranchOp>(dest, args);
})
// Structured control flow
.def("create_for_op",
[](TritonOpBuilder &self, mlir::Value &lb, mlir::Value &ub,
mlir::Value &step,
std::vector<mlir::Value> &initArgs) -> mlir::scf::ForOp {
return self.create<mlir::scf::ForOp>(lb, ub, step, initArgs);
})
.def("create_if_op",
[](TritonOpBuilder &self, std::vector<mlir::Type> &retTypes,
mlir::Value &condition, bool withElse) -> mlir::scf::IfOp {
return self.create<mlir::scf::IfOp>(retTypes, condition, withElse);
})
.def("create_yield_op",
[](TritonOpBuilder &self,
std::vector<mlir::Value> &yields) -> mlir::scf::YieldOp {
return self.create<mlir::scf::YieldOp>(yields);
})
.def("create_while_op",
[](TritonOpBuilder &self, std::vector<mlir::Type> &retTypes,
std::vector<mlir::Value> &initArgs) -> mlir::scf::WhileOp {