0 | {--
   1 | Copyright (C) 2021  Joel Berkeley
   2 |
   3 | This program is free software: you can redistribute it and/or modify
   4 | it under the terms of the GNU Affero General Public License as published
   5 | by the Free Software Foundation, either version 3 of the License, or
   6 | (at your option) any later version.
   7 |
   8 | This program is distributed in the hope that it will be useful,
   9 | but WITHOUT ANY WARRANTY; without even the implied warranty of
  10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11 | GNU Affero General Public License for more details.
  12 |
  13 | You should have received a copy of the GNU Affero General Public License
  14 | along with this program.  If not, see <https://www.gnu.org/licenses/>.
  15 | --}
  16 | ||| Defines `Tensor`, an array of numbers or booleans, along with a number of functions operating on
  17 | ||| `Tensor`s. `Tensor` operations typically leverage hardware acceleration and graph compilation.
  18 | ||| spidr tracks tensor shape and data type in the types, so you can be sure that if your tensor
  19 | ||| code compiles, these are consistent.
  20 | |||
  21 | ||| spidr achieves efficient reuse of tensor computations with `Tag`. See the tutorial
  22 | ||| _Nuisances in the Tensor API_ for a discussion of pitfalls to avoid when using `Tag`.
  23 | module Spidr.Tensor
  24 |
  25 | import public Control.Monad.State
  26 | import Control.Monad.Error.Either
  27 | import Data.Singleton
  28 | import Syntax.PreorderReasoning
  29 |
  30 | import Spidr.Compiler.Xla.PJRT.C.PjrtCApi
  31 | import Spidr.Compiler.Eval
  32 | import Spidr.Compiler.IR
  33 | import Spidr.Compiler.Array
  34 | import Spidr.Compiler.LiteralRW
  35 | import Spidr.Compiler.Passes
  36 | import Spidr.Device
  37 | import public Spidr.DType
  38 | import public Spidr.Data.Literal
  39 | import public Spidr.Shape
  40 | import public Spidr.Data.List
  41 | import Spidr.Data.Vect
  42 |
  43 | ||| A scalar or array. Construct a `Tensor` with function `tensor`.
  44 | export
  45 | data Tensor : Shape -> DType -> Type where
  46 |   MkTensor : Value -> {shape : _} -> {dtype : _} -> Tensor shape dtype
  47 |
  48 | (.type) : Tensor shape dtype -> ValueType
  49 | (.type) (MkTensor {shape, dtype} _) = TensorType shape dtype
  50 |
  51 | (.value) : Tensor s t -> Value
  52 | (.value) (MkTensor v) = v
  53 |
  54 | ||| The effect of tagging nodes in a computational graph.
  55 | export
  56 | data TagT : (Type -> Type) -> Type -> Type where
  57 |   MkTagT : StateT Env m a -> TagT m a
  58 |
  59 | public export 0
  60 | Tag : Type -> Type
  61 | Tag = TagT Identity
  62 |
  63 | export
  64 | Functor m => Functor (TagT m) where
  65 |   map f (MkTagT x) = MkTagT (map f x)
  66 |
  67 | export
  68 | Monad m => Applicative (TagT m) where
  69 |   pure x = MkTagT (pure x)
  70 |   (MkTagT f) <*> (MkTagT x) = MkTagT (f <*> x)
  71 |
  72 | export
  73 | Monad m => Monad (TagT m) where
  74 |   (MkTagT x) >>= f = MkTagT $ x >>= (\y => let MkTagT z = f y in z)
  75 |
  76 | export
  77 | MonadTrans TagT where
  78 |   lift = MkTagT . lift
  79 |
  80 | public export
  81 | interface Taggable a where
  82 |   ||| Mark an expression to be efficiently reused. For example, in
  83 |   ||| ```
  84 |   ||| bad : Tensor [9999999] F64
  85 |   ||| bad = let x = fill {shape = [9999999]} 1.0 in x + x
  86 |   |||
  87 |   ||| good : Tag $ Tensor [9999999] F64
  88 |   ||| good = do x <- tag $ fill {shape = [9999999]} 1.0
  89 |   |||           pure (x + x)
  90 |   ||| ```
  91 |   ||| the large vector `x` is calculated twice in `bad`, but once in `good`, as `tag` marks it for
  92 |   ||| sharing.
  93 |   |||
  94 |   ||| Types that implement this interface should `tag` constituent components it deems worth sharing.
  95 |   ||| For example, see the implementation for tuples.
  96 |   |||
  97 |   ||| See tutorial _Nuisances in the Tensor API_ for details.
  98 |   tag : Monad m => a -> TagT m a
  99 |
 100 | Taggable OpRef where
 101 |   tag = MkTagT . tagOpRef
 102 |
 103 | export
 104 | Taggable (Tensor shape dtype) where
 105 |   tag (MkTensor $ V idx op) = map (\op => MkTensor $ V idx op) (tag op)
 106 |
 107 | export
 108 | (Taggable a, Taggable b) => Taggable (a, b) where
 109 |   tag (a, b) = Prelude.[| (tag a, tag b) |]
 110 |
 111 | val0 : Op -> Value
 112 | val0 = V 0 . Concrete
 113 |
 114 | t0 : {shape : _} -> {dtype : _} -> Op -> Tensor shape dtype
 115 | t0 x = MkTensor $ val0 x
 116 |
 117 | ||| Construct a `Tensor` from `Literal` data. For example
 118 | ||| ```
 119 | ||| x : Tensor [2, 3] S32
 120 | ||| x = tensor [[1, 2, 3],
 121 | |||             [4, 5, 6]]
 122 | ||| ```
 123 | export
 124 | tensor : {shape : _} -> {dtype : _} -> Literal shape (idrisType dtype) -> Tensor shape dtype
 125 | tensor lit = t0 $ Lit shape dtype lit
 126 |
 127 | namespace F64
 128 |   export
 129 |   fromDouble : Double -> Tensor [] F64
 130 |   fromDouble = tensor . Scalar
 131 |
 132 | try : Show e => EitherT e IO a -> IO a
 133 | try = eitherT (\e => assert_total $ idris_crash $ show e) pure
 134 |
 135 | %hide Literal.All2.All2
 136 |
 137 | ||| A function type. For example `Func [Nat, String] Bool` is `Nat -> String -> Bool`.
 138 | public export 0
 139 | Func : Vect arity Type -> Type -> Type
 140 | Func [] r = r
 141 | Func (t :: ts) r = t -> Func ts r
 142 |
 143 | compose : (a -> b) -> {arity : Nat} -> {0 xs : Vect arity Type} -> Func xs a -> Func xs b
 144 | compose f {arity = 0} {xs = []} g = f g
 145 | compose f {arity = (S k)} {xs = _ :: _} g = \x => compose f (g x)
 146 |
 147 | gatherArgs :
 148 |   {ar : _} -> {0 as : Vect ar a} -> {0 bs : Vect ar b} -> {0 p : a -> b -> Type} ->
 149 |   Func [| p as bs |] $ All2 p (toList as) (toList bs)
 150 | gatherArgs {as = [], bs = []} = []
 151 | gatherArgs {as = _ :: _, bs = _ :: _} =
 152 |   \x => compose (\xs => the (All2 p _ _) $ x :: xs) gatherArgs
 153 |
 154 | mkFn' :
 155 |   forall arity, rshapes, rdtypes . (shapes : Vect arity Shape) -> (dtypes : Vect arity DType) ->
 156 |   Func [| Tensor shapes dtypes |] (Tag $ All2 Tensor rshapes rdtypes) ->
 157 |   Tag (Fn arity, All2 Tensor rshapes rdtypes)
 158 | mkFn' shapes dtypes f = MkTagT $ do
 159 |   addr <- reserve
 160 |
 161 |   let leq : length shapes === arity
 162 |       leq = lengthCorrect shapes
 163 |
 164 |   let MkTagT res = applyNary addr (length shapes) _ _ $ rewrite leq in f
 165 |       (env, results) = runState (emptyFrom !get) res
 166 |       resAndTys = fromList $ resultsAndTypes results
 167 |       argValueTypes = zipWith TensorType shapes dtypes
 168 |       f : Fn arity = MkFn addr argValueTypes (snd <$> resAndTys) (fst <$> resAndTys) env
 169 |
 170 |   updateCounterFrom env
 171 |
 172 |   pure (f, results)
 173 |
 174 |   where
 175 |
 176 |   applyNary :
 177 |     (addr, ar : Nat) ->
 178 |     (ss : Vect ar Shape) ->
 179 |     (ds : Vect ar DType) ->
 180 |     Func [| Tensor ss ds |] a -> a
 181 |   applyNary addr 0 [] [] f = f
 182 |   applyNary addr (S a) (s :: ss) (t :: ts) f =
 183 |     applyNary addr a ss ts (f $ MkTensor $ V (length shapes `minus` S a) $ BoundSet addr)
 184 |
 185 |   resultsAndTypes : All2 Tensor s d -> List (Value, ValueType)
 186 |   resultsAndTypes [] = []
 187 |   resultsAndTypes ((MkTensor {shape, dtype} x) :: xs) =
 188 |     (x, TensorType shape dtype) :: resultsAndTypes xs
 189 |
 190 | forProperty' :
 191 |   Applicative m => {xs : _} -> {ys : _} ->
 192 |   All2 f xs ys -> ({x : _} -> {y : _} -> f x y -> m (g x y)) -> m (All2 g xs ys)
 193 | forProperty' [] _ = pure []
 194 | forProperty' (z :: zs) f = [| f z :: forProperty' zs f |]
 195 |
 196 | shiftRightAppOut : (g : a -> b) -> All2 (\x, y => f x (g y)) xs ys -> All2 f xs (g <$> ys)
 197 | shiftRightAppOut _ [] = []
 198 | shiftRightAppOut g (x :: xs) = x :: shiftRightAppOut g xs
 199 |
 200 | rightAppIsMapAppRight :
 201 |   (0 f : a -> b' -> c) ->
 202 |   (0 g : b -> b') ->
 203 |   (xs : Vect n a) -> (ys : Vect n b) ->
 204 |   [| (\x, y => f x (g y)) xs ys |] === [| f xs (g <$> ys) |]
 205 | rightAppIsMapAppRight f g [] [] = Refl
 206 | rightAppIsMapAppRight f g (x :: xs) (y :: ys) = cong2 (::) Refl (rightAppIsMapAppRight f g xs ys)
 207 |
 208 | ||| Just-in-time compile a tensor graph into a function that can be cheaply applied to arbitrary
 209 | ||| literals of the correct shapes and element types. For example,
 210 | ||| ```
 211 | ||| f : Tensor [2] F64 -> Tag $ All2 Tensor [[2], []] [F64, F64]
 212 | ||| f x = do
 213 | |||   y <- reduce @{Sum} [0] x
 214 | |||   pure [-x, y]
 215 | |||
 216 | ||| g : Device -> IO ()
 217 | ||| g dev =
 218 | |||   do fJit <- jit {shapes = [_], dtypes = [_]} dev f
 219 | |||      let [x, y] = fJit [-1.0, 4.0]
 220 | |||      printLn x  -- [1.0, -4.0]
 221 | |||      printLn y  -- 3.0
 222 | ||| ```
 223 | ||| While `eval` needs to be recompiled every time you want to change tensor values, `jit`
 224 | ||| compiles the function *once*, then reuses it for each application.
 225 | export covering
 226 | jit :
 227 |   Device -> {arity : _} ->
 228 |   forall rshapes, rdtypes . {shapes : Vect arity Shape} -> {dtypes : Vect arity DType} ->
 229 |   Func [| Tensor shapes dtypes |] (Tag $ All2 Tensor rshapes rdtypes) ->
 230 |   IO $ Func [| Literal shapes (DType.idrisType <$> dtypes) |] $
 231 |     All2 Literal rshapes (DType.idrisType <$> rdtypes)
 232 | jit device f = rewrite sym $ rightAppIsMapAppRight Literal idrisType shapes dtypes in do
 233 |   let MkTagT f = mkFn' shapes dtypes f
 234 |       (f, outs) = evalState empty f
 235 |       types = mapProperty (\(MkTensor _) => MkTensorData ()) outs
 236 |   exec <- try $ compile device f
 237 |   pure $ compose (\args => unsafePerformIO $ map (shiftRightAppOut idrisType) $ try $ do
 238 |       args <- forProperty' args $ \{x}, {y}, arg =>
 239 |         let _ = dtypeIsArrayType y in MkTensorData <$> fromList (Prelude.toList arg)
 240 |       bufs <- execute device exec args types
 241 |       let lits = mapProperty (\(MkTensorData {dtype} l) => read dtype l) bufs
 242 |       ignore $ forProperty args $ \(MkTensorData arg) => free arg
 243 |       ignore $ forProperty bufs $ \(MkTensorData buf) => free buf
 244 |       pure lits
 245 |     ) gatherArgs
 246 |
 247 | namespace List
 248 |   namespace Tag
 249 |     ||| Convenience alias for `jit` on constant tensor graphs.
 250 |     |||
 251 |     ||| **Note:** Each call to `eval` will compile the tensor graph, even if the graphs only differ
 252 |     ||| in the values of their tensor constants. This can be expensive. If you want to efficiently
 253 |     ||| run your graph for different tensor values, use `jit` and make these tensor values
 254 |     ||| arguments to the graph.
 255 |     |||
 256 |     ||| In contrast to `Tensor.eval` when called on multiple tensors, this function constructs and
 257 |     ||| compiles the graph just once.
 258 |     export covering
 259 |     eval :
 260 |       Device ->
 261 |       Tag (All2 Tensor shapes dtypes) ->
 262 |       IO $ All2 Literal shapes (DType.idrisType <$> dtypes)
 263 |     eval device xs = jit {shapes = [], dtypes = []} device xs
 264 |
 265 |   ||| A convenience alias for `List.Tag.eval` when no tagging is used.
 266 |   export covering
 267 |   eval :
 268 |     forall shapes, dtypes .
 269 |     Device ->
 270 |     All2 Tensor shapes dtypes ->
 271 |     IO (All2 Literal shapes (DType.idrisType <$> dtypes))
 272 |   eval device xs = eval device (pure xs)
 273 |
 274 | namespace Tag
 275 |   ||| A convenience alias for `List.Tag.eval` for a single tensor.
 276 |   export covering
 277 |   eval : Device -> Tag (Tensor shape dtype) -> IO (Literal shape (DType.idrisType dtype))
 278 |   eval device x = map (\[z] => z) $ List.Tag.eval device $ map (\z => [z]) x
 279 |
 280 | ||| A convenience alias for `List.Tag.eval` for a single tensor and no tagging.
 281 | export covering
 282 | eval : Device -> Tensor shape dtype -> IO (Literal shape (DType.idrisType dtype))
 283 | eval device x = eval device (pure x)
 284 |
 285 | ||| A string representation of a tensor graph.
 286 | |||
 287 | ||| There are no guarantees whatsoever as to the string structure and contents.
 288 | export covering
 289 | Show (Tag $ Tensor shape dtype) where
 290 |   show (MkTagT x) =
 291 |     let (env, MkTensor x) = runState empty x
 292 |      in show (MkFn 0 [] [TensorType shape dtype] [x] env)
 293 |
 294 | export covering
 295 | Show (Tensor shape dtype) where show = show . pure {f = Tag}
 296 |
 297 | ||| Positive infinity.
 298 | export
 299 | inf : Tensor [] F64
 300 |
 301 | ||| NaN (not a number).
 302 | export
 303 | nan : Tensor [] F64
 304 |
 305 | namespace Bound
 306 |   ||| Compares less than or equal to any other value (except NaN).
 307 |   export
 308 |   min : Ord dtype => Tensor [] dtype
 309 |   min @{OrdS8}  = t0 $ MinValue S8
 310 |   min @{OrdS16} = t0 $ MinValue S16
 311 |   min @{OrdS32} = t0 $ MinValue S32
 312 |   min @{OrdS64} = t0 $ MinValue S64
 313 |   min @{OrdU8}  = t0 $ MinValue U8
 314 |   min @{OrdU16} = t0 $ MinValue U16
 315 |   min @{OrdU32} = t0 $ MinValue U32
 316 |   min @{OrdU64} = t0 $ MinValue U64
 317 |   min @{OrdF64} = tensor $ Scalar $ -1.0 / 0.0
 318 |
 319 |   ||| Compares greater than or equal to any other value (except NaN).
 320 |   export
 321 |   max : Ord dtype => Tensor [] dtype
 322 |   max @{OrdS8}  = t0 $ MaxValue S8
 323 |   max @{OrdS16} = t0 $ MaxValue S16
 324 |   max @{OrdS32} = t0 $ MaxValue S32
 325 |   max @{OrdS64} = t0 $ MaxValue S64
 326 |   max @{OrdU8}  = t0 $ MaxValue U8
 327 |   max @{OrdU16} = t0 $ MaxValue U16
 328 |   max @{OrdU32} = t0 $ MaxValue U32
 329 |   max @{OrdU64} = t0 $ MaxValue U64
 330 |   max @{OrdF64} = tensor $ Scalar $ 1.0 / 0.0
 331 |
 332 | ||| The most negative possible finite float, approx. -1.8e308
 333 | export
 334 | minFinite : Tensor [] F64
 335 | minFinite = t0 MinFiniteFloat
 336 |
 337 | ||| The most positive possible finite float, approx. 1.8e308
 338 | export
 339 | maxFinite : Tensor [] F64
 340 | maxFinite = t0 MaxFiniteFloat
 341 |
 342 | ||| Cast the element type. For example, `castDtype (tensor {dtype = S32} [1, -2])` is
 343 | ||| `tensor {dtype = F64} [1.0, -2.0]`.
 344 | export
 345 | castDtype : Integral dtype => Tensor shape dtype -> Tensor shape F64
 346 | castDtype $ MkTensor {shape} x = t0 $ Convert F64 shape x
 347 |
 348 | mkFn :
 349 |   {arity : _} -> (shapes : Vect arity Shape) -> (dtypes : Vect arity DType) ->
 350 |   forall rshapes, rdtypes .
 351 |   Func [| Tensor shapes dtypes |] (Tag $ All2 Tensor rshapes rdtypes) -> Tag $ Fn arity
 352 | mkFn shapes dtypes f = fst <$> mkFn' shapes dtypes f
 353 |
 354 | mkFn1 :
 355 |   {arity : _} -> (shapes : Vect arity Shape) -> (dtypes : Vect arity DType) ->
 356 |   Func [| Tensor shapes dtypes |] (Tag $ Tensor rshape rdtype) -> Tag $ Fn arity
 357 | mkFn1 shapes dtypes f =
 358 |   mkFn shapes dtypes $ compose (\x => pure $ the (All2 _ _ _) [!x]) f
 359 |
 360 | covering
 361 | namedFunc :
 362 |   {arity : _} -> {shapes : Vect arity Shape} -> {dtypes : Vect arity DType} ->
 363 |   forall rshapes, rdtypes .
 364 |   (shapeFn : Shape -> Shape) ->
 365 |   (forall extra . Fn (arity + extra) -> Vect arity Value -> Vect extra Value -> Op) ->
 366 |   Func [| Tensor shapes dtypes |] (Tag $ All2 Tensor rshapes rdtypes) ->
 367 |   Tag $ Func [| Tensor (shapeFn <$> shapes) dtypes |] $
 368 |     Tag $ All2 Tensor (shapeFn <$> rshapes) rdtypes
 369 | namedFunc shapeFn remapResults f = do
 370 |   (f, results) <- mkFn' shapes dtypes {rshapes, rdtypes} f
 371 |   let (extraArgs, f) = snd $ removeCaptures {n = arity} f
 372 |   MkTagT $ modify {ops $= ((f.tag, NamedFunc f) ::)}
 373 |   let remap = \args =>
 374 |         retarget 0 results <$> tag (Concrete $ remapResults f args extraArgs)
 375 |   pure $ compose remap $ args [] arity (shapeFn <$> shapes) dtypes
 376 |
 377 |   where
 378 |
 379 |   args :
 380 |     (acc : Vect p Value) ->
 381 |     (0 ar : Nat) ->
 382 |     (ss : Vect ar Shape) ->
 383 |     (ds : Vect ar DType) ->
 384 |     Func [| Tensor ss ds |] $ Vect (p + ar) Value
 385 |   args acc 0 [] [] = rewrite plusZeroRightNeutral p in acc
 386 |   args acc (S a) (s :: ss) (t :: ts) = \(MkTensor x) =>
 387 |     rewrite sym $ plusSuccRightSucc p a in args (snoc acc x) a ss ts
 388 |
 389 |   retarget : Nat -> All2 Tensor ss ds -> OpRef -> All2 Tensor (shapeFn <$> ss) ds
 390 |   retarget k [] x = []
 391 |   retarget k (MkTensor {shape, dtype} _ :: xs) x =
 392 |     MkTensor {shape = shapeFn shape, dtype} (V k x) :: retarget (S k) xs x
 393 |
 394 | ||| Function abstraction in the framework IR.
 395 | |||
 396 | ||| Operations in spidr are, by default, inlined, which can lead to large IRs. `func` abstracts
 397 | ||| (and names) a function in the IR. The resulting function will have the exact same semantics as
 398 | ||| the input, though may perform differently, depending on ML compiler behaviour.
 399 | |||
 400 | ||| Implementation note: MLIR (more specifically the "func" dialect) only supports named functions
 401 | ||| at the top (or module) level. To achieve this, `func` lifts its function to the top level,
 402 | ||| and automatically converts any variable capture to new function arguments. As such, the IR
 403 | ||| may appear different to the Idris code from which it derives.
 404 | export covering
 405 | func :
 406 |   {shapes : Vect arity Shape} -> {dtypes : Vect arity DType} -> forall rshapes, rdtypes .
 407 |   let fn = Func [| Tensor shapes dtypes |] $ Tag $ All2 Tensor rshapes rdtypes in fn -> Tag fn
 408 | func f =
 409 |   rewrite sym $ functorIdentity shapes in
 410 |   rewrite sym $ functorIdentity rshapes in
 411 |   let lc = lengthCorrect (map id shapes) in
 412 |   rewrite sym lc in
 413 |     namedFunc {arity = length (map id shapes)} id (rewrite lc in remapResults) (rewrite lc in f)
 414 |
 415 |   where
 416 |   remapResults : Fn (arity + extra) -> Vect arity Value -> Vect extra Value -> Op
 417 |   remapResults f explicitArgs extraArgs =
 418 |     CallByName f.tag (toList $ f.resultTypes) (toList $ explicitArgs ++ extraArgs)
 419 |
 420 | ||| (Experimental) function vectorization.
 421 | |||
 422 | ||| Lift a function on tensors, so that it applies element-wise across the common leading dimension
 423 | ||| of its tensor arguments. For example, for
 424 | ||| ```
 425 | ||| xs : Tensor [2, 3, 3] S32
 426 | ||| xs = tensor [[[ 0,  1,  2],
 427 | |||               [ 3,  4,  5],
 428 | |||               [ 6,  7,  8]],
 429 | |||              [[ 9, 10, 11],
 430 | |||               [12, 13, 14],
 431 | |||               [15, 16, 17]]]
 432 | |||
 433 | ||| ys : Tensor [2] S32
 434 | ||| ys = Tensor [2, -1]
 435 | ||| ```
 436 | ||| `do !(vmap (\x, y => pure $ y * diag x)) xs ys` produces `tensor [[0, 8, 16], [-9, -13, -17]]`.
 437 | |||
 438 | ||| **Warning:** `vmap` is experimental, and only implemented for a subset of the tensor API. You
 439 | ||| can see approximately which operations are supported on the Enzyme [tracking issue](https://github.com/EnzymeAD/Enzyme-JAX/issues/152).
 440 | export partial
 441 | vmap :
 442 |   {n : _} ->
 443 |   {shapes : Vect arity Shape} -> {dtypes : Vect arity DType} ->
 444 |   {rshapes : _} -> {rdtypes : _} ->
 445 |   Func [| Tensor shapes dtypes |] (Tag $ All2 Tensor rshapes rdtypes) ->
 446 |   Tag $ Func [| Tensor (map (n ::) shapes) dtypes |]
 447 |     (Tag $ All2 Tensor (map (n ::) rshapes) rdtypes)
 448 | vmap f =
 449 |   let lc = lengthCorrect shapes in
 450 |   rewrite sym lc in
 451 |     namedFunc {arity = length shapes} (n ::) (rewrite lc in remapResults) (rewrite lc in f)
 452 |
 453 |   where
 454 |   remapResults : Fn (arity + extra) -> Vect arity Value -> Vect extra Value -> Op
 455 |   remapResults f explicitArgs extraArgs =
 456 |     let extraArgs = map (V 0 . Concrete . Broadcast (AddLeading [n])) extraArgs
 457 |         outTys = zipWith (TensorType . (n ::)) rshapes rdtypes
 458 |      in Vectorize outTys [n] f.tag (toList $ explicitArgs ++ extraArgs)
 459 |
 460 | ||| (Experimental) reverse-mode automatic differentiation.
 461 | |||
 462 | ||| `grad` can be applied repeatedly to obtain higher derivatives, though we do not yet support
 463 | ||| derivatives of vector-valued functions.
 464 | |||
 465 | ||| For example, for
 466 | ||| ```
 467 | ||| f : Tensor [2] F64 -> Tag $ Tensor [] F64
 468 | ||| f x = do
 469 | |||   x <- tag x
 470 | |||   let (x0, x1) = (slice [at 0] x, slice [at 1] x)
 471 | |||   pure $ x0 / x1
 472 | ||| ```
 473 | ||| `grad f (tensor [3.0, 2.0])` produces `tensor [0.5, -0.75]`.
 474 | |||
 475 | ||| **Warning:** `grad` is experimental, and only implemented for a subset of the tensor API. You
 476 | ||| can see approximately which operations are supported on the Enzyme [tracking issue](https://github.com/EnzymeAD/Enzyme-JAX/issues/88).
 477 | export partial
 478 | grad : (Tensor shape F64 -> Tag $ Tensor [] F64) -> Tensor shape F64 -> Tag $ Tensor shape F64
 479 | grad f (MkTensor x) = pure $ t0 $ Grad shape !(mkFn1 [shape] [_] f) x
 480 |
 481 | %hide Prelude.Interfaces.product
 482 |
 483 | public export
 484 | product : List Nat -> Nat
 485 | product [] = 1
 486 | product (x :: xs) = x * product xs
 487 |
 488 | public export
 489 | sum : List Nat -> Nat
 490 | sum [] = 0
 491 | sum (x :: xs) = x + sum xs
 492 |
 493 | export
 494 | flattenable : (xs : List Nat) -> product xs === product [product xs]
 495 | flattenable [] = Refl
 496 | flattenable (x :: xs) = rewrite multOneRightNeutral (x * product xs) in Refl
 497 |
 498 | ||| Reshape a `Tensor`. For example, `reshape {to = [2, 1]} (tensor [3, 4])` is
 499 | ||| `tensor [[3], [4]]`. The output can have a different rank to the input.
 500 | export
 501 | reshape :
 502 |   {to : _} ->
 503 |   {auto 0 sizesEqual : product from = product to} ->
 504 |   Tensor from dtype ->
 505 |   Tensor to dtype
 506 | reshape $ MkTensor {shape} x = t0 $ Reshape dtype to x
 507 |
 508 | ||| Add a dimension of length one at the specified `axis`. The new dimension will be at the
 509 | ||| specified `axis` in the new `Tensor` (as opposed to the original `Tensor`). For example,
 510 | ||| `expand 1 $ tensor [[1, 2], [3, 4], [5, 6]]` is `tensor [[[1, 2]], [[3, 4]], [[5, 6]]]`.
 511 | export
 512 | expand :
 513 |   (axis : Nat) ->
 514 |   {auto 0 inBounds : axis `LTE` length shape} ->
 515 |   Tensor shape dtype ->
 516 |   Tensor (insertAt axis 1 shape) dtype
 517 | expand axis $ MkTensor {shape = _} x = t0 $ Reshape dtype (insertAt axis 1 shape) x
 518 |
 519 | namespace Squeezable
 520 |   ||| A `Squeezable from to` constitutes proof that the shape `from` can be squeezed to the
 521 |   ||| shape `to`. Squeezing is the process of removing any number of dimensions of length one.
 522 |   public export
 523 |   data Squeezable : (0 from : Shape) -> (0 to : Shape) -> Type where
 524 |     ||| Proof that a shape can be squeezed to itself. For example:
 525 |     |||
 526 |     ||| [] to []
 527 |     ||| [3, 4] to [3, 4]
 528 |     Same : Squeezable x x
 529 |
 530 |     ||| Proof that any dimensions (including those of length 1) can be preserved in the process of
 531 |     ||| squeezing. For example:
 532 |     |||
 533 |     ||| ...
 534 |     Match : Squeezable from to -> Squeezable (x :: from) (x :: to)
 535 |
 536 |     ||| Proof that any dimensions of length one can be squeezed out. For example:
 537 |     |||
 538 |     ||| [1, 3, 1, 1, 4] to [3, 4]
 539 |     Nest : Squeezable from to -> Squeezable (1 :: from) to
 540 |
 541 | ||| Remove dimensions of length one from a `Tensor` such that it has the desired shape. For example:
 542 | |||
 543 | ||| ```
 544 | ||| x : Tensor [2, 1, 3, 1] S32
 545 | ||| x = tensor [[[[4], [5], [6]]],
 546 | |||             [[[7], [8], [9]]]]
 547 | |||
 548 | ||| y : Tensor [2, 1, 3] S32
 549 | ||| y = squeeze x
 550 | ||| ```
 551 | ||| is
 552 | ||| ```
 553 | ||| y : Tensor [2, 1, 3] S32
 554 | ||| y = tensor [[[4, 5, 6]],
 555 | |||             [[7, 8, 9]]]
 556 | ||| ```
 557 | export
 558 | squeeze :
 559 |   {to : _} ->
 560 |   {auto 0 shapesSqueezable : Squeezable from to} ->
 561 |   Tensor from dtype ->
 562 |   Tensor to dtype
 563 | squeeze $ MkTensor {shape} x = t0 $ Reshape dtype to x
 564 |
 565 | ||| A `SliceOrIndex d` is a valid slice or index into a dimension of size `d`. See `slice` for
 566 | ||| details.
 567 | export
 568 | data SliceOrIndex : Nat -> Type where
 569 |   Slice :
 570 |     (from, to : Nat) ->
 571 |     {size : _} ->
 572 |     {auto 0 fromTo : from + size = to} ->
 573 |     {auto 0 inDim : LTE to d} ->
 574 |     SliceOrIndex d
 575 |   Index : (idx : Nat) -> {auto 0 inDim : LT idx d} -> SliceOrIndex d
 576 |   DynamicSlice : Tensor [] U64 -> (size : Nat) -> {auto 0 inDim : LTE size d} -> SliceOrIndex d
 577 |   DynamicIndex : Tensor [] U64 -> SliceOrIndex d
 578 |
 579 | ||| Index at `idx`. See `slice` for details.
 580 | public export
 581 | at : (idx : Nat) -> {auto 0 inDim : LT idx d} -> SliceOrIndex d
 582 | at = Index
 583 |
 584 | namespace Dynamic
 585 |   ||| Index at the specified index. See `slice` for details.
 586 |   public export
 587 |   at : Tensor [] U64 -> SliceOrIndex d
 588 |   at = DynamicIndex
 589 |
 590 | ||| Slice from `from` (inclusive) to `to` (exclusive). See `slice` for details.
 591 | public export
 592 | (.to) :
 593 |   (from, to : Nat) ->
 594 |   {size : _} ->
 595 |   {auto 0 fromTo : from + size = to} ->
 596 |   {auto 0 inDim : LTE to d} ->
 597 |   SliceOrIndex d
 598 | (.to) = Slice
 599 |
 600 | ||| Slice `size` elements starting at the specified scalar `U64` index. See `slice` for details.
 601 | public export
 602 | (.size) : Tensor [] U64 -> (size : Nat) -> {auto 0 inDim : LTE size d} -> SliceOrIndex d
 603 | (.size) = DynamicSlice
 604 |
 605 | ||| Slice across all indices along an axis. See `slice` for details.
 606 | public export
 607 | all : {d : _} -> SliceOrIndex d
 608 | all = Slice 0 @{%search} @{reflexive {ty = Nat}} d
 609 |
 610 | ||| A `MultiSlice shape` is a valid multi-dimensional slice into a tensor with shape `shape`.
 611 | ||| See `slice` for details.
 612 | public export
 613 | data MultiSlice : Shape -> Type where
 614 |   Nil : MultiSlice ds
 615 |   (::) : SliceOrIndex d -> MultiSlice ds -> MultiSlice (d :: ds)
 616 |
 617 | namespace MultiSlice
 618 |   ||| The shape of a tensor produced by slicing with the specified multi-dimensional slice. See
 619 |   ||| `Tensor.slice` for details.
 620 |   public export
 621 |   slice : {shape : _} -> MultiSlice shape -> Shape
 622 |   slice {shape} [] = shape
 623 |   slice {shape = (_ :: _)} (Slice {size} _ _ :: xs) = size :: slice xs
 624 |   slice {shape = (_ :: _)} (Index _ :: xs) = slice xs
 625 |   slice {shape = (_ :: _)} (DynamicSlice _ size :: xs) = size :: slice xs
 626 |   slice {shape = (_ :: _)} (DynamicIndex _ :: xs) = slice xs
 627 |
 628 | ||| Slice or index `Tensor` axes. Each axis can be sliced or indexed, and this can be done with
 629 | ||| either static (`Nat`) or dynamic (scalar `U64`) indices.
 630 | |||
 631 | ||| **Static indices**
 632 | |||
 633 | ||| Static indices are `Nat`s. For example, for
 634 | ||| ```
 635 | ||| x : Tensor [5, 6] S32
 636 | ||| x = tensor [[ 0,  1,  2,  3,  4,  5],
 637 | |||             [ 6,  7,  8,  9, 10, 11],
 638 | |||             [12, 13, 14, 15, 16, 17],
 639 | |||             [18, 19, 20, 21, 22, 23],
 640 | |||             [24, 25, 26, 27, 28, 29]]
 641 | ||| ```
 642 | ||| we can index as `slice [at 1] x` to get
 643 | ||| ```
 644 | ||| x : Tensor [6] S32
 645 | ||| x = tensor [6, 7, 8, 9, 10, 11]
 646 | ||| ```
 647 | ||| or we can slice as `slice [2.to 4] x` to get
 648 | ||| ```
 649 | ||| x : Tensor [2, 6] S32
 650 | ||| x = tensor [[12, 13, 14, 15, 16, 17],
 651 | |||             [18, 19, 20, 21, 22, 23]]
 652 | ||| ```
 653 | ||| Note that in `2.to 4`, the 2 is inclusive, and the 4 exclusive, so we return indices 2 and 3.
 654 | |||
 655 | ||| **Dynamic indices**
 656 | |||
 657 | ||| Dynamic indices are scalar `U64` values, and the API works slightly differently because we
 658 | ||| can't know the value of dynamic indices until the graph is executed. For indexing, with scalar
 659 | ||| `U64` index `i` in `slice [at i] x`, `i` is clamped to be a valid index into that dimension.
 660 | ||| For example, for `i = tensor 1`, `slice [at i] x` is
 661 | ||| ```
 662 | ||| x : Tensor [6] S32
 663 | ||| x = tensor [6, 7, 8, 9, 10, 11]
 664 | ||| ```
 665 | ||| as in the static case. However, for `i = tensor 10`, `slice [at i] x` returns the last row
 666 | ||| ```
 667 | ||| x : Tensor [6] S32
 668 | ||| x = tensor [24, 25, 26, 27, 28, 29]
 669 | ||| ```
 670 | ||| We can also slice by specifying a scalar `U64` start index, and a static size, as
 671 | ||| `slice [i.size 2] x` with `i = tensor 2` to get
 672 | ||| ```
 673 | ||| x : Tensor [2, 6] S32
 674 | ||| x = tensor [[12, 13, 14, 15, 16, 17],
 675 | |||             [18, 19, 20, 21, 22, 23]]
 676 | ||| ```
 677 | ||| For a given slice `size`, the dynamic start index is clamped such that we always get `size`
 678 | ||| elements along that axis. For example, `slice [i.size 2] x` with `i = tensor 4` is
 679 | ||| ```
 680 | ||| x : Tensor [2, 6] S32
 681 | ||| x = tensor [[18, 19, 20, 21, 22, 23],
 682 | |||             [24, 25, 26, 27, 28, 29]]
 683 | ||| ```
 684 | ||| which starts at index 3 rather than index 4.
 685 | |||
 686 | ||| **Mixed static, dynamic, slicing and indexing**
 687 | |||
 688 | ||| Each axis can only be sliced or indexed, and must use only static or dynamic indices. However,
 689 | ||| across axes, we can mix these four arbitrarily. For example, with `slice [2.to 4, at 1] x` to
 690 | ||| get
 691 | ||| ```
 692 | ||| x : Tensor [2] S32
 693 | ||| x = tensor [13, 19]
 694 | ||| ```
 695 | ||| or with `i = tensor 2` in `slice [at 1, i.size 2] x` to get
 696 | ||| ```
 697 | ||| x : Tensor [2] S32
 698 | ||| x = tensor [7, 8]
 699 | ||| ```
 700 | |||
 701 | ||| Slices and indices apply to the leading axes of the tensor. For trailing axes omitted from the
 702 | ||| multi-dimensional slice, the whole of the axis is returned. If we want to slice or index over
 703 | ||| later axes and retain all indices in a leading axis, we can use the convenience function `all`,
 704 | ||| as `slice [all, at 3] x` to get
 705 | ||| ```
 706 | ||| x : Tensor [5] S32
 707 | ||| x = tensor [[3], [9], [15], [21], [27]]
 708 | ||| ```
 709 | ||| This is exactly the same as the more manual `slice [0.to 5, at 3] x` and
 710 | ||| `slice [(tensor 0).size 5, at 3] x`.
 711 | |||
 712 | ||| @at The multi-dimensional slices and indices at which to slice the tensor.
 713 | export
 714 | slice : (at : MultiSlice shape) -> Tensor shape dtype -> Tensor (slice at) dtype
 715 | slice at $ MkTensor x = MkTensor $
 716 |   let x = val0 $ Slice (mapd start (const 0) at) (mapd stop id at) (replicate (length shape) 1) x
 717 |       -- we shortcut DynamicSlice to allow autodiff for static slicing
 718 |       x = if isDynamic at then val0 $ DynamicSlice (dynStarts [] at) (mapd size id at) x else x
 719 |    in val0 $ Reshape dtype (MultiSlice.slice at) x
 720 |
 721 |       where
 722 |       mapd : ((Nat -> a) -> {d : Nat} -> SliceOrIndex d -> a) ->
 723 |              (Nat -> a) ->
 724 |              {shape : Shape} ->
 725 |              MultiSlice shape ->
 726 |              List a
 727 |       mapd _ dflt {shape} [] = map dflt shape
 728 |       mapd f dflt (x :: xs) = f dflt x :: mapd f dflt xs
 729 |
 730 |       start : (Nat -> Nat) -> {d : Nat} -> SliceOrIndex d -> Nat
 731 |       start _ (Slice from _) = from
 732 |       start _ (Index idx) = idx
 733 |       start f {d} _ = f d
 734 |
 735 |       stop : (Nat -> Nat) -> {d : Nat} -> SliceOrIndex d -> Nat
 736 |       stop _ (Slice _ to) = to
 737 |       stop _ (Index idx) = S idx
 738 |       stop f {d} _ = f d
 739 |
 740 |       size : (Nat -> Nat) -> {d : Nat} -> SliceOrIndex d -> Nat
 741 |       size _ (Slice {size = size'} _ _) = size'
 742 |       size _ (Index _) = 1
 743 |       size _ (DynamicSlice _ size') = size'
 744 |       size _ (DynamicIndex _) = 1
 745 |
 746 |       zero : Value
 747 |       zero = val0 $ Lit [] U64 $ Scalar 0
 748 |
 749 |       isDynamic : {shape : _} -> MultiSlice shape -> Bool
 750 |       isDynamic [] = False
 751 |       isDynamic {shape = (_ :: _)} (DynamicSlice _ _ :: _) = True
 752 |       isDynamic {shape = (_ :: _)} (DynamicIndex _ :: _) = True
 753 |       isDynamic (_ :: ds) = isDynamic ds
 754 |
 755 |       dynStarts : List Value -> {shape : _} -> MultiSlice shape -> List Value
 756 |       dynStarts idxs {shape} [] = replicate (length shape) zero ++ idxs
 757 |       dynStarts idxs (DynamicSlice (MkTensor i) _ :: ds) = i :: dynStarts idxs ds
 758 |       dynStarts idxs (DynamicIndex (MkTensor i) :: ds) = i :: dynStarts idxs ds
 759 |       dynStarts idxs (_ :: ds) = zero :: dynStarts idxs ds
 760 |
 761 | ||| The starting indices of a slice with shape `sizes`, into a tensor with shape `bounds`.
 762 | export
 763 | data MultiIndex : (sizes, bounds : Shape) -> Type where
 764 |   INil : MultiIndex [] []
 765 |   IConsStatic :
 766 |     (idx : Nat) ->
 767 |     {auto inBounds : LTE (idx + s) b} ->
 768 |     MultiIndex ss bs ->
 769 |     MultiIndex (s :: ss) (b :: bs)
 770 |   IConsDynamic :
 771 |     Tensor [] U64 ->
 772 |     {auto inBounds : LTE s b} ->
 773 |     MultiIndex ss bs ->
 774 |     MultiIndex (s :: ss) (b :: bs)
 775 |
 776 | namespace MultiIndex
 777 |   ||| Scalar.
 778 |   public export
 779 |   Nil : MultiIndex [] []
 780 |   Nil = INil
 781 |
 782 |   namespace Static
 783 |     ||| A `Nat` starting index. This is statically restricted to be in bounds.
 784 |     public export
 785 |     (::) :
 786 |       (idx : Nat) ->
 787 |       {auto inBounds : LTE (idx + s) b} ->
 788 |       MultiIndex ss bs ->
 789 |       MultiIndex (s :: ss) (b :: bs)
 790 |     (::) = IConsStatic
 791 |
 792 |   namespace Dynamic
 793 |     ||| A scalar `U64` starting index. This is dynamically truncated to be in bounds.
 794 |     public export
 795 |     (::) :
 796 |       Tensor [] U64 ->
 797 |       {auto inBounds : LTE s b} ->
 798 |       MultiIndex ss bs ->
 799 |       MultiIndex (s :: ss) (b :: bs)
 800 |     (::) = IConsDynamic
 801 |
 802 | ||| Replace a slice of a tensor. For example, for
 803 | ||| ```
 804 | ||| target : Tensor [3, 4] S32
 805 | ||| target = tensor [[ 0,  1,  2,  3],
 806 | |||                  [ 4,  5,  6,  7],
 807 | |||                  [ 8,  9, 10, 11]]
 808 | |||
 809 | ||| update : Tensor [2, 2] S32
 810 | ||| update = tensor [[12, 13],
 811 | |||                  [14, 15]]
 812 | ||| ```
 813 | ||| `updateSlice [0, 1] update target` is
 814 | ||| ```
 815 | ||| y : Tensor [3, 4] S32
 816 | ||| y = tensor [[ 0, 12, 13,  3],
 817 | |||             [ 4, 14, 15,  7],
 818 | |||             [ 8,  9, 10, 11]]
 819 | ||| ```
 820 | ||| The starting index can be specified along each axis using either a `Nat` or a `U64` scalar.
 821 | ||| Note that the updated slice will always be replaced by `update`, and lie fully within `target`.
 822 | ||| This is checked statically for `Nat`. However, for `U64` scalar, the start index `at` is
 823 | ||| truncated to the maximum index for which the slice remains within `target`. For example,
 824 | ||| `updateSlice [0, (tensor $ Scalar 2)] update target` and
 825 | ||| `updateSlice [0, (tensor $ Scalar 3)] update target`
 826 | ||| ```
 827 | ||| are both
 828 | ||| ```
 829 | ||| y : Tensor [3, 4] S32
 830 | ||| y = tensor [[ 0,  1, 12, 13],
 831 | |||             [ 4,  5, 14, 15],
 832 | |||             [ 8,  9, 10, 11]]
 833 | ||| ```
 834 | |||
 835 | ||| @at The starting indices of the slice to replace.
 836 | ||| @update The tensor to replace the slice with.
 837 | ||| @target The tensor in which to replace the slice.
 838 | export
 839 | updateSlice :
 840 |   (at : MultiIndex updateShape shape) ->
 841 |   (update : Tensor updateShape dtype) ->
 842 |   (target : Tensor shape dtype) ->
 843 |   Tensor shape dtype
 844 | updateSlice at (MkTensor update) (MkTensor target) =
 845 |   t0 $ DynamicUpdateSlice target update (toList at)
 846 |
 847 |   where
 848 |
 849 |   toList : MultiIndex s r -> List Value
 850 |   toList INil = []
 851 |   toList (IConsStatic idx idxs) = val0 (Lit [] U64 (Scalar $ cast idx)) :: toList idxs
 852 |   toList (IConsDynamic (MkTensor idx) idxs) = idx :: toList idxs
 853 |
 854 | unappend : (xs : List a) -> Singleton (xs ++ ys) -> Singleton ys
 855 | unappend xs vxys with 0 (xs ++ ys) proof p
 856 |   unappend [] (Val xys) | xys = rewrite p in Val xys
 857 |   unappend (_ :: xs) (Val (_ :: xys)) | (_ :: xys) =
 858 |     unappend xs (rewrite snd $ biinjective p in Val xys)
 859 |
 860 | head : {0 xs : List a} -> Singleton (x :: xs) -> Singleton x
 861 | head (Val (x :: xs)) = Val x
 862 |
 863 | tail : {0 xs : List a} -> Singleton (x :: xs) -> Singleton xs
 864 | tail (Val (x :: xs)) = Val xs
 865 |
 866 | gather : {0 xs : List a} -> All Singleton xs -> Singleton xs
 867 | gather [] = Val []
 868 | gather (Val x :: xs) = let Val xs = gather xs in Val (x :: xs)
 869 |
 870 | map : (f : a -> b) -> Singleton x -> Singleton (f x)
 871 | map f (Val x) = Val (f x)
 872 |
 873 | shapeOnly : Tensor shape dtype -> Singleton shape
 874 | shapeOnly (MkTensor _) = Val shape
 875 |
 876 | ||| Concatenate tensors along a common axis. For example,
 877 | ||| `concat {leading = []} [tensor [[1, 2]], tensor [[3, 4]], tensor [[5, 6]]]` and
 878 | ||| `concat {leading = [_]} [tensor [[1], [3], [5]], tensor [[2], [4], [6]]]` are both
 879 | ||| `tensor [[1, 2], [3, 4], [5, 6]]`.
 880 | export
 881 | concat :
 882 |   {leading : _} ->
 883 |   All (\n => Tensor (leading ++ n :: tail) dtype) (n :: ns) ->
 884 |   Tensor (leading ++ sum (n :: ns) :: tail) dtype
 885 | -- much of this function is a workaround for https://github.com/idris-lang/Idris2/issues/3860
 886 | concat (x@(MkTensor {shape = shape@(.(_))} _) :: xs) =
 887 |   let nns = gather $ mapProperty (\s => head $ unappend leading $ shapeOnly s) (x :: xs)
 888 |       tail' = Tensor.tail $ unappend leading (shapeOnly x)
 889 |       Val shape@(_) : Singleton _ = map (leading ++) [| map Tensor.sum nns :: tail' |]
 890 |    in t0 {shape} $ Concat (length leading) (x.value :: fromList (forget $ mapProperty (.value) xs))
 891 |
 892 | ||| Transpose a matrix. For example, `(tensor [[1, 2], [3, 4]]).T` is `tensor [[1, 3], [2, 4]]`.
 893 | export
 894 | (.T) : Tensor [m, n] dtype -> Tensor [n, m] dtype
 895 | (MkTensor x).T = t0 $ Transpose [1, 0] x
 896 |
 897 | ||| Transpose axes of a tensor. This is a more general version of `(.T)`, in which you can
 898 | ||| transpose any number of axes in a tensor of arbitrary rank. The i'th axis in the resulting
 899 | ||| tensor corresponds to the `index i ordering`'th axis in the input tensor. For example, for
 900 | ||| ```
 901 | ||| x : Tensor [2, 3, 4] S32
 902 | ||| x = tensor [[[ 0,  1,  2,  3],
 903 | |||              [ 4,  5,  6,  7],
 904 | |||              [ 8,  9, 10, 11]],
 905 | |||             [[12, 13, 14, 15],
 906 | |||              [16, 17, 18, 19],
 907 | |||              [20, 21, 22, 23]]]
 908 | ||| ```
 909 | ||| `transpose [0, 2, 1] x` is
 910 | ||| ```
 911 | ||| x : Tensor [2, 4, 3] S32
 912 | ||| x = tensor [[[ 0,  4,  8],
 913 | |||              [ 1,  5,  9],
 914 | |||              [ 2,  6, 10],
 915 | |||              [ 3,  7, 11]],
 916 | |||             [[12, 16, 20],
 917 | |||              [13, 17, 21],
 918 | |||              [14, 18, 22],
 919 | |||              [15, 19, 23]]]
 920 | ||| ```
 921 | ||| `transpose [2, 0, 1] x` is
 922 | ||| ```
 923 | ||| x : Tensor [4, 2, 3] S32
 924 | ||| x = tensor [[[ 0,  4,  8],
 925 | |||              [12, 16, 20]],
 926 | |||             [[ 1,  5,  9],
 927 | |||              [13, 17, 21]],
 928 | |||             [[ 2,  6, 10],
 929 | |||              [14, 18, 22]],
 930 | |||             [[ 3,  7, 11],
 931 | |||              [15, 19, 23]]]
 932 | ||| ```
 933 | |||
 934 | ||| In order to see what effect transposing a tensor has, it can help to bear in mind the following:
 935 | ||| * if an element can be found with `slice [at 3, at 4, at 5] x` in the original tensor,
 936 | |||   that same element can instead be found with `slice [at 5, at 3, at 4]` given a
 937 | |||   `transpose [2, 0, 1]`. That is, transposing axes re-orders indices when indexing.
 938 | ||| * with `transpose [2, 0, 1]`, traversing the first axis in the result is equivalent to
 939 | |||   traversing the last axis in the input. Similarly, traversing the last axis in the result is
 940 | |||   equivalent to traversing the second axis in the input.
 941 | export
 942 | transpose :
 943 |   (ordering : List Nat) ->
 944 |   Tensor shape dtype ->
 945 |   {auto 0 lengths : length ordering = length shape} ->
 946 |   {auto 0 axesUnique : unique ordering = True} ->
 947 |   {auto 0 inBounds : All (flip InBounds shape) ordering} ->
 948 |   Tensor (multiIndex ordering shape) dtype
 949 | transpose ordering $ MkTensor x = t0 $ Transpose ordering x
 950 |
 951 | ||| A `DimBroadcastable from to` proves that a dimension of size `from` can be broadcast to a
 952 | ||| dimension of size `to`.
 953 | public export
 954 | data DimBroadcastable : (0 from : Nat) -> (0 to : Nat) -> Type where
 955 |   ||| Proof that any dimension can be broadcast to itself. For example in shapes `[2, 3]` to
 956 |   ||| `[2, 3]`.
 957 |   Same : DimBroadcastable x x
 958 |
 959 |   ||| Proof that a dimension of length one can be broadcast to any size. For example in shapes
 960 |   ||| `[2, 1]` to `[2, 3]`
 961 |   Stack : DimBroadcastable 1 _
 962 |
 963 |   ||| Proof that any dimension can be broadcast to zero. For example in shapes `[2, 3]` to `[2, 0]`.
 964 |   Zero : DimBroadcastable _ 0
 965 |
 966 | namespace Broadcastable
 967 |   ||| A `Broadcastable from to` constitutes proof that the shape `from` can be broadcast to the
 968 |   ||| shape `to`.
 969 |   public export
 970 |   data Broadcastable : (0 from : Shape) -> (0 to : Shape) -> Type where
 971 |     ||| Proof that a shape can be broadcast to itself. For example:
 972 |     |||
 973 |     ||| [] to []
 974 |     ||| [3, 4] to [3, 4]
 975 |     |||
 976 |     ||| Implementation note: we could have used `Broadcast [] []`, which would have resulted in more
 977 |     ||| atomic constructors for `Broadcastable`, but the author guesses that this implementation helps
 978 |     ||| the type checker avoid applications of `Match`.
 979 |     Same : Broadcastable x x
 980 |
 981 |     ||| Proof that a dimension of size `f` can be broadcast to size `t` if these dimensions
 982 |     ||| are `DimBroadcastable f t`. For example:
 983 |     |||
 984 |     ||| [2, 3] to [2, 3]
 985 |     ||| [2, 1] to [2, 3]
 986 |     ||| [2, 1] to [2, 0]
 987 |     Match : forall from, to .
 988 |             {auto 0 ranksEq : length from = length to} ->
 989 |             {auto 0 dimBroadcastable : DimBroadcastable f t} ->
 990 |             Broadcastable from to ->
 991 |             Broadcastable (f :: from) (t :: to)
 992 |
 993 |     ||| Proof that broadcasting can add outer dimensions i.e. nesting. For example:
 994 |     |||
 995 |     ||| [3] to [1, 3]
 996 |     ||| [3] to [5, 3]
 997 |     Nest : Broadcastable f t -> Broadcastable f (_ :: t)
 998 |
 999 | ||| A shape can be extended with any number of leading dimensions.
1000 | |||
1001 | ||| @leading The leading dimensions.
1002 | export
1003 | broadcastableByLeading : (leading : List Nat) -> Broadcastable shape (leading ++ shape)
1004 | broadcastableByLeading [] = Same
1005 | broadcastableByLeading (l :: ls) = Nest (broadcastableByLeading ls)
1006 |
1007 | ||| A scalar can be broadcast to any shape.
1008 | %hint
1009 | export
1010 | scalarToAnyOk : (to : Shape) -> Broadcastable [] to
1011 | scalarToAnyOk to = rewrite sym $ appendNilRightNeutral to in broadcastableByLeading to
1012 |
1013 | ||| Broadcast a `Tensor` to a new compatible shape. For example,
1014 | ||| ```
1015 | ||| x : Tensor [2, 3] S32
1016 | ||| x = broadcast (tensor [4, 5, 6])
1017 | ||| ```
1018 | ||| is
1019 | ||| ```
1020 | ||| x : Tensor [2, 3] S32
1021 | ||| x = tensor [[4, 5, 6], [4, 5, 6]]
1022 | ||| ```
1023 | export
1024 | broadcast :
1025 |   {to : _} -> {dtype : _} ->
1026 |   {auto shapesOK : Broadcastable from to} ->
1027 |   Tensor from dtype ->
1028 |   Tensor to dtype
1029 | broadcast $ MkTensor {shape = _} x = t0 $ Broadcast (Explicit to) x
1030 |
1031 | ||| A `Tensor` where every element has the specified value. For example,
1032 | ||| ```
1033 | ||| fives : Tensor [2, 3] S32
1034 | ||| fives = fill 5
1035 | ||| ```
1036 | ||| is
1037 | ||| ```
1038 | ||| fives : Tensor [2, 3] S32
1039 | ||| fives = tensor [[5, 5, 5],
1040 | |||                 [5, 5, 5]]
1041 | ||| ```
1042 | export
1043 | fill : {shape : _} -> {dtype : _} -> idrisType dtype -> Tensor shape dtype
1044 | fill x = broadcast {shapesOK = scalarToAnyOk shape} (tensor (Scalar x))
1045 |
1046 | ||| A constant where values increment from zero along the specified `axis`. For example,
1047 | ||| ```
1048 | ||| x : Tensor [3, 5] S32
1049 | ||| x = iota 1
1050 | ||| ```
1051 | ||| is the same as
1052 | ||| ```
1053 | ||| x : Tensor [3, 5] S32
1054 | ||| x = tensor [[0, 1, 2, 3, 4],
1055 | |||             [0, 1, 2, 3, 4],
1056 | |||             [0, 1, 2, 3, 4]]
1057 | ||| ```
1058 | ||| and
1059 | ||| ```
1060 | ||| x : Tensor [3, 5] S32
1061 | ||| x = iota 0
1062 | ||| ```
1063 | ||| is the same as
1064 | ||| ```
1065 | ||| x : Tensor [3, 5] S32
1066 | ||| x = tensor [[0, 0, 0, 0, 0],
1067 | |||             [1, 1, 1, 1, 1],
1068 | |||             [2, 2, 2, 2, 2]]
1069 | ||| ```
1070 | export
1071 | iota :
1072 |   {shape : _} ->
1073 |   {dtype : _} ->
1074 |   {auto 0 _ : Num dtype} ->
1075 |   (axis : Nat) ->
1076 |   {auto 0 inBounds : InBounds axis shape} ->
1077 |   Tensor shape dtype
1078 | iota dimension = t0 $ Iota shape dtype dimension
1079 |
1080 | ||| A while-loop operating on a single tensor.
1081 | |||
1082 | ||| `while1` iteratively checks if the tensor satisfies `condition`, and if it does, updates it with
1083 | ||| `body`.
1084 | |||
1085 | ||| **Note:** The XLA plugins impose heuristic-based rules on variable capture in higher-order
1086 | ||| functions. We do not comprehensively understand these rules, but you *might* experience runtime
1087 | ||| errors if you capture variables in `condition` or `body`, especially variables other than
1088 | ||| constants, or variables that depend on parameters to enclosing (StableHLO) scopes.
1089 | |||
1090 | ||| @condition The guard condition for each iteration.
1091 | ||| @body The update step.
1092 | ||| @initial The initial tensor.
1093 | export covering
1094 | while1 :
1095 |   (condition : Tensor shape dtype -> Tag $ Tensor [] PRED) ->
1096 |   (body : Tensor shape dtype -> Tag $ Tensor shape dtype) ->
1097 |   (initial : Tensor shape dtype) ->
1098 |   Tag $ Tensor shape dtype
1099 | while1 condition body (MkTensor i0) =
1100 |   pure $ t0 $ While !(mkFn1 [_] [_] condition) !(mkFn1 [_] [_] body) [i0]
1101 |
1102 | ||| A while-loop operating on two tensors.
1103 | |||
1104 | ||| `while2` iteratively checks if the tensors together satisfy `condition`, and if so, updates them
1105 | ||| with `body`.
1106 | |||
1107 | ||| **Note:** The XLA plugins impose heuristic-based rules on variable capture in higher-order
1108 | ||| functions. We do not comprehensively understand these rules, but you *might* experience runtime
1109 | ||| errors if you capture variables in `condition` or `body`, especially variables other than
1110 | ||| constants, or variables that depend on parameters to enclosing (StableHLO) scopes.
1111 | |||
1112 | ||| @condition The guard condition for each iteration.
1113 | ||| @body The update step.
1114 | ||| @initial One initial tensor.
1115 | ||| @initial' The other initial tensor.
1116 | export covering
1117 | while2 :
1118 |   (condition : Tensor s a -> Tensor s' a' -> Tag $ Tensor [] PRED) ->
1119 |   (body : Tensor s a -> Tensor s' a' -> Tag $ All2 Tensor [s, s'] [a, a']) ->
1120 |   (initial : Tensor s a) -> (initial' : Tensor s' a') ->
1121 |   Tag $ All2 Tensor [s, s'] [a, a']
1122 | while2 condition body (MkTensor i) (MkTensor i') = do
1123 |   res <- tag $ Concrete $ While !(mkFn1 [_, _] [_, _] condition) !(mkFn [_, _] [_, _] body) [i, i']
1124 |   pure [MkTensor $ V 0 res, MkTensor $ V 1 res]
1125 |
1126 | ||| Reduce elements along one `axis` of a `Tensor` according to a specified `reducer` `Monoid`.
1127 | ||| For example, if `x = tensor [[0, 1, 2], [3, 4, 5]]`, then reduce @{Sum} 0 x` produces
1128 | ||| `tensor [3, 5, 7]`, and `reduce @{Sum} 1 x` produces `tensor [3, 12]`.
1129 | |||
1130 | ||| **Note:** `Semigroup` doesn't use `Tag`, which limits the functions that can be used in
1131 | ||| `reduce`. However, the most commonly used semigroups don't need `Tag`, including `Sum`,
1132 | ||| `Prod`, `Min` and `Max`, so for ergonomics, we have opted to use `Monoid` as is. We can
1133 | ||| provide an overloaded variant if requested.
1134 | |||
1135 | ||| **Note:** The monoid should not depend on values bound to outer scopes, else runtime errors may
1136 | ||| occur.
1137 | |||
1138 | ||| @reducer How to reduce elements along the given `axis`.
1139 | ||| @axis The axis along which to reduce elements.
1140 | export
1141 | reduce :
1142 |   (reducer : Monoid (Tensor [] dtype)) =>
1143 |   (axes : List Nat) ->
1144 |   {auto 0 axesUnique : Sorted LT axes} ->
1145 |   {auto 0 axesInBounds : All (flip InBounds shape) axes} ->
1146 |   Tensor shape dtype ->
1147 |   Tag $ Tensor (deleteAt axes shape) dtype
1148 | reduce axes $ MkTensor x = do
1149 |   let semigroup : Monoid a -> Semigroup a
1150 |       semigroup _ = %search
1151 |
1152 |   g <- mkFn1 [_, _] [_, _] (pure .: (<+>) @{semigroup reducer})
1153 |   let MkTensor neutral' = neutral @{reducer}
1154 |   pure $ t0 $ Reduce g [neutral'] axes [x]
1155 |
1156 | ||| Sort the elements of a `Tensor` along a specified `dimension` according to a scalar-wise
1157 | ||| ordering. For sorting function `f`, elements are sorted such that for consecutive sorted
1158 | ||| elements `a` and `b`, either `f a b` is true, or `f a b` *and* `f b a` are false.
1159 | |||
1160 | ||| **Note:** Sorting is not stable, meaning elements that compare equal according the ordering may
1161 | ||| be sorted in a different order to the order they appear in the input.
1162 | |||
1163 | ||| **Note:** `sort` is limited to use comparison function without `Tag`. However, since the most
1164 | ||| commonly-used functions, including (>), (<), (>=), and (<=), don't use `Tag`, we have opted to
1165 | ||| omit it for ergonomics. We can trivially provide an overloaded variant if requested.
1166 | |||
1167 | ||| **Note:** The comparison function should not depend on values bound to outer scopes, else
1168 | ||| runtime errors may occur.
1169 | |||
1170 | ||| For example, for `x = tensor [[1, 6, 4], [3, 2, 5]]`, `sort (<) 0 x` produces
1171 | ||| `tensor [[1, 2, 4], [3, 6, 5]]`, while `sort (<) 1 x` produces
1172 | ||| `tensor [[1, 4, 6], [2, 3, 5]]`.
1173 | export
1174 | sort :
1175 |   (Tensor [] dtype -> Tensor [] dtype -> Tensor [] PRED) ->
1176 |   (dimension : Nat) ->
1177 |   Tensor shape dtype ->
1178 |   {auto 0 dimInBounds : InBounds dimension shape} ->
1179 |   Tag $ Tensor shape dtype
1180 | sort comp dimension $ MkTensor x =
1181 |   pure $ t0 $ Sort !(mkFn1 [_, _] [_, _] $ pure .: comp) dimension False x
1182 |
1183 | ||| Reverse elements along the specified axes. For example, for
1184 | ||| ```
1185 | ||| x : Tensor [2, 3] S32
1186 | ||| x = tensor [[-2, -1,  0],
1187 | |||             [ 1,  2,  3]]
1188 | ||| ```
1189 | ||| `reverse [0] x` is
1190 | ||| ```
1191 | ||| x : Tensor [2, 3] S32
1192 | ||| x = tensor [[ 1,  2,  3],
1193 | |||             [-2, -1,  0]]
1194 | ||| ```
1195 | ||| `reverse [1] x` is
1196 | ||| ```
1197 | ||| x : Tensor [2, 3] S32
1198 | ||| x = tensor [[ 0, -1, -2],
1199 | |||             [ 3,  2,  1]]
1200 | ||| ```
1201 | ||| and `reverse [0, 1] x` is
1202 | ||| ```
1203 | ||| x : Tensor [2, 3] S32
1204 | ||| x = tensor [[ 3,  2,  1],
1205 | |||             [ 0, -1, -2]]
1206 | ||| ```
1207 | |||
1208 | ||| **Note:** This function requires `axes` is ordered simply so that elements are unique.
1209 | ||| The ordering itself is irrelevant to the implementation, but ensures uniqueness without using
1210 | ||| proofs of contradiction that can be difficult for Idris to construct.
1211 | export
1212 | reverse :
1213 |   (axes : List Nat) ->
1214 |   {auto 0 axesUnique : Sorted LT axes} ->
1215 |   {auto 0 axesInBounds : All (flip InBounds shape) axes} ->
1216 |   Tensor shape dtype ->
1217 |   Tensor shape dtype
1218 | reverse axes $ MkTensor x = t0 $ Reverse axes x
1219 |
1220 | ewUnary : UnaryOp -> Tensor s a -> Tensor s a
1221 | ewUnary op $ MkTensor x = t0 $ UnaryElementwise op x
1222 |
1223 | ewUnary' : {a' : _} -> UnaryOp -> Tensor s a -> Tensor s a'
1224 | ewUnary' op $ MkTensor x = t0 $ UnaryElementwise op x
1225 |
1226 | ewBinary : BinaryOp -> Tensor s a -> Tensor s a -> Tensor s a
1227 | ewBinary op (MkTensor x) (MkTensor x') = t0 $ BinaryElementwise op x x'
1228 |
1229 | ewBinary' : {out : _} -> BinaryOp -> Tensor s a -> Tensor s a -> Tensor s out
1230 | ewBinary' op (MkTensor x) (MkTensor x') = t0 $ BinaryElementwise op x x'
1231 |
1232 | ||| Element-wise equality. For example, `tensor [1, 2] /= tensor [1, 3]` is
1233 | ||| `tensor [True, False]`.
1234 | export
1235 | (==) : Tensor shape dtype -> Tensor shape dtype -> Tensor shape PRED
1236 | (==) = ewBinary' $ Compare Eq
1237 |
1238 | ||| Element-wise inequality. For example, `tensor [1, 2] /= tensor [1, 3]` is
1239 | ||| `tensor [False, True]`.
1240 | export
1241 | (/=) : Tensor shape dtype -> Tensor shape dtype -> Tensor shape PRED
1242 | (/=) = ewBinary' $ Compare Ne
1243 |
1244 | ||| Element-wise less than. For example, `tensor [1, 2, 3] < tensor [2, 2, 2]` is
1245 | ||| `tensor [True, False, False]`.
1246 | export
1247 | (<) : Ord dtype => Tensor shape dtype -> Tensor shape dtype -> Tensor shape PRED
1248 | (<) = ewBinary' $ Compare Lt
1249 |
1250 | ||| Element-wise greater than. For example, `tensor [1, 2, 3] > tensor [2, 2, 2]` is
1251 | ||| `tensor [False, False, True]`.
1252 | export
1253 | (>) : Ord dtype => Tensor shape dtype -> Tensor shape dtype -> Tensor shape PRED
1254 | (>) = ewBinary' $ Compare Gt
1255 |
1256 | ||| Element-wise less than or equal. For example, `tensor [1, 2, 3] <= tensor [2, 2, 2]`
1257 | ||| is `tensor [True, True, False]`.
1258 | export
1259 | (<=) : Ord dtype => Tensor shape dtype -> Tensor shape dtype -> Tensor shape PRED
1260 | (<=) = ewBinary' $ Compare Le
1261 |
1262 | ||| Element-wise greater than or equal. For example,
1263 | ||| `tensor [1, 2, 3] >= tensor [2, 2, 2]` is `tensor [False, True, True]`.
1264 | export
1265 | (>=) : Ord dtype => Tensor shape dtype -> Tensor shape dtype -> Tensor shape PRED
1266 | (>=) = ewBinary' $ Compare Ge
1267 |
1268 | ||| Element-wise boolean and. For example,
1269 | ||| `tensor [True, True, False, False] && tensor [True, False, True, False]` is
1270 | ||| `tensor [True, False, False, False]`.
1271 | export
1272 | (&&) : Tensor shape PRED -> Tensor shape PRED -> Tensor shape PRED
1273 | (&&) = ewBinary And
1274 |
1275 | namespace Semigroup
1276 |   export
1277 |   [All] Semigroup (Tensor shape PRED) where
1278 |     (<+>) = (&&)
1279 |
1280 | namespace Monoid
1281 |   export
1282 |   [All] {shape : _} -> Monoid (Tensor shape PRED) using Tensor.Semigroup.All where
1283 |     neutral = fill True
1284 |
1285 | ||| Element-wise boolean or. For example,
1286 | ||| `tensor [True, True, False, False] || tensor [True, False, True, False]` is
1287 | ||| `tensor [True, True, True, False]`.
1288 | export
1289 | (||) : Tensor shape PRED -> Tensor shape PRED -> Tensor shape PRED
1290 | (||) = ewBinary Or
1291 |
1292 | namespace Semigroup
1293 |   export
1294 |   [Any] Semigroup (Tensor shape PRED) where
1295 |     (<+>) = (||)
1296 |
1297 | namespace Monoid
1298 |   export
1299 |   [Any] {shape : _} -> Monoid (Tensor shape PRED) using Tensor.Semigroup.Any where
1300 |     neutral = fill False
1301 |
1302 | ||| Element-wise boolean negation. For example, `not (tensor [True, False])` is
1303 | ||| `tensor [False, True]`.
1304 | export
1305 | not : Tensor shape PRED -> Tensor shape PRED
1306 | not = ewUnary Not
1307 |
1308 | ||| Elementwise, bitwise "and".
1309 | export
1310 | (.&.) : Integral dtype => Tensor shape dtype -> Tensor shape dtype -> Tensor shape dtype
1311 | (.&.) = ewBinary And
1312 |
1313 | ||| Elementwise, bitwise "or".
1314 | export
1315 | (.|.) : Integral dtype => Tensor shape dtype -> Tensor shape dtype -> Tensor shape dtype
1316 | (.|.) = ewBinary Or
1317 |
1318 | ||| Elementwise, bitwise exclusive "or".
1319 | export
1320 | xor : Integral dtype => Tensor shape dtype -> Tensor shape dtype -> Tensor shape dtype
1321 | xor = ewBinary Xor
1322 |
1323 | ||| Elementwise, bitwise left shift by `n` bits.
1324 | export
1325 | shiftL : Integral dtype => Tensor shape dtype -> (n : Tensor shape U8) -> Tensor shape dtype
1326 | shiftL (MkTensor x) (MkTensor n) = t0 $ BinaryElementwise ShiftLeft x (val0 $ Convert dtype shape n)
1327 |
1328 | public export
1329 | data ShiftRule = Logical | Arithmetic
1330 |
1331 | ||| Elementwise, bitwise right shift by `n` bits. If the `ShiftRule` is `Logical`, the `n` left-most
1332 | ||| bits are zero. If it is `Arithmetic`, they are copied from the original left-most bit.
1333 | export
1334 | shiftR :
1335 |   ShiftRule ->
1336 |   Integral dtype =>
1337 |   Tensor shape dtype ->
1338 |   (n : Tensor shape U8) ->
1339 |   Tensor shape dtype
1340 | shiftR rule (MkTensor x) (MkTensor n) =
1341 |   let op = case rule of
1342 |         Logical => ShiftRightLogical
1343 |         Arithmetic => ShiftRightArithmetic
1344 |    in t0 $ BinaryElementwise op x (val0 $ Convert dtype shape n)
1345 |
1346 | ||| Elementwise, bitwise complement.
1347 | export
1348 | complement : Integral dtype => Tensor shape dtype -> Tensor shape dtype
1349 | complement = ewUnary Not
1350 |
1351 | ||| Elementwise, the number of bits set in the operand.
1352 | export
1353 | popCount : Integral dtype => Tensor shape dtype -> Tensor shape dtype
1354 | popCount = ewUnary PopulationCount
1355 |
1356 | ||| Elementwise, the number of leading zeros in the operand.
1357 | export
1358 | leadingZeros : Integral dtype => Tensor shape dtype -> Tensor shape dtype
1359 | leadingZeros = ewUnary Clz
1360 |
1361 | ||| Choose elements from two `Tensor`s based on a `Tensor` of predicates. For each element in the
1362 | ||| predicates, the output will use the corresponding element from `onTrue` if the element is
1363 | ||| truthy, else the element from `onFalse`. For example, for
1364 | ||| ```
1365 | ||| preds : Tensor [3] PRED
1366 | ||| preds = tensor [False, True, False]
1367 | |||
1368 | ||| onTrue : Tensor [3] S32
1369 | ||| onTrue = tensor [1, 2, 3]
1370 | |||
1371 | ||| onFalse : Tensor [3] S32
1372 | ||| onFalse = tensor [4, 5, 6]
1373 | ||| ```
1374 | ||| `select preds onTrue onFalse` is `tensor [4, 2, 6]`.
1375 | |||
1376 | ||| @onTrue The elements to choose where the predicate elements are truthy.
1377 | ||| @onFalse The elements to choose where the predicate elements are falsy.
1378 | export
1379 | select :
1380 |   Tensor shape PRED ->
1381 |   (onTrue, onFalse : Tensor shape dtype) ->
1382 |   Tensor shape dtype
1383 | select (MkTensor p) (MkTensor t) (MkTensor f) = t0 $ Select p t f
1384 |
1385 | ||| Use a scalar predicate to evaluate one of two branches. If the predicate is truthy,
1386 | ||| evaluate `onTrue`, else `onFalse`. Each branch is evaluated lazily; only one will be
1387 | ||| evaluated.
1388 | |||
1389 | ||| For example, for
1390 | ||| ```
1391 | ||| f : Tensor [] F64 -> Tag $ Tensor [] F64
1392 | ||| f x = if_ (x < 1.0) (pure $ cos x) (do x <- tag x; x * x)
1393 | ||| ```
1394 | ||| `f 0.0` produces `1.0`, and `f 4.0` produces `8.0`.
1395 | |||
1396 | ||| **Note:** Branches to `if_` are interpreted as constant StableHLO functions. The XLA plugins
1397 | ||| impose heuristic-based rules on variable capture in higher-order functions. We do not
1398 | ||| comprehensively understand these rules, but you *might* experience runtime errors if you capture
1399 | ||| variables in the branches, especially variables other than constants, or variables that depend
1400 | ||| on parameters to enclosing (StableHLO) scopes.
1401 | |||
1402 | ||| @onTrue The branch to evaluate if the predicate is truthy.
1403 | ||| @onFalse The branch to evaluate if the predicate is falsy.
1404 | export
1405 | if_ :
1406 |   {shape : _} -> {dtype : _} ->
1407 |   Tensor [] PRED ->
1408 |   (onTrue, onFalse : Tag $ Tensor shape dtype) ->
1409 |   Tag $ Tensor shape dtype
1410 | if_ (MkTensor pred) onTrue onFalse =
1411 |   pure $ t0 $ If (TensorType shape dtype) pred !(mkFn1 [] [] onTrue) !(mkFn1 [] [] onFalse)
1412 |
1413 | ||| Run the branch in `branches` specified by `index`, and return its result. If `index` is out of
1414 | ||| bounds of `branches`, uses the last branch. Each branch is evaluated lazily; only one is
1415 | ||| evaluated.
1416 | |||
1417 | ||| For example, for
1418 | ||| ```
1419 | ||| f : Int32 -> Tag $ Tensor [] F64
1420 | ||| f x = case_ (tensor x) (pure $ cos 0.0) (pure $ sin pi) (square 2.0)
1421 | ||| ```
1422 | ||| `f 0` produces `1.0` and `f 1` produces `-1.0`, while `f (-1)`, `f 2`, and `f 3`
1423 | ||| all produce `8.0`.
1424 | |||
1425 | ||| **Note:** Branches are interpreted as constant StableHLO functions. The XLA plugins
1426 | ||| impose heuristic-based rules on variable capture in higher-order functions. We do not
1427 | ||| comprehensively understand these rules, but you *might* experience runtime errors if you capture
1428 | ||| variables in the branches, especially variables other than constants, or variables that depend
1429 | ||| on parameters to enclosing (StableHLO) scopes.
1430 | export
1431 | case_ :
1432 |   {shape : _} -> {dtype : _} ->
1433 |   (index : Tensor [] S32) ->
1434 |   (branches : Vect (S _) $ Tag $ Tensor shape dtype) ->
1435 |   Tag $ Tensor shape dtype
1436 | case_ (MkTensor index) branches =
1437 |   pure $ t0 $ Case (TensorType shape dtype) index $ toList !(traverse (mkFn1 [] []) branches)
1438 |
1439 | ||| The identity tensor, with inferred shape and element type. For example,
1440 | ||| ```
1441 | ||| x : Tensor [2, 2] S32
1442 | ||| x = identity
1443 | ||| ```
1444 | ||| is
1445 | ||| ```
1446 | ||| x : Tensor [2, 2] S32
1447 | ||| x = tensor [[1, 0],
1448 | |||             [0, 1]]
1449 | ||| ```
1450 | export
1451 | identity : {n : _} -> {dtype : _} -> Num dtype => Tensor [n, n] dtype
1452 | identity =
1453 |   let MkTensor x = iota 0 {shape = [n, n], dtype = U64} == iota 1
1454 |    in t0 $ Convert dtype [n, n] x
1455 |
1456 | -- see https://www.python.org/dev/peps/pep-0465/#precedence-and-associativity
1457 | export infixl 9 @@
1458 |
1459 | namespace Vector
1460 |   ||| Vector dot product with a tensor of any rank. The vector dot product is with the first axis of
1461 |   ||| the right-hand side tensor. For example `tensor [0, 1, 2] @@ tensor [-1, -3, -1]` is
1462 |   ||| `-1`.
1463 |   export
1464 |   (@@) : Num dtype => Tensor [S m] dtype -> Tensor [S m] dtype -> Tensor [] dtype
1465 |   (MkTensor x) @@ (MkTensor x') = t0 $ DotGeneral [] [] [0] [0] (TensorType [] dtype) x x'
1466 |
1467 | namespace Matrix
1468 |   ||| Matrix multiplication with a matrix or vector. Contraction is along the last axis of the first
1469 |   ||| and the first axis of the last. For example,
1470 |   ||| ```
1471 |   ||| x : Tensor [2, 3] S32
1472 |   ||| x = tensor [[-1, -2, -3],
1473 |   |||             [ 0,  1,  2]]
1474 |   |||
1475 |   ||| y : Tensor [3, 1] S32
1476 |   ||| y = tensor [[4, 0, 5]]
1477 |   |||
1478 |   ||| z : Tensor [2, 1] S32
1479 |   ||| z = x @@ y
1480 |   ||| ```
1481 |   ||| is
1482 |   ||| ```
1483 |   ||| z : Tensor [2, 1] S32
1484 |   ||| z = tensor [-19, 10]
1485 |   ||| ```
1486 |   export
1487 |   (@@) : Num dtype =>
1488 |          Tensor [n, S m] dtype ->
1489 |          Tensor (S m :: tl) dtype ->
1490 |          {auto 0 vectorTail : length tl `LTE` 1} ->
1491 |          Tensor (n :: tl) dtype
1492 |   (MkTensor x) @@ (MkTensor x') = t0 $ DotGeneral [] [] [1] [0] (TensorType (n :: tl) dtype) x x'
1493 |
1494 | ||| The output shape of a `dotGeneral` operation.
1495 | public export
1496 | contract : (lBatch, rBatch, lContract, rContract : List Nat) ->
1497 |            (ls, rs : Shape) ->
1498 |            {auto 0 lInBoundsBatch : All (flip InBounds ls) lBatch} ->
1499 |            {auto 0 rInBoundsBatch : All (flip InBounds rs) rBatch} ->
1500 |            {auto 0 lInBoundsContract : All (flip InBounds ls) lContract} ->
1501 |            {auto 0 rInBoundsContract : All (flip InBounds rs) rContract} ->
1502 |            Shape
1503 | contract lBatch rBatch lContract rContract ls rs =
1504 |   let lResultDims = deleteAt {inBounds = lInBoundsBatch ++ lInBoundsContract}
1505 |                              (lBatch ++ lContract) ls
1506 |       rResultDims = deleteAt {inBounds = rInBoundsBatch ++ rInBoundsContract}
1507 |                              (rBatch ++ rContract) rs
1508 |    in multiIndex lBatch ls ++ lResultDims ++ rResultDims
1509 |
1510 | ||| Matrix multiplication.
1511 | |||
1512 | ||| This is a much more general version of `(@@)`, in which you can specify any number of batch
1513 | ||| and contracting axes. Matrix multiplication is done over each contracting axis.
1514 | ||| The operation is vectorized over batch axes. For each contracting axis on the left-hand
1515 | ||| operand, there is one contracting axis on the right-hand operand. These can be different axes
1516 | ||| in each operand. The same is true for each batch axis.
1517 | |||
1518 | ||| For example, we can vectorize over a typical rank-two matrix multiplication as follows: given
1519 | ||| two inputs tensors
1520 | ||| ```
1521 | ||| let x : Tensor [3, 4, 5, 6] F64
1522 | |||     y : Tensor [3, 4, 6, 7] F64
1523 | ||| ```
1524 | ||| we do
1525 | ||| ```
1526 | ||| let z : Tensor [3, 4, 5, 7] F64 = dotGeneral [0, 1] [0, 1] [3] [2] x y
1527 | ||| ```
1528 | ||| Here, we vectorized over the first two axes `[0, 1]`, and do standard matrix multiplication
1529 | ||| over the remaining axes by specifying the axes 3 and 2 respectively as contracting axes. Notice
1530 | ||| how the batch axes appear once each at the start of the output shape, and the contracting axis
1531 | ||| disappears. Remaining axes appear in order from left to right.
1532 | |||
1533 | ||| Note this API is somewhat of a quickfix to bring general matrix multiplication to the tensor
1534 | |||   API. It is not thoroughly tested. Expect it to change in the future.
1535 | export
1536 | dotGeneral :
1537 |   Num dtype =>
1538 |   (lBatch, rBatch, lContract, rContract : List Nat) ->
1539 |   {auto 0 lUnique : unique (lBatch ++ lContract) = True} ->
1540 |   {auto 0 rUnique : unique (rBatch ++ rContract) = True} ->
1541 |   {auto 0 lInBoundsBatch : All (flip InBounds ls) lBatch} ->
1542 |   {auto 0 rInBoundsBatch : All (flip InBounds rs) rBatch} ->
1543 |   {auto 0 lInBoundsContract : All (flip InBounds ls) lContract} ->
1544 |   {auto 0 rInBoundsContract : All (flip InBounds rs) rContract} ->
1545 |   {auto 0 batchDimsEq : multiIndex lBatch ls = multiIndex rBatch rs} ->
1546 |   {auto 0 contractDimsEq : multiIndex lContract ls = multiIndex rContract rs} ->
1547 |   Tensor ls dtype ->
1548 |   Tensor rs dtype ->
1549 |   Tensor (contract lBatch rBatch lContract rContract ls rs) dtype
1550 | dotGeneral lb rb lc rc (MkTensor x) (MkTensor y) =
1551 |   let resultType = TensorType (contract lb rb lc rc ls rs) dtype
1552 |    in t0 $ DotGeneral lb rb lc rc resultType x y
1553 |
1554 | ||| Element-wise addition. For example, `tensor [1, 2] + tensor [3, 4]` is
1555 | ||| `tensor [4, 6]`.
1556 | export
1557 | (+) : Num dtype => Tensor shape dtype -> Tensor shape dtype -> Tensor shape dtype
1558 | (+) = ewBinary Add
1559 |
1560 | namespace Semigroup
1561 |   export
1562 |   [Sum] Num dtype => Semigroup (Tensor shape dtype) where
1563 |     (<+>) = (+)
1564 |
1565 | namespace Monoid
1566 |   export
1567 |   [Sum] {shape : _} -> {dtype : _} -> Prelude.Num (idrisType dtype) => Num dtype =>
1568 |     Monoid (Tensor shape dtype) using Semigroup.Sum where
1569 |       neutral = fill 0
1570 |
1571 | ||| Element-wise negation. For example, `- tensor [1, -2]` is `tensor [-1, 2]`.
1572 | export
1573 | negate : Neg dtype => Tensor shape dtype -> Tensor shape dtype
1574 | negate $ MkTensor i = t0 $ UnaryElementwise Neg i
1575 |
1576 | ||| Element-wise subtraction. For example, `tensor [3, 4] - tensor [4, 2]` is
1577 | ||| `tensor [-1, 2]`.
1578 | export
1579 | (-) : Neg dtype => Tensor shape dtype -> Tensor shape dtype -> Tensor shape dtype
1580 | (-) = ewBinary Sub
1581 |
1582 | ||| Element-wise multiplication. For example, `tensor [2, 3] * tensor [4, 5]` is
1583 | ||| `tensor [8, 15]`.
1584 | export
1585 | (*) : Num dtype => Tensor shape dtype -> Tensor shape dtype -> Tensor shape dtype
1586 | (*) = ewBinary Mul
1587 |
1588 | namespace Semigroup
1589 |   export
1590 |   [Prod] Num dtype => Semigroup (Tensor shape dtype) where
1591 |     (<+>) = (*)
1592 |
1593 | namespace Monoid
1594 |   export
1595 |   [Prod] {shape : _} -> {dtype : _} -> Prelude.Num (idrisType dtype) => Num dtype =>
1596 |     Monoid (Tensor shape dtype) using Semigroup.Prod where
1597 |       neutral = fill 1
1598 |
1599 | ||| Element-wise floating point division. For example, `tensor [2, 3] / tensor [4, 5]` is
1600 | ||| `tensor [0.5, 0.6]`.
1601 | export
1602 | (/) : Fractional dtype => Tensor shape dtype -> Tensor shape dtype -> Tensor shape dtype
1603 | (/) = ewBinary Div
1604 |
1605 | inf = tensor 1.0 / tensor 0.0
1606 | nan = tensor 0.0 / tensor 0.0
1607 |
1608 | ||| Element-wise division of natural numbers. For example,
1609 | ||| `div (tensor [13, 8]) [3, 4]` is `tensor [4, 2]`.
1610 | |||
1611 | ||| **Note:** Broadcasting a single value into a large `Literal` will be slower than for a `Tensor`.
1612 | ||| For this reason, if you're using a single common denominator, consider using `Scalarwise.div`.
1613 | export
1614 | div : Tensor shape U64 ->
1615 |       (denom : Literal shape Nat) ->
1616 |       {auto 0 isSucc : All IsSucc denom} ->
1617 |       Tensor shape U64
1618 | div x y with (x)
1619 |   _ | (MkTensor {shape = _} _) = ewBinary Div x (tensor {dtype = U64} $ cast <$> y)
1620 |
1621 | namespace Scalarwise
1622 |   ||| Overload of `div` for common denominator. The denominator is broadcast to match the numerator.
1623 |   export
1624 |   div :
1625 |     Tensor (d :: ds) U64 ->
1626 |     (denom : Nat) ->
1627 |     {auto 0 isSucc : IsSucc denom} ->
1628 |     Tensor (d :: ds) U64
1629 |   div x y with (x)
1630 |     _ | (MkTensor {shape = _} _) = ewBinary Div x (fill {dtype = U64} $ cast y)
1631 |
1632 | namespace Integral
1633 |   ||| Element-wise remainder for natural numbers. For example,
1634 |   ||| `rem (tensor [13, 8]) [3, 4]` is `tensor [1, 0]`.
1635 |   |||
1636 |   ||| **Note:** Broadcasting a single value into a large `Literal` will be slower than for a
1637 |   ||| `Tensor`. For this reason, if you're using a single common denominator, consider using
1638 |   ||| `Scalarwise.rem`.
1639 |   export
1640 |   rem : Tensor shape U64 ->
1641 |         (denom : Literal shape Nat) ->
1642 |         {auto 0 isSucc : All IsSucc denom} ->
1643 |         Tensor shape U64
1644 |   rem x y with (x)
1645 |     _ | (MkTensor {shape = _} _) = ewBinary Rem x (tensor {dtype = U64} $ cast <$> y)
1646 |
1647 |   namespace Scalarwise
1648 |     ||| Overload of `rem` for a common denominator. The denominator is broadcast to match the
1649 |     ||| numerator.
1650 |     export
1651 |     rem :
1652 |       Tensor (d :: ds) U64 ->
1653 |       (denom : Nat) ->
1654 |       {auto 0 isSucc : IsSucc denom} ->
1655 |       Tensor (d :: ds) U64
1656 |     rem x y with (x)
1657 |       _ | (MkTensor {shape = _} _) = ewBinary Rem x (fill {dtype = U64} $ cast y)
1658 |
1659 | ||| Each element in `base` raised to the power of the corresponding element in `exponent`.
1660 | ||| example, `pow (tensor [2, 25, -9]) (tensor [3, -0.5, 0.5])` is `tensor [8, 0.2, nan]`.
1661 | |||
1662 | ||| **Note:** The first root is used. Fractional powers of negative numbers return NaN.
1663 | export
1664 | pow : (base, exponent : Tensor shape F64) -> Tensor shape F64
1665 | pow = ewBinary Pow
1666 |
1667 | ||| Element-wise, whether a number is *not* infinity or NaN.
1668 | export
1669 | isFinite : Tensor shape F64 -> Tensor shape PRED
1670 | isFinite = ewUnary' IsFinite
1671 |
1672 | ||| Element-wise sign. For example, `sign (tensor [-2, 0, 2, nan])` is `tensor [-1, 0, 1, nan]`.
1673 | export
1674 | sign : Neg dtype => Tensor shape dtype -> Tensor shape dtype
1675 | sign = ewUnary Sign
1676 |
1677 | ||| Element-wise absolute value. For example, `abs (tensor [-2, 3])` is `tensor [2, 3]`.
1678 | export
1679 | abs : Abs dtype => Tensor shape dtype -> Tensor shape dtype
1680 | abs = ewUnary Abs
1681 |
1682 | ||| The element-wise natural exponential. For example, `exp (tensor [-1, 0, 2])` is
1683 | ||| `tensor [1 / euler, 1, pow euler 2]`.
1684 | export
1685 | exp : Tensor shape F64 -> Tensor shape F64
1686 | exp = ewUnary Exp
1687 |
1688 | ||| The element-wise natural exponential, minus one, equivalent to `(`subtract` 1) . exp`.
1689 | export
1690 | expM1 : Tensor shape F64 -> Tensor shape F64
1691 | expM1 = ewUnary ExpM1
1692 |
1693 | ||| The element-wise floor function. For example,
1694 | ||| `floor (tensor [-1.6, -1.5, -1.4, -1.0, 1.0, 1.4, 1.5, 1.6])` is
1695 | ||| `tensor [-2.0, -2.0, -2.0, -1.0, 1.0, 1.0, 1.0, 1.0]`.
1696 | export
1697 | floor : Tensor shape F64 -> Tensor shape F64
1698 | floor = ewUnary Floor
1699 |
1700 | ||| The element-wise ceiling function. For example,
1701 | ||| `ceil (tensor [-1.6, -1.5, -1.4, -1.0, 1.0, 1.4, 1.5, 1.6])` is
1702 | ||| `tensor [-1.0, -1.0, -1.0, -1.0, 1.0, 2.0, 2.0, 2.0]`.
1703 | export
1704 | ceil : Tensor shape F64 -> Tensor shape F64
1705 | ceil = ewUnary Ceil
1706 |
1707 | public export
1708 | data BreakTies = AwayFromZero | ToEven
1709 |
1710 | ||| Round each element to the nearest integer, breaking ties according to the `BreakTies`.
1711 | |||
1712 | ||| `AwayFromZero` breaks ties away from zero, for example
1713 | ||| `round (tensor [-1.6, -1.5, -1.4, -1.0, -0.5, 0.1, 0.5, 1.0, 1.4, 1.5, 1.6])` is
1714 | ||| `tensor [-2.0, -2.0, -1.0, -1.0, -1.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0]`.
1715 | |||
1716 | ||| `ToEven` breaks ties to the nearest even, for example,
1717 | ||| `round (tensor [-1.6, -1.5, -1.4, -1.0, -0.5, 0.5, 1.0, 1.4, 1.5, 1.6])` is
1718 | ||| `tensor [-2.0, -2.0, -1.0, -1.0, 0.0, 0.0, 1.0, 1.0, 2.0, 2.0]`
1719 | export
1720 | round : BreakTies -> Tensor shape F64 -> Tensor shape F64
1721 | round AwayFromZero = ewUnary RoundAFZ
1722 | round ToEven = ewUnary RoundEven
1723 |
1724 | ||| The element-wise natural logarithm. Negative inputs yield NaN output. For example,
1725 | ||| `log (tensor [1 / euler, 1, euler * euler])` is `tensor [-1, 0, 2]`.
1726 | export
1727 | log : Tensor shape F64 -> Tensor shape F64
1728 | log = ewUnary Log
1729 |
1730 | ||| The element-wise natural logarithm of the input plus one, equivalent to `log . (+ 1)`.
1731 | ||| Inputs less than (-1) yield NaN.
1732 | export
1733 | log1p : Tensor shape F64 -> Tensor shape F64
1734 | log1p = ewUnary Log1p
1735 |
1736 | ||| The element-wise logistic function equivalent to `1 / 1 + exp (-x)`.
1737 | export
1738 | logistic : Tensor shape F64 -> Tensor shape F64
1739 | logistic = ewUnary Logistic
1740 |
1741 | ||| The element-wise sine.
1742 | export
1743 | sin : Tensor shape F64 -> Tensor shape F64
1744 | sin = ewUnary Sin
1745 |
1746 | ||| The element-wise cosine.
1747 | export
1748 | cos : Tensor shape F64 -> Tensor shape F64
1749 | cos = ewUnary Cos
1750 |
1751 | ||| The element-wise tangent.
1752 | export
1753 | tan : Tensor shape F64 -> Tensor shape F64
1754 | tan = ewUnary Tan
1755 |
1756 | ||| The element-wise arcsine.
1757 | export
1758 | asin : Tensor shape F64 -> Tensor shape F64
1759 | asin = ewUnary Asin
1760 |
1761 | ||| The element-wise arccosine.
1762 | export
1763 | acos : Tensor shape F64 -> Tensor shape F64
1764 | acos = ewUnary Acos
1765 |
1766 | ||| The element-wise arctangent.
1767 | export
1768 | atan : Tensor shape F64 -> Tensor shape F64
1769 | atan = ewUnary Atan
1770 |
1771 | ||| The element-wise two-argument arctangent: the angle between the vector (x, y) and the positive
1772 | ||| x-axis.
1773 | export
1774 | atan2 : (y, x : Tensor shape F64) -> Tensor shape F64
1775 | atan2 = ewBinary Atan2
1776 |
1777 | ||| The element-wise hyperbolic sine.
1778 | export
1779 | sinh : Tensor shape F64 -> Tensor shape F64
1780 | sinh = ewUnary Sinh
1781 |
1782 | ||| The element-wise hyperbolic cosine.
1783 | export
1784 | cosh : Tensor shape F64 -> Tensor shape F64
1785 | cosh = ewUnary Cosh
1786 |
1787 | ||| The element-wise hyperbolic tangent.
1788 | export
1789 | tanh : Tensor shape F64 -> Tensor shape F64
1790 | tanh = ewUnary Tanh
1791 |
1792 | ||| The element-wise hyperbolic arcsine.
1793 | export
1794 | asinh : Tensor shape F64 -> Tensor shape F64
1795 | asinh = ewUnary Asinh
1796 |
1797 | ||| The element-wise hyperbolic arccosine.
1798 | export
1799 | acosh : Tensor shape F64 -> Tensor shape F64
1800 | acosh = ewUnary Acosh
1801 |
1802 | ||| The element-wise hyperbolic arctangent.
1803 | export
1804 | atanh : Tensor shape F64 -> Tensor shape F64
1805 | atanh = ewUnary Atanh
1806 |
1807 | ||| An approximation to the element-wise error function.
1808 | export
1809 | erf : Tensor shape F64 -> Tensor shape F64
1810 | erf = ewUnary Erf
1811 |
1812 | erfInv : Tensor shape F64 -> Tensor shape F64
1813 | erfInv = ewUnary ErfInv
1814 |
1815 | ||| The element-wise square. For example, `square (tensor [-2, 0, 3])`
1816 | ||| is `tensor [4, 0, 9]`.
1817 | export
1818 | square : Num dtype => Tensor shape dtype -> Tensor shape dtype
1819 | square = ewUnary Square
1820 |
1821 | ||| The element-wise square root. The first root is used. Negative inputs yield NaN output.
1822 | ||| For example, `sqrt (tensor [0, 9])` is `tensor [0, 3]`.
1823 | export
1824 | sqrt : Tensor shape F64 -> Tensor shape F64
1825 | sqrt = ewUnary Sqrt
1826 |
1827 | ||| The element-wise reciprocal square root. The first root is used. Negative inputs yield NaN output.
1828 | ||| For example, `rsqrt (tensor [0, 4])` is `tensor [inf, 0.5]`.
1829 | export
1830 | rsqrt : Tensor shape F64 -> Tensor shape F64
1831 | rsqrt = ewUnary Rsqrt
1832 |
1833 | ||| The element-wise cube root. The first root is used. Negative inputs yield negative outputs.
1834 | ||| For example, `cbrt (tensor [8, -27])` is `tensor [2, -3]`.
1835 | export
1836 | cbrt : Tensor shape F64 -> Tensor shape F64
1837 | cbrt = ewUnary Cbrt
1838 |
1839 | ||| The element-wise minimum of the first argument compared to the second. For example,
1840 | ||| `min (tensor [-3, -1, 3]) (tensor [-1, 0, 1])` is `tensor [-3, -1, 1]`.
1841 | export
1842 | min : Ord dtype => Tensor shape dtype -> Tensor shape dtype -> Tensor shape dtype
1843 | min (MkTensor x) (MkTensor x') = t0 $ BinaryElementwise Min x x'
1844 |
1845 | namespace Semigroup
1846 |   export
1847 |   [Min] {shape : _} -> Ord dtype => Semigroup (Tensor shape dtype) where
1848 |     (<+>) = min
1849 |
1850 | namespace Monoid
1851 |   export
1852 |   [Min] {shape : _} -> {dtype : _} -> Ord dtype =>
1853 |     Monoid (Tensor shape dtype) using Semigroup.Min where
1854 |       neutral = broadcast max
1855 |
1856 | ||| The element-wise maximum of the first argument compared to the second. For example,
1857 | ||| `max (tensor [-3, -1, 3]) (tensor [-1, 0, 1])` is `tensor [-1, 0, 3]`.
1858 | export
1859 | max : Ord dtype => Tensor shape dtype -> Tensor shape dtype -> Tensor shape dtype
1860 | max (MkTensor x) (MkTensor x') = t0 $ BinaryElementwise Max x x'
1861 |
1862 | namespace Semigroup
1863 |   export
1864 |   [Max] Ord dtype => Semigroup (Tensor shape dtype) where
1865 |     (<+>) = max
1866 |
1867 | namespace Monoid
1868 |   export
1869 |   [Max] {shape : _} -> {dtype : _} -> Ord dtype =>
1870 |     Monoid (Tensor shape dtype) using Semigroup.Max where
1871 |       neutral = broadcast min
1872 |
1873 | ||| The diagonal of a matrix as a vector. For example, for
1874 | ||| ```
1875 | ||| x : Tensor [3, 3] S32
1876 | ||| x = tensor [[0, 1, 2],
1877 | |||             [3, 4, 5],
1878 | |||             [6, 7, 8]]
1879 | ||| ```
1880 | ||| `diag x` is `tensor [0, 4, 8]`.
1881 | export
1882 | diag : Num dtype => Prelude.Num (idrisType dtype) => Tensor [n, n] dtype -> Tensor [n] dtype
1883 | diag {n = 0} x@(MkTensor {shape = [0, 0]} _) = reshape x
1884 | diag {n = S n} x@(MkTensor {shape = [S n, S n]} _) = (x * identity) @@ fill 1
1885 |
1886 | argmxx :
1887 |   Ord dtype =>
1888 |   (Tensor [] dtype -> Tensor [] dtype -> Tensor [] PRED) ->
1889 |   Tensor [] dtype ->
1890 |   Tensor [S n] dtype ->
1891 |   Tag $ Tensor [] U64
1892 | argmxx cmp (MkTensor bound) x@(MkTensor {shape = _} _) = do
1893 |   let MkTensor idxs : Tensor [S n] U64 = iota 0
1894 |       MkTensor x = x
1895 |       MkTensor zero = tensor {dtype = U64} 0
1896 |
1897 |       mon :
1898 |         Tensor [] dtype -> Tensor [] U64 ->
1899 |         Tensor [] dtype -> Tensor [] U64 ->
1900 |         Tag (Tensor [] dtype, Tensor [] U64)
1901 |       mon x y x' y' =
1902 |         let useNext = x == x && (cmp x' x || x' /= x')
1903 |          in pure (select useNext x' x, select useNext y' y)
1904 |
1905 |   MkTagT $ do
1906 |     addr <- reserve
1907 |
1908 |     let MkTagT res = mon
1909 |           (MkTensor $ V 0 $ BoundSet addr)
1910 |           (MkTensor $ V 1 $ BoundSet addr)
1911 |           (MkTensor $ V 2 $ BoundSet addr)
1912 |           (MkTensor $ V 3 $ BoundSet addr)
1913 |         (env, (MkTensor m, MkTensor i)) = runState (emptyFrom !get) res
1914 |         argTys = [TensorType [] dtype, TensorType [] U64]
1915 |         f = MkFn addr (argTys ++ argTys) argTys [m, i] env
1916 |
1917 |     updateCounterFrom env
1918 |     pure $ MkTensor $ V 1 $ Concrete $ Reduce f [bound, zero] [0] [x, idxs]
1919 |
1920 | ||| The first index of the maximum value in a vector. For example,
1921 | ||| `argmax (tensor [-1, 3, -2, -2, 3])` produces `tensor 1`. If the vector contains NaN values,
1922 | ||| `argmax` returns the index of the first NaN.
1923 | export
1924 | argmax : Ord dtype => Tensor [S n] dtype -> Tag $ Tensor [] U64
1925 | argmax x@(MkTensor {dtype} _) = argmxx (>) min x
1926 |
1927 | ||| The first index of the minimum value in a vector. For example,
1928 | ||| `argmin (tensor [-1, 3, -2, -2, 3])` produces `tensor 2`. If the vector contains NaN values,
1929 | ||| `argmin` returns the index of the first NaN.
1930 | export
1931 | argmin : Ord dtype => Tensor [S n] dtype -> Tag $ Tensor [] U64
1932 | argmin x@(MkTensor {dtype} _) = argmxx (<) max x
1933 |
1934 | ||| Represents the upper- or lower-triangular component of a matrix.
1935 | public export
1936 | data Triangle = Upper | Lower
1937 |
1938 | ||| Get the upper- or lower-triangular component of a matrix, always including the matrix diagonal.
1939 | ||| Remaining elements will be zero. For example, for
1940 | ||| ```
1941 | ||| x : Tensor [3, 3] S32
1942 | ||| x = tensor [[1, 2, 3],
1943 | |||             [4, 5, 6],
1944 | |||             [7, 8, 9]]
1945 | ||| ```
1946 | ||| `triangle Lower x` produces
1947 | ||| ```
1948 | ||| x : Tensor [3, 3] S32
1949 | ||| x = tensor [[1, 0, 0],
1950 | |||             [4, 5, 0],
1951 | |||             [7, 8, 9]]
1952 | ||| ```
1953 | export
1954 | triangle :
1955 |   Prelude.Num (idrisType dtype) =>
1956 |   Triangle ->
1957 |   Tensor [n, n] dtype ->
1958 |   Tag $ Tensor [n, n] dtype
1959 | triangle tri (MkTensor x) = do
1960 |   let range : Tensor [n * n] U64 = iota 0
1961 |   indices <- tag $ reshape {to = [n, n], sizesEqual = productSquare n} range
1962 |   let op = case tri of
1963 |         Upper => Tensor.(>)
1964 |         Lower => Tensor.(<)
1965 |   pure $ select (op indices indices.T) (fill $ fromInteger 0) (MkTensor x)
1966 |
1967 |   where
1968 |
1969 |   productSquare : (m : Nat) -> product [m * m] = product [m, m]
1970 |   productSquare m =
1971 |     rewrite multOneRightNeutral (m * m) in
1972 |     rewrite multOneRightNeutral m in
1973 |     Refl
1974 |
1975 | ||| Cholesky decomposition. Computes the lower triangular matrix `L` from the symmetric, positive
1976 | ||| semi-definite matrix `X` s.t. `X = L @@ L.T`. Values will be NaN if the input matrix is not
1977 | ||| positive semi-definite. The remaining matrix components - those not in the lower triangle or
1978 | ||| diagonal - will always be zero.
1979 | export
1980 | cholesky : Tensor [S n, S n] F64 -> Tag $ Tensor [S n, S n] F64
1981 | cholesky $ MkTensor x = triangle Lower (t0 $ Cholesky x)
1982 |
1983 | export infix 9 |\, \|
1984 |
1985 | namespace Matrix
1986 |   ||| Solve the set of linear equations `a @@ x = b` for `x` where `a` is a lower-triangular matrix.
1987 |   ||| `a` is given by the lower-triangular elements of the first argument. Values in the
1988 |   ||| upper-triangular part are ignored. If `a` is lower-triangular already,
1989 |   ||| this is written `a |\ b`.
1990 |   |||
1991 |   ||| The operator is shaped like the lower-triangular portion of a matrix to signal that it uses
1992 |   ||| this portion of its argument. This is in contrast to `(\|)`.
1993 |   export
1994 |   (|\) : Tensor [m, m] F64 -> Tensor [m, n] F64 -> Tensor [m, n] F64
1995 |   (MkTensor a) |\ (MkTensor b) = t0 $ TriangularSolve a b True
1996 |
1997 |   ||| Solve the set of linear equations `a @@ x = b` for `x` where `a` is an upper-triangular
1998 |   ||| matrix. `a` is given by the upper-triangular elements of the first argument. Values in the
1999 |   ||| lower-triangular part are ignored. If `a` is upper-triangular already, this is written
2000 |   ||| `a \| b`.
2001 |   |||
2002 |   ||| The operator is shaped like the upper-triangular portion of a matrix to signal that it uses
2003 |   ||| this portion of its argument. This is in contrast to `(|\)`.
2004 |   export
2005 |   (\|) : Tensor [m, m] F64 -> Tensor [m, n] F64 -> Tensor [m, n] F64
2006 |   (MkTensor a) \| (MkTensor b) = t0 $ TriangularSolve a b False
2007 |
2008 | namespace Vector
2009 |   ||| Solve the set of linear equations `a @@ x = b` for `x` where `a` is a lower-triangular matrix.
2010 |   ||| `a` is given by the lower-triangular elements of the first argument. Values in the
2011 |   ||| upper-triangular part are ignored. If `a` is lower-triangular already,
2012 |   ||| this is written `a |\ b`.
2013 |   |||
2014 |   ||| The operator is shaped like the lower-triangular portion of a matrix to signal that it uses
2015 |   ||| this portion of its argument. This is in contrast to `(\|)`.
2016 |   export
2017 |   (|\) : Tensor [m, m] F64 -> Tensor [m] F64 -> Tensor [m] F64
2018 |   a |\ b = let (MkTensor {shape = [_]} _) = b in squeeze (a |\ expand 1 b)
2019 |
2020 |   ||| Solve the set of linear equations `a @@ x = b` for `x` where `a` is an upper-triangular
2021 |   ||| matrix. `a` is given by the upper-triangular elements of the first argument. Values in the
2022 |   ||| lower-triangular part are ignored. If `a` is upper-triangular already, this is written
2023 |   ||| `a \| b`.
2024 |   |||
2025 |   ||| The operator is shaped like the upper-triangular portion of a matrix to signal that it uses
2026 |   ||| this portion of its argument. This is in contrast to `(|\)`.
2027 |   export
2028 |   (\|) : Tensor [m, m] F64 -> Tensor [m] F64 -> Tensor [m] F64
2029 |   a \| b = let (MkTensor {shape = [_]} _) = b in squeeze (a \| expand 1 b)
2030 |
2031 | ||| Sum the elements along the diagonal of the input. For example,
2032 | ||| `trace (tensor [[-1, 5], [1, 4]])` produces `3`.
2033 | export
2034 | trace : Num dtype => Prelude.Num (idrisType dtype) =>
2035 |         Tensor [S n, S n] dtype ->
2036 |         Tag $ Tensor [] dtype
2037 | trace x with (x)
2038 |   _ | MkTensor {shape = [_, _]} _ = reduce @{Sum} [0, 1] $ x * identity
2039 |
2040 | ||| A `Rand a` produces a pseudo-random value of type `a` from a `Tensor [2] U64` state.
2041 | ||| The state is updated every time a new value is generated.
2042 | public export 0
2043 | Rand : Type -> Type
2044 | Rand = StateT (Tensor [2] U64) Tag
2045 |
2046 | ||| Generate independent and identically distributed (IID) uniform samples.
2047 | |||
2048 | ||| The generated samples are a deterministic function of the input key and state, but may vary
2049 | ||| between PJRT plugin and library version.
2050 | |||
2051 | ||| Example usage, multiplying two uniform samples
2052 | ||| ```
2053 | ||| x : Tag $ Tensor [3] U64
2054 | ||| x = let seed = tensor [1, 1] in evalStateT seed [| rng * rng |]
2055 | ||| ```
2056 | export
2057 | rng : {shape : _} -> Rand $ Tensor shape U64
2058 | rng = ST $ \(MkTensor state) => do
2059 |   res <- tag $ Concrete $ Rng state (TensorType shape U64)
2060 |   pure (MkTensor $ V 0 res, MkTensor $ V 1 res)
2061 |
2062 | ||| Generate independent and identically distributed (IID) from the uniform distribution U(0, 1).
2063 | |||
2064 | ||| The generated samples are a deterministic function of the input key and state, but may vary
2065 | ||| between PJRT plugin and library version.
2066 | |||
2067 | ||| Example usage, multiplying two uniform samples
2068 | ||| ```
2069 | ||| x : Rand $ Tensor [3] F64
2070 | ||| x = [| uniform * uniform |]
2071 | ||| ```
2072 | export
2073 | uniform : {shape : _} -> Rand $ Tensor shape F64
2074 | uniform =
2075 |   let numMantissaBits : Bits8 = 52
2076 |       scale = broadcast $ 2.0 `pow` tensor (Scalar $ - cast {to = Double} numMantissaBits)
2077 |       shift = fill $ 64 - numMantissaBits
2078 |    in rng {shape} <&> \x => castDtype (shiftR Logical x shift) * scale
2079 |
2080 | ||| Generate independent and identically distributed (IID) samples from the standard normal
2081 | ||| distribution N(0, 1).
2082 | |||
2083 | ||| The generated samples are a deterministic function of the input key and state, but may vary
2084 | ||| between PJRT plugin and library version.
2085 | |||
2086 | ||| Example usage, multiplying two normal samples
2087 | ||| ```
2088 | ||| x : Rand $ Tensor [3] F64
2089 | ||| x = [| normal * normal |]
2090 | ||| ```
2091 | export
2092 | normal : {shape : _} -> Rand $ Tensor shape F64
2093 | normal = uniform <&> \x => sqrt (broadcast 2.0) * erfInv (broadcast 2.0 * x - broadcast 1.0)
2094 |