brainwires-training 0.10.0

Model training and fine-tuning for the Brainwires Agent Framework — cloud fine-tuning and local LoRA/QLoRA/DoRA training
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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
//! Burn-native modules for LoRA fine-tuning.
//!
//! These are actual `burn::module::Module` implementations that run on GPU via WGPU.

use burn_core::module::{Module, Param};
use burn_core::prelude::*;
use burn_core::tensor::activation;
use burn_nn as nn;

/// LoRA adapter module in Burn.
///
/// Wraps a frozen base linear layer with trainable low-rank A/B matrices.
/// Forward: y = W_frozen @ x + (B @ A @ x) * scaling
#[derive(Module, Debug)]
pub struct LoraLinear<B: Backend> {
    /// Frozen base weight (not updated during training).
    base: nn::Linear<B>,
    /// Down-projection: (rank × in_features).
    lora_a: nn::Linear<B>,
    /// Up-projection: (out_features × rank).
    lora_b: nn::Linear<B>,
    /// Scaling factor: alpha / rank.
    #[module(skip)]
    scaling: f32,
    /// Whether the LoRA adapter is active.
    #[module(skip)]
    active: bool,
}

/// Configuration for creating a LoRA linear layer.
#[derive(Config, Debug)]
pub struct LoraLinearConfig {
    /// Input dimension.
    pub in_features: usize,
    /// Output dimension.
    pub out_features: usize,
    /// LoRA rank (bottleneck dimension).
    #[config(default = "16")]
    pub rank: usize,
    /// Alpha scaling factor.
    #[config(default = "32.0")]
    pub alpha: f32,
}

impl LoraLinearConfig {
    /// Initialize LoRA linear layer with random base weights.
    ///
    /// Base weights are initialized from a normal distribution (would be loaded from model).
    /// LoRA A is initialized with Kaiming uniform, B is initialized to zero
    /// (so initial LoRA contribution is zero).
    pub fn init<B: Backend>(&self, device: &B::Device) -> LoraLinear<B> {
        let base = nn::LinearConfig::new(self.in_features, self.out_features)
            .with_bias(false)
            .init(device);

        // A: (in_features → rank) — Kaiming init
        let lora_a = nn::LinearConfig::new(self.in_features, self.rank)
            .with_bias(false)
            .init(device);

        // B: (rank → out_features) — zero init so LoRA starts as identity
        let lora_b_config = nn::LinearConfig::new(self.rank, self.out_features).with_bias(false);
        let mut lora_b = lora_b_config.init(device);
        // Zero-initialize B so the LoRA contribution starts at zero
        lora_b.weight = lora_b.weight.map(|w| w.zeros_like());

        LoraLinear {
            base,
            lora_a,
            lora_b,
            scaling: self.alpha / self.rank as f32,
            active: true,
        }
    }

    /// Initialize LoRA linear layer with pre-loaded base weights.
    ///
    /// Use this when loading real model weights from SafeTensors.
    /// The base weight tensor should have shape `[in_features, out_features]`.
    pub fn init_with_base_weights<B: Backend>(
        &self,
        base_weight: Tensor<B, 2>,
        device: &B::Device,
    ) -> LoraLinear<B> {
        let base = nn::Linear {
            weight: Param::from_tensor(base_weight),
            bias: None,
        };

        let lora_a = nn::LinearConfig::new(self.in_features, self.rank)
            .with_bias(false)
            .init(device);

        let lora_b_config = nn::LinearConfig::new(self.rank, self.out_features).with_bias(false);
        let mut lora_b = lora_b_config.init(device);
        lora_b.weight = lora_b.weight.map(|w| w.zeros_like());

        LoraLinear {
            base,
            lora_a,
            lora_b,
            scaling: self.alpha / self.rank as f32,
            active: true,
        }
    }
}

impl<B: Backend> LoraLinear<B> {
    /// Get LoRA A weight data for serialization.
    pub fn lora_a_weight(&self) -> Tensor<B, 2> {
        self.lora_a.weight.val()
    }

    /// Get LoRA B weight data for serialization.
    pub fn lora_b_weight(&self) -> Tensor<B, 2> {
        self.lora_b.weight.val()
    }

    /// Forward pass: base + LoRA adapter.
    pub fn forward(&self, input: Tensor<B, 2>) -> Tensor<B, 2> {
        let base_out = self.base.forward(input.clone());

        if !self.active {
            return base_out;
        }

        // LoRA path: input → A → B, scaled
        let lora_out = self.lora_b.forward(self.lora_a.forward(input));
        let lora_scaled = lora_out.mul_scalar(self.scaling);

        base_out + lora_scaled
    }

