17 | module Spidr.Compiler.IR
19 | import Control.Monad.State
20 | import Data.Primitives.Interpolation
21 | import Derive.Prelude
22 | import Language.Reflection
24 | import public Spidr.Compiler.Stablehlo.Dialect.StablehloEnums
25 | import Spidr.Compiler.LiteralRW
26 | import Spidr.Data.Literal
29 | import Spidr.Data.List
31 | %language ElabReflection
33 | Show a => Interpolation (List a) where
39 | TensorType Shape DType
44 | Show ValueType where
45 | show (TensorType shape dtype) = "\{show shape} \{show dtype}"
46 | show (TypeRef idx tag) = "type of \{show idx} of \{show tag}"
48 | public export data Op : Type
61 | ops : List (Nat, Op)
68 | emptyFrom : Env -> Env
69 | emptyFrom (MkEnv n _) = MkEnv n []
72 | updateCounterFrom : Env -> State Env ()
73 | updateCounterFrom (MkEnv n _) = do
77 | public export data OpRef : Type
80 | data Value = V Nat OpRef
85 | record Fn (arity : Nat) where
88 | paramTypes : Vect arity ValueType
89 | resultTypes : Vect resultCount ValueType
90 | results : Vect resultCount Value
95 | Compare ComparisonDirection | And | Or | Add | Sub | Mul | Div | Rem | Pow | Min | Max | Atan2
96 | | ShiftRightLogical | ShiftRightArithmetic | ShiftLeft | Xor
98 | %runElab derive "ComparisonDirection" [Show]
99 | %runElab derive "BinaryOp" [Show]
103 | Not | Clz | PopulationCount
104 | | Ceil | Floor | RoundAFZ | RoundEven | Neg | Abs | Sign | IsFinite
105 | | Log | Log1p | Exp | ExpM1 | Logistic | Erf | ErfInv
106 | | Sqrt | Rsqrt | Cbrt | Square
107 | | Sin | Cos | Tan | Asin | Acos | Atan | Sinh | Cosh | Tanh | Asinh | Acosh | Atanh
109 | %runElab derive "UnaryOp" [Show]
112 | data BroadcastShape = Explicit Shape | AddLeading (List Nat)
115 | data Op : Type where
122 | NamedFunc : Fn arity -> Op
127 | CallByName : (name : Nat) -> (resultTypes : List ValueType) -> List Value -> Op
129 | Lit : (shape : Shape) -> (dtype : DType) -> Literal shape (idrisType dtype) -> Op
130 | Grad : Shape -> Fn 1 -> Value -> Op
132 | (resultTypes : List ValueType) ->
133 | (batchShape : Shape) ->
134 | (targetFunc : Nat) ->
135 | (args : List Value) ->
137 | MinValue : DType -> Op
138 | MaxValue : DType -> Op
139 | MinFiniteFloat : Op
140 | MaxFiniteFloat : Op
141 | Iota : (shape : Shape) -> DType -> (axis : Nat) -> Op
142 | BitCastConvert : DType -> Shape -> Value -> Op
143 | Convert : DType -> Shape -> Value -> Op
144 | Reshape : DType -> Shape -> Value -> Op
145 | Slice : (starts, stops, strides : List Nat) -> Value -> Op
146 | DynamicSlice : (starts : List Value) -> (sizes : List Nat) -> Value -> Op
147 | DynamicUpdateSlice : (operand, update : Value) -> (starts : List Value) -> Op
148 | Concat : (axis : Nat) -> Vect (S n) Value -> Op
149 | Transpose : (ordering : List Nat) -> Value -> Op
150 | Broadcast : BroadcastShape -> Value -> Op
151 | Reduce : Fn (n + n) -> (inits : Vect n Value) -> (axes : List Nat) -> Vect n Value -> Op
152 | Sort : Fn 2 -> (axis : Nat) -> (isStable : Bool) -> Value -> Op
153 | Reverse : (axes : List Nat) -> Value -> Op
154 | BinaryElementwise : BinaryOp -> Value -> Value -> Op
155 | UnaryElementwise : UnaryOp -> Value -> Op
156 | Select : (predicate, onTrue, onFalse : Value) -> Op
157 | While : (condition, body : Fn n) -> (init : Vect n Value) -> Op
158 | If : (resultType : ValueType) -> (predicate : Value) -> (onTrue, onFalse : Fn 0) -> Op
159 | Case : (resultType : ValueType) -> (index : Value) -> List (Fn 0) -> Op
161 | (lBatch, lContract, rBatch, rContract: List Nat) ->
162 | (resultType : ValueType) ->
166 | Cholesky : Value -> Op
167 | TriangularSolve : Value -> Value -> (isLower : Bool) -> Op
168 | Rng : (state : Value) -> (resultType : ValueType) -> Op
171 | data OpRef = BoundSet Nat | Concrete Op
174 | tagOpRef : Monad m => OpRef -> StateT Env m OpRef
175 | tagOpRef (BoundSet x) = pure $
BoundSet x
176 | tagOpRef (Concrete expr) = do
177 | MkEnv next env <- get
178 | put $
MkEnv (S next) ((next, expr) :: env)
179 | pure (BoundSet next)
182 | reserve : State Env Nat
184 | MkEnv next env <- get
185 | put $
MkEnv (S next) env
189 | showOp : Nat -> Op -> String
192 | showOpRef : Nat -> OpRef -> String
193 | showOpRef indent (BoundSet k) = "Bound \{k}"
194 | showOpRef indent (Concrete x) = showOp indent x
197 | showValue : Nat -> Value -> String
198 | showValue indent (V idx op) = "(\{showOpRef indent op}):\{show idx}"
201 | showValueList : Traversable t => Nat -> t Value -> String
202 | showValueList indent xs = "[" ++ joinBy ", " (toList $
map (showValue indent) xs) ++ "]"
205 | showEnv : Nat -> Env -> String
206 | showEnv indent (MkEnv max env) = joinBy "\n" $
map fmt (reverse env)
210 | fmt : (Nat, Op) -> String
212 | let sep = replicate (4 + length (show max) `minus` length (show n)) ' '
213 | in "\{replicate indent ' '}\{show n}\{sep}\{showOp indent x}"
216 | showFn : Nat -> Fn arity -> String
217 | showFn indent (MkFn parameterSetTag paramTypes resultTypes results env@(MkEnv _ env')) =
218 | let params = "\{show parameterSetTag} \{show paramTypes}"
219 | res = "\{showValueList (indent + 2) $ toList results}" in
221 | [] => "\{params} => \{res}"
223 | "\{params} => \{res} with vars {\n\{showEnv (indent + 4) env}\n\{replicate (indent + 2) ' '}}"
226 | Show (Fn arity) where show = showFn 0
228 | showOp indent (NamedFunc f) = "NamedFunc \{showFn indent f}"
229 | showOp indent (CallByName fTag _ xs) = "Call {targetFunc = \{show fTag}} \{showValueList indent xs}"
230 | showOp indent (Lit shape dtype x) = "Lit \{shape} \{show dtype}"
231 | showOp indent (Grad _ op x) = "Grad {op = \{showFn indent op}} \{showValue indent x}"
232 | showOp indent (Vectorize _ batchShape fTag xs) =
233 | "Vectorize {batchShape = \{show batchShape}, targetFunc = \{show fTag}}"
234 | ++ " \{showValueList indent xs}"
235 | showOp _ (MinValue dtype) = "MinValue \{show dtype}"
236 | showOp _ (MaxValue dtype) = "MaxValue \{show dtype}"
237 | showOp _ MinFiniteFloat = "MinFiniteFloat"
238 | showOp _ MaxFiniteFloat = "MaxFiniteFloat"
239 | showOp indent (Iota dtype shape axis) =
240 | "Iota {shape = \{show shape}, dtype = \{show dtype}, axis = \{axis}}"
241 | showOp indent (Convert dtype shape x) =
242 | "Convert {dtype = \{show dtype}} \{showValue indent x}"
243 | showOp indent (BitCastConvert dtype shape x) =
244 | "BitCastConvert {dtype = \{show dtype}} \{showValue indent x}"
245 | showOp indent (Reshape _ to x) = "Reshape {to = \{to}} \{showValue indent x}"
246 | showOp indent (Slice starts stops strides x) =
247 | "Slice {starts = \{starts}, stops = \{stops}, strides = \{strides}} \{showValue indent x}"
248 | showOp indent (DynamicSlice starts sizes x) =
249 | "DynamicSlice {starts = \{showValueList indent starts}, sizes = \{sizes}} \{showValue indent x}"
250 | showOp indent (DynamicUpdateSlice x update starts) =
251 | "DynamicSlice {update = \{showValue indent update}, starts = \{showValueList indent starts}}"
252 | ++ " \{showValue indent x}"
253 | showOp indent (Concat axis xs) = "Concat {axis = \{axis}} \{showValueList indent $ toList xs}"
254 | showOp indent (Transpose ordering x) = "Transpose {ordering = \{ordering}} \{showValue indent x}"
255 | showOp indent (Broadcast bs x) =
256 | let bs : String = case bs of
257 | Explicit shape => "to = \{show shape}"
258 | AddLeading lead => "withLeading = \{show lead}"
259 | in "Broadcast {\{bs}} \{showValue indent x}"
260 | showOp indent (Reduce op neutrals axes xs) =
261 | "Reduce {op = \{showFn indent op}, inits = \{showValueList indent $ toList neutrals}," ++
262 | " axes = \{axes}} \{showValueList indent $ toList xs}"
263 | showOp indent (Sort f axis _ xs) =
264 | "Sort {f = \{showFn indent f}, axis = \{axis}} \{showValue indent xs}"
265 | showOp indent (Reverse axes x) = "Reverse \{axes} \{showValue indent x}"
266 | showOp indent (BinaryElementwise op x y) = "\{show op} \{showValue indent x} \{showValue indent y}"
267 | showOp indent (UnaryElementwise op x) = "\{show op} \{showValue indent x}"
268 | showOp indent (Select p t f) =
269 | "Select {predicate = \{showValue indent p}, onTrue = \{showValue indent t}," ++
270 | " onFalse = \{showValue indent f}}"
271 | showOp indent (While c b is) =
272 | "While {condition = \{showFn indent c}, body = \{showFn indent b}," ++
273 | " initials = \{showValueList indent $ toList is}}"
274 | showOp indent (If _ p ft ff) =
275 | "If {predicate = \{showValue indent p}, onTrue = \{showFn indent ft}," ++
276 | " onFalse = \{showFn indent ff}}"
277 | showOp indent (Case _ idx fs) =
278 | "Case {index = \{showValue indent idx}, branches = [\{joinBy ",\n" $ map (showFn indent) fs}}]"
279 | showOp indent (DotGeneral lBatch lContract rBatch rContract _ x y) =
280 | "DotGeneral {lBatch = \{lBatch}, lContract = \{lContract}," ++
281 | " rBatch = \{rBatch}, rContract = \{rContract}} \{showValue indent x} \{showValue indent y}"
282 | showOp indent (Cholesky x) = "Cholesky \{showValue indent x}"
283 | showOp indent (TriangularSolve x y isLower) =
284 | "TriangularSolve {isLower = \{show isLower}} \{showValue indent x} \{showValue indent y}"
285 | showOp indent (Rng state shape) = "Rng {state = \{showValue indent state}, shape = \{show shape}}"