Skip to main content

ferric_core/
lib.rs

1//! Ferric core — L0 (portable device/fabric abstraction) + L1 (kernel dispatch), on `wgpu`.
2//!
3//! `wgpu` gives us one API over WebGPU (browser), Vulkan, Metal, DX12, and GL. This crate wraps it
4//! into a tiny `Context` and the first real kernel (matmul), written ONCE in WGSL and run on any
5//! fabric. The same source compiles to native (Metal/Vulkan/DX12) and to `wasm32` for the browser.
6//! Numerics are validated against a plain-Rust CPU reference so "runs everywhere" also means
7//! "computes the same everywhere".
8
9use std::borrow::Cow;
10
11pub type Result<T> = std::result::Result<T, String>;
12
13mod kernels;
14pub use kernels::cpu; // CPU references for validation
15pub mod demo; // a small deterministic Llama-style LM, same code native + browser
16
17/// A compute context bound to one GPU adapter on whatever fabric is available.
18pub struct Context {
19    pub device: wgpu::Device,
20    pub queue: wgpu::Queue,
21    pub backend: wgpu::Backend,
22    pub adapter_name: String,
23}
24
25/// An f32 tensor living in GPU memory. Ops chain Tensor→Tensor with no host readback until `to_vec`,
26/// so a whole model runs on-device — this is the L2/L3 substrate (the graph executor works on these).
27pub struct Tensor {
28    pub buf: wgpu::Buffer,
29    pub shape: Vec<usize>,
30}
31impl Tensor {
32    pub fn len(&self) -> usize { self.shape.iter().product() }
33    pub fn is_empty(&self) -> bool { self.len() == 0 }
34}
35
36impl Context {
37    /// Acquire the best available compute device on this fabric (native GPU or browser WebGPU).
38    pub async fn new() -> Result<Self> {
39        let instance = wgpu::Instance::default();
40        let adapter = instance
41            .request_adapter(&wgpu::RequestAdapterOptions {
42                power_preference: wgpu::PowerPreference::HighPerformance,
43                ..Default::default()
44            })
45            .await
46            .map_err(|e| format!("no compute adapter: {e:?}"))?;
47        let info = adapter.get_info();
48        let (device, queue) = adapter
49            .request_device(&wgpu::DeviceDescriptor {
50                label: Some("ferric"),
51                required_features: wgpu::Features::empty(),
52                // downlevel defaults keep us inside the WebGPU baseline → the same limits hold in a browser
53                required_limits: wgpu::Limits::downlevel_defaults(),
54                memory_hints: wgpu::MemoryHints::Performance,
55                ..Default::default()
56            })
57            .await
58            .map_err(|e| format!("no compute device: {e:?}"))?;
59        Ok(Self { device, queue, backend: info.backend, adapter_name: info.name })
60    }
61
62    pub(crate) fn storage(&self, label: &str, data: &[f32]) -> wgpu::Buffer {
63        use wgpu::util::DeviceExt;
64        self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
65            label: Some(label),
66            contents: bytemuck::cast_slice(data),
67            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
68        })
69    }
70    pub(crate) fn storage_u32(&self, label: &str, data: &[u32]) -> wgpu::Buffer {
71        use wgpu::util::DeviceExt;
72        self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
73            label: Some(label),
74            contents: bytemuck::cast_slice(data),
75            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
76        })
77    }
78    /// Copy a buffer into a fresh one of the same byte length (used for Reshape/Cast — data unchanged).
79    pub(crate) fn copy_buf(&self, src: &wgpu::Buffer, len: usize) -> wgpu::Buffer {
80        let dst = self.device.create_buffer(&wgpu::BufferDescriptor {
81            label: Some("dup"),
82            size: (len * 4) as u64,
83            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST,
84            mapped_at_creation: false,
85        });
86        let mut enc = self.device.create_command_encoder(&Default::default());
87        enc.copy_buffer_to_buffer(src, 0, &dst, 0, (len * 4) as u64);
88        self.queue.submit([enc.finish()]);
89        dst
90    }
91    pub(crate) fn uniform_u32(&self, label: &str, data: &[u32]) -> wgpu::Buffer {
92        use wgpu::util::DeviceExt;
93        self.device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
94            label: Some(label),
95            contents: bytemuck::cast_slice(data),
96            usage: wgpu::BufferUsages::UNIFORM,
97        })
98    }
99    /// An empty output storage buffer of `len` f32s (readable back via `readback`).
100    pub(crate) fn out_buffer(&self, len: usize) -> wgpu::Buffer {
101        self.device.create_buffer(&wgpu::BufferDescriptor {
102            label: Some("out"),
103            size: (len * 4) as u64,
104            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
105            mapped_at_creation: false,
106        })
107    }
108    /// Compile a WGSL compute pipeline (entry `main`, auto bind-group layout).
109    pub(crate) fn pipeline(&self, label: &str, wgsl: &str) -> wgpu::ComputePipeline {
110        let module = self.device.create_shader_module(wgpu::ShaderModuleDescriptor {
111            label: Some(label),
112            source: wgpu::ShaderSource::Wgsl(std::borrow::Cow::Owned(wgsl.to_string())),
113        });
114        self.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
115            label: Some(label),
116            layout: None,
117            module: &module,
118            entry_point: Some("main"),
119            compilation_options: Default::default(),
120            cache: None,
121        })
122    }
123    /// Dispatch a compute pipeline over `binds` with `groups` workgroups (queue-ordered before readback).
124    pub(crate) fn dispatch(&self, pipeline: &wgpu::ComputePipeline, binds: &[&wgpu::Buffer], groups: (u32, u32, u32)) {
125        let entries: Vec<wgpu::BindGroupEntry> = binds.iter().enumerate()
126            .map(|(i, b)| wgpu::BindGroupEntry { binding: i as u32, resource: b.as_entire_binding() })
127            .collect();
128        let bg = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
129            label: Some("bg"),
130            layout: &pipeline.get_bind_group_layout(0),
131            entries: &entries,
132        });
133        let mut enc = self.device.create_command_encoder(&Default::default());
134        {
135            let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: None, timestamp_writes: None });
136            pass.set_pipeline(pipeline);
137            pass.set_bind_group(0, &bg, &[]);
138            pass.dispatch_workgroups(groups.0, groups.1, groups.2);
139        }
140        self.queue.submit([enc.finish()]);
141    }
142    /// Read `len` f32s back from a storage buffer (works native + wasm).
143    pub(crate) async fn readback(&self, buf: &wgpu::Buffer, len: usize) -> Result<Vec<f32>> {
144        let bytes = (len * 4) as u64;
145        let staging = self.device.create_buffer(&wgpu::BufferDescriptor {
146            label: Some("staging"),
147            size: bytes,
148            usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
149            mapped_at_creation: false,
150        });
151        let mut enc = self.device.create_command_encoder(&Default::default());
152        enc.copy_buffer_to_buffer(buf, 0, &staging, 0, bytes);
153        self.queue.submit([enc.finish()]);
154        let (tx, rx) = flume::bounded(1);
155        staging.slice(..).map_async(wgpu::MapMode::Read, move |r| { let _ = tx.send(r); });
156        let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
157        rx.recv_async().await.map_err(|e| format!("recv: {e:?}"))?.map_err(|e| format!("map: {e:?}"))?;
158        let data = staging.slice(..).get_mapped_range().map_err(|e| format!("map range: {e:?}"))?;
159        let out: Vec<f32> = bytemuck::cast_slice(&data).to_vec();
160        drop(data);
161        staging.unmap();
162        Ok(out)
163    }
164
165    /// C = A(m×k) · B(k×n), row-major, f32. One kernel, any fabric.
166    pub async fn matmul(&self, a: &[f32], b: &[f32], m: u32, k: u32, n: u32) -> Result<Vec<f32>> {
167        assert_eq!(a.len(), (m * k) as usize);
168        assert_eq!(b.len(), (k * n) as usize);
169        let out_len = (m * n) as usize;
170        let out_bytes = (out_len * 4) as u64;
171
172        let a_buf = self.storage("a", a);
173        let b_buf = self.storage("b", b);
174        let dims_buf = self.uniform_u32("dims", &[m, k, n, 0]);
175        let out_buf = self.device.create_buffer(&wgpu::BufferDescriptor {
176            label: Some("out"),
177            size: out_bytes,
178            usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
179            mapped_at_creation: false,
180        });
181
182        let shader = self.device.create_shader_module(wgpu::ShaderModuleDescriptor {
183            label: Some("matmul"),
184            source: wgpu::ShaderSource::Wgsl(Cow::Borrowed(MATMUL_WGSL)),
185        });
186        let pipeline = self.device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
187            label: Some("matmul"),
188            layout: None,
189            module: &shader,
190            entry_point: Some("main"),
191            compilation_options: Default::default(),
192            cache: None,
193        });
194        let bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
195            label: Some("matmul-bg"),
196            layout: &pipeline.get_bind_group_layout(0),
197            entries: &[
198                wgpu::BindGroupEntry { binding: 0, resource: a_buf.as_entire_binding() },
199                wgpu::BindGroupEntry { binding: 1, resource: b_buf.as_entire_binding() },
200                wgpu::BindGroupEntry { binding: 2, resource: out_buf.as_entire_binding() },
201                wgpu::BindGroupEntry { binding: 3, resource: dims_buf.as_entire_binding() },
202            ],
203        });
204
205        let mut enc = self.device.create_command_encoder(&Default::default());
206        {
207            let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
208                label: Some("matmul"),
209                timestamp_writes: None,
210            });
211            pass.set_pipeline(&pipeline);
212            pass.set_bind_group(0, &bind_group, &[]);
213            let gx = (m + 15) / 16;
214            let gy = (n + 15) / 16;
215            pass.dispatch_workgroups(gx, gy, 1);
216        }
217        // copy to a mappable staging buffer for readback
218        let staging = self.device.create_buffer(&wgpu::BufferDescriptor {
219            label: Some("staging"),
220            size: out_bytes,
221            usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
222            mapped_at_creation: false,
223        });
224        enc.copy_buffer_to_buffer(&out_buf, 0, &staging, 0, out_bytes);
225        self.queue.submit([enc.finish()]);
226
227        // async readback that works on native (poll blocks) and wasm (browser drives the queue)
228        let (tx, rx) = flume::bounded(1);
229        staging.slice(..).map_async(wgpu::MapMode::Read, move |r| { let _ = tx.send(r); });
230        let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
231        rx.recv_async().await.map_err(|e| format!("recv: {e:?}"))?.map_err(|e| format!("map: {e:?}"))?;
232        let data = staging.slice(..).get_mapped_range().map_err(|e| format!("map range: {e:?}"))?;
233        let out: Vec<f32> = bytemuck::cast_slice(&data).to_vec();
234        drop(data);
235        staging.unmap();
236        Ok(out)
237    }
238}
239
240pub(crate) const MATMUL_WGSL: &str = r#"
241@group(0) @binding(0) var<storage, read>       a: array<f32>;
242@group(0) @binding(1) var<storage, read>       b: array<f32>;
243@group(0) @binding(2) var<storage, read_write> out: array<f32>;
244@group(0) @binding(3) var<uniform>             dims: vec4<u32>; // m, k, n, _
245
246@compute @workgroup_size(16, 16, 1)
247fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
248    let m = dims.x; let k = dims.y; let n = dims.z;
249    let row = gid.x; let col = gid.y;
250    if (row >= m || col >= n) { return; }
251    var acc: f32 = 0.0;
252    for (var i: u32 = 0u; i < k; i = i + 1u) {
253        acc = acc + a[row * k + i] * b[i * n + col];
254    }
255    out[row * n + col] = acc;
256}
257"#;
258
259/// Plain-Rust CPU reference (the source of truth for validation).
260pub fn matmul_cpu(a: &[f32], b: &[f32], m: usize, k: usize, n: usize) -> Vec<f32> {
261    let mut c = vec![0.0f32; m * n];
262    for row in 0..m {
263        for col in 0..n {
264            let mut acc = 0.0f32;
265            for i in 0..k {
266                acc += a[row * k + i] * b[i * n + col];
267            }
268            c[row * n + col] = acc;
269        }
270    }
271    c
272}
273
274/// Max absolute difference between two equal-length vectors.
275pub fn max_abs_diff(x: &[f32], y: &[f32]) -> f32 {
276    x.iter().zip(y).map(|(a, b)| (a - b).abs()).fold(0.0, f32::max)
277}