scirs2-neural 0.4.2

Neural network building blocks module for SciRS2 (scirs2-neural) - Minimal Version
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
//! Flash Attention implementation
//!
//! This module implements the Flash Attention algorithm as described in:
//! "FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness"
//! by Tri Dao et al. (<https://arxiv.org/abs/2205.14135>)
//!
//! Flash Attention computes exact attention with O(N) memory instead of O(N²)
//! by using a tiling approach with online softmax computation.

use crate::error::{NeuralError, Result};
use crate::layers::attention::AttentionConfig;
use crate::layers::Layer;
use scirs2_core::ndarray::{s, Array, Array2, Array4, ArrayView2, IxDyn, ScalarOperand, Zip};
use scirs2_core::numeric::{Float, NumAssign};
use scirs2_core::random::{Rng, RngExt};
use std::fmt::Debug;

/// Configuration for Flash Attention
#[derive(Debug, Clone)]
pub struct FlashAttentionConfig {
    /// Number of attention heads
    pub num_heads: usize,
    /// Dimension of each attention head
    pub head_dim: usize,
    /// Block size for tiling (typically 64-256)
    pub block_size_q: usize,
    /// Block size for keys/values
    pub block_size_kv: usize,
    /// Whether to use causal masking
    pub causal: bool,
    /// Dropout probability
    pub dropout_prob: f64,
    /// Custom scaling factor (default is 1/sqrt(head_dim))
    pub scale: Option<f64>,
}

impl Default for FlashAttentionConfig {
    fn default() -> Self {
        Self {
            num_heads: 8,
            head_dim: 64,
            block_size_q: 64,
            block_size_kv: 64,
            causal: false,
            dropout_prob: 0.0,
            scale: None,
        }
    }
}

impl FlashAttentionConfig {
    /// Create a new FlashAttentionConfig
    pub fn new(num_heads: usize, head_dim: usize) -> Self {
        Self {
            num_heads,
            head_dim,
            ..Default::default()
        }
    }

    /// Set block size for queries
    pub fn with_block_size_q(mut self, block_size: usize) -> Self {
        self.block_size_q = block_size;
        self
    }

    /// Set block size for keys/values
    pub fn with_block_size_kv(mut self, block_size: usize) -> Self {
        self.block_size_kv = block_size;
        self
    }

    /// Enable causal masking
    pub fn with_causal(mut self, causal: bool) -> Self {
        self.causal = causal;
        self
    }

    /// Set dropout probability
    pub fn with_dropout(mut self, dropout_prob: f64) -> Self {
        self.dropout_prob = dropout_prob;
        self
    }

    /// Set custom scale factor
    pub fn with_scale(mut self, scale: f64) -> Self {
        self.scale = Some(scale);
        self
    }
}

/// Flash Attention layer
///
/// Implements memory-efficient attention using tiling and online softmax.
/// This reduces memory usage from O(N²) to O(N) while computing exact attention.
///
/// # Algorithm Overview
///
/// 1. Divide Q into blocks of size B_q
/// 2. Divide K, V into blocks of size B_kv
/// 3. For each Q block:
///    - Initialize output accumulator O and softmax statistics (m, l)
///    - For each K, V block:
///      - Compute attention scores S = Q_block @ K_block^T
///      - Update softmax statistics using online softmax
///      - Accumulate weighted values into O
///    - Rescale final output
///
/// # Memory Complexity
///
/// - Standard attention: O(N²) for storing attention matrix
/// - Flash attention: O(N) - only stores block-sized matrices
///
/// # Examples
///
/// ```rust
/// use scirs2_neural::layers::{FlashAttention, FlashAttentionConfig, Layer};
/// use scirs2_core::ndarray::Array3;
/// use scirs2_core::random::rng;
///
/// let mut rng = rng();
/// let config = FlashAttentionConfig::new(8, 64).with_causal(true);
/// let flash_attn = FlashAttention::<f64>::new(512, config, &mut rng).expect("Operation failed");
///
/// // Input shape: [batch, seq_len, d_model]
/// let input = Array3::<f64>::from_elem((2, 128, 512), 0.1).into_dyn();
/// let output = flash_attn.forward(&input).expect("Operation failed");
/// ```
#[derive(Debug)]
pub struct FlashAttention<F: Float + Debug + Send + Sync + NumAssign> {
    /// Model dimension
    d_model: usize,
    /// Configuration
    config: FlashAttentionConfig,
    /// Query projection weights [d_model, d_model]
    w_query: Array<F, IxDyn>,
    /// Key projection weights [d_model, d_model]
    w_key: Array<F, IxDyn>,
    /// Value projection weights [d_model, d_model]
    w_value: Array<F, IxDyn>,
    /// Output projection weights [d_model, d_model]
    w_output: Array<F, IxDyn>,
    /// Scaling factor for attention scores
    scale: F,
}