    /// Freeze the base layer (already frozen by design, but explicit).
    pub fn set_active(&mut self, active: bool) {
        self.active = active;
    }

    /// Number of trainable parameters (A + B only).
    pub fn trainable_param_count(&self) -> usize {
        let a_shape = self.lora_a.weight.val().shape();
        let a_params = a_shape.dims[0] * a_shape.dims[1];
        let b_shape = self.lora_b.weight.val().shape();
        let b_params = b_shape.dims[0] * b_shape.dims[1];
        a_params + b_params
    }
}

/// RMS Layer Normalization (used in LLaMA-style models).
#[derive(Module, Debug)]
pub struct RmsNorm<B: Backend> {
    /// Learnable scale parameter.
    weight: Param<Tensor<B, 1>>,
    /// Epsilon for numerical stability.
    #[module(skip)]
    eps: f64,
}

/// Configuration for RMS normalization.
#[derive(Config, Debug)]
pub struct RmsNormConfig {
    /// Hidden dimension size.
    pub hidden_size: usize,
    /// Epsilon for numerical stability.
    #[config(default = "1e-5")]
    pub eps: f64,
}

impl RmsNormConfig {
    /// Initialize an RMS normalization layer on the given device.
    pub fn init<B: Backend>(&self, device: &B::Device) -> RmsNorm<B> {
        let weight = Tensor::ones([self.hidden_size], device);
        RmsNorm {
            weight: Param::from_tensor(weight),
            eps: self.eps,
        }
    }
}

impl<B: Backend> RmsNorm<B> {
    /// Forward pass: normalize input using root mean square.
    pub fn forward(&self, x: Tensor<B, 2>) -> Tensor<B, 2> {
        let variance = x.clone().powf_scalar(2.0).mean_dim(1);
        let rms = (variance + self.eps).sqrt();
        let normed = x / rms;
        normed * self.weight.val().unsqueeze_dim(0)
    }
}

/// SwiGLU feed-forward network (LLaMA-style).
#[derive(Module, Debug)]
pub struct SwiGluFfn<B: Backend> {
    gate_proj: nn::Linear<B>,
    up_proj: nn::Linear<B>,
    down_proj: nn::Linear<B>,
}

/// Configuration for SwiGLU FFN.
#[derive(Config, Debug)]
pub struct SwiGluFfnConfig {
    /// Model hidden dimension.
    pub hidden_size: usize,
    /// FFN intermediate dimension.
    pub intermediate_size: usize,
}

impl SwiGluFfnConfig {
    /// Initialize a SwiGLU feed-forward network on the given device.
    pub fn init<B: Backend>(&self, device: &B::Device) -> SwiGluFfn<B> {
        SwiGluFfn {
            gate_proj: nn::LinearConfig::new(self.hidden_size, self.intermediate_size)
                .with_bias(false)
                .init(device),
            up_proj: nn::LinearConfig::new(self.hidden_size, self.intermediate_size)
                .with_bias(false)
                .init(device),
            down_proj: nn::LinearConfig::new(self.intermediate_size, self.hidden_size)
                .with_bias(false)
                .init(device),
        }
    }
}

impl<B: Backend> SwiGluFfn<B> {
    /// Forward pass: gate with SiLU activation, element-wise multiply, and project down.
    pub fn forward(&self, x: Tensor<B, 2>) -> Tensor<B, 2> {
        let gate = activation::silu(self.gate_proj.forward(x.clone()));
        let up = self.up_proj.forward(x);
        self.down_proj.forward(gate * up)
    }
}

/// Simple cross-entropy loss for language modeling.
pub fn cross_entropy_loss<B: Backend>(
    logits: Tensor<B, 2>,       // [batch * seq_len, vocab_size]
    targets: Tensor<B, 1, Int>, // [batch * seq_len]
) -> Tensor<B, 1> {
    let log_softmax = activation::log_softmax(logits, 1);
    let batch_size = targets.dims()[0];

    // Gather the log probabilities at target indices
    let targets_2d = targets.reshape([batch_size, 1]);
    let gathered = log_softmax.gather(1, targets_2d);

    // Negative log likelihood
    gathered.neg().mean()
}

/// Training step output.
#[derive(Debug)]
pub struct TrainStepOutput<B: Backend> {
    /// Loss tensor from the training step.
    pub loss: Tensor<B, 1>,
    /// Number of tokens processed in this step.
    pub num_tokens: usize,
}

