use metal::MTLSize;
use crate::buffer::MlxBuffer;
use crate::dtypes::DType;
use crate::encoder::{CapturedOpKind, CommandEncoder, KernelArg};
use crate::error::{MlxError, Result};
use crate::kernel_registry::KernelRegistry;
pub const KERNEL: &str = "dflash2_rms_norm_bf16";
pub static SOURCE: &str = include_str!("../shaders/dflash2_rms_norm.metal");
pub fn register(registry: &mut KernelRegistry) {
registry.register_source(KERNEL, SOURCE);
}
#[allow(clippy::too_many_arguments)]
pub fn dispatch_dflash2_rms_norm_bf16(
encoder: &mut CommandEncoder,
registry: &mut KernelRegistry,
device: &metal::DeviceRef,
input: &MlxBuffer,
weight: &MlxBuffer,
output: &MlxBuffer,
params: &MlxBuffer,
rows: u32,
dim: u32,
) -> Result<()> {
if rows == 0 || dim == 0 || dim > (1 << 24) {
return Err(MlxError::InvalidArgument(
"DFlash2 RMS requires positive rows and dim <= 2^24".into(),
));
}
let bytes = (rows as usize)
.checked_mul(dim as usize)
.and_then(|n| n.checked_mul(std::mem::size_of::<f32>()))
.ok_or_else(|| MlxError::InvalidArgument("DFlash2 RMS size overflow".into()))?;
for (name, buffer, required) in [
("input", input, bytes),
("weight", weight, dim as usize * std::mem::size_of::<f32>()),
("output", output, bytes),
("params", params, std::mem::size_of::<f32>()),
] {
if buffer.dtype() != DType::F32
|| buffer.byte_offset() % std::mem::align_of::<f32>() as u64 != 0
|| buffer.data_byte_len() < required
{
return Err(MlxError::InvalidArgument(format!(
"DFlash2 RMS {name} requires F32 and at least {required} bytes in its aligned view"
)));
}
}
let pipeline = registry.get_pipeline(KERNEL, device)?;
if pipeline.thread_execution_width() != 32
|| pipeline.max_total_threads_per_threadgroup() < 256
|| pipeline.static_threadgroup_memory_length() > device.max_threadgroup_memory_length()
{
return Err(MlxError::InvalidArgument(
"DFlash2 RMS requires eight 32-thread SIMD groups and its static partial storage".into(),
));
}
encoder.set_op_kind(CapturedOpKind::Other);
encoder.encode_threadgroups_with_args(
pipeline,
&[
(0, KernelArg::Buffer(input)),
(1, KernelArg::Buffer(weight)),
(2, KernelArg::Buffer(output)),
(3, KernelArg::Buffer(params)),
(4, KernelArg::Bytes(bytemuck::bytes_of(&dim))),
],
MTLSize::new(u64::from(rows), 1, 1),
MTLSize::new(256, 1, 1),
);
Ok(())
}