impl<F: Float + Debug + ScalarOperand + Send + Sync + 'static + NumAssign> FlashAttention<F> {
    /// Create a new Flash Attention layer
    ///
    /// # Arguments
    /// * `d_model` - Model dimension (embedding size)
    /// * `config` - Flash attention configuration
    /// * `rng` - Random number generator for weight initialization
    pub fn new<R: Rng>(d_model: usize, config: FlashAttentionConfig, rng: &mut R) -> Result<Self> {
        let total_dim = config.num_heads * config.head_dim;
        if total_dim != d_model {
            return Err(NeuralError::InvalidArchitecture(format!(
                "num_heads * head_dim ({}) must equal d_model ({})",
                total_dim, d_model
            )));
        }

        // Xavier initialization for weights
        let xavier_std = (F::from(2.0).expect("Failed to convert constant to float")
            / F::from(d_model + d_model).expect("Failed to convert to float"))
        .sqrt();

        let w_query = Self::init_weight(d_model, d_model, xavier_std, rng);
        let w_key = Self::init_weight(d_model, d_model, xavier_std, rng);
        let w_value = Self::init_weight(d_model, d_model, xavier_std, rng);
        let w_output = Self::init_weight(d_model, d_model, xavier_std, rng);

        let scale = config
            .scale
            .map(|s| F::from(s).expect("Failed to convert to float"))
            .unwrap_or_else(|| {
                F::one()
                    / F::from(config.head_dim)
                        .expect("Failed to convert to float")
                        .sqrt()
            });

        Ok(Self {
            d_model,
            config,
            w_query,
            w_key,
            w_value,
            w_output,
            scale,
        })
    }

    /// Initialize a weight matrix with Xavier initialization
    fn init_weight<R: Rng>(in_dim: usize, out_dim: usize, std: F, rng: &mut R) -> Array<F, IxDyn> {
        let mut weights = Array::zeros(IxDyn(&[in_dim, out_dim]));
        for w in weights.iter_mut() {
            // Use Box-Muller transform for normal distribution
            let u1: f64 = rng.random();
            let u2: f64 = rng.random();
            let z = (-2.0 * u1.ln()).sqrt() * (2.0 * std::f64::consts::PI * u2).cos();
            *w = F::from(z).expect("Failed to convert to float") * std;
        }
        weights
    }

    /// Compute Flash Attention forward pass
    ///
    /// This implements the tiled attention algorithm from the Flash Attention paper.
    /// The key insight is using online softmax to avoid materializing the full N×N matrix.
    fn flash_attention_forward(
        &self,
        query: &Array2<F>,
        key: &Array2<F>,
        value: &Array2<F>,
    ) -> Result<Array2<F>> {
        let seq_len_q = query.nrows();
        let seq_len_kv = key.nrows();
        let head_dim = query.ncols();

        let block_size_q = self.config.block_size_q.min(seq_len_q);
        let block_size_kv = self.config.block_size_kv.min(seq_len_kv);

        // Output accumulator
        let mut output = Array2::<F>::zeros((seq_len_q, head_dim));
        // Running maximum for softmax stability
        let mut row_max = vec![F::neg_infinity(); seq_len_q];
        // Running sum of exp for softmax normalization
        let mut row_sum = vec![F::zero(); seq_len_q];

        // Number of blocks
        let num_blocks_q = seq_len_q.div_ceil(block_size_q);
        let num_blocks_kv = seq_len_kv.div_ceil(block_size_kv);

        // Process each query block
        for q_block_idx in 0..num_blocks_q {
            let q_start = q_block_idx * block_size_q;
            let q_end = (q_start + block_size_q).min(seq_len_q);
            let q_block_size = q_end - q_start;

            // Get query block
            let q_block = query.slice(s![q_start..q_end, ..]);

            // Process each key/value block
            for kv_block_idx in 0..num_blocks_kv {
                let kv_start = kv_block_idx * block_size_kv;
                let kv_end = (kv_start + block_size_kv).min(seq_len_kv);

                // Skip if causal masking and this KV block is entirely in the future
                if self.config.causal && kv_start > q_end - 1 {
                    continue;
                }

                // Get key and value blocks
                let k_block = key.slice(s![kv_start..kv_end, ..]);
                let v_block = value.slice(s![kv_start..kv_end, ..]);

                // Compute attention scores: S = Q_block @ K_block^T * scale
                let scores = self.compute_block_scores(&q_block, &k_block);

                // Apply causal mask if needed
                let masked_scores = if self.config.causal {
                    self.apply_causal_mask(&scores, q_start, kv_start)
                } else {
                    scores
                };

                // Online softmax update and value accumulation
                self.online_softmax_update(
                    &masked_scores,
                    &v_block,
                    &mut output,
                    &mut row_max,
                    &mut row_sum,
                    q_start,
                    q_block_size,
                );
            }
        }

        // Final rescaling by row sums
        for i in 0..seq_len_q {
            if row_sum[i] > F::zero() {
                let inv_sum = F::one() / row_sum[i];
                for j in 0..head_dim {
                    output[[i, j]] *= inv_sum;
                }
            }
        }

        Ok(output)
    }

    /// Compute attention scores for a block: Q_block @ K_block^T * scale
    fn compute_block_scores(&self, q_block: &ArrayView2<F>, k_block: &ArrayView2<F>) -> Array2<F> {
        let q_size = q_block.nrows();
        let k_size = k_block.nrows();

        let mut scores = Array2::<F>::zeros((q_size, k_size));

        // Compute S = Q @ K^T * scale
        for i in 0..q_size {
            for j in 0..k_size {
                let mut dot = F::zero();
                for d in 0..q_block.ncols() {
                    dot += q_block[[i, d]] * k_block[[j, d]];
                }
                scores[[i, j]] = dot * self.scale;
            }
        }

        scores
    }

    /// Apply causal mask to attention scores
    fn apply_causal_mask(
        &self,
        scores: &Array2<F>,
        q_offset: usize,
        kv_offset: usize,
    ) -> Array2<F> {
        let mut masked = scores.clone();
        let q_size = scores.nrows();
        let k_size = scores.ncols();

        for i in 0..q_size {
            let q_pos = q_offset + i;
            for j in 0..k_size {
                let k_pos = kv_offset + j;
                if k_pos > q_pos {
                    masked[[i, j]] = F::neg_infinity();
                }
            }
        }

        masked
    }

    /// Online softmax update with value accumulation
    ///
    /// This is the key innovation of Flash Attention - updating softmax statistics
    /// incrementally without storing the full attention matrix.
    ///
    /// For each row i:
    /// - m_new = max(m_old, max(scores[i, :]))
    /// - l_new = l_old * exp(m_old - m_new) + sum(exp(scores[i, :] - m_new))
    /// - O_new = O_old * exp(m_old - m_new) + sum(exp(scores[i, :] - m_new) * V)
    fn online_softmax_update(
        &self,
        scores: &Array2<F>,
        v_block: &ArrayView2<F>,
        output: &mut Array2<F>,
        row_max: &mut [F],
        row_sum: &mut [F],
        q_offset: usize,
        q_block_size: usize,
    ) {
        let k_size = scores.ncols();
        let head_dim = v_block.ncols();

        for local_i in 0..q_block_size {
            let global_i = q_offset + local_i;

            // Find max in current block
            let mut block_max = F::neg_infinity();
            for j in 0..k_size {
                if scores[[local_i, j]] > block_max {
                    block_max = scores[[local_i, j]];
                }
            }

            // Update running max
            let old_max = row_max[global_i];
            let new_max = if old_max > block_max {
                old_max
            } else {
                block_max
            };

            // Compute correction factor for previous accumulations
            let correction = if old_max == F::neg_infinity() {
                F::zero()
            } else {
                (old_max - new_max).exp()
            };

            // Update output with correction factor
            for d in 0..head_dim {
                output[[global_i, d]] *= correction;
            }

            // Update row sum with correction
            row_sum[global_i] *= correction;

            // Accumulate new values with stable softmax
            for j in 0..k_size {
                if scores[[local_i, j]] > F::neg_infinity() {
                    let exp_score = (scores[[local_i, j]] - new_max).exp();
                    row_sum[global_i] += exp_score;

                    // Accumulate weighted values
                    for d in 0..head_dim {
                        output[[global_i, d]] += exp_score * v_block[[j, d]];
                    }
                }
            }

            row_max[global_i] = new_max;
        }
    }

    /// Get the configuration
    pub fn config(&self) -> &FlashAttentionConfig {
        &self.config
    }

    /// Get model dimension
    pub fn d_model(&self) -> usize {
        self.d_model
    }
}

