mistralrs_core/vision_models/llava/llava_llm/
llama.rs

1//LLaMA without fused RoPE
2#![allow(
3    clippy::cast_possible_truncation,
4    clippy::cast_precision_loss,
5    clippy::too_many_arguments
6)]
7
8use std::sync::Arc;
9
10use candle_core::{DType, Device, Result, Tensor};
11use candle_nn::{Embedding, Module};
12use mistralrs_quant::{
13    ColumnParallelLayer, QuantMethod, QuantMethodConfig, RowParallelLayer, ShardedVarBuilder,
14    UnquantLinear,
15};
16
17use crate::{
18    amoe::{AnyMoeBaseModelMixin, AnyMoeTrainableLayer, MlpLayer, MoeMlp},
19    attention::SdpaParams,
20    device_map::DeviceMapper,
21    get_delta_from_lora_ab,
22    layers::{
23        embedding, linear_no_bias as linear, Activation, CausalMasker, MatMul, RmsNorm, Sdpa,
24    },
25    layers_masker::PastKvLenCache,
26    models::llama::Config,
27    paged_attention::{AttentionImplementation, ModelConfigMetadata, PagedAttention},
28    pipeline::{
29        extract_logits,
30        text_models_inputs_processor::{FlashParams, PagedAttentionInputMetadata},
31        IsqModel, NormalLoadingMetadata, NormalModel,
32    },
33    utils::progress::NiceProgressBar,
34    AnyMoeConfig, AnyMoeExpertType,
35};
36
37use super::{LLaVALLM, OrdinaryRoPE};
38
39struct CausalSelfAttention {
40    q_proj: Arc<dyn QuantMethod>,
41    k_proj: Arc<dyn QuantMethod>,
42    v_proj: Arc<dyn QuantMethod>,
43    o_proj: Arc<dyn QuantMethod>,
44    num_attention_heads: usize,
45    num_key_value_heads: usize,
46    head_dim: usize,
47    max_seq_len: usize,
48    paged_attn: Option<PagedAttention>,
49    sdpa_params: SdpaParams,
50}
51
52impl CausalSelfAttention {
53    fn forward(
54        &self,
55        x: &Tensor,
56        attention_mask: &Option<Tensor>,
57        seqlen_offsets: &[usize],
58        block_idx: usize,
59        kv_cache: &mut crate::pipeline::LayerCaches,
60        rope_parameter: (&Tensor, &Tensor),
61        metadata: Option<((Tensor, Tensor), &PagedAttentionInputMetadata)>,
62        flash_params: &FlashParams,
63    ) -> Result<Tensor> {
64        let (b_sz, seq_len, _) = x.dims3()?;
65
66        let original_dtype = x.dtype();
67        let mut x = x.clone();
68        if let Some(t) = self.q_proj.quantized_act_type() {
69            x = x.to_dtype(t)?;
70        }
71        let mut q = MatMul.qmethod_matmul(&x, &*self.q_proj)?;
72        let mut k = MatMul.qmethod_matmul(&x, &*self.k_proj)?;
73        let mut v = MatMul.qmethod_matmul(&x, &*self.v_proj)?;
74        if self.q_proj.quantized_act_type().is_some() {
75            q = q.to_dtype(original_dtype)?;
76            k = k.to_dtype(original_dtype)?;
77            v = v.to_dtype(original_dtype)?;
78        }
79
80        let mut q = q
81            .reshape((b_sz, seq_len, self.num_attention_heads, self.head_dim))?
82            .transpose(1, 2)?
83            .contiguous()?;
84        let mut k = k
85            .reshape((b_sz, seq_len, self.num_key_value_heads, self.head_dim))?
86            .transpose(1, 2)?
87            .contiguous()?;
88        q = OrdinaryRoPE::forward(&q, seqlen_offsets[0], rope_parameter.0, rope_parameter.1)?;
89        k = OrdinaryRoPE::forward(&k, seqlen_offsets[0], rope_parameter.0, rope_parameter.1)?;
90        let v = v
91            .reshape((b_sz, seq_len, self.num_key_value_heads, self.head_dim))?
92            .transpose(1, 2)?;
93
94        let mut y = match &self.paged_attn {
95            Some(paged_attn) => match metadata {
96                Some(((key_cache, value_cache), input_metadata)) => paged_attn.forward(
97                    &q,
98                    &k,
99                    &v,
100                    attention_mask.clone().as_ref(),
101                    Some(key_cache),
102                    Some(value_cache),
103                    input_metadata,
104                    &self.sdpa_params,
105                    Some(flash_params),
106                )?,
107                None => {
108                    // If we don't have metadata, we are most likely generating an imatrix so we don't want to populate that.
109                    // Generating the dummy metadata with the assumption that we are not generating text (only processing prompts).
110                    let input_metadata = PagedAttentionInputMetadata::dummy(q.device())?;
111                    // Sanity check.
112                    assert!(attention_mask.is_some());
113                    paged_attn.forward(
114                        &q,
115                        &k,
116                        &v,
117                        attention_mask.clone().as_ref(),
118                        None,
119                        None,
120                        &input_metadata,
121                        &self.sdpa_params,
122                        Some(flash_params),
123                    )?
124                }
125            },
126            None => {
127                let (k, v) =
128                    crate::pipeline::Cache::update_kv_cache(&mut kv_cache[block_idx], k, v, false)?;
129
130                Sdpa.run_attention(
131                    &q,
132                    &k,
133                    &v,
134                    attention_mask.clone().as_ref(),
135                    Some(flash_params),
136                    &self.sdpa_params,
137                )?
138            }
139        };
140
141        if let Some(t) = self.q_proj.quantized_act_type() {
142            y = y.to_dtype(t)?;
143        }
144        y = if attention_mask.is_some() {
145            y.transpose(1, 2)?.reshape((b_sz, seq_len, ()))?
146        } else {
147            y.reshape((b_sz, seq_len, ()))?
148        };
149        let mut res = MatMul.qmethod_matmul(&y, &*self.o_proj)?;
150        if self.q_proj.quantized_act_type().is_some() {
151            res = res.to_dtype(original_dtype)?;
152        }
153        Ok(res)
154    }
155
156    fn load(
157        vb: ShardedVarBuilder,
158        cfg: &Config,
159        paged_attn: Option<PagedAttention>,
160        comm: &Arc<mistralrs_quant::Comm>,
161    ) -> Result<Self> {
162        let size_in = cfg.hidden_size;
163        let size_q = (cfg.hidden_size / cfg.num_attention_heads) * cfg.num_attention_heads;
164        let size_kv = (cfg.hidden_size / cfg.num_attention_heads) * cfg.num_key_value_heads;
165        let q_proj = ColumnParallelLayer::new(
166            size_in,
167            size_q,
168            &cfg.quantization_config,
169            false,
170            comm,
171            vb.pp("q_proj"),
172        )?;
173        let kv_shard = mistralrs_quant::compute_kv_shard(
174            cfg.num_key_value_heads,
175            cfg.hidden_size / cfg.num_attention_heads,
176            comm,
177        );
178        let k_proj = ColumnParallelLayer::new_with_shard(
179            size_in,
180            size_kv,
181            &cfg.quantization_config,
182            false,
183            comm,
184            kv_shard,
185            vb.pp("k_proj"),
186        )?;
187        let v_proj = ColumnParallelLayer::new_with_shard(
188            size_in,
189            size_kv,
190            &cfg.quantization_config,
191            false,
192            comm,
193            kv_shard,
194            vb.pp("v_proj"),
195        )?;
196        let o_proj = RowParallelLayer::new(
197            size_q,
198            size_in,
199            &cfg.quantization_config,
200            false,
201            comm,
202            vb.pp("o_proj"),
203        )?;
204        Ok(Self {
205            q_proj,
206            k_proj,
207            v_proj,
208            o_proj,
209            num_attention_heads: cfg.num_attention_heads / comm.world_size(),
210            num_key_value_heads: (cfg.num_key_value_heads / comm.world_size()).max(1),
211            head_dim: cfg.hidden_size / cfg.num_attention_heads,
212            max_seq_len: cfg.max_position_embeddings,
213            paged_attn,
214            sdpa_params: SdpaParams {
215                n_kv_groups: mistralrs_quant::compute_n_kv_groups(
216                    cfg.num_key_value_heads,
217                    cfg.num_attention_heads,
218                    comm,
219                ),
220                use_flash_attn: cfg.use_flash_attn,
221                softcap: None,
222                softmax_scale: 1.0 / ((cfg.hidden_size / cfg.num_attention_heads) as f32).sqrt(),
223                sliding_window: None,
224            },
225        })
226    }
227}
228#[derive(Clone)]
229struct Mlp {
230    c_fc1: Arc<dyn QuantMethod>,
231    c_fc2: Arc<dyn QuantMethod>,
232    c_proj: Arc<dyn QuantMethod>,
233    params: Vec<usize>,
234}
235
236impl Mlp {
237    fn load(
238        vb: ShardedVarBuilder,
239        cfg: &Config,
240        comm: &Arc<mistralrs_quant::Comm>,
241    ) -> Result<Self> {
242        let h_size = cfg.hidden_size;
243        let i_size = cfg.intermediate_size;
244        let c_fc1 = ColumnParallelLayer::new(
245            h_size,
246            i_size,
247            &cfg.quantization_config,
248            false,
249            comm,
250            vb.pp("gate_proj"),
251        )?;
252        let c_fc2 = ColumnParallelLayer::new(
253            h_size,
254            i_size,
255            &cfg.quantization_config,
256            false,
257            comm,
258            vb.pp("up_proj"),
259        )?;
260        let c_proj = RowParallelLayer::new(
261            i_size,
262            h_size,
263            &cfg.quantization_config,
264            false,
265            comm,
266            vb.pp("down_proj"),
267        )?;
268        Ok(Self {
269            c_fc1,
270            c_fc2,
271            c_proj,
272            params: vec![h_size, i_size],
273        })
274    }
275}
276
277impl AnyMoeTrainableLayer for Mlp {}
278
279impl MlpLayer for Mlp {
280    fn forward(&self, x: &Tensor) -> Result<Tensor> {
281        let original_dtype = x.dtype();
282        let mut x = x.clone();
283        if let Some(t) = self.c_fc1.quantized_act_type() {
284            x = x.to_dtype(t)?;
285        }
286        let x = (candle_nn::ops::silu(&MatMul.qmethod_matmul(&x, &*self.c_fc1)?)?
287            * MatMul.qmethod_matmul(&x, &*self.c_fc2)?)?;
288        let mut res = MatMul.qmethod_matmul(&x, &*self.c_proj)?;
289        if self.c_fc1.quantized_act_type().is_some() {
290            res = res.to_dtype(original_dtype)?;
291        }
292        Ok(res)
293    }
294    fn get_isq_layers(&mut self) -> Vec<&mut Arc<dyn QuantMethod>> {
295        vec![&mut self.c_fc1, &mut self.c_fc2, &mut self.c_proj]
296    }
297    fn clone(&self) -> Box<dyn MlpLayer> {
298        Box::new(Clone::clone(self))
299    }
300    fn get_params(&self) -> &[usize] {
301        &self.params
302    }
303    fn hidden_act(&self) -> Activation {
304        Activation::Silu
305    }
306    // c_fc1, c_fc2, c_proj
307    fn new_added_delta(&self, deltas: Vec<Option<Tensor>>) -> Result<Box<dyn MlpLayer>> {
308        let new_c_fc1 = if let Some(ref delta) = deltas[0] {
309            self.c_fc1.add_delta_w(delta)?
310        } else {
311            self.c_fc1.clone()
312        };
313        let new_c_fc2 = if let Some(ref delta) = deltas[1] {
314            self.c_fc2.add_delta_w(delta)?
315        } else {
316            self.c_fc2.clone()
317        };
318        let new_c_proj = if let Some(ref delta) = deltas[2] {
319            self.c_proj.add_delta_w(delta)?
320        } else {
321            self.c_proj.clone()
322        };
323
324        Ok(Box::new(Self {
325            c_fc1: new_c_fc1,
326            c_fc2: new_c_fc2,
327            c_proj: new_c_proj,
328            params: self.params.clone(),
329        }))
330    }
331
332    fn dtype_device(&self) -> (DType, Device) {
333        self.c_fc1.dtype_and_device()
334    }
335}
336
337struct Block {
338    rms_1: RmsNorm,
339    attn: CausalSelfAttention,
340    rms_2: RmsNorm,
341    mlp: Box<dyn MlpLayer>,
342    rope_parameter: (Tensor, Tensor),
343}
344
345impl Block {
346    fn forward(
347        &self,
348        x: &Tensor,
349        attention_mask: &Option<Tensor>,
350        seqlen_offsets: &[usize],
351        block_idx: usize,
352        kv_cache: &mut crate::pipeline::LayerCaches,
353        metadata: Option<((Tensor, Tensor), &PagedAttentionInputMetadata)>,
354        flash_params: &FlashParams,
355    ) -> Result<Tensor> {
356        let residual = x;
357        let mut x = self.rms_1.forward(x)?;
358        x = (self.attn.forward(
359            &x,
360            attention_mask,
361            seqlen_offsets,
362            block_idx,
363            kv_cache,
364            (&self.rope_parameter.0, &self.rope_parameter.1),
365            metadata,
366            flash_params,
367        )? + residual)?;
368        let residual = &x;
369        x = (self.mlp.forward(&self.rms_2.forward(&x)?)? + residual)?;
370        Ok(x)
371    }
372
373    fn load(
374        vb: ShardedVarBuilder,
375        cfg: &Config,
376        mapper: &dyn DeviceMapper,
377        layer_idx: usize,
378        loading_isq: bool,
379        paged_attn: Option<PagedAttention>,
380        rope_parameter: (Tensor, Tensor),
381        comm: &Arc<mistralrs_quant::Comm>,
382    ) -> Result<Self> {
383        let attn = CausalSelfAttention::load(
384            mapper.set_device(layer_idx, vb.pp("self_attn"), loading_isq),
385            cfg,
386            paged_attn,
387            comm,
388        )?;
389        let mlp = Mlp::load(
390            mapper.set_device(layer_idx, vb.pp("mlp"), loading_isq),
391            cfg,
392            comm,
393        )?;
394        let rms_1 = RmsNorm::new(
395            cfg.hidden_size,
396            cfg.rms_norm_eps,
397            mapper.set_device(layer_idx, vb.pp("input_layernorm"), false),
398        )?;
399        let rms_2 = RmsNorm::new(
400            cfg.hidden_size,
401            cfg.rms_norm_eps,
402            mapper.set_device(layer_idx, vb.pp("post_attention_layernorm"), false),
403        )?;
404        Ok(Self {
405            rms_1,
406            attn,
407            rms_2,
408            mlp: Box::new(mlp),
409            rope_parameter,
410        })
411    }
412}
413
414pub struct Llama {
415    wte: Embedding,
416    blocks: Vec<Block>,
417    ln_f: RmsNorm,
418    lm_head: Arc<dyn QuantMethod>,
419    kv_cache: crate::pipeline::EitherCache,
420    device: Device,
421    mapper: Box<dyn DeviceMapper + Send + Sync>,
422    cfg: ModelConfigMetadata,
423}
424
425impl Llama {
426    pub fn forward_input(
427        &self,
428        input_ids: &Tensor,
429        seqlen_offsets: &[usize],
430        context_lens: Vec<(usize, usize)>,
431        metadata: Option<(Vec<(Tensor, Tensor)>, &PagedAttentionInputMetadata)>,
432        flash_params: &FlashParams,
433    ) -> Result<Tensor> {
434        let x = self.wte.forward(input_ids)?;
435        self.forward_input_embed(
436            input_ids,
437            x,
438            seqlen_offsets,
439            context_lens,
440            metadata,
441            flash_params,
442        )
443    }
444
445    pub fn new(
446        cfg: &Config,
447        vb: ShardedVarBuilder,
448        _is_gptx: bool,
449        normal_loading_metadata: NormalLoadingMetadata,
450        attention_mechanism: AttentionImplementation,
451    ) -> Result<Self> {
452        let mapper = normal_loading_metadata.mapper;
453        let wte = embedding(
454            cfg.vocab_size,
455            cfg.hidden_size,
456            mapper.set_nm_device(vb.pp("model.embed_tokens"), false),
457        )?;
458        let lm_head = linear(
459            cfg.hidden_size,
460            cfg.vocab_size,
461            mapper.set_nm_device(vb.pp("lm_head"), normal_loading_metadata.loading_isq),
462        )?;
463        let ln_f = RmsNorm::new(
464            cfg.hidden_size,
465            cfg.rms_norm_eps,
466            mapper.set_nm_device(vb.pp("model.norm"), false),
467        )?;
468        let head_dim = cfg.hidden_size / cfg.num_attention_heads;
469
470        let blocks: Vec<_> = NiceProgressBar::<_, 'b'>(
471            0..cfg.num_hidden_layers,
472            "Loading repeating layers",
473            &normal_loading_metadata.multi_progress,
474        )
475        .into_iter()
476        .map(|i| {
477            let vb_m = vb.pp(format!("model.layers.{i}"));
478            let device = mapper
479                .device_for(i, false)
480                .unwrap_or(&normal_loading_metadata.real_device);
481            let rope_parameters = OrdinaryRoPE::create_parameters(
482                head_dim,
483                cfg.max_position_embeddings,
484                cfg.rope_theta,
485                vb_m.dtype(),
486                device,
487            )
488            .unwrap();
489            let paged_attn = match &attention_mechanism {
490                AttentionImplementation::Eager => None,
491                AttentionImplementation::PagedAttention => Some(
492                    PagedAttention::new(head_dim, device, None)
493                        .expect("Failed to create PagedAttention"),
494                ),
495            };
496            let comm = mapper.get_comm_for(i).unwrap();
497            Block::load(
498                vb_m,
499                cfg,
500                &*mapper,
501                i,
502                normal_loading_metadata.loading_isq,
503                paged_attn,
504                rope_parameters,
505                &comm,
506            )
507            .expect("Failed to load block.")
508        })
509        .collect();
510
511        Ok(Self {
512            wte,
513            blocks,
514            ln_f,
515            lm_head: Arc::new(UnquantLinear::new(QuantMethodConfig::Unquantized(lm_head))?),
516            kv_cache: crate::pipeline::EitherCache::Full(crate::pipeline::Cache::new(
517                cfg.num_hidden_layers,
518                false,
519            )),
520            device: normal_loading_metadata.real_device,
521            cfg: ModelConfigMetadata {
522                max_seq_len: cfg.max_position_embeddings,
523                num_layers: cfg.num_hidden_layers,
524                hidden_size: cfg.hidden_size,
525                num_attn_heads: cfg.num_attention_heads / mapper.get_comm_for(0)?.world_size(),
526                num_kv_heads: (cfg.num_key_value_heads / mapper.get_comm_for(0)?.world_size())
527                    .max(1),
528                sliding_window: None,
529                k_head_dim: cfg.hidden_size / cfg.num_attention_heads,
530                v_head_dim: cfg.hidden_size / cfg.num_attention_heads,
531            },
532            mapper,
533        })
534    }
535}
536
537impl IsqModel for Llama {
538    fn get_layers(
539        &mut self,
540    ) -> (
541        Vec<(&mut Arc<dyn QuantMethod>, Option<usize>)>,
542        &dyn DeviceMapper,
543    ) {
544        let mut tensors = Vec::new();
545        tensors.push((&mut self.lm_head, None));
546        for (i, layer) in self.blocks.iter_mut().enumerate() {
547            tensors.push((&mut layer.attn.q_proj, Some(i)));
548            tensors.push((&mut layer.attn.k_proj, Some(i)));
549            tensors.push((&mut layer.attn.v_proj, Some(i)));
550            tensors.push((&mut layer.attn.o_proj, Some(i)));
551            tensors.extend(
552                layer
553                    .mlp
554                    .get_isq_layers()
555                    .into_iter()
556                    .map(|m| (m, Some(i)))
557                    .collect::<Vec<_>>(),
558            );
559        }
560        (tensors, &*self.mapper)
561    }
562
563    fn residual_tensors(&self) -> Vec<(String, Tensor)> {
564        Vec::new()
565    }
566}
567
568impl LLaVALLM for Llama {
569    fn embed(&self, input_ids: &Tensor) -> Result<Tensor> {
570        self.wte.forward(input_ids)
571    }
572    fn forward_input_embed(
573        &self,
574        input_ids: &Tensor,
575        input_embed: Tensor,
576        seqlen_offsets: &[usize],
577        context_lens: Vec<(usize, usize)>,
578        metadata: Option<(Vec<(Tensor, Tensor)>, &PagedAttentionInputMetadata)>,
579        flash_params: &FlashParams,
580    ) -> Result<Tensor> {
581        let mut x = input_embed;
582        let mut cache = self.kv_cache.full().lock();
583        let mask = CausalMasker.make_causal_mask_matrix(
584            input_ids,
585            metadata
586                .as_ref()
587                .map(|(_, _)| &seqlen_offsets as &dyn PastKvLenCache)
588                .unwrap_or(&*cache as &dyn PastKvLenCache),
589            x.dtype(),
590            self.blocks[0].attn.num_attention_heads,
591        )?;
592        let mask = mask.filter(|_| {
593            metadata
594                .as_ref()
595                .map(|(_, meta)| meta.is_first_prompt_chunk)
596                .unwrap_or(true)
597        });
598        for (block_idx, block) in self.blocks.iter().enumerate() {
599            x = self.mapper.map(x, block_idx)?;
600            x = block.forward(
601                &x,
602                &mask.clone().map(|m| m.to_device(x.device()).unwrap()),
603                seqlen_offsets,
604                block_idx,
605                &mut cache,
606                metadata
607                    .as_ref()
608                    .map(|(kv_cache, metadata)| (kv_cache[block_idx].clone(), *metadata)),
609                flash_params,
610            )?;
611        }
612        x = x.to_device(&self.device)?;
613        x = self.ln_f.forward(&x)?;
614        if let Some(t) = self.lm_head.quantized_act_type() {
615            x = x.to_dtype(t)?;
616        }
617        let xs = MatMul.qmethod_matmul(&x, &*self.lm_head)?;
618        extract_logits(&xs, context_lens)
619    }
620}
621
622impl NormalModel for Llama {
623    fn forward(
624        &self,
625        input_ids: &Tensor,
626        seqlen_offsets: &[usize],
627        context_lens: Vec<(usize, usize)>,
628        _position_ids: Vec<usize>,
629        metadata: Option<(Vec<(Tensor, Tensor)>, &PagedAttentionInputMetadata)>,
630        flash_params: &FlashParams,
631    ) -> Result<Tensor> {
632        self.forward_input(
633            input_ids,
634            seqlen_offsets,
635            context_lens,
636            metadata,
637            flash_params,
638        )
639    }
640    fn xlora_forward(
641        &self,
642        _input_ids: &Tensor,
643        _input_ids_full: &Tensor,
644        _seqlen_offsets: &[usize],
645        _seqlen_offsets_full: &[usize],
646        _no_kv_cache: bool,
647        _non_granular_state: &Option<crate::xlora_models::NonGranularState>,
648        _context_lens: Vec<(usize, usize)>,
649        _position_ids: Vec<usize>,
650        _flash_params: &FlashParams,
651        _flash_params_full: &FlashParams,
652    ) -> Result<Tensor> {
653        unimplemented!()
654    }
655    fn cache(&self) -> &crate::pipeline::EitherCache {
656        &self.kv_cache
657    }
658    fn cache_mut(&mut self) -> &mut crate::pipeline::EitherCache {
659        &mut self.kv_cache
660    }
661    fn device(&self) -> &Device {
662        &self.device
663    }
664    fn is_xlora(&self) -> bool {
665        false
666    }
667    fn max_seq_len(&self) -> usize {
668        self.blocks[0].attn.max_seq_len
669    }
670    fn config(&self) -> &ModelConfigMetadata {
671        &self.cfg
672    }
673}
674
675impl AnyMoeBaseModelMixin for Llama {
676    fn get_mlps(&self) -> Vec<&dyn MlpLayer> {
677        let mut mlps = Vec::new();
678        for layer in &self.blocks {
679            mlps.push(&*layer.mlp);
680        }
681        mlps
682    }
683    fn get_mlps_mut(&mut self) -> Vec<&mut Box<dyn MlpLayer>> {
684        let mut mlps = Vec::new();
685        for layer in &mut self.blocks {
686            mlps.push(&mut layer.mlp);
687        }
688        mlps
689    }
690    fn create_anymoe_layers(
691        &mut self,
692        additional_vbs: Vec<ShardedVarBuilder>,
693        config: AnyMoeConfig,
694        (prefix, mlp): (String, String),
695        mut layers: Vec<usize>,
696        expert_type: AnyMoeExpertType,
697        gate_vb: Option<ShardedVarBuilder>,
698    ) -> Result<()> {
699        let mut experts: Vec<Vec<Box<dyn MlpLayer>>> = Vec::new();
700        if layers.is_empty() {
701            layers = (0..self.blocks.len()).collect::<Vec<_>>();
702        }
703        for _ in 0..layers.len() {
704            experts.push(Vec::new());
705        }
706        for vb in additional_vbs {
707            let vb = vb.pp(&prefix);
708            for (layer, row) in experts.iter_mut().enumerate() {
709                if !layers.contains(&layer) {
710                    continue;
711                }
712
713                let intermediate_size = self.blocks[layer].mlp.get_params()[1];
714                let hidden_size = self.blocks[layer].mlp.get_params()[0];
715                match expert_type {
716                    AnyMoeExpertType::FineTuned => {
717                        let (dtype, device) = self.blocks[layer].mlp.dtype_device();
718                        row.push(Box::new(Mlp::load(
719                            vb.pp(layer).pp(&mlp).set_dtype(dtype).set_device(device),
720                            &Config {
721                                intermediate_size: self.blocks[layer].mlp.get_params()[1],
722                                hidden_size: self.blocks[layer].mlp.get_params()[0],
723                                ..Default::default()
724                            },
725                            &self.mapper.get_comm_for(layer)?,
726                        )?));
727                    }
728                    AnyMoeExpertType::LoraAdapter {
729                        rank,
730                        alpha,
731                        ref target_modules,
732                    } => {
733                        let vb_mlp = vb.pp(layer).pp(&mlp);
734
735                        let c_fc1_delta = if target_modules.contains(&"c_fc1".to_string()) {
736                            Some(get_delta_from_lora_ab!(
737                                vb_mlp,
738                                rank,
739                                alpha,
740                                (hidden_size, intermediate_size),
741                                "c_fc1"
742                            ))
743                        } else {
744                            None
745                        };
746                        let c_fc2_delta = if target_modules.contains(&"c_fc2".to_string()) {
747                            Some(get_delta_from_lora_ab!(
748                                vb_mlp,
749                                rank,
750                                alpha,
751                                (hidden_size, intermediate_size),
752                                "c_fc2"
753                            ))
754                        } else {
755                            None
756                        };
757                        let c_proj_delta = if target_modules.contains(&"c_proj".to_string()) {
758                            Some(get_delta_from_lora_ab!(
759                                vb_mlp,
760                                rank,
761                                alpha,
762                                (intermediate_size, hidden_size),
763                                "c_proj"
764                            ))
765                        } else {
766                            None
767                        };
768
769                        row.push(self.blocks[layer].mlp.new_added_delta(vec![
770                            c_fc1_delta,
771                            c_fc2_delta,
772                            c_proj_delta,
773                        ])?);
774                    }
775                }
776            }
777        }
778        for (layer, expert) in layers.into_iter().zip(experts) {
779            let mut experts_all = vec![self.blocks[layer].mlp.clone()];
780            experts_all.extend(expert);
781            let (dtype, device) = self.blocks[layer].mlp.dtype_device();
782            self.blocks[layer].mlp = Box::new(MoeMlp::new(
783                experts_all,
784                config.clone(),
785                dtype,
786                &device,
787                layer,
788                gate_vb.as_ref(),
789            )?);
790        }
791        Ok(())
792    }
793    fn amoe_supported(&self) -> bool {
794        true
795    }
796}