use crate::device::{DeviceCapabilities, WgpuDevice, WorkloadType};
use crate::error::Result;
use crate::tensor::Tensor;
use std::sync::Arc;
const SHADER_F64: &str = include_str!("../shaders/misc/fill_f64.wgsl");
static SHADER_F32: std::sync::LazyLock<String> =
std::sync::LazyLock::new(|| SHADER_F64.to_string());
#[must_use]
pub fn wgsl_meshgrid() -> &'static str {
static SHADER: std::sync::LazyLock<String> =
std::sync::LazyLock::new(|| include_str!("../shaders/misc/meshgrid_f64.wgsl").to_string());
std::sync::LazyLock::force(&SHADER).as_str()
}
#[repr(C)]
#[derive(Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)]
struct FillParams {
value: f32,
_padding: [f32; 7],
}
pub struct Fill {
shape: Vec<usize>,
value: f32,
device: Arc<WgpuDevice>,
}
impl Fill {
#[must_use]
pub fn new(shape: Vec<usize>, value: f32, device: Arc<WgpuDevice>) -> Self {
Self {
shape,
value,
device,
}
}
fn wgsl_shader() -> &'static str {
&SHADER_F32
}
pub fn execute(self) -> Result<Tensor> {
let size: usize = self.shape.iter().product();
let output_buffer = self.device.create_buffer_f32(size)?;
let params = FillParams {
value: self.value,
_padding: [0.0; 7],
};
let params_buffer =
self.device
.device
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Fill Params"),
contents: bytemuck::bytes_of(¶ms),
usage: wgpu::BufferUsages::UNIFORM,
});
let shader = self
.device
.compile_shader(Self::wgsl_shader(), Some("Fill Shader"));
let pipeline =
self.device
.device
.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("Fill Pipeline"),
layout: None,
module: &shader,
entry_point: Some("main"),
cache: None,
compilation_options: Default::default(),
});
let bind_group_layout = pipeline.get_bind_group_layout(0);
let bind_group = self
.device
.device
.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Fill Bind Group"),
layout: &bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: output_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: params_buffer.as_entire_binding(),
},
],
});
let mut encoder = self
.device
.create_encoder_guarded(&wgpu::CommandEncoderDescriptor {
label: Some("Fill Encoder"),
});
{
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("Fill Pass"),
timestamp_writes: None,
});
compute_pass.set_pipeline(&pipeline);
compute_pass.set_bind_group(0, Some(&bind_group), &[]);
let caps = DeviceCapabilities::from_device(&self.device);
let optimal_wg_size = caps.optimal_workgroup_size(WorkloadType::ElementWise);
let workgroups = (size as u32).div_ceil(optimal_wg_size);
compute_pass.dispatch_workgroups(workgroups, 1, 1);
}
self.device.submit_commands(Some(encoder.finish()));
Ok(Tensor::from_buffer(output_buffer, self.shape, self.device))
}
}
impl Tensor {
pub fn fill(shape: Vec<usize>, value: f32, device: Arc<WgpuDevice>) -> Result<Self> {
Fill::new(shape, value, device).execute()
}
pub fn fill_with(self, value: f32) -> Result<Self> {
Fill::new(self.shape().to_vec(), value, self.device().clone()).execute()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_fill_basic() {
let device = crate::device::test_pool::get_test_device().await;
let result = Tensor::fill(vec![3, 4], 7.5, device).unwrap();
let output = result.to_vec().unwrap();
assert_eq!(output.len(), 12);
for val in &output {
assert_eq!(*val, 7.5);
}
}
#[tokio::test]
async fn test_fill_edge_cases() {
let device = crate::device::test_pool::get_test_device().await;
let result = Tensor::fill(vec![1], 99.0, device.clone()).unwrap();
let output = result.to_vec().unwrap();
assert_eq!(output.len(), 1);
assert_eq!(output[0], 99.0);
let result = Tensor::fill(vec![5, 5], 0.0, device.clone()).unwrap();
let output = result.to_vec().unwrap();
assert_eq!(output.len(), 25);
assert!(output.iter().all(|&x| x == 0.0));
let result = Tensor::fill(vec![3], -5.5, device).unwrap();
let output = result.to_vec().unwrap();
assert!(output.iter().all(|&x| x == -5.5));
}
#[tokio::test]
async fn test_fill_boundary() {
let device = crate::device::test_pool::get_test_device().await;
let result = Tensor::fill(vec![4], 1e-10, device.clone()).unwrap();
let output = result.to_vec().unwrap();
assert!(output.iter().all(|&x| (x - 1e-10).abs() < 1e-15));
let result = Tensor::fill(vec![4], 1e10, device.clone()).unwrap();
let output = result.to_vec().unwrap();
assert!(output.iter().all(|&x| (x - 1e10).abs() < 1e5));
let result = Tensor::fill(vec![2, 3, 4], 2.78, device).unwrap();
let output = result.to_vec().unwrap();
assert_eq!(output.len(), 24);
assert!(output.iter().all(|&x| (x - 2.78).abs() < 1e-6));
}
#[tokio::test]
async fn test_fill_large_batch() {
let device = crate::device::test_pool::get_test_device().await;
let result = Tensor::fill(vec![100, 100], 42.0, device).unwrap();
let output = result.to_vec().unwrap();
assert_eq!(output.len(), 10_000);
assert!(output.iter().all(|&x| x == 42.0));
}
#[tokio::test]
async fn test_fill_precision() {
let device = crate::device::test_pool::get_test_device().await;
let result = Tensor::fill(vec![10], 2.5, device.clone()).unwrap();
let output = result.to_vec().unwrap();
assert!(output.iter().all(|&x| x == 2.5));
let result = Tensor::fill(vec![5], 1.234567, device).unwrap();
let output = result.to_vec().unwrap();
for val in &output {
assert!((val - 1.234567).abs() < 1e-6);
}
}
}