impl<F> Layer<F> for FlashAttention<F>
where
    F: Float + Debug + ScalarOperand + Send + Sync + 'static + NumAssign,
{
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }

    fn forward(&self, input: &Array<F, IxDyn>) -> Result<Array<F, IxDyn>> {
        // Input shape: [batch, seq_len, d_model]
        if input.ndim() != 3 {
            return Err(NeuralError::InvalidArchitecture(format!(
                "Flash Attention expects 3D input [batch, seq_len, d_model], got {} dimensions",
                input.ndim()
            )));
        }

        let shape = input.shape();
        let batch_size = shape[0];
        let seq_len = shape[1];
        let d_model = shape[2];

        if d_model != self.d_model {
            return Err(NeuralError::InvalidArchitecture(format!(
                "Input dimension {} does not match model dimension {}",
                d_model, self.d_model
            )));
        }

        let num_heads = self.config.num_heads;
        let head_dim = self.config.head_dim;

        // Project input to Q, K, V
        // Reshape input to 2D for projection: [batch * seq_len, d_model]
        let input_2d = input
            .clone()
            .into_shape_with_order(IxDyn(&[batch_size * seq_len, d_model]))
            .map_err(|e| NeuralError::InferenceError(format!("Failed to reshape input: {}", e)))?;

        let input_2d_view = input_2d
            .view()
            .into_dimensionality::<scirs2_core::ndarray::Ix2>()
            .map_err(|_| NeuralError::InferenceError("Failed to convert to 2D".to_string()))?;

        let w_q_2d = self
            .w_query
            .view()
            .into_dimensionality::<scirs2_core::ndarray::Ix2>()
            .map_err(|_| NeuralError::InferenceError("Failed to convert Q weights".to_string()))?;
        let w_k_2d = self
            .w_key
            .view()
            .into_dimensionality::<scirs2_core::ndarray::Ix2>()
            .map_err(|_| NeuralError::InferenceError("Failed to convert K weights".to_string()))?;
        let w_v_2d = self
            .w_value
            .view()
            .into_dimensionality::<scirs2_core::ndarray::Ix2>()
            .map_err(|_| NeuralError::InferenceError("Failed to convert V weights".to_string()))?;
        let w_o_2d = self
            .w_output
            .view()
            .into_dimensionality::<scirs2_core::ndarray::Ix2>()
            .map_err(|_| NeuralError::InferenceError("Failed to convert O weights".to_string()))?;

        // Project to Q, K, V: [batch * seq_len, d_model]
        let q_proj = input_2d_view.dot(&w_q_2d);
        let k_proj = input_2d_view.dot(&w_k_2d);
        let v_proj = input_2d_view.dot(&w_v_2d);

        // Reshape to [batch, seq_len, num_heads, head_dim]
        let q_4d = q_proj
            .into_shape_with_order((batch_size, seq_len, num_heads, head_dim))
            .map_err(|e| NeuralError::InferenceError(format!("Failed to reshape Q: {}", e)))?;
        let k_4d = k_proj
            .into_shape_with_order((batch_size, seq_len, num_heads, head_dim))
            .map_err(|e| NeuralError::InferenceError(format!("Failed to reshape K: {}", e)))?;
        let v_4d = v_proj
            .into_shape_with_order((batch_size, seq_len, num_heads, head_dim))
            .map_err(|e| NeuralError::InferenceError(format!("Failed to reshape V: {}", e)))?;

        // Process each batch and head with Flash Attention
        let mut output_4d = Array4::<F>::zeros((batch_size, seq_len, num_heads, head_dim));

        for b in 0..batch_size {
            for h in 0..num_heads {
                // Extract Q, K, V for this batch and head
                let q_head: Array2<F> = q_4d
                    .slice(s![b, .., h, ..])
                    .to_owned()
                    .into_shape_with_order((seq_len, head_dim))
                    .map_err(|e| {
                        NeuralError::InferenceError(format!("Failed to get Q head: {}", e))
                    })?;

                let k_head: Array2<F> = k_4d
                    .slice(s![b, .., h, ..])
                    .to_owned()
                    .into_shape_with_order((seq_len, head_dim))
                    .map_err(|e| {
                        NeuralError::InferenceError(format!("Failed to get K head: {}", e))
                    })?;

                let v_head: Array2<F> = v_4d
                    .slice(s![b, .., h, ..])
                    .to_owned()
                    .into_shape_with_order((seq_len, head_dim))
                    .map_err(|e| {
                        NeuralError::InferenceError(format!("Failed to get V head: {}", e))
                    })?;

                // Apply Flash Attention
                let attn_output = self.flash_attention_forward(&q_head, &k_head, &v_head)?;

                // Copy to output
                for i in 0..seq_len {
                    for d in 0..head_dim {
                        output_4d[[b, i, h, d]] = attn_output[[i, d]];
                    }
                }
            }
        }

        // Reshape to [batch, seq_len, d_model]
        let output_3d = output_4d
            .into_shape_with_order((batch_size, seq_len, d_model))
            .map_err(|e| NeuralError::InferenceError(format!("Failed to reshape output: {}", e)))?;

        // Apply output projection
        let output_2d = output_3d
            .into_shape_with_order((batch_size * seq_len, d_model))
            .map_err(|e| {
                NeuralError::InferenceError(format!("Failed to reshape for output proj: {}", e))
            })?;

        let final_output = output_2d.dot(&w_o_2d);

        // Reshape back to [batch, seq_len, d_model]
        let result = final_output
            .into_shape_with_order((batch_size, seq_len, d_model))
            .map_err(|e| {
                NeuralError::InferenceError(format!("Failed to reshape final output: {}", e))
            })?;

        Ok(result.into_dyn())
    }

    fn backward(
        &self,
        _input: &Array<F, IxDyn>,
        _grad_output: &Array<F, IxDyn>,
    ) -> Result<Array<F, IxDyn>> {
        // Flash Attention backward is more complex - uses recomputation
        // For now, return a placeholder
        // TODO: Implement Flash Attention backward pass with recomputation
        Err(NeuralError::NotImplemented(
            "Flash Attention backward pass not yet implemented".to_string(),
        ))
    }

    fn update(&mut self, _learning_rate: F) -> Result<()> {
        // Updates would be applied to stored gradients
        Ok(())
    }
}

