Skip to main content

runtime/models_v2/
baichuan.rs

1//! Baichuan Model V2 - Clean implementation using solid abstractions
2//!
3//! This implements the Baichuan architecture including:
4//! - Baichuan-7B, Baichuan-13B, Baichuan2-7B, Baichuan2-13B
5//!
6//! Key differences from LLaMA:
7//! - Packed QKV attention (W_pack weight) - single weight matrix for Q, K, V
8//! - ALiBi (Attention with Linear Biases) instead of RoPE
9//! - Standard transformer structure otherwise
10
11use crate::model_config;
12use super::traits::*;
13use anyhow::Result;
14use serde::{Serialize, Deserialize};
15
16/// Baichuan model configuration using the model_config macro
17model_config!(BaichuanConfig {
18    vocab_size: usize = 64000,
19    hidden_size: usize = 4096,
20    intermediate_size: usize = 11008,
21    num_hidden_layers: usize = 32,
22    num_attention_heads: usize = 32,
23    num_key_value_heads: usize = 32,
24    hidden_act: String = "silu".to_string(),
25    max_position_embeddings: usize = 4096,
26    initializer_range: f32 = 0.02,
27    rms_norm_eps: f32 = 1e-6,
28    use_cache: bool = true,
29    pad_token_id: i64 = 0,
30    bos_token_id: i64 = 1,
31    eos_token_id: i64 = 2,
32    tie_word_embeddings: bool = false,
33    // Baichuan specific - using ALiBi instead of RoPE
34    use_alibi: bool = true,
35    model_max_length: usize = 4096,
36    z_loss_weight: f32 = 0.0,
37});
38
39impl BaichuanConfig {
40    /// Create BaichuanConfig from GGUF model configuration
41    pub fn from_gguf_config(gguf: &crate::weight_loader_core::GGUFModelConfig) -> Self {
42        Self {
43            vocab_size: gguf.vocab_size,
44            hidden_size: gguf.hidden_size,
45            intermediate_size: gguf.intermediate_size,
46            num_hidden_layers: gguf.num_hidden_layers,
47            num_attention_heads: gguf.num_attention_heads,
48            num_key_value_heads: gguf.num_key_value_heads,
49            rms_norm_eps: gguf.rms_norm_eps,
50            max_position_embeddings: gguf.max_position_embeddings,
51            ..Default::default()
52        }
53    }
54}
55
56/// Main Baichuan model implementation
57pub struct BaichuanModelV2 {
58    config: BaichuanConfig,
59    device: Device,
60
61    // Model components using unified Tensor type
62    embed_tokens: Tensor,
63    layers: Vec<BaichuanLayer>,
64    norm: Tensor,
65    lm_head: Tensor,
66}
67
68/// Baichuan transformer layer
69pub struct BaichuanLayer {
70    self_attn: BaichuanAttention,
71    mlp: BaichuanMLP,
72    input_layernorm: Tensor,
73    post_attention_layernorm: Tensor,
74}
75
76/// Baichuan attention mechanism with packed QKV and ALiBi
77pub struct BaichuanAttention {
78    w_pack: Tensor, // Packed Q, K, V weights [hidden_size, 3 * hidden_size]
79    o_proj: Tensor,
80    num_heads: usize,
81    num_key_value_heads: usize,
82    head_dim: usize,
83    scale: f32,
84}
85
86/// Baichuan MLP (feed-forward network)
87pub struct BaichuanMLP {
88    gate_proj: Tensor,
89    up_proj: Tensor,
90    down_proj: Tensor,
91    hidden_act: String,
92}
93
94impl Model for BaichuanModelV2 {
95    type Config = BaichuanConfig;
96
97    fn new(config: Self::Config) -> Result<Self> {
98        let device = Device::CPU;
99
100        // Create model tensors with correct shapes
101        let embed_tokens = ops_fn::zeros(
102            &[config.vocab_size, config.hidden_size],
103            DataType::Float32,
104            &device
105        )?;
106
107        let norm = ops_fn::zeros(
108            &[config.hidden_size],
109            DataType::Float32,
110            &device
111        )?;
112
113        let lm_head = if config.tie_word_embeddings {
114            embed_tokens.clone()
115        } else {
116            ops_fn::zeros(
117                &[config.hidden_size, config.vocab_size],
118                DataType::Float32,
119                &device
120            )?
121        };
122
123        // Create transformer layers
124        let mut layers = Vec::with_capacity(config.num_hidden_layers);
125        for _ in 0..config.num_hidden_layers {
126            layers.push(BaichuanLayer::new(&config, &device)?);
127        }
128
129        Ok(Self {
130            config,
131            device,
132            embed_tokens,
133            layers,
134            norm,
135            lm_head,
136        })
137    }
138
139    fn from_weights(config: Self::Config, weights: ModelWeights) -> Result<Self> {
140        let mut model = Self::new(config)?;
141
142        // Load weights from the unified weight container
143        // Note: embedding weight is not transposed (used for index lookup)
144        if let Some(embed_weights) = weights.get("model.embed_tokens.weight") {
145            model.embed_tokens = embed_weights.clone();
146        }
147
148        if let Some(norm_weights) = weights.get("model.norm.weight") {
149            model.norm = norm_weights.clone();
150        }
151
152        // lm_head weight needs transpose: [vocab, hidden] -> [hidden, vocab] for matmul
153        if let Some(lm_head_weights) = weights.get("lm_head.weight") {
154            model.lm_head = ops_fn::transpose(lm_head_weights)?;
155        }
156
157        // Load layer weights
158        for (i, layer) in model.layers.iter_mut().enumerate() {
159            layer.load_weights(&weights, i)?;
160        }
161
162        Ok(model)
163    }
164
165    fn forward(&self, inputs: &ModelInputs) -> Result<ModelOutputs> {
166        match inputs {
167            ModelInputs::Text { input_ids, attention_mask, .. } => {
168                // 1. Token embedding
169                let mut hidden_states = ops_fn::embedding(input_ids, &self.embed_tokens)?;
170
171                // 2. Apply transformer layers (with ALiBi)
172                for layer in &self.layers {
173                    hidden_states = layer.forward(&hidden_states, attention_mask.as_ref())?;
174                }
175
176                // 3. Final layer norm
177                hidden_states = ops_fn::layer_norm(&hidden_states, &self.norm, None, self.config.rms_norm_eps)?;
178
179                // 4. Language modeling head
180                let logits = ops_fn::matmul(&hidden_states, &self.lm_head)?;
181
182                Ok(ModelOutputs::Logits {
183                    logits,
184                    hidden_states: None, // Don't return hidden states to save memory
185                })
186            }
187            ModelInputs::Multimodal { input_ids, .. } => {
188                // For multimodal inputs, just process text part for now
189                let text_inputs = ModelInputs::Text {
190                    input_ids: input_ids.clone(),
191                    attention_mask: None,
192                    position_ids: None,
193                };
194                self.forward(&text_inputs)
195            }
196            _ => Err(anyhow::anyhow!("Baichuan model only supports text and multimodal inputs")),
197        }
198    }
199
200    fn generate(&self, prompt: &str, config: &GenerationConfig) -> Result<String> {
201        use crate::tokenizer::Tokenizer;
202        use rand::Rng;
203
204        // 1. Tokenize prompt
205        let tokenizer = Tokenizer::new();
206        let mut tokens: Vec<u32> = tokenizer.encode(prompt);
207
208        // 2. Generation loop
209        for _ in 0..config.max_new_tokens {
210            // Create input tensor from current tokens
211            let tokens_i64: Vec<i64> = tokens.iter().map(|&t| t as i64).collect();
212            let input_tensor = Tensor::from_i64_slice(&tokens_i64, &[1, tokens.len()], &self.device)?;
213
214            let inputs = ModelInputs::Text {
215                input_ids: input_tensor,
216                attention_mask: None,
217                position_ids: None,
218            };
219
220            // 3. Forward pass
221            let outputs = self.forward(&inputs)?;
222
223            // 4. Get logits and sample next token
224            let logits = match outputs {
225                ModelOutputs::Logits { logits, .. } => logits,
226                _ => return Err(anyhow::anyhow!("Expected logits output")),
227            };
228
229            // Get last token logits
230            let logits_candle = logits.to_candle()?;
231            let shape = logits_candle.dims();
232
233            // Extract last position logits [batch, seq, vocab] -> [vocab]
234            let last_logits = if shape.len() == 3 {
235                let seq_len = shape[1];
236                logits_candle
237                    .narrow(1, seq_len - 1, 1)?
238                    .squeeze(1)?
239                    .squeeze(0)?
240            } else {
241                let seq_len = shape[0];
242                logits_candle
243                    .narrow(0, seq_len - 1, 1)?
244                    .squeeze(0)?
245            };
246
247            // Convert to probabilities and sample
248            let logits_vec: Vec<f32> = last_logits.to_vec1()?;
249
250            let next_token = if config.do_sample && config.temperature > 0.0 {
251                // Temperature sampling
252                let scaled: Vec<f32> = logits_vec.iter()
253                    .map(|&x| x / config.temperature)
254                    .collect();
255
256                // Softmax
257                let max_val = scaled.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
258                let exp_sum: f32 = scaled.iter().map(|&x| (x - max_val).exp()).sum();
259                let probs: Vec<f32> = scaled.iter()
260                    .map(|&x| (x - max_val).exp() / exp_sum)
261                    .collect();
262
263                // Sample from distribution
264                let mut rng = rand::thread_rng();
265                let random_val: f32 = rng.gen();
266                let mut cumulative = 0.0;
267                let mut sampled = 0u32;
268
269                for (idx, &prob) in probs.iter().enumerate() {
270                    cumulative += prob;
271                    if random_val <= cumulative {
272                        sampled = idx as u32;
273                        break;
274                    }
275                }
276                sampled
277            } else {
278                // Greedy sampling
279                let mut max_idx = 0;
280                let mut max_val = logits_vec[0];
281                for (idx, &val) in logits_vec.iter().enumerate() {
282                    if val > max_val {
283                        max_val = val;
284                        max_idx = idx;
285                    }
286                }
287                max_idx as u32
288            };
289
290            // 5. Check for EOS
291            if next_token == config.eos_token_id {
292                break;
293            }
294
295            // 6. Append token
296            tokens.push(next_token);
297        }
298
299        // 7. Decode and return
300        Ok(tokenizer.decode(&tokens))
301    }
302
303    fn config(&self) -> &Self::Config {
304        &self.config
305    }
306
307    fn memory_requirements(&self) -> MemoryRequirements {
308        // Calculate approximate memory requirements
309        let param_size = self.config.vocab_size * self.config.hidden_size + // embeddings
310                        self.config.num_hidden_layers * (
311                            3 * self.config.hidden_size * self.config.hidden_size + // packed QKV attention
312                            self.config.hidden_size * self.config.hidden_size + // o_proj
313                            3 * self.config.hidden_size * self.config.intermediate_size // MLP
314                        );
315
316        let param_bytes = param_size * 4; // float32
317        let kv_cache_bytes = 2 * self.config.num_hidden_layers *
318                           self.config.max_position_embeddings *
319                           self.config.hidden_size * 4; // K and V caches
320
321        MemoryRequirements {
322            gpu_memory: param_bytes,
323            cpu_memory: param_bytes / 4, // Reduced for CPU
324            kv_cache_memory: kv_cache_bytes,
325            peak_memory: param_bytes + kv_cache_bytes,
326        }
327    }
328
329    fn to_device(&mut self, device: &Device) -> Result<()> {
330        // Move all tensors to the specified device
331        self.embed_tokens = self.embed_tokens.to_device(device)?;
332        self.norm = self.norm.to_device(device)?;
333        self.lm_head = self.lm_head.to_device(device)?;
334
335        for layer in &mut self.layers {
336            layer.to_device(device)?;
337        }
338
339        self.device = device.clone();
340        Ok(())
341    }
342}
343
344impl BaichuanLayer {
345    fn new(config: &BaichuanConfig, device: &Device) -> Result<Self> {
346        let self_attn = BaichuanAttention::new(config, device)?;
347        let mlp = BaichuanMLP::new(config, device)?;
348
349        let input_layernorm = ops_fn::zeros(&[config.hidden_size], DataType::Float32, device)?;
350        let post_attention_layernorm = ops_fn::zeros(&[config.hidden_size], DataType::Float32, device)?;
351
352        Ok(Self {
353            self_attn,
354            mlp,
355            input_layernorm,
356            post_attention_layernorm,
357        })
358    }
359
360    fn forward(&self, hidden_states: &Tensor, attention_mask: Option<&Tensor>) -> Result<Tensor> {
361        // 1. Pre-attention layer norm
362        let normed = ops_fn::layer_norm(hidden_states, &self.input_layernorm, None, 1e-6)?;
363
364        // 2. Self attention (with ALiBi)
365        let attn_output = self.self_attn.forward(&normed, attention_mask)?;
366
367        // 3. Residual connection
368        let hidden_states = ops_fn::add(hidden_states, &attn_output)?;
369
370        // 4. Pre-MLP layer norm
371        let normed = ops_fn::layer_norm(&hidden_states, &self.post_attention_layernorm, None, 1e-6)?;
372
373        // 5. MLP
374        let mlp_output = self.mlp.forward(&normed)?;
375
376        // 6. Residual connection
377        let output = ops_fn::add(&hidden_states, &mlp_output)?;
378
379        Ok(output)
380    }
381
382    fn load_weights(&mut self, weights: &ModelWeights, layer_idx: usize) -> Result<()> {
383        let prefix = format!("model.layers.{}", layer_idx);
384
385        // Load packed QKV attention weight (W_pack) - transpose for matmul: [out, in] -> [in, out]
386        if let Some(w_pack) = weights.get(&format!("{}.self_attn.W_pack.weight", prefix)) {
387            self.self_attn.w_pack = ops_fn::transpose(w_pack)?;
388        }
389        if let Some(o_proj) = weights.get(&format!("{}.self_attn.o_proj.weight", prefix)) {
390            self.self_attn.o_proj = ops_fn::transpose(o_proj)?;
391        }
392
393        // Load MLP weights (transpose for matmul: [out, in] -> [in, out])
394        if let Some(gate_proj) = weights.get(&format!("{}.mlp.gate_proj.weight", prefix)) {
395            self.mlp.gate_proj = ops_fn::transpose(gate_proj)?;
396        }
397        if let Some(up_proj) = weights.get(&format!("{}.mlp.up_proj.weight", prefix)) {
398            self.mlp.up_proj = ops_fn::transpose(up_proj)?;
399        }
400        if let Some(down_proj) = weights.get(&format!("{}.mlp.down_proj.weight", prefix)) {
401            self.mlp.down_proj = ops_fn::transpose(down_proj)?;
402        }
403
404        // Load layer norm weights (no transpose needed - 1D tensors)
405        if let Some(input_ln) = weights.get(&format!("{}.input_layernorm.weight", prefix)) {
406            self.input_layernorm = input_ln.clone();
407        }
408        if let Some(post_ln) = weights.get(&format!("{}.post_attention_layernorm.weight", prefix)) {
409            self.post_attention_layernorm = post_ln.clone();
410        }
411
412        Ok(())
413    }
414
415    fn to_device(&mut self, device: &Device) -> Result<()> {
416        self.self_attn.to_device(device)?;
417        self.mlp.to_device(device)?;
418        self.input_layernorm = self.input_layernorm.to_device(device)?;
419        self.post_attention_layernorm = self.post_attention_layernorm.to_device(device)?;
420        Ok(())
421    }
422}
423
424/// Compute ALiBi (Attention with Linear Biases) slopes for each head
425/// ALiBi slopes follow a geometric sequence: 2^(-8/n), 2^(-16/n), ..., 2^(-8)
426/// where n is the number of attention heads
427fn compute_alibi_slopes(num_heads: usize) -> Vec<f32> {
428    // For power of 2 heads, use standard geometric sequence
429    // For non-power of 2, use closest power of 2 and interpolate
430    let closest_power_of_2 = 2_usize.pow((num_heads as f32).log2().floor() as u32);
431    let base = 2.0_f32.powf(-8.0 / closest_power_of_2 as f32);
432
433    let mut slopes = Vec::with_capacity(num_heads);
434
435    if num_heads == closest_power_of_2 {
436        // Standard case: power of 2 heads
437        for i in 1..=num_heads {
438            slopes.push(base.powi(i as i32));
439        }
440    } else {
441        // Non-power of 2: use extra slopes from double the base
442        let extra_base = 2.0_f32.powf(-8.0 / (2 * closest_power_of_2) as f32);
443        let num_remaining = num_heads - closest_power_of_2;
444
445        // First add slopes from the larger base
446        for i in 1..=closest_power_of_2 {
447            slopes.push(base.powi(i as i32));
448        }
449
450        // Then add interleaved slopes from the extra base
451        for i in 1..=num_remaining {
452            slopes.push(extra_base.powi((2 * i - 1) as i32));
453        }
454    }
455
456    slopes
457}
458
459/// Build ALiBi bias matrix for attention scores
460/// bias[i,j] = -abs(i - j) * slope for each head
461fn build_alibi_bias(
462    seq_len: usize,
463    num_heads: usize,
464    device: &candle_core::Device,
465) -> Result<candle_core::Tensor> {
466    let slopes = compute_alibi_slopes(num_heads);
467
468    // Create position difference matrix: -|i - j| for all positions
469    let mut bias_data = Vec::with_capacity(num_heads * seq_len * seq_len);
470
471    for (_head_idx, &slope) in slopes.iter().enumerate() {
472        for i in 0..seq_len {
473            for j in 0..seq_len {
474                // ALiBi bias: -|query_pos - key_pos| * slope
475                let distance = (i as i32 - j as i32).abs() as f32;
476                bias_data.push(-distance * slope);
477            }
478        }
479    }
480
481    // Shape: [num_heads, seq_len, seq_len]
482    let bias = candle_core::Tensor::from_vec(
483        bias_data,
484        &[num_heads, seq_len, seq_len],
485        device
486    )?;
487
488    // Expand to [1, num_heads, seq_len, seq_len] for broadcasting
489    Ok(bias.unsqueeze(0)?)
490}
491
492impl BaichuanAttention {
493    fn new(config: &BaichuanConfig, device: &Device) -> Result<Self> {
494        let num_heads = config.num_attention_heads;
495        let num_key_value_heads = config.num_key_value_heads;
496        let head_dim = config.hidden_size / num_heads;
497        let scale = 1.0 / (head_dim as f32).sqrt();
498
499        // Packed QKV: [hidden_size, 3 * hidden_size] for Q, K, V combined
500        let total_kv_size = num_key_value_heads * head_dim;
501        let total_q_size = num_heads * head_dim;
502        let w_pack = ops_fn::zeros(
503            &[config.hidden_size, total_q_size + 2 * total_kv_size],
504            DataType::Float32,
505            device
506        )?;
507
508        let o_proj = ops_fn::zeros(
509            &[num_heads * head_dim, config.hidden_size],
510            DataType::Float32,
511            device
512        )?;
513
514        Ok(Self {
515            w_pack,
516            o_proj,
517            num_heads,
518            num_key_value_heads,
519            head_dim,
520            scale,
521        })
522    }
523
524    fn forward(&self, hidden_states: &Tensor, _attention_mask: Option<&Tensor>) -> Result<Tensor> {
525        // Get batch and sequence length from hidden_states shape
526        let shape = hidden_states.shape();
527        let (batch_size, seq_len, _hidden_size) = if shape.len() == 3 {
528            (shape[0], shape[1], shape[2])
529        } else if shape.len() == 2 {
530            (1, shape[0], shape[1])
531        } else {
532            return Err(anyhow::anyhow!("Invalid hidden_states shape: {:?}", shape));
533        };
534
535        // 1. Packed QKV projection
536        // [batch, seq, hidden] @ [hidden, q_size + 2*kv_size] -> [batch, seq, q_size + 2*kv_size]
537        let qkv = ops_fn::matmul(hidden_states, &self.w_pack)?;
538        let qkv_candle = qkv.to_candle()?;
539
540        // 2. Split into Q, K, V
541        let q_size = self.num_heads * self.head_dim;
542        let kv_size = self.num_key_value_heads * self.head_dim;
543
544        let query_states = qkv_candle.narrow(2, 0, q_size)?;
545        let key_states = qkv_candle.narrow(2, q_size, kv_size)?;
546        let value_states = qkv_candle.narrow(2, q_size + kv_size, kv_size)?;
547
548        // 3. Reshape for multi-head attention
549        // Q: [batch, seq, num_heads * head_dim] -> [batch, num_heads, seq, head_dim]
550        // K, V: [batch, seq, num_kv_heads * head_dim] -> [batch, num_kv_heads, seq, head_dim]
551        let q_reshaped = query_states
552            .reshape(&[batch_size, seq_len, self.num_heads, self.head_dim])?
553            .transpose(1, 2)?; // [batch, heads, seq, head_dim]
554
555        let k_reshaped = key_states
556            .reshape(&[batch_size, seq_len, self.num_key_value_heads, self.head_dim])?
557            .transpose(1, 2)?; // [batch, kv_heads, seq, head_dim]
558
559        let v_reshaped = value_states
560            .reshape(&[batch_size, seq_len, self.num_key_value_heads, self.head_dim])?
561            .transpose(1, 2)?; // [batch, kv_heads, seq, head_dim]
562
563        // 4. Handle GQA (Grouped Query Attention) - repeat K/V heads to match Q heads
564        let num_groups = self.num_heads / self.num_key_value_heads;
565        let (k_expanded, v_expanded) = if num_groups > 1 {
566            // Repeat K and V along the head dimension
567            // [batch, kv_heads, seq, head_dim] -> [batch, num_heads, seq, head_dim]
568            let k_rep = k_reshaped
569                .unsqueeze(2)? // [batch, kv_heads, 1, seq, head_dim]
570                .broadcast_as(&[batch_size, self.num_key_value_heads, num_groups, seq_len, self.head_dim])?
571                .reshape(&[batch_size, self.num_heads, seq_len, self.head_dim])?;
572            let v_rep = v_reshaped
573                .unsqueeze(2)?
574                .broadcast_as(&[batch_size, self.num_key_value_heads, num_groups, seq_len, self.head_dim])?
575                .reshape(&[batch_size, self.num_heads, seq_len, self.head_dim])?;
576            (k_rep, v_rep)
577        } else {
578            (k_reshaped, v_reshaped)
579        };
580
581        // 5. Scaled dot-product attention with ALiBi
582        // scores = Q @ K^T / sqrt(head_dim)
583        // [batch, heads, seq, head_dim] @ [batch, heads, head_dim, seq] -> [batch, heads, seq, seq]
584        let k_t = k_expanded.transpose(2, 3)?; // [batch, heads, head_dim, seq]
585
586        // Make tensors contiguous for matmul (required by candle)
587        let q_contiguous = q_reshaped.contiguous()?;
588        let k_contiguous = k_t.contiguous()?;
589
590        let scores = q_contiguous.matmul(&k_contiguous)?;
591        let scaled_scores = (scores * (self.scale as f64))?;
592
593        // Build ALiBi bias and add to scores
594        let device = scaled_scores.device();
595        let alibi_bias = build_alibi_bias(seq_len, self.num_heads, device)?;
596        let scores_with_alibi = scaled_scores.broadcast_add(&alibi_bias)?;
597
598        // Apply causal mask: prevent attending to future positions
599        let causal_mask = {
600            let mut mask_data = vec![0.0f32; seq_len * seq_len];
601            for i in 0..seq_len {
602                for j in 0..seq_len {
603                    if j > i {
604                        // Future position - mask out with large negative value
605                        mask_data[i * seq_len + j] = f32::NEG_INFINITY;
606                    }
607                }
608            }
609            candle_core::Tensor::from_vec(mask_data, &[1, 1, seq_len, seq_len], device)?
610        };
611
612        // Add causal mask to scores (broadcast over batch and heads)
613        let masked_scores = scores_with_alibi.broadcast_add(&causal_mask)?;
614
615        // Softmax over last dimension
616        let attention_weights = candle_nn::ops::softmax_last_dim(&masked_scores)?;
617
618        // Apply attention to values
619        // [batch, heads, seq, seq] @ [batch, heads, seq, head_dim] -> [batch, heads, seq, head_dim]
620        let v_contiguous = v_expanded.contiguous()?;
621        let attn_output = attention_weights.matmul(&v_contiguous)?;
622
623        // 6. Reshape back: [batch, heads, seq, head_dim] -> [batch, seq, heads * head_dim]
624        let attn_output = attn_output
625            .transpose(1, 2)? // [batch, seq, heads, head_dim]
626            .reshape(&[batch_size, seq_len, self.num_heads * self.head_dim])?;
627
628        let attn_output = Tensor::from_candle(attn_output);
629
630        // 7. Output projection
631        let output = ops_fn::matmul(&attn_output, &self.o_proj)?;
632
633        Ok(output)
634    }
635
636    fn to_device(&mut self, device: &Device) -> Result<()> {
637        self.w_pack = self.w_pack.to_device(device)?;
638        self.o_proj = self.o_proj.to_device(device)?;
639        Ok(())
640    }
641}
642
643impl BaichuanMLP {
644    fn new(config: &BaichuanConfig, device: &Device) -> Result<Self> {
645        let gate_proj = ops_fn::zeros(&[config.hidden_size, config.intermediate_size], DataType::Float32, device)?;
646        let up_proj = ops_fn::zeros(&[config.hidden_size, config.intermediate_size], DataType::Float32, device)?;
647        let down_proj = ops_fn::zeros(&[config.intermediate_size, config.hidden_size], DataType::Float32, device)?;
648
649        Ok(Self {
650            gate_proj,
651            up_proj,
652            down_proj,
653            hidden_act: config.hidden_act.clone(),
654        })
655    }
656
657    fn forward(&self, hidden_states: &Tensor) -> Result<Tensor> {
658        // 1. Gate and up projections
659        let gate_output = ops_fn::matmul(hidden_states, &self.gate_proj)?;
660        let up_output = ops_fn::matmul(hidden_states, &self.up_proj)?;
661
662        // 2. Apply activation (SiLU for Baichuan)
663        let gate_activated = match self.hidden_act.as_str() {
664            "silu" | "swish" => ops_fn::silu(&gate_output)?,
665            "gelu" => ops_fn::gelu(&gate_output)?,
666            _ => return Err(anyhow::anyhow!("Unsupported activation: {}", self.hidden_act)),
667        };
668
669        // 3. Element-wise multiplication (gating)
670        let gated = ops_fn::mul(&gate_activated, &up_output)?;
671
672        // 4. Down projection
673        let output = ops_fn::matmul(&gated, &self.down_proj)?;
674
675        Ok(output)
676    }
677
678    fn to_device(&mut self, device: &Device) -> Result<()> {
679        self.gate_proj = self.gate_proj.to_device(device)?;
680        self.up_proj = self.up_proj.to_device(device)?;
681        self.down_proj = self.down_proj.to_device(device)?;
682        Ok(())
683    }
684}
685
686#[cfg(test)]
687mod tests {
688    use super::*;
689
690    #[test]
691    fn test_baichuan_model_creation() {
692        let config = BaichuanConfig {
693            vocab_size: 1000,
694            hidden_size: 128,
695            intermediate_size: 512,
696            num_hidden_layers: 2,
697            num_attention_heads: 8,
698            num_key_value_heads: 8,
699            ..Default::default()
700        };
701
702        let model = BaichuanModelV2::new(config).unwrap();
703        assert_eq!(model.config().vocab_size(), 1000);
704        assert_eq!(model.config().hidden_size(), 128);
705        assert_eq!(model.config().num_layers(), 2);
706    }
707
708    #[test]
709    fn test_baichuan_forward_pass() {
710        let config = BaichuanConfig {
711            vocab_size: 100,
712            hidden_size: 64,
713            intermediate_size: 256,
714            num_hidden_layers: 1,
715            num_attention_heads: 4,
716            num_key_value_heads: 4,
717            ..Default::default()
718        };
719
720        let model = BaichuanModelV2::new(config).unwrap();
721        let input_ids = ops_fn::zeros(&[2, 8], DataType::Int64, &Device::CPU).unwrap();
722        let inputs = ModelInputs::text(input_ids);
723
724        let outputs = model.forward(&inputs).unwrap();
725        match outputs {
726            ModelOutputs::Logits { logits, .. } => {
727                assert_eq!(logits.shape(), &[2, 8, 100]); // batch, seq, vocab
728            }
729            _ => panic!("Expected logits output"),
730        }
731    }
732
733    #[test]
734    fn test_alibi_slopes() {
735        // Test power of 2 heads
736        let slopes_8 = compute_alibi_slopes(8);
737        assert_eq!(slopes_8.len(), 8);
738        // First slope should be 2^(-1) = 0.5
739        assert!((slopes_8[0] - 0.5).abs() < 1e-6);
740
741        // Test non-power of 2 heads
742        let slopes_12 = compute_alibi_slopes(12);
743        assert_eq!(slopes_12.len(), 12);
744    }
745
746    #[test]
747    fn test_baichuan_generation() {
748        // Use a small config for testing
749        // vocab_size must be >= basic tokenizer's vocab (~200 tokens)
750        let config = BaichuanConfig {
751            vocab_size: 256,
752            hidden_size: 64,
753            intermediate_size: 256,
754            num_hidden_layers: 1,
755            num_attention_heads: 4,
756            num_key_value_heads: 4,
757            ..Default::default()
758        };
759        let model = BaichuanModelV2::new(config).unwrap();
760        let gen_config = GenerationConfig {
761            max_new_tokens: 5, // Generate only a few tokens for testing
762            ..Default::default()
763        };
764
765        let output = model.generate("Hello", &gen_config).unwrap();
766        assert!(!output.is_empty());
767    }
768}