// ────────────────────────────────────────────────────────────────────────────
// Phase 5: DoRA, DPO/ORPO tensor losses, Transformer block
// ────────────────────────────────────────────────────────────────────────────

/// DoRA (Weight-Decomposed Low-Rank Adaptation) module in Burn.
///
/// Decomposes weight update into direction and magnitude:
///   W' = m * (W₀ + B·A) / ‖W₀ + B·A‖_col
///
/// Where m is a learnable per-output-neuron magnitude vector.
#[derive(Module, Debug)]
pub struct DoraLinear<B: Backend> {
    /// Frozen base weight.
    base: nn::Linear<B>,
    /// Down-projection: (in_features → rank).
    lora_a: nn::Linear<B>,
    /// Up-projection: (rank → out_features).
    lora_b: nn::Linear<B>,
    /// Learnable magnitude vector (one scalar per output neuron).
    magnitude: Param<Tensor<B, 1>>,
    /// Scaling factor: alpha / rank.
    #[module(skip)]
    scaling: f32,
}

/// Configuration for DoRA linear layer.
#[derive(Config, Debug)]
pub struct DoraLinearConfig {
    /// Input dimension.
    pub in_features: usize,
    /// Output dimension.
    pub out_features: usize,
    /// LoRA rank for the directional component.
    #[config(default = "16")]
    pub rank: usize,
    /// Alpha scaling factor.
    #[config(default = "32.0")]
    pub alpha: f32,
}

impl DoraLinearConfig {
    /// Initialize a DoRA linear layer with random base weights.
    pub fn init<B: Backend>(&self, device: &B::Device) -> DoraLinear<B> {
        let base = nn::LinearConfig::new(self.in_features, self.out_features)
            .with_bias(false)
            .init(device);

        let lora_a = nn::LinearConfig::new(self.in_features, self.rank)
            .with_bias(false)
            .init(device);

        let lora_b_config = nn::LinearConfig::new(self.rank, self.out_features).with_bias(false);
        let mut lora_b = lora_b_config.init(device);
        lora_b.weight = lora_b.weight.map(|w| w.zeros_like());

        // Initialize magnitude from base weight column norms.
        let base_w = base.weight.val();
        let col_norms = base_w
            .clone()
            .powf_scalar(2.0)
            .sum_dim(0)
            .sqrt()
            .squeeze::<1>();
        let magnitude = Param::from_tensor(col_norms);

        DoraLinear {
            base,
            lora_a,
            lora_b,
            magnitude,
            scaling: self.alpha / self.rank as f32,
        }
    }

    /// Initialize a DoRA linear layer with pre-loaded base weights.
    ///
    /// Use this when loading real model weights from SafeTensors.
    /// The base weight tensor should have shape `[in_features, out_features]`.
    pub fn init_with_base_weights<B: Backend>(
        &self,
        base_weight: Tensor<B, 2>,
        device: &B::Device,
    ) -> DoraLinear<B> {
        let col_norms = base_weight
            .clone()
            .powf_scalar(2.0)
            .sum_dim(0)
            .sqrt()
            .squeeze::<1>();
        let magnitude = Param::from_tensor(col_norms);

        let base = nn::Linear {
            weight: Param::from_tensor(base_weight),
            bias: None,
        };

        let lora_a = nn::LinearConfig::new(self.in_features, self.rank)
            .with_bias(false)
            .init(device);

        let lora_b_config = nn::LinearConfig::new(self.rank, self.out_features).with_bias(false);
        let mut lora_b = lora_b_config.init(device);
        lora_b.weight = lora_b.weight.map(|w| w.zeros_like());

        DoraLinear {
            base,
            lora_a,
            lora_b,
            magnitude,
            scaling: self.alpha / self.rank as f32,
        }
    }
}

impl<B: Backend> DoraLinear<B> {
    /// Get LoRA A weight data for serialization.
    pub fn lora_a_weight(&self) -> Tensor<B, 2> {
        self.lora_a.weight.val()
    }

    /// Get LoRA B weight data for serialization.
    pub fn lora_b_weight(&self) -> Tensor<B, 2> {
        self.lora_b.weight.val()
    }

    /// Get magnitude vector data for serialization.
    pub fn magnitude_data(&self) -> Tensor<B, 1> {
        self.magnitude.val()
    }