/// Memory-efficient attention computation (no projection weights)
///
/// This is a standalone function for computing attention without the
/// full FlashAttention layer overhead. Useful for custom attention patterns.
///
/// # Arguments
/// * `query` - Query tensor [batch, seq_q, head_dim]
/// * `key` - Key tensor [batch, seq_k, head_dim]
/// * `value` - Value tensor [batch, seq_k, head_dim]
/// * `causal` - Whether to apply causal masking
/// * `block_size` - Block size for tiling
///
/// # Returns
/// * Attention output [batch, seq_q, head_dim]
pub fn flash_attention_compute<F: Float + Debug + ScalarOperand + NumAssign>(
    query: &Array<F, IxDyn>,
    key: &Array<F, IxDyn>,
    value: &Array<F, IxDyn>,
    causal: bool,
    block_size: usize,
) -> Result<Array<F, IxDyn>> {
    if query.ndim() != 3 || key.ndim() != 3 || value.ndim() != 3 {
        return Err(NeuralError::InvalidArchitecture(
            "Query, key, value must be 3D tensors".to_string(),
        ));
    }

    let batch_size = query.shape()[0];
    let seq_len_q = query.shape()[1];
    let seq_len_kv = key.shape()[1];
    let head_dim = query.shape()[2];

    let scale = F::one()
        / F::from(head_dim)
            .expect("Failed to convert to float")
            .sqrt();

    let mut output = Array::zeros(IxDyn(&[batch_size, seq_len_q, head_dim]));

    for b in 0..batch_size {
        let q_batch = query.slice(s![b, .., ..]);
        let k_batch = key.slice(s![b, .., ..]);
        let v_batch = value.slice(s![b, .., ..]);

        // Convert to 2D for processing
        let q_2d: Array2<F> = q_batch
            .to_owned()
            .into_shape_with_order((seq_len_q, head_dim))
            .map_err(|_| NeuralError::InferenceError("Failed to reshape Q".to_string()))?;

        let k_2d: Array2<F> = k_batch
            .to_owned()
            .into_shape_with_order((seq_len_kv, head_dim))
            .map_err(|_| NeuralError::InferenceError("Failed to reshape K".to_string()))?;

        let v_2d: Array2<F> = v_batch
            .to_owned()
            .into_shape_with_order((seq_len_kv, head_dim))
            .map_err(|_| NeuralError::InferenceError("Failed to reshape V".to_string()))?;

        // Compute tiled attention
        let batch_output = tiled_attention_compute(&q_2d, &k_2d, &v_2d, scale, causal, block_size)?;

        // Copy to output
        for i in 0..seq_len_q {
            for d in 0..head_dim {
                output[[b, i, d]] = batch_output[[i, d]];
            }
        }
    }

    Ok(output)
}

