17 | module Spidr.Compiler.Eval
21 | import Spidr.Compiler.Enzyme.MLIR.Dialect.Ops
22 | import Spidr.Compiler.LLVM.ADT.APFloat
23 | import Spidr.Compiler.LLVM.ADT.APInt
24 | import Spidr.Compiler.LLVM.Support.RawOStream
25 | import Spidr.Compiler.MLIR.Dialect.Func.IR.FuncOps
26 | import Spidr.Compiler.MLIR.IR
27 | import Spidr.Compiler.MLIR.Pass.PassManager
28 | import Spidr.Compiler.Stablehlo.Dialect.ChloOps
29 | import Spidr.Compiler.Stablehlo.Dialect.Serialization
30 | import Spidr.Compiler.Stablehlo.Dialect.StablehloAttrs
31 | import Spidr.Compiler.Stablehlo.Dialect.StablehloEnums
32 | import Spidr.Compiler.Stablehlo.Dialect.StablehloOps
33 | import Spidr.Compiler.Stablehlo.Dialect.Version
34 | import Spidr.Compiler.Xla.Client.ExecutableBuildOptions
35 | import Spidr.Compiler.Xla.PJRT.C.PjrtCApi
36 | import Spidr.Compiler.Xla.PJRT.PjrtExecutable
37 | import Spidr.Compiler.DType
38 | import Spidr.Compiler.IR
39 | import Spidr.Compiler.Array
40 | import Spidr.Compiler.FFI
41 | import Spidr.Compiler.String
42 | import Spidr.Compiler.LiteralRW
44 | import Spidr.Data.Literal
45 | import Spidr.Data.List
50 | = OutOfBounds Nat Nat
53 | | NoAddressableDevice
54 | | MlirPassError String
55 | | InvalidHloError String
57 | data BoundSet : Type where
58 | Parameters : Block -> BoundSet
59 | OpLike : {auto iface : Op a} -> a -> BoundSet
63 | show (OutOfBounds idx size) = "Index \{show idx} is out of bounds for array of size \{show size}"
64 | show (ValueNotFound idx) = "Value not found at index \{show idx}"
65 | show (PjrtErr err) = show err
66 | show NoAddressableDevice = "No addressable devices found"
67 | show (MlirPassError err) = "MlirPassError: \{err}"
68 | show (InvalidHloError err) = "InvalidHloError: \{err}"
71 | ErrIO : Type -> Type
72 | ErrIO = EitherT Err IO
74 | set : IOArray a -> Nat -> a -> ErrIO ()
75 | set cache idx x = do
76 | False <- writeArray cache (cast idx) x | True => right ()
77 | left $
OutOfBounds idx (cast $
max cache)
79 | get : IOArray a -> Nat -> ErrIO a
81 | Nothing <- readArray cache (cast idx) | Just x => right x
82 | let max = cast (max cache)
83 | left $
if idx >= max then OutOfBounds idx max else ValueNotFound idx
85 | iboundset : Nat -> BoundSet -> ErrIO Value.Value
86 | iboundset pos (Parameters block) = cast <$> getArgument block pos
87 | iboundset pos (OpLike x {iface}) = cast <$> (flip getOpResult pos =<< getOperation x)
89 | itype : IOArray BoundSet -> MLIRContext -> ValueType -> ErrIO Type_
90 | itype cache ctx (TensorType shape dtype) = cast <$> RankedTensorType.get shape !(mlirType ctx dtype)
91 | itype cache ctx (TypeRef pos tag) = getType =<< (iboundset pos =<< get cache tag) {m = ErrIO}
93 | itypes : IOArray BoundSet -> MLIRContext -> Vect n ValueType -> ErrIO TypeRange
94 | itypes cache ctx types = mkTypeRange =<< traverse (itype cache ctx) (toList types)
96 | 0 Finalizer : Type -> Type
97 | Finalizer a = OpBuilder -> Location -> ValueRange -> ErrIO a
101 | {auto moduleOp : ModuleOp} ->
102 | IOArray BoundSet ->
112 | {auto moduleOp : ModuleOp} ->
115 | IOArray BoundSet ->
119 | interpretFunc ctx uloc cache name f = do
120 | fnType <- FunctionType.get ctx !(itypes cache ctx f.paramTypes) !(itypes cache ctx f.resultTypes)
121 | fn <- FuncOp.create uloc name fnType
122 | interpretBody cache ctx uloc !(addEntryBlock fn) f FuncOps.ReturnOp.create
123 | pushBack moduleOp !(getOperation fn)
126 | interpretBody cache ctx uloc block f finalizer = do
127 | builder <- atBlockEnd block
128 | set cache f.tag (Parameters block)
129 | for_ (reverse f.env.ops) $
\(i, expr) => set cache i !(iop expr)
130 | results <- traverse ivalue f.results
131 | ignore $
finalizer builder uloc !(mkValueRange $
toList results)
135 | iop : {auto builder : OpBuilder} -> Op -> ErrIO BoundSet
137 | iopref : {auto builder : OpBuilder} -> OpRef -> ErrIO BoundSet
138 | iopref (BoundSet k) = get cache k
139 | iopref (Concrete x) = iop x
141 | ivalue : {auto builder : OpBuilder} -> IR.Value -> ErrIO Value.Value
142 | ivalue (V pos op) = iopref op >>= iboundset pos
144 | addArguments : Fn n -> Block -> ErrIO ()
145 | addArguments f body = for_ f.paramTypes $
\t => addArgument body !(itype cache ctx t) uloc
147 | iop (NamedFunc f) = OpLike <$> interpretFunc ctx uloc cache "func\{show f.tag}" f
148 | iop (CallByName fTag resTys xs) = do
149 | resTys <- mkTypeRange !(traverse (itype cache ctx) resTys)
150 | let name = "func\{show fTag}"
151 | args <- mkValueRange !(traverse ivalue $
toList xs)
152 | OpLike <$> CallOp.create builder uloc name resTys args
153 | iop (Grad shape f x) = do
154 | revInit <- ivalue $
V 0 $
Concrete $
Lit [] F64 1.0
155 | args <- mkValueRange [!(ivalue x), cast revInit]
156 | retTys <- mkTypeRange [!(itype cache ctx $
TensorType shape F64)]
157 | op <- AutoDiffRegionOp.create builder ctx uloc retTys args EnzymeActive EnzymeActivenoneed
158 | body <- emplaceBlock $
getBody op
159 | addArguments f body
160 | interpretBody cache ctx uloc body f YieldOp.create
162 | iop (Vectorize outTys batch fTag xs) = do
163 | let fName = "func\{show fTag}"
164 | outTys <- mkTypeRange !(traverse (itype cache ctx) outTys)
165 | inputs <- mkValueRange !(traverse ivalue xs)
166 | OpLike <$> BatchOp.create builder ctx uloc outTys fName inputs batch
167 | iop (MinValue dtype) = do
170 | then getSignedMinValue (numBits dtype)
171 | else getMinValue (numBits dtype)
172 | type <- cast <$> RankedTensorType.get [] !(mlirType ctx dtype)
173 | attr <- APInt.get type apInt
174 | OpLike <$> ConstantOp.create builder uloc attr
175 | iop (MaxValue dtype) = do
178 | then getSignedMaxValue (numBits dtype)
179 | else getMaxValue (numBits dtype)
180 | type <- cast <$> RankedTensorType.get [] !(mlirType ctx dtype)
181 | attr <- APInt.get type apInt
182 | OpLike <$> ConstantOp.create builder uloc attr
183 | iop MinFiniteFloat = do
184 | type <- cast <$> RankedTensorType.get [] !(mlirType ctx F64)
185 | attr <- APFloat.get type !(getLargest True)
186 | OpLike <$> ConstantOp.create builder uloc attr
187 | iop MaxFiniteFloat = do
188 | type <- cast <$> RankedTensorType.get [] !(mlirType ctx F64)
189 | attr <- APFloat.get type !(getLargest False)
190 | OpLike <$> ConstantOp.create builder uloc attr
191 | iop (Lit shape dtype lit) =
192 | OpLike <$> ConstantOp.create builder uloc !(mkDenseElementsAttr ctx lit)
193 | iop (Broadcast bs x) = do
196 | let xType = unsafeCastToRankedTensorType xType
197 | xShape <- getShape xType
198 | let from = cast {to = Nat} <$> Array.toList xShape
200 | let to : Shape = case bs of
202 | AddLeading lead => lead ++ from
203 | toArr <- fromList $
cast {to = Int64} <$> to
204 | resTy <- clone xType toArr
208 | attr <- DenseElementsAttr.ArrayRef.Attribute.get resTy []
209 | OpLike <$> ConstantOp.create builder uloc attr
211 | let broadcastDims = map (+ length to `minus` length from) $
List.range $
length from
212 | OpLike <$> BroadcastInDimOp.create builder uloc (cast resTy) x broadcastDims
213 | iop (UnaryElementwise f x) = do
214 | let W
mkop @{iface} = f.create
215 | OpLike <$> mkop builder uloc !(ivalue x)
219 | data Wrap : Type where
220 | W : forall a . (OpBuilder -> Location -> Value.Value -> ErrIO a) -> Op a => Wrap
222 | (.create) : UnaryOp -> Wrap
224 | Abs => W AbsOp.create
225 | Cbrt => W CbrtOp.create
226 | Ceil => W CeilOp.create
227 | Cos => W CosineOp.create
228 | Exp => W ExpOp.create
229 | ExpM1 => W Expm1Op.create
230 | Floor => W FloorOp.create
231 | IsFinite => W IsFiniteOp.create
232 | Log => W LogOp.create
233 | Log1p => W Log1pOp.create
234 | Logistic => W LogisticOp.create
235 | Not => W NotOp.create
236 | Clz => W ClzOp.create
237 | PopulationCount => W PopulationCountOp.create
238 | Neg => W NegOp.create
239 | RoundAFZ => W RoundOp.create
240 | RoundEven => W RoundNearestEvenOp.create
241 | Rsqrt => W RsqrtOp.create
242 | Sign => W SignOp.create
243 | Sin => W SineOp.create
244 | Sqrt => W SqrtOp.create
245 | Tan => W TanOp.create
246 | Tanh => W TanhOp.create
248 | Acos => W AcosOp.create
249 | Acosh => W AcoshOp.create
250 | Asin => W AsinOp.create
251 | Asinh => W AsinhOp.create
252 | Atan => W AtanOp.create
253 | Atanh => W AtanhOp.create
254 | Cosh => W CoshOp.create
255 | Sinh => W SinhOp.create
256 | Erf => W ErfOp.create
257 | ErfInv => W ErfInvOp.create
258 | Square => W SquareOp.create
259 | iop (Convert dtype resultShape x) = do
260 | resultType <- cast <$> RankedTensorType.get resultShape !(mlirType ctx dtype)
261 | OpLike <$> ConvertOp.create builder uloc resultType !(ivalue x)
262 | iop (BitCastConvert dtype resultShape x) = do
263 | resultType <- cast <$> RankedTensorType.get resultShape !(mlirType ctx dtype)
264 | OpLike <$> ConvertOp.create builder uloc resultType !(ivalue x)
265 | iop (BinaryElementwise f lhs rhs) = do
266 | let W
mkop @{iface} = f.create
267 | OpLike <$> mkop builder uloc !(ivalue lhs) !(ivalue rhs)
271 | data Wrap : Type where
272 | W : forall a . (OpBuilder -> Location -> Value.Value -> Value.Value -> ErrIO a) -> Op a => Wrap
274 | (.create) : BinaryOp -> Wrap
276 | Compare direction => W (\b, l, x, y => CompareOp.create b l x y (cast direction))
277 | Add => W AddOp.create
278 | Div => W DivOp.create
279 | Max => W MaxOp.create
280 | Min => W MinOp.create
281 | Mul => W MulOp.create
282 | Pow => W PowOp.create
283 | Rem => W RemOp.create
284 | Sub => W SubtractOp.create
285 | Atan2 => W Atan2Op.create
286 | And => W AndOp.create
287 | Or => W OrOp.create
288 | Xor => W XorOp.create
289 | ShiftLeft => W ShiftLeftOp.create
290 | ShiftRightLogical => W ShiftRightLogicalOp.create
291 | ShiftRightArithmetic => W ShiftRightArithmeticOp.create
292 | iop (If resTy pred true false) = do
293 | op <- IfOp.create builder uloc !(itype cache ctx resTy) !(ivalue pred)
294 | bodyT <- emplaceBlock $
getTrueBranch op
295 | bodyF <- emplaceBlock $
getFalseBranch op
296 | addArguments true bodyT
297 | addArguments false bodyF
298 | interpretBody cache ctx uloc bodyT true StablehloOps.ReturnOp.create
299 | interpretBody cache ctx uloc bodyF false StablehloOps.ReturnOp.create
301 | iop (Case resTy idx branches) = do
302 | op <- CaseOp.create builder uloc !(itype cache ctx resTy) !(ivalue idx) (length branches)
303 | for_ (enumerate branches) $
\(i, br) => do
304 | body <- emplaceBlock $
getBranch op (cast i)
305 | addArguments br body
306 | interpretBody cache ctx uloc body br StablehloOps.ReturnOp.create
308 | iop (While cond body inits) = do
309 | inits <- mkValueRange =<< traverse ivalue (toList inits)
310 | op <- WhileOp.create builder uloc inits
311 | cond' <- emplaceBlock $
getCond op
312 | body' <- emplaceBlock $
getBody op
313 | addArguments body body'
314 | addArguments cond cond'
315 | interpretBody cache ctx uloc cond' cond StablehloOps.ReturnOp.create
316 | interpretBody cache ctx uloc body' body StablehloOps.ReturnOp.create
318 | iop (Reduce body inits axes xs) = do
319 | inits <- mkValueRange !(traverse ivalue $
toList inits)
320 | xs <- mkValueRange !(traverse ivalue $
toList xs)
321 | op <- ReduceOp.create builder uloc xs inits axes
322 | body' <- emplaceBlock $
getBody op
323 | addArguments body body'
324 | interpretBody cache ctx uloc body' body StablehloOps.ReturnOp.create
326 | iop (Slice starts stops strides x) = do
327 | OpLike <$> SliceOp.create builder uloc !(ivalue x) starts stops strides
328 | iop (DynamicSlice starts sizes x) = do
329 | starts <- mkValueRange !(traverse ivalue starts)
330 | OpLike <$> DynamicSliceOp.create builder uloc !(ivalue x) starts sizes
331 | iop (DynamicUpdateSlice x update starts) = do
332 | starts <- mkValueRange !(traverse ivalue starts)
333 | OpLike <$> DynamicUpdateSliceOp.create builder uloc !(ivalue x) !(ivalue update) starts
334 | iop (Cholesky x) = OpLike <$> CholeskyOp.create builder uloc !(ivalue x) True
335 | iop (Concat axis xs) = do
336 | xs <- mkValueRange =<< traverse ivalue (toList xs)
337 | OpLike <$> ConcatenateOp.create builder uloc xs axis
338 | iop (Iota shape dtype dim) = do
339 | resultType <- cast <$> RankedTensorType.get shape !(mlirType ctx dtype)
340 | OpLike <$> IotaOp.create builder uloc resultType dim
341 | iop (DotGeneral lb rb lc rc resultType lhs rhs) = do
342 | ddn <- DotDimensionNumbersAttr.get ctx lb rb lc rc
343 | resTy <- itype cache ctx resultType
344 | OpLike <$> DotGeneralOp.create builder uloc resTy !(ivalue lhs) !(ivalue rhs) ddn
345 | iop (Reshape dtype to x) = do
346 | resultType <- cast <$> RankedTensorType.get to !(mlirType ctx dtype)
347 | OpLike <$> ReshapeOp.create builder uloc resultType !(ivalue x)
348 | iop (Select pred true false) = do
349 | OpLike <$> SelectOp.create builder uloc !(ivalue pred) !(ivalue true) !(ivalue false)
350 | iop (Sort comp axis isStable x) = do
351 | op <- SortOp.create builder uloc !(ivalue x) axis isStable
352 | comp' <- emplaceBlock $
getComparator op
353 | addArguments comp comp'
354 | interpretBody cache ctx uloc comp' comp StablehloOps.ReturnOp.create
356 | iop (Reverse axes x) = OpLike <$> ReverseOp.create builder uloc !(ivalue x) axes
357 | iop (Transpose ordering x) = OpLike <$> TransposeOp.create builder uloc !(ivalue x) ordering
358 | iop (TriangularSolve a b lower) =
359 | OpLike <$> TriangularSolveOp.create
360 | builder uloc !(ivalue a) !(ivalue b) True lower False NoTranspose
361 | iop (Rng state resultType) = do
362 | stateTy <- itype cache ctx $
TensorType [2] U64
363 | OpLike <$> RngBitGeneratorOp.create
364 | builder uloc stateTy !(itype cache ctx resultType) ThreeFry !(ivalue state)
367 | compile : Device -> Fn n -> ErrIO PjrtLoadedExecutable
368 | compile (MkDevice mlirCtx passManager api client) f = do
369 | uloc <- UnknownLoc.get mlirCtx
370 | cache <- newArray $
cast $
counter f.env
371 | moduleOp <- ModuleOp.create uloc "root"
372 | ignore $
interpretFunc mlirCtx uloc cache "main" f
373 | True <- run passManager !(getOperation moduleOp)
374 | | _ => throwE $
MlirPassError "Failed to run MLIR passes"
376 | version <- toString !getCurrentVersion
377 | True <- serializePortableArtifact moduleOp version !(rawStringOStream code)
378 | | False => throwE $
InvalidHloError "Failed to serialize MLIR for version \{c_str version}"
379 | bimapEitherT PjrtErr id $
do
380 | executableBuildOptions <- mkExecutableBuildOptions
381 | compileOptions <- serializeAsString !(mkCompileOptions executableBuildOptions)
382 | program <- mkPjrtProgram code
383 | loadedExec <- pjrtClientCompile api client program compileOptions
386 | delete compileOptions
387 | delete executableBuildOptions
391 | data TensorData : (Shape -> DType -> Type) -> Shape -> DType -> Type where
392 | MkTensorData : {shape : _} -> {dtype : _} -> f shape dtype -> TensorData f shape dtype
394 | %hide Literal.All2.All2
397 | (xs : All2 (TensorData $
\_, _ => a) shapes dtypes) ->
398 | Vect (length xs) b ->
399 | All2 (TensorData $
\_, _ => b) shapes dtypes
401 | replace (MkTensorData _ :: xs) (y :: ys) = MkTensorData y :: replace xs ys
403 | forget : All2 (\_, _ => a) xs ys -> List a
405 | forget (x :: xs) = x :: forget xs
407 | errLift : (e -> e') -> Functor m => EitherT e m a -> EitherT e' m a
408 | errLift f = bimapEitherT f id
414 | PjrtLoadedExecutable ->
415 | All2 (TensorData $
\_ => Array . DType.idrisType) ishapes idtypes ->
416 | All2 (TensorData $
\_, _ => ()) oshapes odtypes ->
417 | ErrIO $
All2 (TensorData $
\_ => Array . DType.idrisType) oshapes odtypes
418 | execute (MkDevice _ _ api client) loadedExec args types = do
419 | (device :: _) <- errLift PjrtErr $
pjrtClientAddressableDevices api client
420 | | [] => left NoAddressableDevice
421 | errLift PjrtErr $
do
422 | argBufs <- forProperty args $
\(MkTensorData {shape, dtype} arg) => do
423 | let _ = dtypeIsArrayType dtype
424 | shape <- fromList $
cast {to = Int64} <$> shape
425 | arg <- pjrtClientBufferFromHostBuffer api client shape dtype arg device
428 | outs <- pjrtLoadedExecutableExecute api loadedExec (forget argBufs) (length types) device
429 | for_ (forget argBufs) (pjrtBufferDestroy api)
430 | forProperty (replace types outs) $
\(MkTensorData {shape, dtype} buffer) => do
431 | let at = dtypeIsArrayType dtype
432 | arr <- mkArray (product shape)
433 | pjrtBufferToHostBuffer api buffer arr
434 | pjrtBufferDestroy api buffer
435 | pure (MkTensorData arr)