    /// Forward pass with direction-magnitude decomposition.
    pub fn forward(&self, input: Tensor<B, 2>) -> Tensor<B, 2> {
        // Burn stores Linear weights as [in_features, out_features].
        // LoRA update: A_w @ B_w in Burn convention (opposite of PyTorch's B @ A).
        let lora_a_w = self.lora_a.weight.val(); // [in_features, rank]
        let lora_b_w = self.lora_b.weight.val(); // [rank, out_features]
        let lora_update = lora_a_w.matmul(lora_b_w).mul_scalar(self.scaling); // [in, out]
        let updated_w = self.base.weight.val() + lora_update; // [in, out]

        // Per-output-neuron norms: sum across dim 0 (input dim) since columns = outputs
        let col_norms = updated_w.clone().powf_scalar(2.0).sum_dim(0).sqrt(); // [1, out]
        let eps: f32 = 1e-8;
        let col_norms_safe = col_norms + eps;

        // Normalize: direction = W' / ‖W'‖
        let direction = updated_w / col_norms_safe; // [in, out]

        // Apply magnitude: W_final = m * direction
        let m = self.magnitude.val().unsqueeze_dim(0); // [1, out]
        let final_w = direction * m; // [in, out]

        // Forward: y = input @ W (Burn convention, no transpose needed)
        input.matmul(final_w)
    }

    /// Total trainable parameters: LoRA A + LoRA B + magnitude vector.
    pub fn trainable_param_count(&self) -> usize {
        let a_shape = self.lora_a.weight.val().shape();
        let b_shape = self.lora_b.weight.val().shape();
        let m_shape = self.magnitude.val().shape();
        a_shape.dims[0] * a_shape.dims[1] + b_shape.dims[0] * b_shape.dims[1] + m_shape.dims[0]
    }
}

/// QLoRA adapter module in Burn.
///
/// Like `LoraLinear`, but the base weight was loaded from a quantized source
/// and dequantized at init time. The frozen base linear is identical in structure;
/// memory savings come from the quantized *storage* format (SafeTensors + INT4/INT8).
#[derive(Module, Debug)]
pub struct QLoraLinear<B: Backend> {
    /// Frozen base weight (dequantized from quantized storage).
    base: nn::Linear<B>,
    /// Down-projection: (in_features → rank).
    lora_a: nn::Linear<B>,
    /// Up-projection: (rank → out_features).
    lora_b: nn::Linear<B>,
    /// Scaling factor: alpha / rank.
    #[module(skip)]
    scaling: f32,
    /// Whether the LoRA adapter is active.
    #[module(skip)]
    active: bool,
}

/// Configuration for creating a QLoRA linear layer.
#[derive(Config, Debug)]
pub struct QLoraLinearConfig {
    /// Input dimension.
    pub in_features: usize,
    /// Output dimension.
    pub out_features: usize,
    /// LoRA rank (bottleneck dimension).
    #[config(default = "16")]
    pub rank: usize,
    /// Alpha scaling factor.
    #[config(default = "32.0")]
    pub alpha: f32,
    /// Quantization bits (4 or 8).
    #[config(default = "4")]
    pub bits: u8,
}

impl QLoraLinearConfig {
    /// Initialize QLoRA with pre-dequantized base weights.
    ///
    /// The `base_weight_f32` slice contains weights that have already been
    /// through the quantize → dequantize pipeline (i.e., they carry quantization
    /// noise but are in f32 format for training).
    pub fn init_quantized<B: Backend>(
        &self,
        base_weight_f32: &[f32],
        device: &B::Device,
    ) -> QLoraLinear<B> {
        let weight_tensor = Tensor::<B, 1>::from_floats(
            burn_core::tensor::TensorData::new(base_weight_f32.to_vec(), [base_weight_f32.len()]),
            device,
        )
        .reshape([self.in_features, self.out_features]);

        let base = nn::Linear {
            weight: Param::from_tensor(weight_tensor),
            bias: None,
        };

        let lora_a = nn::LinearConfig::new(self.in_features, self.rank)
            .with_bias(false)
            .init(device);

        let lora_b_config = nn::LinearConfig::new(self.rank, self.out_features).with_bias(false);
        let mut lora_b = lora_b_config.init(device);
        lora_b.weight = lora_b.weight.map(|w| w.zeros_like());

        QLoraLinear {
            base,
            lora_a,
            lora_b,
            scaling: self.alpha / self.rank as f32,
            active: true,
        }
    }