/// Core tiled attention computation
fn tiled_attention_compute<F: Float + Debug + NumAssign>(
    query: &Array2<F>,
    key: &Array2<F>,
    value: &Array2<F>,
    scale: F,
    causal: bool,
    block_size: usize,
) -> Result<Array2<F>> {
    let seq_len_q = query.nrows();
    let seq_len_kv = key.nrows();
    let head_dim = query.ncols();

    let block_size = block_size.min(seq_len_q).min(seq_len_kv).max(1);

    let mut output = Array2::<F>::zeros((seq_len_q, head_dim));
    let mut row_max = vec![F::neg_infinity(); seq_len_q];
    let mut row_sum = vec![F::zero(); seq_len_q];

    let num_blocks_q = seq_len_q.div_ceil(block_size);
    let num_blocks_kv = seq_len_kv.div_ceil(block_size);

    for q_block_idx in 0..num_blocks_q {
        let q_start = q_block_idx * block_size;
        let q_end = (q_start + block_size).min(seq_len_q);
        let q_block_size = q_end - q_start;

        for kv_block_idx in 0..num_blocks_kv {
            let kv_start = kv_block_idx * block_size;
            let kv_end = (kv_start + block_size).min(seq_len_kv);
            let kv_block_size = kv_end - kv_start;

            if causal && kv_start > q_end - 1 {
                continue;
            }

            // Compute block scores
            let mut scores = Array2::<F>::zeros((q_block_size, kv_block_size));
            for i in 0..q_block_size {
                for j in 0..kv_block_size {
                    let mut dot = F::zero();
                    for d in 0..head_dim {
                        dot += query[[q_start + i, d]] * key[[kv_start + j, d]];
                    }
                    let s = dot * scale;

                    // Apply causal mask
                    if causal && (kv_start + j) > (q_start + i) {
                        scores[[i, j]] = F::neg_infinity();
                    } else {
                        scores[[i, j]] = s;
                    }
                }
            }

            // Online softmax update
            for local_i in 0..q_block_size {
                let global_i = q_start + local_i;

                let mut block_max = F::neg_infinity();
                for j in 0..kv_block_size {
                    if scores[[local_i, j]] > block_max {
                        block_max = scores[[local_i, j]];
                    }
                }

                let old_max = row_max[global_i];
                let new_max = if old_max > block_max {
                    old_max
                } else {
                    block_max
                };

                let correction = if old_max == F::neg_infinity() {
                    F::zero()
                } else {
                    (old_max - new_max).exp()
                };

                for d in 0..head_dim {
                    output[[global_i, d]] *= correction;
                }
                row_sum[global_i] *= correction;

                for j in 0..kv_block_size {
                    if scores[[local_i, j]] > F::neg_infinity() {
                        let exp_score = (scores[[local_i, j]] - new_max).exp();
                        row_sum[global_i] += exp_score;

                        for d in 0..head_dim {
                            output[[global_i, d]] += exp_score * value[[kv_start + j, d]];
                        }
                    }
                }

                row_max[global_i] = new_max;
            }
        }
    }

    // Final normalization
    for i in 0..seq_len_q {
        if row_sum[i] > F::zero() {
            let inv_sum = F::one() / row_sum[i];
            for d in 0..head_dim {
                output[[i, d]] *= inv_sum;
            }
        }
    }

    Ok(output)
}

