Module Nx.Ptree
Structures of arrays.
A structure is a type ('a, 'd) t with one function, walk, that walks the parts of a value with a Ptree.Walk.cursor: the positions of its parameter 'a, its arrays of a fixed type, its fixed arrays, on the set 'd, and the data a program depends on (a window, a list's length, a variant's case). Every operation here runs that function, so all of them visit the parts in one order: maps and folds, casts, placement, the names under which arrays are saved and the lists of arrays that interpreters trace.
A description, ('s, 'd) t, is a structure at one type 's whose arrays are all on 'd. A map's function may then close over an array of 'd. Changing the set of a value, as changing a dtype, goes through the structure's module: Ptree.place and Ptree.cast take one.
A description is made where it is used. Every description but Ptree.tensor, Ptree.unit and Rng.ptree is a function's result, so OCaml fixes its dtype and its set at its first use, and a set minted in a local scope has no description outside it. A library therefore exports a structure's module, or a walk such as Rng.walk, and its users describe the structure at their dtype and set.
type 'a linear = { w : 'a; b : 'a option } module Linear = struct type ('a, _) t = 'a linear let walk c { w; b } = let open Nx.Ptree.Walk in let w = field c "w" leaf w in let b = field c "b" (option leaf) b in { w; b } end let params = { w = Nx.ones Nx.float32 [| 4; 2 |]; b = None } let linear = Nx.Ptree.instantiate (module Linear) let zeros = Nx.Ptree.map linear (fun _ x -> Nx.zeros_like x) params let on_gpu = Nx.Ptree.place (module Linear) Gpu.on params
Paths
Writing a structure
type ('s, 'd) tThe type for descriptions of structures 's whose arrays are on 'd.
Descriptions
instantiate (module U) is U with arrays at its parameter's positions: nest (module U) tensor. A binding is at one dtype and one set, as every description (Ptree), annotated only where nothing else in its compilation unit fixes them.
nest (module U) s is U whose parameter's positions are values of s, walked by s with their paths after the position's. An optimiser's state over a model is nested.
val v : ('a 'b. ('a, 'b, 'd, 'd) Walk.cursor -> 's -> 's) -> ('s, 'd) tv walk is the description whose values walk walks: a structure without a parameter, on one set, such as a record of parts walked with Walk.structure. walk keeps the contract of S's walk, with no position of a parameter. place cannot move its values: a structure that moves between sets has a module.
pair a b walks a pair's first component with a at Index 0, then its second with b at Index 1.
triple a b c walks a triple's components with a, b and c at Index 0, Index 1 and Index 2, in that order.
quad a b c e walks a quadruple's components with a, b, c and e at Index 0 to Index 3, in that order. A value of more parts is a record or a labelled tuple described with v, each part walked with Walk.field at its name.
option a reports presence as Walk.option does and walks the content with a at the same path.
list a reports the length as Walk.list does and walks the i-th element with a at Index i.
Maps and folds
These pass every array its path, in walk order. Each array has its own dtype, so their functions are polymorphic; fixed arrays are arrays like the others.
Two values that differ raise Invalid_argument with the message fn: p: a in the first value, b in the second, p the path of the first visit at which they differ and a and b what each holds there, as pp_visit words it, or nothing for a value with no more visits. Where the two visits are at different paths, b reads b at q, q the second's path; paths that print alike print as their steps.
map s f x is x with each array a at path p replaced by f p a.
donate s x is x with each array given up by its owner: Nx.donate of each, in walk order. A consumer of the arrays, an operation or a compiled call, may then write its results into their memory.
Raises Invalid_argument naming Nx.Ptree.donate and the path of the first dead array, as Nx.Ptree.donate: w: float32 [2] was donated to Nx.copy.
val map2 :
('s, 'd) t ->
('v 'r. Path.t ->
('v, 'r, 'd) tensor ->
('v, 'r, 'd) tensor ->
('v, 'r, 'd) tensor) ->
's ->
's ->
'smap2 s f x y is x with each array a at path p replaced by f p a b, b y's array at p.
Raises Invalid_argument before applying f if x and y have different visits, with the message of Maps and folds prefixed by "Nx.Ptree.map2"; and, after applying f to the arrays before p, if the arrays at p differ in dtype, as in "Nx.Ptree.map2: w: float32 in the first value, int32 in the second", or if s walks one value two ways, which breaks S's contract.
val fold :
('s, 'd) t ->
('v 'r. Path.t -> ('v, 'r, 'd) tensor -> 'acc -> 'acc) ->
's ->
'acc ->
'accfold s f x acc is f pn an (… (f p1 a1 acc)), a1, …, an x's arrays and p1, …, pn their paths. f takes the accumulator last, as Map.fold's does.
Sets, dtypes and payloads
A structure's walk also changes the type of its parameter's positions and the set of its fixed arrays. These take the structure's module, since only a module names its type constructor.
val place :
(module U : S)
->
'e Placement.t ->
(('v, 's, 'd) tensor, 'd) U.t ->
(('v, 's, 'e) tensor, 'e) U.tval cast :
(module U : S)
->
('w, 'r) dtype ->
(('v, 's, 'd) tensor, 'd) U.t ->
(('w, 'r, 'd) tensor, 'd) U.tcast (module U) dt x is x with each array at a position of U's parameter cast to dt, as Nx.cast. Fixed arrays are kept.
Maps and folds at any payload: a mask, a learning rate per array, a plan, dimensions. The positions of the parameter hold the payloads; fixed arrays, and those of parts walked with Walk.structure, are kept from the first value, and neither passed nor compared.
Arithmetic
A value's float and complex arrays are one real vector, each complex element two of its coordinates, its real and imaginary parts: the inner product of two complex arrays is Re (conj a · b). These functions are the vector's linear algebra, the steps of optimisers, integrators and samplers written over a structure. An array of another dtype, a counter or a key, is not part of the vector: dot and norm skip it, scale and axpy keep it.
The functions of two values raise Invalid_argument as map2 does, with their own name, and where the arrays at one path differ in shape, as in "Nx.Ptree.dot: w: [2; 3] in the first value, [3; 2] in the second".
dot s dt x y is the 0-d inner product of x and y at dt: from 0, the sum in walk order, over each array a of the vector and y's array b at its path, of vdot (cast dt a) (cast dt b) for floats and of the same over the real parts, then the imaginary parts, stored in dt, for complex arrays. The 0 it starts from lies whole on each device of the placement of x's first array in walk order.
Raises Invalid_argument naming Nx.Ptree.dot if x holds no array.
norm s dt x is x's Euclidean norm, sqrt (dot s dt x x) in exact arithmetic, computed so that no square overflows: each coordinate is divided by their greatest magnitude m, and m multiplies the root of the quotients' sum of squares. It computes in dt's carrier, float32 for a narrower float, and rounds once to dt, so it is finite wherever the norm is: +∞ where a coordinate is infinite and none is NaN, NaN where one is NaN, 0 of no coordinate. Its constants lie as dot's 0 does.
Raises Invalid_argument naming Nx.Ptree.norm if x holds no array.
scale s k x is x with each array a of the vector replaced by k' * a, k' k cast to a's format, part by part for a complex a.
Raises Invalid_argument naming Nx.Ptree.scale unless k is 0-d.
axpy s k x y is x with each array a replaced by k' * a + b, b y's array at its path and k' k cast to a's format, the product and the sum each rounded to it, a complex a part by part; and by b where a is not in the vector.
Raises Invalid_argument naming Nx.Ptree.axpy unless k is 0-d.
Visits
type report = The type for what a walk reports.
type visit = The type for the steps of a walk.
visits s x is the steps of s's walk of x, in walk order. A structure's test compares them with the arrays, integers and cases its walk must visit.
pp_visit ppf v formats v as its path and what is there: "blocks.3.moe: case \"mxfp4\"", "0.keys: a leaf", "layers: length 4", "bias: Some", "window: int 8". The root is formatted "the root".
Signatures of compiled functions
A signature has the shape of the function an interpreter compiles: tensor @-> index @-> caches @-> returns (pair tensor caches). Each argument has its own type, so tensor @-> tensor @-> … takes arrays of two dtypes. A caller gives up an argument by donating it at the call (donate).
type (_, 'd) fn = private The type for signatures of functions of type 'f on the set 'd.
a @-> f takes an argument of a, then is f.
Flattening
Low level. A value as its arrays and its skeleton: what interpreters key compiled programs on and put results back with.
val flatten : ('s, 'd) t -> 's -> 'd packed list * Skeleton.tflatten s x is x's arrays in walk order and x's skeleton.
rebuild s ~like xs is like with its arrays replaced by xs, in walk order. rebuild s ~like (fst (flatten s like)) is like.
Raises Invalid_argument naming Nx.Ptree.rebuild if xs has fewer arrays than like, naming the path of the first left without one; if it has more, naming both counts; or if an array has another dtype than like's at its position, naming the path and both dtypes.