    /// Initialize QLoRA with random base weights (fallback when no model file).
    pub fn init<B: Backend>(&self, device: &B::Device) -> QLoraLinear<B> {
        let base = nn::LinearConfig::new(self.in_features, self.out_features)
            .with_bias(false)
            .init(device);

        let lora_a = nn::LinearConfig::new(self.in_features, self.rank)
            .with_bias(false)
            .init(device);

        let lora_b_config = nn::LinearConfig::new(self.rank, self.out_features).with_bias(false);
        let mut lora_b = lora_b_config.init(device);
        lora_b.weight = lora_b.weight.map(|w| w.zeros_like());

        QLoraLinear {
            base,
            lora_a,
            lora_b,
            scaling: self.alpha / self.rank as f32,
            active: true,
        }
    }
}

impl<B: Backend> QLoraLinear<B> {
    /// Forward pass: base + LoRA adapter (identical to LoRA).
    pub fn forward(&self, input: Tensor<B, 2>) -> Tensor<B, 2> {
        let base_out = self.base.forward(input.clone());

        if !self.active {
            return base_out;
        }

        let lora_out = self.lora_b.forward(self.lora_a.forward(input));
        let lora_scaled = lora_out.mul_scalar(self.scaling);
        base_out + lora_scaled
    }

    /// Get LoRA A weight data for serialization.
    pub fn lora_a_weight(&self) -> Tensor<B, 2> {
        self.lora_a.weight.val()
    }

    /// Get LoRA B weight data for serialization.
    pub fn lora_b_weight(&self) -> Tensor<B, 2> {
        self.lora_b.weight.val()
    }

    /// Number of trainable parameters (A + B only, base is frozen).
    pub fn trainable_param_count(&self) -> usize {
        let a_shape = self.lora_a.weight.val().shape();
        let b_shape = self.lora_b.weight.val().shape();
        a_shape.dims[0] * a_shape.dims[1] + b_shape.dims[0] * b_shape.dims[1]
    }

    /// Set whether the LoRA adapter is active.
    pub fn set_active(&mut self, active: bool) {
        self.active = active;
    }
}

/// DPO loss computed on Burn tensors.
///
/// L_DPO = -log σ(β * (log π(y_w|x)/π_ref(y_w|x) - log π(y_l|x)/π_ref(y_l|x)))
pub fn dpo_loss<B: Backend>(
    chosen_logps: Tensor<B, 1>,       // Log-prob of chosen under policy
    rejected_logps: Tensor<B, 1>,     // Log-prob of rejected under policy
    ref_chosen_logps: Tensor<B, 1>,   // Log-prob of chosen under reference
    ref_rejected_logps: Tensor<B, 1>, // Log-prob of rejected under reference
    beta: f32,
) -> Tensor<B, 1> {
    let chosen_rewards = (chosen_logps - ref_chosen_logps).mul_scalar(beta);
    let rejected_rewards = (rejected_logps - ref_rejected_logps).mul_scalar(beta);
    let logits = chosen_rewards - rejected_rewards;

    // -log σ(logits) = log(1 + exp(-logits)) = softplus(-logits)
    let neg_logits = logits.neg();
    // softplus: log(1 + exp(x)) — numerically stable
    let loss = (neg_logits.clone().exp() + 1.0).log();
    loss.mean()
}

/// ORPO alignment loss computed on Burn tensors.
///
/// L_OR = -log σ(log(odds(chosen) / odds(rejected)))
/// where odds(p) = p / (1-p)
pub fn orpo_alignment_loss<B: Backend>(
    chosen_probs: Tensor<B, 1>,   // Average token probability for chosen
    rejected_probs: Tensor<B, 1>, // Average token probability for rejected
) -> Tensor<B, 1> {
    let eps: f32 = 1e-10;
    let one_minus_eps: f32 = 1.0 - eps;

    // Clamp probabilities to avoid log(0)
    let chosen_clamped = chosen_probs.clamp(eps, one_minus_eps);
    let rejected_clamped = rejected_probs.clamp(eps, one_minus_eps);

    // odds = p / (1 - p)
    let ones = Tensor::ones_like(&chosen_clamped);
    let chosen_odds = chosen_clamped.clone() / (ones.clone() - chosen_clamped);
    let rejected_odds = rejected_clamped.clone() / (ones - rejected_clamped);

    // log odds ratio
    let log_odds_ratio = (chosen_odds / rejected_odds).log();

    // -log σ(log_odds_ratio) = softplus(-log_odds_ratio)
    let neg_lor = log_odds_ratio.neg();
    let loss = (neg_lor.exp() + 1.0).log();
    loss.mean()
}