#[cfg(test)]
mod tests {
    use super::*;
    use scirs2_core::ndarray::Array3;

    #[test]
    fn test_flash_attention_config() {
        let config = FlashAttentionConfig::new(8, 64)
            .with_causal(true)
            .with_block_size_q(32)
            .with_block_size_kv(32)
            .with_dropout(0.1);

        assert_eq!(config.num_heads, 8);
        assert_eq!(config.head_dim, 64);
        assert!(config.causal);
        assert_eq!(config.block_size_q, 32);
        assert_eq!(config.block_size_kv, 32);
        assert!((config.dropout_prob - 0.1).abs() < 1e-10);
    }

    #[test]
    fn test_flash_attention_creation() {
        let mut rng = scirs2_core::random::rng();
        let config = FlashAttentionConfig::new(4, 16);
        let flash_attn = FlashAttention::<f64>::new(64, config, &mut rng);
        assert!(flash_attn.is_ok());
    }

    #[test]
    fn test_flash_attention_forward() {
        let mut rng = scirs2_core::random::rng();
        let config = FlashAttentionConfig::new(4, 16)
            .with_block_size_q(8)
            .with_block_size_kv(8);
        let flash_attn =
            FlashAttention::<f64>::new(64, config, &mut rng).expect("Operation failed");

        // Input: [batch=2, seq_len=16, d_model=64]
        let input = Array3::<f64>::from_elem((2, 16, 64), 0.1).into_dyn();
        let output = flash_attn.forward(&input);

        assert!(output.is_ok());
        let output = output.expect("Operation failed");
        assert_eq!(output.shape(), &[2, 16, 64]);
    }

