Something went wrong. Try again.
forked from raven-ml/raven
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332(*--------------------------------------------------------------------------- Copyright (c) 2026 The Raven authors. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*)
(* Data in and out: values made from OCaml data, and the reads that give a value's elements back, at every dtype and brand. *)
open Windtrapopen Nx_supportmodule A = Nx_arraymodule D = Nx_array.Dtypemodule L = Nx_array.Layout
let m = Nx_support.memory
module S2 = (val Nx.devices [ m 0; m 1 ])
let invalid ~by f = raises_match (Exn.invalid_arg ~substring:(by ^ ": ")) f
(* Elements *)
(* Two elements of [dt] are one value: floats by their bits, any two NaNs alike. *)(* Values of [dt] at shape [s], from drawn bytes: every value of the format, NaNs, signed zeros and infinities among them. *)let drawn (type v s) (dt : (v, s) D.t) s : v array Gen.t = let open Gen in let n = Array.fold_left ( * ) 1 s in let+ data = string_of ~size:(constant (D.bytes dt n)) char in let data = match dt with | D.Bool -> String.map (fun c -> Char.chr (Char.code c land 1)) data | _ -> data in A.to_array (A.v dt (L.contiguous (Iarray.of_array s)) (Rig.Buffer.of_string (if data = "" then "\000" else data)))
let shape = Gen.array ~size:(Gen.int_range 0 3) (Gen.frequency [ (1, Gen.constant 0); (1, Gen.constant 1); (4, Gen.int_range 2 4) ])
type case = Case : ('v, 's) D.t * int array * 'v array -> case
let cases_gen = let open Gen in let* (D.Any dt) = of_list ~pp:(fun ppf (D.Any dt) -> D.pp ppf dt) D.all in let* s = shape in let+ vs = drawn dt s in Case (dt, s, vs)
let case = Gen.with_pp (fun ppf (Case (dt, s, _)) -> Format.fprintf ppf "%a %a" D.pp dt pp_ints s) cases_gen
let floats s = Array.init (Array.fold_left ( * ) 1 s) float_of_intlet f32 = Nx.float32
(* From OCaml values *)
(* A float is stored as [Dtype.of_float] says. *)let stored (type v s) (dt : (v, s) D.t) (v : v) : v = match D.kind dt with D.Float -> D.of_float dt v | _ -> v
let law_round_trip (Case (dt, s, vs)) = cover "no element" (Array.exists (( = ) 0) s); cover "rank 0" (s = [||]); let x = Nx.create dt s vs in equal (array int) s (Nx.shape x); equal_elements dt (Array.map (stored dt) vs) (Nx.to_array x)
(* [item i x] is the element of [to_array x] at [i]'s position in C order, written with positive or negative positions. *)let law_item (Case (dt, s, vs), (seed, negative)) = assume (Array.length vs > 0); let flat = seed mod Array.length vs in let i = Array.make (Array.length s) 0 and j = ref flat in for a = Array.length s - 1 downto 0 do i.(a) <- !j mod s.(a); j := !j / s.(a) done; let p = Array.mapi (fun a q -> if negative then q - s.(a) else q) i in cover "negative" negative; equal (elements dt) [ vs.(flat) ] [ Nx.item (Array.to_list p) (Nx.create dt s vs) ]
let test_init_order () = let calls = ref [] in let x = Nx.init Nx.int32 [| 2; 3 |] (fun i -> calls := Array.copy i :: !calls; Int32.of_int ((10 * i.(0)) + i.(1))) in equal (list (array int)) [ [| 0; 0 |]; [| 0; 1 |]; [| 0; 2 |]; [| 1; 0 |]; [| 1; 1 |]; [| 1; 2 |] ] (List.rev !calls); equal (array int32) [| 0l; 1l; 2l; 10l; 11l; 12l |] (Nx.to_array x)
let test_init_fresh_index () = let kept = ref [] in let _ = Nx.init Nx.int8 [| 3 |] (fun i -> kept := i :: !kept; 0) in equal (list (array int)) [ [| 2 |]; [| 1 |]; [| 0 |] ] !kept
let test_unpack () = let x = Nx.create f32 [| 2 |] [| 1.; 2. |] in equal (array float_exact) [| 1.; 2. |] (Nx.to_array (Nx.unpack f32 (Nx.P x))); invalid ~by:"Nx.unpack" (fun () -> Nx.unpack Nx.int32 (Nx.P x))
let refusals = [ ( "create: too few values", fun () -> ignore (Nx.create f32 [| 2; 2 |] [| 1.; 2.; 3. |]) ); ( "create: a negative extent", fun () -> ignore (Nx.create f32 [| -1 |] [||]) ); ( "create: an int outside the dtype", fun () -> ignore (Nx.create Nx.uint8 [| 1 |] [| 256 |]) ); ( "create: an int below the dtype", fun () -> ignore (Nx.create Nx.int4 [| 1 |] [| -9 |]) ); ("init: a negative extent", fun () -> ignore (Nx.init f32 [| -2 |] (fun _ -> 0.))); ( "item: too few positions", fun () -> ignore (Nx.item [ 0 ] (Nx.zeros f32 [| 2; 2 |])) ); ( "item: a position past the axis", fun () -> ignore (Nx.item [ 2 ] (Nx.zeros f32 [| 2 |])) ); ( "item: a position before the axis", fun () -> ignore (Nx.item [ -3 ] (Nx.zeros f32 [| 2 |])) ); ( "item: an empty axis", fun () -> ignore (Nx.item [ 0 ] (Nx.zeros f32 [| 0 |])) ); ( "of_bigarray: a char bigarray", fun () -> ignore (Nx.of_bigarray (Bigarray.Genarray.create Bigarray.char Bigarray.c_layout [| 2 |])) ); ]
let name_of label = "Nx." ^ String.sub label 0 (String.index label ':')
let ocaml = group "from OCaml values" [ prop "to_array (create dt s vs) is vs as dt stores them" case law_round_trip; prop "item reads to_array's element at its index" (Gen.pair case (Gen.pair Gen.nat Gen.bool)) law_item; test "init calls f once per index, in C order" test_init_order; test "init gives f a fresh index each call" test_init_fresh_index; test "unpack fixes the dtype or names both" test_unpack; cases "refusals name the function" ~name:fst refusals (fun (label, f) -> invalid ~by:(name_of label) f); ]
(* Bigarrays *)
let test_bigarray_round_trip () = let b = Bigarray.Genarray.create Bigarray.float64 Bigarray.c_layout [| 2; 3 |] in for i = 0 to 1 do for j = 0 to 2 do Bigarray.Genarray.set b [| i; j |] (float_of_int ((3 * i) + j)) done done; let x = Nx.of_bigarray b in equal (array int) [| 2; 3 |] (Nx.shape x); Bigarray.Genarray.set b [| 0; 0 |] 99.; equal (array float_exact) [| 0.; 1.; 2.; 3.; 4.; 5. |] (Nx.to_array x); let c = Nx.to_bigarray Bigarray.float64 x in equal (array int) [| 2; 3 |] (Bigarray.Genarray.dims c); Bigarray.Genarray.set c [| 1; 2 |] 77.; equal float_exact 5. (Nx.item [ 1; 2 ] x)
let test_bigarray_kinds () = let ints = Nx.to_bigarray Bigarray.int8_unsigned (Nx.create Nx.uint8 [| 2 |] [| 0; 255 |]) in equal int 255 (Bigarray.Genarray.get ints [| 1 |]); let z = Nx.create Nx.complex64 [| 1 |] [| { Complex.re = 1.5; im = -0. } |] in let back = Nx.of_bigarray (Nx.to_bigarray Bigarray.complex32 z) in equal_elements Nx.complex64 (Nx.to_array z) (Nx.to_array back); let h = Nx.to_bigarray Bigarray.float16 (Nx.create Nx.float16 [||] [| 0.5 |]) in equal float_exact 0.5 (Bigarray.Genarray.get h [||])
let bigarrays = group "bigarrays" [ test "of_bigarray copies; to_bigarray is fresh" test_bigarray_round_trip; test "kinds carry their dtypes" test_bigarray_kinds; ]
(* Reads at every brand *)
let test_read_split () = let s = [| 4; 3 |] in let x = Nx.place (S2.split ~axis:0) (Nx.create f32 s (floats s)) in equal (array float_exact) (floats s) (Nx.to_array x); equal float_exact 10. (Nx.item [ 3; 1 ] x); equal (array float_exact) (floats s) (let b = Nx.to_bigarray Bigarray.float32 x in Array.init 12 (fun j -> Bigarray.Genarray.get b [| j / 3; j mod 3 |])); equal bool true (Nx.Placement.equal (S2.split ~axis:0) (Nx.placement x))
let test_read_created () = let x = Nx.add (Nx.zeros f32 [| 3 |]) (Nx.scalar f32 2.) in equal (array float_exact) [| 2.; 2.; 2. |] (Nx.to_array x); equal float_exact 2. (Nx.item [ -1 ] x); equal bool true (Nx.Placement.equal Nx.Host.on (Nx.placement x))
let test_read_view () = let x = Nx.transpose (Nx.create Nx.int16 [| 2; 3 |] [| 1; 2; 3; 4; 5; 6 |]) in equal (array int) [| 1; 4; 2; 5; 3; 6 |] (Nx.to_array x); equal int 6 (Nx.item [ 2; 1 ] x)
let test_read_dead () = let x = Nx.create f32 [| 2 |] [| 1.; 2. |] in let _ = Nx.add (Nx.donate x) (Nx.create f32 [| 2 |] [| 0.; 0. |]) in invalid ~by:"Nx.to_array" (fun () -> Nx.to_array x); invalid ~by:"Nx.item" (fun () -> Nx.item [ 0 ] x)
type ('v, 's, 'd) Nx.Prim.payload += Mark : ('v, 's, 'd) Nx.Prim.payload
let mark i ~by op = Nx.Prim.results ~by (fun _ f -> Nx.Prim.traced i f Mark) op
let test_read_traced () = let x = Nx.create f32 [| 2 |] [| 1.; 2. |] in Nx.Prim.interpret ~name:"test.reads" Values mark (fun i -> let t = Nx.Prim.traced i (Nx.Prim.form x) Mark in raises_match (Exn.invalid_arg ~substring:"Nx.to_array: the value is traced by test.reads") (fun () -> Nx.to_array t); raises_match (Exn.invalid_arg ~substring:"Nx.item: the value is traced by test.reads") (fun () -> Nx.item [ 0 ] t))
(* An extent reaches every operation on its fiber; a read is none. *)let test_read_under_extent () = let x = Nx.create f32 [| 2 |] [| 1.; 2. |] and c = Nx.zeros f32 [| 1 |] in let got = Nx.Prim.interpret ~name:"test.extent" Extent mark (fun _ -> (Nx.to_array x, Nx.item [ 1 ] x, Nx.to_array c)) in let a, v, z = got in equal (array float_exact) [| 1.; 2. |] a; equal float_exact 2. v; equal (array float_exact) [| 0. |] z
let reads = group "reads" [ test "a split value reads whole and stays split" test_read_split; test "a host creation reads its elements" test_read_created; test "a view reads in its own C order" test_read_view; test "a dead value raises naming the read" test_read_dead; test "a traced value raises naming the read" test_read_traced; test "an extent receives no read" test_read_under_extent; ]
(* Maps on the host *)
(* [map_item f] is [create] of [f] over the elements: with [f] the identity, a round trip, NaN payloads, signed zeros and every dtype included. *)let law_map_identity (Case (dt, s, vs)) = let x = Nx.create dt s vs in let y = Nx.map_item Fun.id x in equal (array int) s (Nx.shape y); equal_elements dt (Nx.to_array x) (Nx.to_array y)
(* An element's image under [f], at each dtype a function of that dtype: [f] is applied to the element, and the store rounds a float once. *)let test_map_values () = let x = Nx.create f32 [| 2; 2 |] [| 1.; -0.; nan; 0.1 |] in equal_elements Nx.float32 (Nx.to_array (Nx.create f32 [| 4 |] [| -1.; 0.; nan; -0.1 |])) (Nx.to_array (Nx.map_item Float.neg x)); let i = Nx.create Nx.int8 [| 3 |] [| -128; 0; 127 |] in equal (array int) [| 127; -1; -128 |] (Nx.to_array (Nx.map_item (fun v -> -v - 1) i)); let b = Nx.create Nx.bool [| 2 |] [| true; false |] in equal (array bool) [| false; true |] (Nx.to_array (Nx.map_item not b))
let test_map_order () = let seen = ref [] in let x = Nx.transpose (Nx.create Nx.int32 [| 2; 3 |] [| 0l; 1l; 2l; 3l; 4l; 5l |]) in let _ = Nx.map_item (fun v -> seen := v :: !seen; v) x in equal (list int32) [ 0l; 3l; 1l; 4l; 2l; 5l ] (List.rev !seen)
let test_map_range () = invalid ~by:"Nx.map_item" (fun () -> Nx.map_item (fun _ -> 300) (Nx.zeros Nx.uint8 [| 2 |]))
let test_map_creation () = let x = Nx.add (Nx.zeros f32 [| 3 |]) (Nx.scalar f32 2.) in equal (array float_exact) [| 4.; 4.; 4. |] (Nx.to_array (Nx.map_item (fun v -> v *. 2.) x))
(* A value on a device set is read as [to_array] reads it, and the result lies on the host. *)let test_map_device () = let s = [| 4; 3 |] in let x = Nx.place (S2.split ~axis:0) (Nx.create f32 s (floats s)) in let y : Nx.host Nx.float32_t = Nx.map_item Float.neg x in equal (array float_exact) (Array.map Float.neg (floats s)) (Nx.to_array y); equal (array float_exact) (floats s) (Nx.to_array x)
let test_map_dead () = let x = Nx.create f32 [| 2 |] [| 1.; 2. |] in let _ = Nx.add (Nx.donate x) (Nx.create f32 [| 2 |] [| 0.; 0. |]) in invalid ~by:"Nx.map_item" (fun () -> Nx.map_item Fun.id x)
let test_map_traced () = let x = Nx.create f32 [| 2 |] [| 1.; 2. |] in Nx.Prim.interpret ~name:"test.reads" Values mark (fun i -> let t = Nx.Prim.traced i (Nx.Prim.form x) Mark in raises_match (Exn.invalid_arg ~substring:"Nx.map_item: the value is traced by test.reads") (fun () -> Nx.map_item Fun.id t))
let maps = group "map_item" [ prop "the identity gives the value back" case law_map_identity; test "each element is f of the element, stored in the dtype" test_map_values; test "f runs once per element in C order" test_map_order; test "an int outside the dtype raises" test_map_range; test "a host creation maps as any host value" test_map_creation; test "a value on a device set gives a host value" test_map_device; test "a dead value raises" test_map_dead; test "a traced value raises" test_map_traced; ]
let () = exit (run "nx data" [ ocaml; bigarrays; reads; maps ])