/// Full ORPO loss: SFT + lambda * alignment.
pub fn orpo_loss<B: Backend>(
    sft_loss: Tensor<B, 1>,
    chosen_probs: Tensor<B, 1>,
    rejected_probs: Tensor<B, 1>,
    lambda: f32,
) -> Tensor<B, 1> {
    let align = orpo_alignment_loss(chosen_probs, rejected_probs);
    sft_loss + align.mul_scalar(lambda)
}

/// Minimal transformer block as a Burn Module.
///
/// Components: RMSNorm → Attention (simplified) → Residual → RMSNorm → SwiGLU FFN → Residual
#[derive(Module, Debug)]
pub struct BurnTransformerBlock<B: Backend> {
    pre_norm: RmsNorm<B>,
    /// Simplified multi-head attention (Q/K/V projections + output).
    q_proj: nn::Linear<B>,
    k_proj: nn::Linear<B>,
    v_proj: nn::Linear<B>,
    o_proj: nn::Linear<B>,
    post_norm: RmsNorm<B>,
    ffn: SwiGluFfn<B>,
    #[module(skip)]
    num_heads: usize,
    #[module(skip)]
    head_dim: usize,
}

/// Configuration for a transformer block.
#[derive(Config, Debug)]
pub struct BurnTransformerBlockConfig {
    /// Model hidden dimension.
    pub hidden_size: usize,
    /// Number of attention heads.
    pub num_heads: usize,
    /// FFN intermediate dimension.
    pub intermediate_size: usize,
}

impl BurnTransformerBlockConfig {
    /// Initialize a transformer block on the given device.
    pub fn init<B: Backend>(&self, device: &B::Device) -> BurnTransformerBlock<B> {
        let head_dim = self.hidden_size / self.num_heads;

        BurnTransformerBlock {
            pre_norm: RmsNormConfig::new(self.hidden_size).init(device),
            q_proj: nn::LinearConfig::new(self.hidden_size, self.hidden_size)
                .with_bias(false)
                .init(device),
            k_proj: nn::LinearConfig::new(self.hidden_size, self.hidden_size)
                .with_bias(false)
                .init(device),
            v_proj: nn::LinearConfig::new(self.hidden_size, self.hidden_size)
                .with_bias(false)
                .init(device),
            o_proj: nn::LinearConfig::new(self.hidden_size, self.hidden_size)
                .with_bias(false)
                .init(device),
            post_norm: RmsNormConfig::new(self.hidden_size).init(device),
            ffn: SwiGluFfnConfig::new(self.hidden_size, self.intermediate_size).init(device),
            num_heads: self.num_heads,
            head_dim,
        }
    }
}