    #[test]
    fn test_flash_attention_causal() {
        let mut rng = scirs2_core::random::rng();
        let config = FlashAttentionConfig::new(4, 16)
            .with_causal(true)
            .with_block_size_q(4)
            .with_block_size_kv(4);
        let flash_attn =
            FlashAttention::<f64>::new(64, config, &mut rng).expect("Operation failed");

        let input = Array3::<f64>::from_elem((1, 8, 64), 0.1).into_dyn();
        let output = flash_attn.forward(&input);

        assert!(output.is_ok());
        assert_eq!(output.expect("Operation failed").shape(), &[1, 8, 64]);
    }

    #[test]
    fn test_flash_attention_compute_function() {
        let query = Array3::<f64>::from_elem((2, 8, 32), 0.1).into_dyn();
        let key = Array3::<f64>::from_elem((2, 8, 32), 0.1).into_dyn();
        let value = Array3::<f64>::from_elem((2, 8, 32), 0.1).into_dyn();

        let output = flash_attention_compute(&query, &key, &value, false, 4);
        assert!(output.is_ok());
        assert_eq!(output.expect("Operation failed").shape(), &[2, 8, 32]);
    }

    #[test]
    fn test_flash_attention_numerical_stability() {
        // Test with large values that would overflow standard softmax
        let mut rng = scirs2_core::random::rng();
        let config = FlashAttentionConfig::new(2, 8)
            .with_block_size_q(4)
            .with_block_size_kv(4);
        let flash_attn =
            FlashAttention::<f64>::new(16, config, &mut rng).expect("Operation failed");

        let mut input = Array3::<f64>::zeros((1, 8, 16));
        // Fill with varying values
        for i in 0..8 {
            for j in 0..16 {
                input[[0, i, j]] = i as f64 * 0.1 + j as f64 * 0.01;
            }
        }

        let output = flash_attn.forward(&input.into_dyn());
        assert!(output.is_ok());

        // Check output is finite (no NaN or Inf)
        let output = output.expect("Operation failed");
        for val in output.iter() {
            assert!(val.is_finite(), "Output contains non-finite values");
        }
    }

