1use crate::arena::Arena;
23use crate::kernels;
24use rlx_ir::op::{Activation, BinaryOp, ReduceOp};
25use rlx_ir::{Graph, NodeId, Op};
26use std::collections::HashMap;
27
28pub struct ExternalBuffers<'a> {
30 pub buffers: HashMap<NodeId, &'a [f32]>,
32}
33
34pub fn execute(graph: &Graph, arena: &mut Arena, external: &ExternalBuffers) {
42 let schedule: Vec<NodeId> = arena.schedule().to_vec();
43 for &node_id in &schedule {
44 let node = graph.node(node_id);
45
46 match &node.op {
47 Op::Input { .. } | Op::Param { .. } | Op::Constant { .. } => {}
50
51 Op::FusedMatMulBiasAct { activation } => {
53 let input_id = node.inputs[0];
54 let weight_id = node.inputs[1];
55 let bias_id = node.inputs[2];
56
57 let input = get_data(arena, external, input_id);
58 let weight = get_data(arena, external, weight_id);
59 let bias = get_data(arena, external, bias_id);
60 let output = get_output(arena, node_id);
61
62 let shape = &node.shape;
64 let n = shape.dim(shape.rank() - 1).unwrap_static();
65 let m = shape.num_elements().unwrap() / n;
66 let k = input.len() / m;
67
68 matmul(input, weight, output, m, k, n);
72
73 match activation {
75 Some(Activation::Gelu) => kernels::par_bias_gelu(output, bias, m, n),
76 Some(Activation::Silu) => {
77 crate::blas::bias_add(output, bias, m, n);
78 kernels::silu_inplace(output);
79 }
80 _ => crate::blas::bias_add(output, bias, m, n),
81 }
82 }
83
84 Op::FusedResidualLN { has_bias, eps } => {
86 let x_id = node.inputs[0];
87 let residual_id = node.inputs[1];
88 let h = node.shape.dim(node.shape.rank() - 1).unwrap_static();
89 let zero_bias = vec![0f32; h];
90 let (gamma_id, beta_id, bias_slice) = if *has_bias {
91 let b = get_data(arena, external, node.inputs[2]);
92 (node.inputs[3], node.inputs[4], b)
93 } else {
94 (node.inputs[2], node.inputs[3], zero_bias.as_slice())
95 };
96
97 let x = get_data(arena, external, x_id);
98 let residual = get_data(arena, external, residual_id);
99 let gamma = get_data(arena, external, gamma_id);
100 let beta = get_data(arena, external, beta_id);
101 let output = get_output(arena, node_id);
102
103 let n = x.len() / h;
104
105 let x_ptr = x.as_ptr() as usize;
107 let r_ptr = residual.as_ptr() as usize;
108 let o_ptr = output.as_mut_ptr() as usize;
109 let bi_ptr = bias_slice.as_ptr() as usize;
110 let g_ptr = gamma.as_ptr() as usize;
111 let b_ptr = beta.as_ptr() as usize;
112 let e = *eps;
113 crate::pool::par_for(n, 4, &|off, cnt| unsafe {
114 let x_s =
115 std::slice::from_raw_parts((x_ptr as *const f32).add(off * h), cnt * h);
116 let r_s =
117 std::slice::from_raw_parts((r_ptr as *const f32).add(off * h), cnt * h);
118 let o_s =
119 std::slice::from_raw_parts_mut((o_ptr as *mut f32).add(off * h), cnt * h);
120 let bi = std::slice::from_raw_parts(bi_ptr as *const f32, h);
121 let g = std::slice::from_raw_parts(g_ptr as *const f32, h);
122 let b = std::slice::from_raw_parts(b_ptr as *const f32, h);
123 kernels::residual_bias_layer_norm(x_s, r_s, bi, g, b, o_s, cnt, h, e);
124 });
125 }
126
127 Op::FusedResidualRmsNorm { has_bias, eps } => {
129 let x_id = node.inputs[0];
130 let residual_id = node.inputs[1];
131 let h = node.shape.dim(node.shape.rank() - 1).unwrap_static();
132 let zero_bias = vec![0f32; h];
133 let (gamma_id, beta_id, bias_slice) = if *has_bias {
134 let b = get_data(arena, external, node.inputs[2]);
135 (node.inputs[3], node.inputs[4], b)
136 } else {
137 (node.inputs[2], node.inputs[3], zero_bias.as_slice())
138 };
139
140 let x = get_data(arena, external, x_id);
141 let residual = get_data(arena, external, residual_id);
142 let gamma = get_data(arena, external, gamma_id);
143 let beta = get_data(arena, external, beta_id);
144 let output = get_output(arena, node_id);
145
146 let n = x.len() / h;
147
148 let x_ptr = x.as_ptr() as usize;
149 let r_ptr = residual.as_ptr() as usize;
150 let o_ptr = output.as_mut_ptr() as usize;
151 let bi_ptr = bias_slice.as_ptr() as usize;
152 let g_ptr = gamma.as_ptr() as usize;
153 let b_ptr = beta.as_ptr() as usize;
154 let e = *eps;
155 crate::pool::par_for(n, 4, &|off, cnt| unsafe {
156 let x_s =
157 std::slice::from_raw_parts((x_ptr as *const f32).add(off * h), cnt * h);
158 let r_s =
159 std::slice::from_raw_parts((r_ptr as *const f32).add(off * h), cnt * h);
160 let o_s =
161 std::slice::from_raw_parts_mut((o_ptr as *mut f32).add(off * h), cnt * h);
162 let bi = std::slice::from_raw_parts(bi_ptr as *const f32, h);
163 let g = std::slice::from_raw_parts(g_ptr as *const f32, h);
164 let b = std::slice::from_raw_parts(b_ptr as *const f32, h);
165 kernels::residual_bias_rms_norm(x_s, r_s, bi, g, b, o_s, cnt, h, e);
166 });
167 }
168
169 Op::MatMul => {
171 let lhs = get_data(arena, external, node.inputs[0]);
172 let rhs = get_data(arena, external, node.inputs[1]);
173 let output = get_output(arena, node_id);
174
175 let shape = &node.shape;
176 let lhs_shape = &graph.node(node.inputs[0]).shape;
177 let rhs_shape = &graph.node(node.inputs[1]).shape;
178 let n = shape.dim(shape.rank() - 1).unwrap_static();
179 let out_m_inner = shape.dim(shape.rank() - 2).unwrap_static();
180 let k = lhs_shape.dim(lhs_shape.rank() - 1).unwrap_static();
181
182 let total = shape.num_elements().unwrap();
185 let per_batch_out = out_m_inner * n;
186 let batches = total / per_batch_out;
187
188 if batches == 1 {
189 matmul(lhs, rhs, output, out_m_inner, k, n);
190 } else {
191 let lhs_batched =
192 lhs_shape.num_elements().unwrap_or(0) == batches * out_m_inner * k;
193 let rhs_batched = rhs_shape.num_elements().unwrap_or(0) == batches * k * n;
194 for b in 0..batches {
195 let l_off = if lhs_batched { b * out_m_inner * k } else { 0 };
196 let r_off = if rhs_batched { b * k * n } else { 0 };
197 let o_off = b * out_m_inner * n;
198 let l_slice = &lhs[l_off..l_off + out_m_inner * k];
199 let r_slice = &rhs[r_off..r_off + k * n];
200 let o_slice = &mut output[o_off..o_off + out_m_inner * n];
201 matmul(l_slice, r_slice, o_slice, out_m_inner, k, n);
202 }
203 }
204 }
205
206 Op::Binary(op) => {
208 let lhs = get_data(arena, external, node.inputs[0]);
209 let rhs = get_data(arena, external, node.inputs[1]);
210 let output = get_output(arena, node_id);
211 let len = output.len();
212 let rhs_len = rhs.len();
213
214 if matches!(op, BinaryOp::Add) && rhs_len < len && len.is_multiple_of(rhs_len) {
216 output.copy_from_slice(lhs);
217 crate::blas::bias_add(output, rhs, len / rhs_len, rhs_len);
218 } else if rhs_len == len {
219 for i in 0..len {
220 output[i] = binary_op(*op, lhs[i], rhs[i]);
221 }
222 } else {
223 for i in 0..len {
224 output[i] = binary_op(*op, lhs[i], rhs[i % rhs_len]);
225 }
226 }
227 }
228
229 Op::Activation(act) => {
231 let input = get_data(arena, external, node.inputs[0]);
232 let output = get_output(arena, node_id);
233 output.copy_from_slice(input);
234 let zeros = vec![0f32; node.shape.dim(node.shape.rank() - 1).unwrap_static()];
235 let m = output.len() / zeros.len();
236 let n = zeros.len();
237 match act {
238 Activation::Gelu => kernels::par_bias_gelu(output, &zeros, m, n),
239 Activation::Silu => kernels::silu_inplace(output),
240 Activation::Relu => {
241 for v in output.iter_mut() {
242 *v = v.max(0.0);
243 }
244 }
245 Activation::Exp => {
246 for v in output.iter_mut() {
247 *v = v.exp();
248 }
249 }
250 Activation::Sqrt => {
251 for v in output.iter_mut() {
252 *v = v.sqrt();
253 }
254 }
255 Activation::Neg => {
256 for v in output.iter_mut() {
257 *v = -*v;
258 }
259 }
260 Activation::Tanh => {
261 for v in output.iter_mut() {
262 *v = v.tanh();
263 }
264 }
265 Activation::Sigmoid => {
266 for v in output.iter_mut() {
267 *v = 1.0 / (1.0 + (-*v).exp());
268 }
269 }
270 _ => {}
271 }
272 }
273
274 Op::Gather { axis } => {
276 let table = get_data(arena, external, node.inputs[0]);
277 let indices = get_data(arena, external, node.inputs[1]);
278 let output = get_output(arena, node_id);
279
280 let table_shape = &graph.node(node.inputs[0]).shape;
281 let _out_shape = &node.shape;
282
283 if *axis == 0 {
285 let trailing: usize = (1..table_shape.rank())
286 .map(|i| table_shape.dim(i).unwrap_static())
287 .product();
288 for (i, &idx_f32) in indices.iter().enumerate() {
289 let idx = idx_f32 as usize;
290 let src = idx * trailing;
291 let dst = i * trailing;
292 output[dst..dst + trailing].copy_from_slice(&table[src..src + trailing]);
293 }
294 } else {
295 output.fill(0.0);
297 }
298 }
299
300 Op::Narrow { axis, start, len } => {
302 let input = get_data(arena, external, node.inputs[0]);
303 let output = get_output(arena, node_id);
304 let in_shape = &graph.node(node.inputs[0]).shape;
305
306 let rank = in_shape.rank();
307 let outer: usize = (0..*axis)
308 .map(|i| in_shape.dim(i).unwrap_static())
309 .product::<usize>()
310 .max(1);
311 let inner: usize = (*axis + 1..rank)
312 .map(|i| in_shape.dim(i).unwrap_static())
313 .product::<usize>()
314 .max(1);
315 let in_axis_size = in_shape.dim(*axis).unwrap_static();
316
317 for o in 0..outer {
318 for s in 0..*len {
319 let src_off = o * in_axis_size * inner + (*start + s) * inner;
320 let dst_off = o * len * inner + s * inner;
321 output[dst_off..dst_off + inner]
322 .copy_from_slice(&input[src_off..src_off + inner]);
323 }
324 }
325 }
326
327 Op::Transpose { perm } => {
329 let input = get_data(arena, external, node.inputs[0]);
330 let output = get_output(arena, node_id);
331 let in_shape = &graph.node(node.inputs[0]).shape;
332 let rank = in_shape.rank();
333
334 let in_dims: Vec<usize> =
335 (0..rank).map(|i| in_shape.dim(i).unwrap_static()).collect();
336 let out_dims: Vec<usize> = perm.iter().map(|&i| in_dims[i]).collect();
337
338 let mut in_strides = vec![1usize; rank];
341 for i in (0..rank - 1).rev() {
342 in_strides[i] = in_strides[i + 1] * in_dims[i + 1];
343 }
344 let mut out_strides = vec![1usize; rank];
345 for i in (0..rank - 1).rev() {
346 out_strides[i] = out_strides[i + 1] * out_dims[i + 1];
347 }
348
349 let total = output.len();
350 for flat_out in 0..total {
351 let mut in_flat = 0;
352 for d in 0..rank {
353 let coord = (flat_out / out_strides[d]) % out_dims[d];
355 in_flat += coord * in_strides[perm[d]];
357 }
358 output[flat_out] = input[in_flat];
359 }
360 }
361
362 Op::Concat { axis } => {
364 let output = get_output(arena, node_id);
365 let out_shape = &node.shape;
366 let rank = out_shape.rank();
367
368 let outer: usize = (0..*axis)
369 .map(|i| out_shape.dim(i).unwrap_static())
370 .product::<usize>()
371 .max(1);
372 let inner: usize = (*axis + 1..rank)
373 .map(|i| out_shape.dim(i).unwrap_static())
374 .product::<usize>()
375 .max(1);
376
377 let mut dst_off = 0;
378 for o in 0..outer {
379 for &inp_id in &node.inputs {
380 let inp = get_data(arena, external, inp_id);
381 let inp_shape = &graph.node(inp_id).shape;
382 let inp_axis = inp_shape.dim(*axis).unwrap_static();
383 let chunk = inp_axis * inner;
384 let src_off = o * chunk;
385 output[dst_off..dst_off + chunk]
386 .copy_from_slice(&inp[src_off..src_off + chunk]);
387 dst_off += chunk;
388 }
389 }
390 }
391
392 Op::Reshape { .. } | Op::Expand { .. } => {
394 let input = get_data(arena, external, node.inputs[0]);
395 let output = get_output(arena, node_id);
396 output[..input.len()].copy_from_slice(input);
397 }
398
399 Op::LayerNorm { eps, .. } => {
401 let input = get_data(arena, external, node.inputs[0]);
402 let gamma = get_data(arena, external, node.inputs[1]);
403 let beta = get_data(arena, external, node.inputs[2]);
404 let output = get_output(arena, node_id);
405 let h = node.shape.dim(node.shape.rank() - 1).unwrap_static();
406 let n = input.len() / h;
407 for row in 0..n {
408 let base = row * h;
409 kernels::layer_norm_row(
410 &input[base..base + h],
411 gamma,
412 beta,
413 &mut output[base..base + h],
414 h,
415 *eps,
416 );
417 }
418 }
419
420 Op::GroupNorm { num_groups, eps } => {
421 let input = get_data(arena, external, node.inputs[0]);
422 let gamma = get_data(arena, external, node.inputs[1]);
423 let beta = get_data(arena, external, node.inputs[2]);
424 let output = get_output(arena, node_id);
425 let n = node.shape.dim(0).unwrap_static();
426 let c = node.shape.dim(1).unwrap_static();
427 let h = node.shape.dim(2).unwrap_static();
428 let w = node.shape.dim(3).unwrap_static();
429 kernels::group_norm_nchw(input, gamma, beta, output, n, c, h, w, *num_groups, *eps);
430 }
431
432 Op::ResizeNearest2x => {
433 let input = get_data(arena, external, node.inputs[0]);
434 let output = get_output(arena, node_id);
435 let n = node.shape.dim(0).unwrap_static();
436 let c = node.shape.dim(1).unwrap_static();
437 let h = node.shape.dim(2).unwrap_static() / 2;
438 let w = node.shape.dim(3).unwrap_static() / 2;
439 let in_plane = c * h * w;
440 let out_plane = c * h * 2 * w * 2;
441 for ni in 0..n {
442 kernels::resize_nearest_2x_nchw(
443 &input[ni * in_plane..(ni + 1) * in_plane],
444 &mut output[ni * out_plane..(ni + 1) * out_plane],
445 c,
446 h,
447 w,
448 );
449 }
450 }
451
452 Op::AxialRope2d {
453 end_x,
454 end_y,
455 head_dim,
456 num_heads,
457 theta,
458 repeat_factor,
459 } => {
460 let input = get_data(arena, external, node.inputs[0]);
461 let output = get_output(arena, node_id);
462 let batch = node.shape.dim(0).unwrap_static();
463 let seq = node.shape.dim(1).unwrap_static();
464 let plane = seq * node.shape.dim(2).unwrap_static();
465 for bi in 0..batch {
466 let rotated = rlx_ir::ops::axial_rope2d::apply_axial_rope2d(
467 &input[bi * plane..(bi + 1) * plane],
468 *num_heads,
469 seq,
470 *head_dim,
471 *end_x,
472 *end_y,
473 *theta,
474 *repeat_factor,
475 );
476 output[bi * plane..(bi + 1) * plane].copy_from_slice(&rotated);
477 }
478 }
479
480 Op::Softmax { axis } => {
482 let input = get_data(arena, external, node.inputs[0]);
483 let output = get_output(arena, node_id);
484 output.copy_from_slice(input);
485 let rank = node.shape.rank();
486 let ax = if *axis < 0 {
487 (rank as i32 + axis) as usize
488 } else {
489 *axis as usize
490 };
491 let cols = node.shape.dim(ax).unwrap_static();
492 let rows = output.len() / cols;
493 crate::naive::softmax(output, rows, cols);
494 }
495
496 Op::Attention {
498 num_heads,
499 head_dim,
500 mask_kind,
501 score_scale,
502 attn_logit_softcap,
503 } => {
504 let q = get_data(arena, external, node.inputs[0]);
505 let k = get_data(arena, external, node.inputs[1]);
506 let v = get_data(arena, external, node.inputs[2]);
507 let mask: &[f32] = if matches!(
511 mask_kind,
512 rlx_ir::op::MaskKind::Custom | rlx_ir::op::MaskKind::Bias
513 ) {
514 get_data(arena, external, node.inputs[3])
515 } else {
516 &[]
517 };
518 let output = get_output(arena, node_id);
519
520 let q_shape = &graph.node(node.inputs[0]).shape;
521 let k_shape = &graph.node(node.inputs[1]).shape;
522 let hs = num_heads * head_dim;
523 let scale = score_scale.unwrap_or((*head_dim as f32).powf(-0.5));
524 let (batch_size, s_q) = if q_shape.rank() >= 3 {
525 (
526 q_shape.dim(0).unwrap_static(),
527 q_shape.dim(1).unwrap_static(),
528 )
529 } else {
530 (1, q_shape.dim(0).unwrap_static())
531 };
532 let s_k = if k_shape.rank() >= 3 {
537 k_shape.dim(1).unwrap_static()
538 } else {
539 k_shape.dim(0).unwrap_static()
540 };
541 let q_offset = s_k.saturating_sub(s_q);
542
543 let q_buf_len = s_q * head_dim;
545 let k_buf_len = s_k * head_dim;
546 let mut q_head = vec![0f32; q_buf_len];
547 let mut k_head = vec![0f32; k_buf_len];
548 let mut v_head = vec![0f32; k_buf_len];
549 let mut scores = vec![0f32; s_q * s_k];
550 let mut out_head = vec![0f32; q_buf_len];
551
552 for bi in 0..batch_size {
553 for hi in 0..*num_heads {
554 for si in 0..s_q {
556 let off = bi * s_q * hs + si * hs + hi * head_dim;
557 q_head[si * head_dim..(si + 1) * head_dim]
558 .copy_from_slice(&q[off..off + head_dim]);
559 }
560 for si in 0..s_k {
562 let off = bi * s_k * hs + si * hs + hi * head_dim;
563 k_head[si * head_dim..(si + 1) * head_dim]
564 .copy_from_slice(&k[off..off + head_dim]);
565 v_head[si * head_dim..(si + 1) * head_dim]
566 .copy_from_slice(&v[off..off + head_dim]);
567 }
568 if s_q.max(s_k) <= 32 {
571 for qi in 0..s_q {
572 for ki in 0..s_k {
573 let q_off = qi * head_dim;
574 let k_off = ki * head_dim;
575 #[cfg(target_arch = "aarch64")]
576 let mut dot;
577 #[cfg(not(target_arch = "aarch64"))]
578 let mut dot = 0f32;
579 #[cfg(target_arch = "aarch64")]
580 unsafe {
581 use std::arch::aarch64::*;
582 let chunks = head_dim / 4;
583 let mut acc = vdupq_n_f32(0.0);
584 for c in 0..chunks {
585 let vq = vld1q_f32(q_head.as_ptr().add(q_off + c * 4));
586 let vk = vld1q_f32(k_head.as_ptr().add(k_off + c * 4));
587 acc = vfmaq_f32(acc, vq, vk);
588 }
589 dot = vaddvq_f32(acc);
590 for d in (chunks * 4)..*head_dim {
591 dot += q_head[q_off + d] * k_head[k_off + d];
592 }
593 }
594 #[cfg(not(target_arch = "aarch64"))]
595 {
596 for d in 0..*head_dim {
597 dot += q_head[q_off + d] * k_head[k_off + d];
598 }
599 }
600 scores[qi * s_k + ki] = dot * scale;
601 }
602 }
603 } else {
604 crate::blas::sgemm_bt(
605 &q_head,
606 &k_head,
607 &mut scores,
608 s_q,
609 *head_dim,
610 s_k,
611 scale,
612 );
613 }
614 match mask_kind {
619 rlx_ir::op::MaskKind::None => {}
620 rlx_ir::op::MaskKind::Causal => {
621 for qi in 0..s_q {
622 let abs_q = q_offset + qi;
623 for ki in (abs_q + 1)..s_k {
624 scores[qi * s_k + ki] = -1e9;
625 }
626 }
627 }
628 rlx_ir::op::MaskKind::SlidingWindow(w) => {
629 for qi in 0..s_q {
630 let abs_q = q_offset + qi;
631 let lo = abs_q.saturating_sub(*w);
632 for ki in 0..s_k {
633 if ki < lo || ki > abs_q {
634 scores[qi * s_k + ki] = -1e9;
635 }
636 }
637 }
638 }
639 rlx_ir::op::MaskKind::Custom => {
640 if mask.len() >= (bi + 1) * s_k {
641 let m = &mask[bi * s_k..(bi + 1) * s_k];
642 for qi in 0..s_q {
643 for ki in 0..s_k {
644 if m[ki] < 0.5 {
645 scores[qi * s_k + ki] = -1e9;
646 }
647 }
648 }
649 }
650 }
651 rlx_ir::op::MaskKind::Bias => {
652 let per_bh = s_q * s_k;
656 let need = (bi * *num_heads + hi + 1) * per_bh;
657 if mask.len() >= need {
658 let bias_off = (bi * *num_heads + hi) * per_bh;
659 let b = &mask[bias_off..bias_off + per_bh];
660 for i in 0..per_bh {
661 scores[i] += b[i];
662 }
663 }
664 }
665 }
666 if let Some(cap) = attn_logit_softcap {
667 if *cap > 0.0 {
668 for s in scores.iter_mut() {
669 *s = cap * (*s / cap).tanh();
670 }
671 }
672 }
673 crate::naive::softmax(&mut scores, s_q, s_k);
674 if s_q.max(s_k) <= 32 {
676 out_head.fill(0.0);
677 for qi in 0..s_q {
678 for ki in 0..s_k {
679 let sc = scores[qi * s_k + ki];
680 if sc > 1e-8 {
681 let v_off = ki * head_dim;
682 let o_off = qi * head_dim;
683 #[cfg(target_arch = "aarch64")]
684 unsafe {
685 use std::arch::aarch64::*;
686 let vsc = vdupq_n_f32(sc);
687 let chunks = head_dim / 4;
688 for c in 0..chunks {
689 let off = c * 4;
690 let vo =
691 vld1q_f32(out_head.as_ptr().add(o_off + off));
692 let vv =
693 vld1q_f32(v_head.as_ptr().add(v_off + off));
694 vst1q_f32(
695 out_head.as_mut_ptr().add(o_off + off),
696 vfmaq_f32(vo, vsc, vv),
697 );
698 }
699 }
700 #[cfg(not(target_arch = "aarch64"))]
701 for d in 0..*head_dim {
702 out_head[o_off + d] += sc * v_head[v_off + d];
703 }
704 }
705 }
706 }
707 } else {
708 crate::blas::sgemm(
709 &scores,
710 &v_head,
711 &mut out_head,
712 s_q,
713 s_k,
714 *head_dim,
715 );
716 }
717 for si in 0..s_q {
719 let off = bi * s_q * hs + si * hs + hi * head_dim;
720 output[off..off + head_dim]
721 .copy_from_slice(&out_head[si * head_dim..(si + 1) * head_dim]);
722 }
723 }
724 }
725 }
726
727 Op::Rope { head_dim, n_rot } => {
729 let head_dim = *head_dim;
730 let n_rot = *n_rot;
731 let x = get_data(arena, external, node.inputs[0]);
732 let cos_cache = get_data(arena, external, node.inputs[1]);
733 let sin_cache = get_data(arena, external, node.inputs[2]);
734 let output = get_output(arena, node_id);
735 output.copy_from_slice(x);
736
737 let rot_half = n_rot / 2;
738 let tab_half = head_dim / 2;
739 let total = output.len();
740 let num_chunks = total / head_dim;
741 for chunk in 0..num_chunks {
742 let off = chunk * head_dim;
743 let cos_len = cos_cache.len();
744 let max_seq = cos_len / tab_half;
745 let pos = chunk % max_seq;
746 let cos_off = pos * tab_half;
747
748 for i in 0..rot_half {
749 let cos_v = cos_cache[cos_off + i];
750 let sin_v = sin_cache[cos_off + i];
751 let x1 = output[off + i];
752 let x2 = output[off + rot_half + i];
753 output[off + i] = x1 * cos_v - x2 * sin_v;
754 output[off + rot_half + i] = x2 * cos_v + x1 * sin_v;
755 }
756 output[(n_rot + off)..(head_dim + off)]
757 .copy_from_slice(&x[(n_rot + off)..(head_dim + off)]);
758 }
759 }
760
761 Op::Compare(cmp) => {
763 let lhs = get_data(arena, external, node.inputs[0]);
764 let rhs = get_data(arena, external, node.inputs[1]);
765 let output = get_output(arena, node_id);
766 let rhs_len = rhs.len();
767 for i in 0..output.len() {
768 let a = lhs[i];
769 let b = rhs[i % rhs_len];
770 output[i] = if compare_op(*cmp, a, b) { 1.0 } else { 0.0 };
771 }
772 }
773
774 Op::Where => {
776 let cond = get_data(arena, external, node.inputs[0]);
777 let on_true = get_data(arena, external, node.inputs[1]);
778 let on_false = get_data(arena, external, node.inputs[2]);
779 let output = get_output(arena, node_id);
780 for i in 0..output.len() {
781 output[i] = if cond[i] > 0.5 {
782 on_true[i]
783 } else {
784 on_false[i]
785 };
786 }
787 }
788
789 Op::Reduce {
791 op: reduce_op,
792 axes,
793 keep_dim: _,
794 } => {
795 let input = get_data(arena, external, node.inputs[0]);
796 let output = get_output(arena, node_id);
797 output.fill(0.0);
798 if axes.len() == 1 {
800 let in_shape = &graph.node(node.inputs[0]).shape;
801 let axis = axes[0];
802 let rank = in_shape.rank();
803 let outer: usize = (0..axis)
804 .map(|i| in_shape.dim(i).unwrap_static())
805 .product::<usize>()
806 .max(1);
807 let axis_size = in_shape.dim(axis).unwrap_static();
808 let inner: usize = (axis + 1..rank)
809 .map(|i| in_shape.dim(i).unwrap_static())
810 .product::<usize>()
811 .max(1);
812
813 match reduce_op {
814 ReduceOp::Sum | ReduceOp::Mean => {
815 for o in 0..outer {
816 for i in 0..inner {
817 let mut acc = 0f32;
818 for a in 0..axis_size {
819 acc += input[o * axis_size * inner + a * inner + i];
820 }
821 if matches!(reduce_op, ReduceOp::Mean) {
822 acc /= axis_size as f32;
823 }
824 output[o * inner + i] = acc;
825 }
826 }
827 }
828 ReduceOp::Max => {
829 output.fill(f32::NEG_INFINITY);
830 for o in 0..outer {
831 for i in 0..inner {
832 for a in 0..axis_size {
833 let v = input[o * axis_size * inner + a * inner + i];
834 let idx = o * inner + i;
835 if v > output[idx] {
836 output[idx] = v;
837 }
838 }
839 }
840 }
841 }
842 _ => {} }
844 }
845 }
846
847 Op::Cast { .. } => {
849 let input = get_data(arena, external, node.inputs[0]);
850 let output = get_output(arena, node_id);
851 output[..input.len()].copy_from_slice(input);
852 }
853
854 Op::FusedSwiGLU { cast_to: _, .. } => {
862 let input = get_data(arena, external, node.inputs[0]);
863 let output = get_output(arena, node_id);
864 let n = node.shape.dim(node.shape.rank() - 1).unwrap_static();
868 let outer = output.len() / n;
869 debug_assert_eq!(
870 outer * 2 * n,
871 input.len(),
872 "FusedSwiGLU: input/output shape mismatch"
873 );
874 for o in 0..outer {
875 let in_row = &input[o * 2 * n..(o + 1) * 2 * n];
876 let out_row = &mut output[o * n..(o + 1) * n];
877 for i in 0..n {
878 let up = in_row[i];
879 let gate = in_row[n + i];
880 let silu_gate = gate / (1.0 + (-gate).exp());
881 out_row[i] = up * silu_gate;
882 }
883 }
884 }
885
886 Op::DenseSolve => {
888 let a_shape = &graph.node(node.inputs[0]).shape;
889 let n = a_shape.dim(0).unwrap_static();
890 let b_elems = node.shape.num_elements().unwrap();
891 let nrhs = b_elems / n.max(1);
892 match node.shape.dtype() {
893 rlx_ir::DType::F32 => {
894 let a = get_data(arena, external, node.inputs[0]);
895 let b = get_data(arena, external, node.inputs[1]);
896 let x = get_output(arena, node_id);
897 let mut a_scratch = a.to_vec();
898 let mut x_buf = b.to_vec();
899 let info = crate::blas::sgesv(&mut a_scratch, &mut x_buf, n, nrhs);
900 if info != 0 {
901 panic!("DenseSolve: singular matrix (info={info})");
902 }
903 x[..x_buf.len()].copy_from_slice(&x_buf);
904 }
905 rlx_ir::DType::F64 => {
906 let (a_ptr, a_len) = arena.raw_ptr(node.inputs[0]);
907 let (b_ptr, b_len) = arena.raw_ptr(node.inputs[1]);
908 let (x_ptr, x_len) = arena.raw_ptr(node_id);
909 unsafe {
910 let a_src = std::slice::from_raw_parts(a_ptr as *const f64, a_len / 8);
911 let b_src = std::slice::from_raw_parts(b_ptr as *const f64, b_len / 8);
912 let mut a_scratch = a_src.to_vec();
913 let mut x_buf = b_src.to_vec();
914 let info = crate::blas::dgesv(&mut a_scratch, &mut x_buf, n, nrhs);
915 if info != 0 {
916 panic!("DenseSolve: singular matrix (info={info})");
917 }
918 std::slice::from_raw_parts_mut(x_ptr as *mut f64, x_len / 8)
919 .copy_from_slice(&x_buf);
920 }
921 }
922 other => panic!("DenseSolve executor: unsupported dtype {other:?}"),
923 }
924 }
925
926 _ => {
928 if !node.inputs.is_empty() && arena.has_buffer(node_id) {
929 let input = get_data(arena, external, node.inputs[0]);
930 let output = get_output(arena, node_id);
931 let len = output.len().min(input.len());
932 output[..len].copy_from_slice(&input[..len]);
933 }
934 }
935 }
936 }
937}
938
939fn get_data<'a>(arena: &'a Arena, external: &'a ExternalBuffers, id: NodeId) -> &'a [f32] {
943 if let Some(&ext) = external.buffers.get(&id) {
946 ext
947 } else if arena.has_buffer(id) {
948 let (ptr, len) = arena.raw_ptr(id);
949 unsafe { std::slice::from_raw_parts(ptr, len) }
950 } else {
951 panic!("no data for node {id}")
952 }
953}
954
955#[allow(clippy::mut_from_ref)]
961fn get_output(arena: &Arena, id: NodeId) -> &mut [f32] {
962 let (ptr, len) = arena.raw_ptr(id);
963 unsafe { std::slice::from_raw_parts_mut(ptr, len) }
964}
965
966#[inline]
968fn matmul(a: &[f32], b: &[f32], c: &mut [f32], m: usize, k: usize, n: usize) {
969 crate::blas::sgemm(a, b, c, m, k, n);
971}
972
973fn binary_op(op: rlx_ir::op::BinaryOp, a: f32, b: f32) -> f32 {
974 use rlx_ir::op::BinaryOp::*;
975 match op {
976 Add => a + b,
977 Sub => a - b,
978 Mul => a * b,
979 Div => a / b,
980 Max => a.max(b),
981 Min => a.min(b),
982 Pow => a.powf(b),
983 }
984}
985
986fn compare_op(op: rlx_ir::op::CmpOp, a: f32, b: f32) -> bool {
987 use rlx_ir::op::CmpOp::*;
988 match op {
989 Eq => a == b,
990 Ne => a != b,
991 Lt => a < b,
992 Le => a <= b,
993 Gt => a > b,
994 Ge => a >= b,
995 }
996}
997
998#[allow(dead_code)]
1000fn scalar_gelu(x: f32) -> f32 {
1001 let sign = if x >= 0.0 { 1.0f32 } else { -1.0 };
1002 let xa = x.abs();
1003 let t = 1.0 / (1.0 + 0.3275911 * xa);
1004 let y = t
1005 * (0.254_829_6
1006 + t * (-0.284_496_72 + t * (1.421_413_8 + t * (-1.453_152_1 + t * 1.061_405_4))));
1007 let erf = sign * (1.0 - y * (-xa * xa).exp());
1008 x * 0.5 * (1.0 + erf)
1009}
1010
1011#[cfg(test)]
1012mod tests {
1013 use super::*;
1014 use rlx_ir::*;
1015
1016 use rlx_opt::fusion::FuseMatMulBiasAct;
1017 use rlx_opt::memory;
1018 use rlx_opt::pass::Pass;
1019
1020 #[test]
1022 fn execute_fused_matmul_bias_gelu() {
1023 let mut g = Graph::new("test");
1025 let x_id = g.input("x", Shape::new(&[2, 4], DType::F32));
1026 let w_id = g.param("w", Shape::new(&[4, 3], DType::F32));
1027 let b_id = g.param("b", Shape::new(&[3], DType::F32));
1028 let mm = g.matmul(x_id, w_id, Shape::new(&[2, 3], DType::F32));
1029 let add = g.binary(BinaryOp::Add, mm, b_id, Shape::new(&[2, 3], DType::F32));
1030 let out = g.activation(Activation::Gelu, add, Shape::new(&[2, 3], DType::F32));
1031 g.set_outputs(vec![out]);
1032
1033 let fused = FuseMatMulBiasAct.run(g);
1035 println!("{fused}");
1036
1037 let plan = memory::plan_memory(&fused);
1039 println!("Arena: {} bytes", plan.arena_size);
1040
1041 let x_data = vec![1.0f32, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0]; let w_data = vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]; let b_data = vec![0.5, -0.5, 0.0]; let mut ext = ExternalBuffers {
1047 buffers: HashMap::new(),
1048 };
1049 ext.buffers.insert(fused.outputs[0], &[]); for node in fused.nodes() {
1052 match &node.op {
1053 Op::Input { name } if name == "x" => {
1054 ext.buffers.insert(node.id, &x_data);
1055 }
1056 Op::Param { name } if name == "w" => {
1057 ext.buffers.insert(node.id, &w_data);
1058 }
1059 Op::Param { name } if name == "b" => {
1060 ext.buffers.insert(node.id, &b_data);
1061 }
1062 _ => {}
1063 }
1064 }
1065
1066 let mut arena = Arena::from_plan(plan);
1068 execute(&fused, &mut arena, &ext);
1069
1070 let output_id = fused.outputs[0];
1072 let result = arena.slice(output_id);
1073 println!("Result: {result:?}");
1074
1075 assert!((result[0] - 1.399).abs() < 0.01, "got {}", result[0]);
1079 assert!((result[1] - -0.154).abs() < 0.01, "got {}", result[1]);
1080 assert!((result[2] - 0.0).abs() < 0.01, "got {}", result[2]);
1081 assert!((result[3] - 0.346).abs() < 0.01, "got {}", result[3]);
1082 }
1083
1084 #[test]
1086 fn execute_gather() {
1087 use rlx_ir::infer::GraphExt;
1088 let mut g = Graph::new("gather_test");
1089 let table = g.param("table", Shape::new(&[4, 3], DType::F32));
1091 let indices = g.input("ids", Shape::new(&[2], DType::F32)); let out = g.gather_(table, indices, 0);
1093 g.set_outputs(vec![out]);
1094
1095 let plan = memory::plan_memory(&g);
1096 let mut arena = Arena::from_plan(plan);
1097
1098 let table_data = vec![
1099 10.0, 11.0, 12.0, 20.0, 21.0, 22.0, 30.0, 31.0, 32.0, 40.0, 41.0, 42.0, ];
1104 let ids_data = vec![2.0, 0.0]; let mut ext = ExternalBuffers {
1107 buffers: HashMap::new(),
1108 };
1109 for node in g.nodes() {
1110 match &node.op {
1111 Op::Param { name } if name == "table" => {
1112 ext.buffers.insert(node.id, &table_data);
1113 }
1114 Op::Input { name } if name == "ids" => {
1115 ext.buffers.insert(node.id, &ids_data);
1116 }
1117 _ => {}
1118 }
1119 }
1120
1121 execute(&g, &mut arena, &ext);
1122 let result = arena.slice(g.outputs[0]);
1123 assert_eq!(&result[..3], &[30.0, 31.0, 32.0]); assert_eq!(&result[3..6], &[10.0, 11.0, 12.0]); }
1126
1127 #[test]
1129 fn execute_narrow() {
1130 use rlx_ir::infer::GraphExt;
1131 let mut g = Graph::new("narrow_test");
1132 let x = g.input("x", Shape::new(&[2, 6], DType::F32));
1133 let sliced = g.narrow_(x, 1, 2, 3); g.set_outputs(vec![sliced]);
1135
1136 let plan = memory::plan_memory(&g);
1137 let mut arena = Arena::from_plan(plan);
1138
1139 let data = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0];
1140 let mut ext = ExternalBuffers {
1141 buffers: HashMap::new(),
1142 };
1143 for node in g.nodes() {
1144 if let Op::Input { .. } = &node.op {
1145 ext.buffers.insert(node.id, &data);
1146 }
1147 }
1148
1149 execute(&g, &mut arena, &ext);
1150 let result = arena.slice(g.outputs[0]);
1151 assert_eq!(result, &[2.0, 3.0, 4.0, 8.0, 9.0, 10.0]);
1152 }
1153
1154 #[test]
1156 fn execute_softmax() {
1157 use rlx_ir::infer::GraphExt;
1158 let mut g = Graph::new("softmax_test");
1159 let x = g.input("x", Shape::new(&[1, 4], DType::F32));
1160 let sm = g.sm(x, -1);
1161 g.set_outputs(vec![sm]);
1162
1163 let plan = memory::plan_memory(&g);
1164 let mut arena = Arena::from_plan(plan);
1165
1166 let data = vec![1.0, 2.0, 3.0, 4.0];
1167 let mut ext = ExternalBuffers {
1168 buffers: HashMap::new(),
1169 };
1170 for node in g.nodes() {
1171 if let Op::Input { .. } = &node.op {
1172 ext.buffers.insert(node.id, &data);
1173 }
1174 }
1175
1176 execute(&g, &mut arena, &ext);
1177 let result = arena.slice(g.outputs[0]);
1178 let sum: f32 = result.iter().sum();
1179 assert!(
1180 (sum - 1.0).abs() < 1e-5,
1181 "softmax should sum to 1, got {sum}"
1182 );
1183 assert!(result[0] < result[1]);
1185 assert!(result[1] < result[2]);
1186 assert!(result[2] < result[3]);
1187 }
1188
1189 #[test]
1191 fn execute_rope() {
1192 use rlx_ir::infer::GraphExt;
1193 let head_dim = 4;
1194 let half = head_dim / 2;
1195 let seq = 2;
1196
1197 let mut g = Graph::new("rope_test");
1198 let x = g.input("x", Shape::new(&[seq, head_dim], DType::F32));
1200 let cos = g.param("cos", Shape::new(&[seq, half], DType::F32));
1201 let sin = g.param("sin", Shape::new(&[seq, half], DType::F32));
1202 let rotated = g.rope(x, cos, sin, head_dim);
1203 g.set_outputs(vec![rotated]);
1204
1205 let plan = memory::plan_memory(&g);
1206 let mut arena = Arena::from_plan(plan);
1207
1208 let x_data = vec![1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0f32];
1210 let cos_data = vec![1.0, 0.0, 0.0, 1.0f32];
1212 let sin_data = vec![0.0, 1.0, 1.0, 0.0f32];
1213
1214 let mut ext = ExternalBuffers {
1215 buffers: HashMap::new(),
1216 };
1217 for node in g.nodes() {
1218 match &node.op {
1219 Op::Input { name } if name == "x" => {
1220 ext.buffers.insert(node.id, &x_data);
1221 }
1222 Op::Param { name } if name == "cos" => {
1223 ext.buffers.insert(node.id, &cos_data);
1224 }
1225 Op::Param { name } if name == "sin" => {
1226 ext.buffers.insert(node.id, &sin_data);
1227 }
1228 _ => {}
1229 }
1230 }
1231
1232 execute(&g, &mut arena, &ext);
1233 let result = arena.slice(g.outputs[0]);
1234
1235 assert!((result[0] - 1.0).abs() < 1e-5, "pos0[0]={}", result[0]);
1241 assert!((result[1] - -1.0).abs() < 1e-5, "pos0[1]={}", result[1]);
1242 assert!((result[2] - 0.0).abs() < 1e-5, "pos0[2]={}", result[2]);
1243 assert!((result[3] - 0.0).abs() < 1e-5, "pos0[3]={}", result[3]);
1244
1245 assert!((result[4] - 0.0).abs() < 1e-5, "pos1[0]={}", result[4]);
1249 assert!((result[5] - 1.0).abs() < 1e-5, "pos1[1]={}", result[5]);
1250 assert!((result[6] - 1.0).abs() < 1e-5, "pos1[2]={}", result[6]);
1251 assert!((result[7] - 0.0).abs() < 1e-5, "pos1[3]={}", result[7]);
1252 }
1253
1254 #[test]
1256 fn execute_layer_norm() {
1257 use rlx_ir::infer::GraphExt;
1258 let mut g = Graph::new("ln_test");
1259 let x = g.input("x", Shape::new(&[1, 4], DType::F32));
1260 let gamma = g.param("g", Shape::new(&[4], DType::F32));
1261 let beta = g.param("b", Shape::new(&[4], DType::F32));
1262 let ln = g.ln(x, gamma, beta, 1e-5);
1263 g.set_outputs(vec![ln]);
1264
1265 let plan = memory::plan_memory(&g);
1266 let mut arena = Arena::from_plan(plan);
1267
1268 let x_data = vec![1.0, 2.0, 3.0, 4.0];
1269 let g_data = vec![1.0, 1.0, 1.0, 1.0];
1270 let b_data = vec![0.0, 0.0, 0.0, 0.0];
1271
1272 let mut ext = ExternalBuffers {
1273 buffers: HashMap::new(),
1274 };
1275 for node in g.nodes() {
1276 match &node.op {
1277 Op::Input { name } if name == "x" => {
1278 ext.buffers.insert(node.id, &x_data);
1279 }
1280 Op::Param { name } if name == "g" => {
1281 ext.buffers.insert(node.id, &g_data);
1282 }
1283 Op::Param { name } if name == "b" => {
1284 ext.buffers.insert(node.id, &b_data);
1285 }
1286 _ => {}
1287 }
1288 }
1289
1290 execute(&g, &mut arena, &ext);
1291 let result = arena.slice(g.outputs[0]);
1292 let sum: f32 = result.iter().sum();
1293 assert!(
1294 sum.abs() < 1e-3,
1295 "LN output should be zero-centered, sum={sum}"
1296 );
1297 }
1298}