impl<B: Backend> BurnTransformerBlock<B> {
    /// Forward pass through the transformer block.
    ///
    /// Input: [batch_size, hidden_size] (single position, no sequence dim for simplicity).
    pub fn forward(&self, x: Tensor<B, 2>) -> Tensor<B, 2> {
        // Pre-norm + attention + residual
        let normed = self.pre_norm.forward(x.clone());
        let q = self.q_proj.forward(normed.clone());
        let k = self.k_proj.forward(normed.clone());
        let v = self.v_proj.forward(normed);

        // Simplified attention: softmax(Q·K^T / sqrt(d)) · V
        let scale = (self.head_dim as f32).sqrt();
        let attn_weights = q.matmul(k.transpose()).div_scalar(scale);
        let attn_weights = activation::softmax(attn_weights, 1);
        let attn_out = attn_weights.matmul(v);
        let attn_proj = self.o_proj.forward(attn_out);

        let h = x + attn_proj; // residual

        // Post-norm + FFN + residual
        let normed2 = self.post_norm.forward(h.clone());
        let ffn_out = self.ffn.forward(normed2);

        h + ffn_out // residual
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use burn_ndarray::NdArray;

    type TestBackend = NdArray;

    #[test]
    fn test_lora_linear_forward() {
        let device = Default::default();
        let config = LoraLinearConfig::new(64, 128);
        let layer = config.init::<TestBackend>(&device);

        let input = Tensor::<TestBackend, 2>::random(
            [4, 64],
            burn_core::tensor::Distribution::Normal(0.0, 1.0),
            &device,
        );
        let output = layer.forward(input);

        assert_eq!(output.dims(), [4, 128]);
    }

    #[test]
    fn test_lora_linear_zero_init() {
        let device = Default::default();
        let config = LoraLinearConfig::new(32, 32);
        let layer = config.init::<TestBackend>(&device);

        // With B zero-initialized, LoRA contribution should be zero
        // so output should equal base output
        let input = Tensor::<TestBackend, 2>::random(
            [2, 32],
            burn_core::tensor::Distribution::Normal(0.0, 1.0),
            &device,
        );

        let base_out = layer.base.forward(input.clone());
        let full_out = layer.forward(input);

        let diff = (full_out - base_out).abs().sum().into_scalar();
        assert!(
            diff < 1e-5,
            "LoRA should contribute zero initially, diff={}",
            diff
        );
    }

    #[test]
    fn test_lora_inactive() {
        let device = Default::default();
        let config = LoraLinearConfig::new(32, 32);
        let mut layer = config.init::<TestBackend>(&device);
        layer.set_active(false);

        let input = Tensor::<TestBackend, 2>::random(
            [2, 32],
            burn_core::tensor::Distribution::Normal(0.0, 1.0),
            &device,
        );
        let base_out = layer.base.forward(input.clone());
        let full_out = layer.forward(input);

        let diff = (full_out - base_out).abs().sum().into_scalar();
        assert!(diff < 1e-6, "Inactive LoRA should not contribute");
    }

    #[test]
    fn test_rms_norm() {
        let device = Default::default();
        let norm = RmsNormConfig::new(64).init::<TestBackend>(&device);

        let input = Tensor::<TestBackend, 2>::random(
            [4, 64],
            burn_core::tensor::Distribution::Normal(0.0, 1.0),
            &device,
        );
        let output = norm.forward(input);

        assert_eq!(output.dims(), [4, 64]);
    }

    #[test]
    fn test_swiglu_ffn() {
        let device = Default::default();
        let ffn = SwiGluFfnConfig::new(64, 128).init::<TestBackend>(&device);

        let input = Tensor::<TestBackend, 2>::random(
            [4, 64],
            burn_core::tensor::Distribution::Normal(0.0, 1.0),
            &device,
        );
        let output = ffn.forward(input);

        assert_eq!(output.dims(), [4, 64]);
    }

    #[test]
    fn test_trainable_params() {
        let device = Default::default();
        let config = LoraLinearConfig::new(4096, 4096).with_rank(16);
        let layer = config.init::<TestBackend>(&device);

        let params = layer.trainable_param_count();
        assert_eq!(params, 16 * 4096 + 4096 * 16); // A + B
    }

    // ── Phase 5 tests ──

    #[test]
    fn test_dora_forward() {
        let device = Default::default();
        let config = DoraLinearConfig::new(64, 128).with_rank(8);
        let layer = config.init::<TestBackend>(&device);

        let input = Tensor::<TestBackend, 2>::random(
            [4, 64],
            burn_core::tensor::Distribution::Normal(0.0, 1.0),
            &device,
        );
        let output = layer.forward(input);
        assert_eq!(output.dims(), [4, 128]);
    }

    #[test]
    fn test_dora_trainable_params() {
        let device = Default::default();
        let config = DoraLinearConfig::new(256, 256).with_rank(16);
        let layer = config.init::<TestBackend>(&device);

        let params = layer.trainable_param_count();
        // A: 16*256 + B: 256*16 + magnitude: 256
        assert_eq!(params, 16 * 256 + 256 * 16 + 256);
    }

    #[test]
    fn test_dpo_loss_tensor() {
        let device = Default::default();
        let chosen = Tensor::<TestBackend, 1>::from_floats([-1.0, -0.5, -0.8], &device);
        let rejected = Tensor::<TestBackend, 1>::from_floats([-3.0, -2.5, -2.8], &device);
        let ref_chosen = Tensor::<TestBackend, 1>::from_floats([-1.5, -1.0, -1.2], &device);
        let ref_rejected = Tensor::<TestBackend, 1>::from_floats([-1.5, -1.0, -1.2], &device);

        let loss = dpo_loss(chosen, rejected, ref_chosen, ref_rejected, 0.1);
        let val: f32 = loss.into_scalar();
        assert!(val > 0.0, "DPO loss should be positive, got {}", val);
        assert!(val < 5.0, "DPO loss should be reasonable, got {}", val);
    }

    #[test]
    fn test_dpo_loss_equal_logps() {
        let device = Default::default();
        // When chosen and rejected are equal, loss should be log(2)
        let logps = Tensor::<TestBackend, 1>::from_floats([-2.0], &device);
        let loss = dpo_loss(logps.clone(), logps.clone(), logps.clone(), logps, 0.1);
        let val: f32 = loss.into_scalar();
        assert!(
            (val - (2.0f32).ln()).abs() < 0.01,
            "Expected ~ln(2), got {}",
            val
        );
    }

    #[test]
    fn test_orpo_alignment_loss() {
        let device = Default::default();
        let chosen = Tensor::<TestBackend, 1>::from_floats([0.8, 0.7], &device);
        let rejected = Tensor::<TestBackend, 1>::from_floats([0.3, 0.2], &device);

        let loss = orpo_alignment_loss(chosen, rejected);
        let val: f32 = loss.into_scalar();
        assert!(val > 0.0, "ORPO alignment loss should be positive");
    }

    #[test]
    fn test_orpo_full_loss() {
        let device = Default::default();
        let sft = Tensor::<TestBackend, 1>::from_floats([2.0], &device);
        let chosen = Tensor::<TestBackend, 1>::from_floats([0.7], &device);
        let rejected = Tensor::<TestBackend, 1>::from_floats([0.3], &device);

        let total = orpo_loss(sft, chosen, rejected, 0.5);
        let val: f32 = total.into_scalar();
        assert!(val > 2.0, "Total should be > SFT loss, got {}", val);
    }

    #[test]
    fn test_transformer_block() {
        let device = Default::default();
        let config = BurnTransformerBlockConfig::new(64, 4, 128);
        let block = config.init::<TestBackend>(&device);

        let input = Tensor::<TestBackend, 2>::random(
            [8, 64],
            burn_core::tensor::Distribution::Normal(0.0, 0.1),
            &device,
        );
        let output = block.forward(input);
        assert_eq!(
            output.dims(),
            [8, 64],
            "Transformer block should preserve shape"
        );
    }

    #[test]
    fn test_lora_init_with_base_weights() {
        let device = Default::default();
        let config = LoraLinearConfig::new(32, 64).with_rank(8);

        // Create known base weight
        let base_weight = Tensor::<TestBackend, 2>::random(
            [32, 64],
            burn_core::tensor::Distribution::Normal(0.0, 0.1),
            &device,
        );

        let layer = config.init_with_base_weights::<TestBackend>(base_weight.clone(), &device);
        let input = Tensor::<TestBackend, 2>::random(
            [4, 32],
            burn_core::tensor::Distribution::Normal(0.0, 1.0),
            &device,
        );
        let output = layer.forward(input.clone());
        assert_eq!(output.dims(), [4, 64]);

        // With zero-init B, output should match base @ input
        let expected = input.matmul(base_weight);
        let diff = (output - expected).abs().sum().into_scalar();
        assert!(
            diff < 1e-4,
            "LoRA with base weights should match base output initially, diff={}",
            diff
        );
    }

    #[test]
    fn test_dora_init_with_base_weights() {
        let device = Default::default();
        let config = DoraLinearConfig::new(32, 64).with_rank(8);

        let base_weight = Tensor::<TestBackend, 2>::random(
            [32, 64],
            burn_core::tensor::Distribution::Normal(0.0, 0.1),
            &device,
        );

        let layer = config.init_with_base_weights::<TestBackend>(base_weight, &device);
        let input = Tensor::<TestBackend, 2>::random(
            [4, 32],
            burn_core::tensor::Distribution::Normal(0.0, 1.0),
            &device,
        );
        let output = layer.forward(input);
        assert_eq!(output.dims(), [4, 64]);
    }

    #[test]
    fn test_qlora_forward() {
        let device = Default::default();
        let config = QLoraLinearConfig::new(64, 128).with_rank(8);
        let layer = config.init::<TestBackend>(&device);

        let input = Tensor::<TestBackend, 2>::random(
            [4, 64],
            burn_core::tensor::Distribution::Normal(0.0, 1.0),
            &device,
        );
        let output = layer.forward(input);
        assert_eq!(output.dims(), [4, 128]);
    }

    #[test]
    fn test_qlora_init_quantized() {
        let device = Default::default();
        let config = QLoraLinearConfig::new(16, 32).with_rank(4).with_bits(4);

        // Simulate dequantized weights
        let base_weights: Vec<f32> = (0..16 * 32).map(|i| (i as f32) * 0.001).collect();
        let layer = config.init_quantized::<TestBackend>(&base_weights, &device);

        let input = Tensor::<TestBackend, 2>::random(
            [2, 16],
            burn_core::tensor::Distribution::Normal(0.0, 1.0),
            &device,
        );
        let output = layer.forward(input);
        assert_eq!(output.dims(), [2, 32]);
        assert_eq!(layer.trainable_param_count(), 4 * 16 + 32 * 4);
    }
}