    #[test]
    fn test_flash_vs_standard_attention() {
        // Verify Flash Attention produces similar results to standard attention
        let query = Array3::<f64>::from_elem((1, 4, 8), 0.5).into_dyn();
        let key = query.clone();
        let value = query.clone();

        let flash_output =
            flash_attention_compute(&query, &key, &value, false, 2).expect("Operation failed");

        // Standard attention computation for comparison
        let q_2d = query
            .slice(s![0, .., ..])
            .to_owned()
            .into_shape_with_order((4, 8))
            .expect("Operation failed");
        let k_2d = key
            .slice(s![0, .., ..])
            .to_owned()
            .into_shape_with_order((4, 8))
            .expect("Operation failed");
        let v_2d = value
            .slice(s![0, .., ..])
            .to_owned()
            .into_shape_with_order((4, 8))
            .expect("Operation failed");

        let scale = 1.0 / (8.0_f64).sqrt();

        // S = Q @ K^T * scale
        let mut scores = Array2::<f64>::zeros((4, 4));
        for i in 0..4 {
            for j in 0..4 {
                let mut dot = 0.0;
                for d in 0..8 {
                    dot += q_2d[[i, d]] * k_2d[[j, d]];
                }
                scores[[i, j]] = dot * scale;
            }
        }

        // Softmax
        let mut attention = scores.clone();
        for i in 0..4 {
            let max_val = attention.row(i).fold(f64::NEG_INFINITY, |a, &b| a.max(b));
            let mut sum = 0.0;
            for j in 0..4 {
                let exp_val = (attention[[i, j]] - max_val).exp();
                attention[[i, j]] = exp_val;
                sum += exp_val;
            }
            for j in 0..4 {
                attention[[i, j]] /= sum;
            }
        }

        // Output = attention @ V
        let mut standard_output = Array2::<f64>::zeros((4, 8));
        for i in 0..4 {
            for d in 0..8 {
                let mut sum = 0.0;
                for j in 0..4 {
                    sum += attention[[i, j]] * v_2d[[j, d]];
                }
                standard_output[[i, d]] = sum;
            }
        }

        // Compare outputs
        for i in 0..4 {
            for d in 0..8 {
                let flash_val = flash_output[[0, i, d]];
                let std_val = standard_output[[i, d]];
                assert!(
                    (flash_val - std_val).abs() < 1e-10,
                    "Mismatch at [{}, {}]: flash={}, std={}",
                    i,
                    d,
                    flash_val,
                    std_val
                );
            }
        }
    }
}