Skip to main content

MetalKernel

Struct MetalKernel 

Source
pub struct MetalKernel { /* private fields */ }
Expand description

A Metal kernel built from source, as MLX’s mx.fast.metal_kernel: a name, the names of its inputs and outputs, and the body of a kernel function. Calling it generates the function’s signature as MLX does:

  • an input of at least one dimension is const device T* name, a 0-d input const constant T& name; name_shape, name_strides and name_ndim are added when the body uses them;
  • an output is device T* name (device atomic<T>* name with atomic outputs);
  • thread attributes the body uses (thread_position_in_grid, thread_index_in_simdgroup, …) become parameters;
  • template arguments become constexpr values and typedefs at the top of the body; MLX’s type names (bfloat16_t, float16_t) and elem_to_loc are defined.

It runs on the GPU only, one thread per grid position (dispatchThreads), and has no derivative or batching rule; wrap it in crate::custom_function (or crate::custom_function_flat) to give it one.

The source is trusted code, run as written: nuvec checks the inputs, outputs and launch configuration, but not what the body does with them. A body that reads or writes outside its inputs’ and outputs’ elements accesses other GPU memory, which is undefined behaviour (as with any unsafe code); pass only source you would compile into your program.

use nuvec_core::fast::{KernelConfig, MetalKernel};
use nuvec_core::{Array, DType, Device, Result, array, default_stream};

let exp = MetalKernel::new(
    "myexp",
    &["inp"],
    &["out"],
    "uint elem = thread_position_in_grid.x;\nout[elem] = metal::exp(inp[elem]);",
);
let x = array![0.0, 1.0];
let config = KernelConfig { grid: [2, 1, 1], threadgroup: [2, 1, 1], ..Default::default() };
let y = exp.call(&[x], &[(&[2], DType::F32)], &config).remove(0);
assert!((y.to_vec::<f32>()?[1] - std::f32::consts::E).abs() < 1e-6);

Implementations§

Source§

impl MetalKernel

Source

pub fn new(name: &str, inputs: &[&str], outputs: &[&str], source: &str) -> Self

A kernel named name (letters, digits and underscores) whose body source reads inputs and writes outputs (in this order).

Each distinct instantiation (source, template arguments, input and output types and layouts) compiles one pipeline, cached for the life of the process: call a kernel with a bounded set of template arguments (not, say, a sequence length) to keep the cache bounded.

Source

pub fn header(self, header: &str) -> Self

Code placed before the kernel function (helper functions, includes).

Source

pub fn ensure_row_contiguous(self, yes: bool) -> Self

Whether inputs are copied to row-major order first (the default, as MLX); otherwise the body indexes them through name_strides.

Source

pub fn atomic_outputs(self, yes: bool) -> Self

Whether outputs are device atomic<T>* (to be updated with atomic_* functions).

Source

pub fn call( &self, inputs: &[Array], outputs: &[(&[i32], DType)], config: &KernelConfig, ) -> Vec<Array>

Runs the kernel on inputs, producing one array per output of the given shape and dtype. Invalid arguments (names, counts, dtypes, sizes) give failed arrays.

Trait Implementations§

Source§

impl Clone for MetalKernel

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for MetalKernel

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> AutoreleaseSafe for T
where T: ?Sized,

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.