Sarek_ir_typesSarek_ir_types - Pure type definitions for GPU kernel IR
This module contains only type definitions with no external dependencies. Used by spoc_framework for typed generate_source signature.
module Type_id : sig ... endRuntime type identities with equality proofs.
type elttype = | TInt32| TInt64| TFloat16IEEE binary16 storage type. Values are stored/loaded as binary16; arithmetic promotes to TFloat32, computes there, and rounds back on store. There is deliberately no CFloat16 constant: f16 values are produced by conversion (ECast (TFloat16, _)), never by a literal.
| TFloat32| TFloat64| TUint8Unsigned 8-bit integer storage type, on the TFloat16 model: an array element occupies one byte, but there is no 8-bit value at run time and no 8-bit arithmetic. Reading an element gives an int32 (zero-extended); storing an int32 keeps its low 8 bits; ECast (TUint8, e) is the int32 e land 0xff. Valid as the element type of a global (TVec) or shared (DShared, EArrayCreate (_, _, Shared)) array and as a cast target; an 8-bit scalar binder, record field or private array is refused (see Sarek_ir_int8, which holds the shared semantics).
It is also the element type of an 8-bit cooperative-matrix operand buffer, of either signedness: coopMatLoad requires the backing array's element type to match the fragment's component type, and the s8 fragments of this IR read a TUint8 buffer as signed.
| TInt8Signed 8-bit integer storage type: as TUint8, with the read sign-extended and ECast (TInt8, e) the low byte of e sign-extended.
| TBool| TUnit| TRecord of string * (string * elttype) listRecord type: name and field list
*)| TVariant of string * (string * elttype list) listVariant type: name and constructor list with arg types
*)| TArray of elttype * memspaceArray type with element type and memory space
*)| TVec of elttypeVector (GPU array parameter)
*)Element types
Variables with type info
type binop = | Add| Sub| Mul| Div| Mod| Eq| Ne| Lt| Le| Gt| Ge| And| Or| Shl| ShrArithmetic (sign-extending) shift right: OCaml asr.
| Lshr32Logical (zero-filling) shift right of a 32-bit operand: OCaml lsr on int/int32. Its own operator because the C-family emitters must spell the unsigned type and cannot infer it from the operands.
| Lshr64Logical shift right of a 64-bit operand: lsr on int64.
| BitAnd| BitOr| BitXorBinary operators
type expr = | EConst of const| EVar of var| EBinop of binop * expr * expr| EUnop of unop * expr| EArrayRead of string * exprarridx
| EArrayReadExpr of expr * exprbase_expridx for complex bases
| ERecordField of expr * stringr.field
*)| EIntrinsic of string list * string * expr listmodule path, name, args
*)| ECast of elttype * expr| ETuple of expr list| EApp of expr * expr list| ERecord of string * (string * expr) listRecord construction: type name, field values
*)| EVariant of string * string * expr listVariant construction: type name, constructor, args
*)| EArrayLen of stringArray length intrinsic
*)| EArrayCreate of elttype * expr * memspaceelem type, size, memspace
*)| EIf of expr * expr * exprcondition, then, else - value-returning if
*)| EMatch of expr * (pattern * expr) listscrutinee, cases - value-returning match
*)Expressions (pure, no side effects)
type stmt = | SAssign of lvalue * expr| SSeq of stmt list| SIf of expr * stmt * stmt option| SWhile of expr * stmt| SFor of var * expr * expr * for_dir * stmt| SMatch of expr * (pattern * stmt) list| SReturn of expr| SBarrierBlock-level barrier (__syncthreads)
*)| SWarpBarrierWarp-level sync (__syncwarp)
*)| SExpr of exprSide-effecting expression
*)| SEmpty| SLet of var * expr * stmtLet binding: let v = e in body
*)| SLetMut of var * expr * stmtMutable let: let v = ref e in body
*)| SPragma of string list * stmtPragma hints wrapping a statement
*)| SMemFenceMemory fence (threadfence)
*)| SBlock of stmtScoped block - creates a C scope for variable isolation
*)| SNative of {gpu : framework:string -> string;Generate GPU code for framework
*)ocaml : ocaml_closure;Typed OCaml fallback
*)}Inline native GPU code with OCaml fallback
*)| SCoopmat of coopmat_opA cooperative-matrix (tensor-core) operation — backlog-62 slice 3.
Why ONE statement constructor carrying an operation family, rather than four constructors. Seventeen places in this repository match exhaustively on stmt, and most of them are backends whose only correct response to any of these operations is the same refusal. Four constructors would be sixty-eight arms to write and to keep in agreement; one is seventeen, and a backend that handles SCoopmat at all is then forced by the compiler to consider every member of coopmat_op in one place where the four cases sit next to each other.
Why fragments are NOT vars and NOT an elttype. A fragment is a subgroup-cooperative value: the whole subgroup collectively holds rows * columns components and each invocation holds a few of them at an implementation-defined position. It cannot be indexed, assigned to, added, cast, passed to a helper, or stored in an array. Giving it an elttype would make every one of those spellable in the IR and would oblige ~36 exhaustive elttype matches to invent an answer for a type none of them can represent. Fragments therefore live in their own namespace, addressed by name, and the only things that can be done to one are the five below.
Statements (imperative, side effects)
and coopmat_op = | CM_decl of {name : string;frag : Sarek_coopmat_types.fragment;}Bring a fragment into scope for the rest of the enclosing block.
The fragment is zero-initialised (every component, normative on every backend): a kernel may CM_muladd into a declared accumulator without loading it, and may leave a CM_load out entirely. The Interpreter zero-fills, CUDA emits fill_fragment(f, 0), HIP = {}, GLSL coopmat<..>(0). A backend that cannot guarantee this must refuse the declaration, never emit an uninitialised fragment.
Statement-level rather than a scoping form like SLet, because GLSL, MSL and C all admit a declaration in the middle of a block and because D = A * B + C wants four fragments live at once — nesting four SLet-shaped binders to express that is noise with no invariant behind it.
| CM_load of {dst : string;frag : Sarek_coopmat_types.fragment;src : string;index : expr;stride : expr;layout : Sarek_coopmat_types.layout;}Fill dst from the buffer src, element (0, 0) at index. With layout = Row_major, stride elements separate consecutive rows (element (r, c) is at index + r * stride + c); with Col_major, they separate consecutive columns (index + c * stride + r).
frag is repeated here rather than looked up from the CM_decl: a codegen backend must be able to emit this statement without carrying a fragment environment, and an interpreter must be able to CHECK the two agree. A single source of truth that every consumer has to reconstruct is not a single source of truth.
layout is required, not defaulted, so every construction site states which of the two it means. Column-major is what lets an operand stored transposed (a B kept as nk, token-major activations) be loaded with contiguous reads: on HIP gfx11 a column-major B fragment is one contiguous 16-element run per lane, a row-major one a stride-stride gather (specs/coopmat-hip-wmma.md). A backend that cannot lower a layout refuses the statement.
| CM_store of {src : string;frag : Sarek_coopmat_types.fragment;dst : string;index : expr;stride : expr;layout : Sarek_coopmat_types.layout;}The inverse of CM_load, with the same layout semantics.
Overlapping rows. With a stride below the tile edge the rows (columns) of the tile overlap in memory, and a cell is then written twice, with different values. The LAST write of the interpreter's loop wins (rows outer, columns inner, whatever the layout), and that is the semantics: CUDA/C and CUDA/PTX write such a tile serially, in that order, instead of leaving it to the matrix-unit store, which promises no order; HIP agrees on gfx11 (tested). (A CM_load with such a stride is well defined: it reads shared cells.)
| CM_muladd of {dst : string;a : string;b : string;c : string;cfg : Sarek_coopmat_types.config;}dst = a * b + c, the tensor-core instruction itself.
cfg is the whole point of carrying a configuration rather than four fragments: it is what the device gate is keyed on, it is what says whether the accumulation SATURATES (a property of the operation and not of any operand), and it is what Sarek_coopmat_types.accumulation_is_exact reads to decide whether this statement is under the strict contract or needs the relaxation of docs/design/f16-relaxed-accuracy.md §1.6.
| CM_scale_add of {dst : string;dst_frag : Sarek_coopmat_types.fragment;src : string;src_frag : Sarek_coopmat_types.fragment;row : coopmat_scale;col : coopmat_scale option;offset : coopmat_offset option;accumulate : bool;}Scaled accumulation (docs/design/coopmat-scaled-accumulate.md): for every element, with r i = row.(i), c j = col.(j) (1 when col = None) and (p, q) the offset scales, dst[i][j] <- (dst[i][j] + (f32 (src[i][j]) * r i) * c j) - p i * q j.
The order is the semantics. Each step is one binary32 operation rounded to nearest even, in exactly this order, never contracted: t1 = f32 src, t2 = t1 * r, t3 = t2 * c, t4 = dst + t3 (t3 when accumulate = false: the old dst is not read), t5 = p * q, dst = t4 - t5. It is therefore Strict: a device performing these operations produces the interpreter's bits, and no accuracy grant is involved.
dst_frag is an f32 accumulator; src_frag an s32 or f32 accumulator of the same shape and scope (u32 is refused: its conversion would need its own meaning). dst and src may name the same f32 fragment (the per-row rescale of online softmax). The scale buffers are float32, global or shared, and their indices are uniform across the subgroup, as for CM_load.
The consumer is a quantised GEMM that accumulates each block exactly in int32 and then applies the block's per-row and per-column scales once. Without this statement that needs a store of the int32 fragment, a scalar pass and a load back.
*)The five things that can be done with a cooperative-matrix fragment.
Fragment names live in a namespace of their own, separate from var. They are plain strings for the same reason an SShared array name is: a fragment is not an l-value, cannot be captured, and cannot escape the kernel body, so there is nothing for a var's mutability or type field to carry that Sarek_coopmat_types.fragment does not already say.
One scale vector of CM_scale_add: element i is scale_buf.(scale_index + i).
The offset of CM_scale_add: off_row.(i) * off_col.(j) is subtracted.
Declarations
Helper function (device function called from kernel)
and native_arg = | NA_Int32 of int32| NA_Int64 of int64| NA_Float32 of float| NA_Float64 of float| NA_Vec of native_vecNative argument type for kernel execution. Typed arguments with runtime type witnesses - used by PPX-generated native functions.
and ('elt, 'underlying) native_vec_ops = {length : int;elem_size : int;type_name : string;type_id : 'elt Type_id.t;get_f32 : int -> float;set_f32 : int -> float -> unit;get_f64 : int -> float;set_f64 : int -> float -> unit;get_i32 : int -> int32;set_i32 : int -> int32 -> unit;get_i64 : int -> int64;set_i64 : int -> int64 -> unit;get_typed : int -> 'elt;set_typed : int -> 'elt -> unit;underlying_type_id : 'underlying Type_id.t;underlying : 'underlying;}and ocaml_closure = {run : block:(int * int * int) ->
grid:(int * int * int) ->
native_arg array ->
unit;}val vec_get_custom : 'a. 'a Type_id.t -> native_arg -> int -> 'aGet element from NA_Vec as a type checked custom value.
val vec_set_custom : 'a. 'a Type_id.t -> native_arg -> int -> 'a -> unitSet element in NA_Vec from a type checked custom value.
val vec_length : native_arg -> intGet length from NA_Vec
val vec_as_vector : 'a. 'a Type_id.t -> native_arg -> 'aGet the checked underlying vector/buffer value.
type native_fn_t = | NativeFn of parallel:bool ->
block:(int * int * int) ->
grid:(int * int * int) ->
native_arg array ->
unitNative function type for V2 execution. Uses typed native_arg.
Upper bound on the work-group size a kernel may be launched with.
Declared in the kernel body with pragma ["sarek.max_threads N"]. It lets backends that compile for the worst case (1024 threads) lift the register cap. A kernel without the hint is generated exactly as before.
type kernel = {kern_name : string;kern_params : decl list;kern_locals : decl list;kern_body : stmt;kern_types : (string * (string * elttype) list) list;Record type definitions: (type_name, (field_name, field_type); ...)
kern_variants : (string * (string * elttype list) list) list;Variant type definitions: (type_name, (constructor_name, payload_types); ...)
kern_funcs : helper_func list;Helper functions defined in kernel scope
*)kern_native_fn : native_fn_t option;Optional pre-compiled native function for CPU execution
*)kern_launch_bounds : launch_bounds option;Optional work-group size bound (sarek.max_threads); None means the backend default.
}Kernel representation
val combine_launch_bounds : launch_bounds option list -> launch_bounds optionBound of a kernel built from several kernels (fusion): the smallest declared bound, since the fused kernel must satisfy every member. None when no member declares one.
val default_kernel : kernelA kernel with every field at its empty value, for use as the base of a record update: {default_kernel with kern_name = "k"; kern_body = b}.
WHY THIS EXISTS. OCaml requires every field at every record literal, so adding one field to kernel used to mean editing all 119 construction sites in the tree — which is why the type has been avoided rather than extended. A record UPDATE names only the fields it sets, so once a site is written this way a new field costs it nothing.
Prefer this over spelling out the empty fields. make_kernel is the same thing with labels, for new code that would otherwise set most fields.
val make_kernel :
?params:decl list ->
?locals:decl list ->
?types:(string * (string * elttype) list) list ->
?variants:(string * (string * elttype list) list) list ->
?funcs:helper_func list ->
?native_fn:native_fn_t ->
?launch_bounds:launch_bounds ->
name:string ->
body:stmt ->
unit ->
kerneldefault_kernel with labels. ~name and ~body are required because a kernel with neither is not a kernel; everything else defaults to empty.